-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathvcs2vtk.py
More file actions
1452 lines (1352 loc) · 45.4 KB
/
vcs2vtk.py
File metadata and controls
1452 lines (1352 loc) · 45.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## This module contains some convenience function from vcs2vtk
import vcs
import vtk
import numpy
import sys
import json
import os
import meshfill
from vtk.util import numpy_support as VN
import cdms2
import warnings
import cdtime
from projection import round_projections
f = open(os.path.join(vcs.prefix,"share","vcs","wmo_symbols.json"))
wmo = json.load(f)
def applyAttributesFromVCStmpl(tmpl,tmplattribute,txtobj=None):
tatt = getattr(tmpl,tmplattribute)
if txtobj is None:
txtobj = vcs.createtext(To_source=tatt.textorientation,Tt_source=tatt.texttable)
for att in ["x","y","priority"]:
setattr(txtobj,att,getattr(tatt,att))
return txtobj
def numpy_to_vtk_wrapper(numpyArray, deep=False, array_type=None):
result = VN.numpy_to_vtk(numpyArray, deep, array_type)
# Prevent garbage collection on shallow copied data:
if not deep:
result.numpyArray = numpyArray
return result
def putMaskOnVTKGrid(data,grid,actorColor=None,cellData=True,deep=True):
#Ok now looking
msk = data.mask
imsk = numpy_to_vtk_wrapper(msk.astype(numpy.int).flat,deep=deep)
mapper = None
if msk is not numpy.ma.nomask and not numpy.allclose(msk,False):
msk = numpy_to_vtk_wrapper(numpy.logical_not(msk).astype(numpy.uint8).flat,deep=deep)
nomsk = numpy_to_vtk_wrapper(numpy.ones(data.mask.shape,numpy.uint8).flat,deep=deep)
if actorColor is not None:
if grid.IsA("vtkStructuredGrid"):
grid2 = vtk.vtkStructuredGrid()
else:
grid2 = vtk.vtkUnstructuredGrid()
grid2.CopyStructure(grid)
geoFilter = vtk.vtkDataSetSurfaceFilter()
lut = vtk.vtkLookupTable()
r,g,b = actorColor
lut.SetNumberOfTableValues(2)
if not cellData:
if grid2.IsA("vtkStructuredGrid"):
grid2.SetPointVisibilityArray(nomsk)
grid2.GetPointData().SetScalars(imsk)
#grid2.SetCellVisibilityArray(imsk)
#p2c = vtk.vtkPointDataToCellData()
#p2c.SetInputData(grid2)
#geoFilter.SetInputConnection(p2c.GetOutputPort())
geoFilter.SetInputData(grid2)
lut.SetTableValue(0,r/100.,g/100.,b/100.,1.)
lut.SetTableValue(1,r/100.,g/100.,b/100.,1.)
else:
if grid2.IsA("vtkStructuredGrid"):
grid2.SetCellVisibilityArray(nomsk)
grid2.GetCellData().SetScalars(imsk)
geoFilter.SetInputData(grid2)
lut.SetTableValue(0,r/100.,g/100.,b/100.,0.)
lut.SetTableValue(1,r/100.,g/100.,b/100.,1.)
geoFilter.Update()
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputData(geoFilter.GetOutput())
mapper.SetLookupTable(lut)
mapper.SetScalarRange(0,1)
if grid.IsA("vtkStructuredGrid"):
if not cellData:
grid.SetPointVisibilityArray(msk)
else:
grid.SetCellVisibilityArray(msk)
return mapper
def genGridOnPoints(data1,gm,deep=True,grid=None,geo=None):
continents = False
xm,xM,ym,yM = None, None, None, None
useStructuredGrid = True
try:
g=data1.getGrid()
if grid is None:
x = g.getLongitude()[:]
y = g.getLatitude()[:]
continents=True
wrap=[0,360]
if isinstance(g,cdms2.gengrid.AbstractGenericGrid): # Ok need unstrctured grid
useStructuredGrid = False
except:
#hum no grid that's much easier
wrap=None
if grid is None:
x=data1.getAxis(-1)[:]
y=data1.getAxis(-2)[:]
if grid is None:
if x.ndim==1:
y = y[:,numpy.newaxis]*numpy.ones(x.shape)[numpy.newaxis,:]
x = x[numpy.newaxis,:]*numpy.ones(y.shape)
x=x.flatten()
y=y.flatten()
sh =list(x.shape)
sh.append(1)
x=numpy.reshape(x,sh)
y=numpy.reshape(y,sh)
#Ok we have our points in 2D let's create unstructured points grid
xm=x.min()
xM=x.max()
ym=y.min()
yM=y.max()
z = numpy.zeros(x.shape)
m3 = numpy.concatenate((x,y),axis=1)
m3 = numpy.concatenate((m3,z),axis=1)
deep = True
pts = vtk.vtkPoints()
## Convert nupmy array to vtk ones
ppV = numpy_to_vtk_wrapper(m3,deep=deep)
pts.SetData(ppV)
else:
xm,xM,ym,yM,tmp,tmp2 = grid.GetPoints().GetBounds()
vg = grid
projection = vcs.elements["projection"][gm.projection]
xm,xM,ym,yM = getRange(gm,xm,xM,ym,yM)
if geo is None:
geo, geopts = project(pts,projection,[xm,xM,ym,yM])
## Sets the vertices into the grid
if grid is None:
if useStructuredGrid:
vg = vtk.vtkStructuredGrid()
vg.SetDimensions(data1.shape[1],data1.shape[0],1)
else:
vg = vtk.vtkUnstructuredGrid()
vg.SetPoints(geopts)
else:
vg=grid
out={"vtk_backend_grid":vg,
"xm":xm,
"xM":xM,
"ym":ym,
"yM":yM,
"continents":continents,
"wrap":wrap,
"geo":geo,
}
return out
def genGrid(data1,data2,gm,deep=True,grid=None,geo=None):
continents = False
wrap = None
m3 = None
g = None
cellData = True
xm,xM,ym,yM = None, None, None, None
try: #First try to see if we can get a mesh out of this
g=data1.getGrid()
if isinstance(g,cdms2.gengrid.AbstractGenericGrid): # Ok need unstrctured grid
continents = True
wrap = [0.,360.]
if grid is None:
m=g.getMesh()
xm = m[:,1].min()
xM = m[:,1].max()
ym = m[:,0].min()
yM = m[:,0].max()
N=m.shape[0]
#For vtk we need to reorder things
m2 = numpy.ascontiguousarray(numpy.transpose(m,(0,2,1)))
m2.resize((m2.shape[0]*m2.shape[1],m2.shape[2]))
m2=m2[...,::-1]
# here we add dummy levels, might want to reconsider converting "trimData" to "reOrderData" and use actual levels?
m3=numpy.concatenate((m2,numpy.zeros((m2.shape[0],1))),axis=1)
## Could still be meshfill with mesh data
## Ok probably should do a test for hgrid before sending data2
if isinstance(gm,meshfill.Gfm) and data2 is not None:
wrap = gm.wrap
if gm.wrap[1]==360.:
continents = True
if grid is None:
xm = data2[:,1].min()
xM = data2[:,1].max()
ym = data2[:,0].min()
yM = data2[:,0].max()
N = data2.shape[0]
m2 = numpy.ascontiguousarray(numpy.transpose(data2,(0,2,1)))
nVertices = m2.shape[-2]
m2.resize((m2.shape[0]*m2.shape[1],m2.shape[2]))
m2=m2[...,::-1]
# here we add dummy levels, might want to reconsider converting "trimData" to "reOrderData" and use actual levels?
m3=numpy.concatenate((m2,numpy.zeros((m2.shape[0],1))),axis=1)
except Exception,err: # Ok no mesh on file, will do with lat/lon
pass
if m3 is not None:
#Create unstructured grid points
vg = vtk.vtkUnstructuredGrid()
lst = vtk.vtkIdTypeArray()
cells = vtk.vtkCellArray()
numberOfCells = N
lst.SetNumberOfComponents(nVertices + 1)
lst.SetNumberOfTuples(numberOfCells)
for i in range(N):
tuple = [None] * (nVertices + 1)
tuple[0] = nVertices
for j in range(nVertices):
tuple[j + 1] = i * nVertices + j
lst.SetTuple(i, tuple)
## ??? TODO ??? when 3D use CUBE?
cells.SetCells(numberOfCells, lst)
vg.SetCells(vtk.VTK_POLYGON, cells)
else:
#Ok a simple structured grid is enough
if grid is None:
vg = vtk.vtkStructuredGrid()
if g is not None:
# Ok we have grid
continents = True
wrap = [0.,360.]
if grid is None:
lat = g.getLatitude()
lon = g.getLongitude()
if isinstance(g,cdms2.hgrid.AbstractCurveGrid):
#Ok in this case it is a structured grid we have no bounds, using ponitData
## ??? We should probably revist and see if we can use the "bounds" attribute
## to generate cell instead of points
cellData = False
elif grid is None:
lon=data1.getAxis(-1)
lat=data1.getAxis(-2)
xm=lon[0]
xM=lon[-1]
ym=lat[0]
yM=lat[-1]
lat2 = numpy.zeros(len(lat)+1)
lon2 = numpy.zeros(len(lon)+1)
# Ok let's try to get the bounds
try:
blat = lat.getBounds()
blon = lon.getBounds()
lat2[:len(lat)]=blat[:,0]
lat2[len(lat)]=blat[-1,1]
lon2[:len(lon)]=blon[:,0]
lon2[len(lon)]=blon[-1,1]
xm=blon[0][0]
xM=blon[-1][1]
ym=blat[0][0]
yM=blat[-1][1]
except Exception,err:
## No luck we have to generate bounds ourselves
lat2[1:-1]=(lat[:-1]+lat[1:])/2.
lat2[0]=lat[0]-(lat[1]-lat[0])/2.
lat2[-1]=lat[-1]+(lat[-1]-lat[-2])/2.
lon2[1:-1]=(lon[:-1]+lon[1:])/2.
lon2[0]=lon[0]-(lon[1]-lon[0])/2.
lon2[-1]=lat[-1]+(lat[-1]-lat[-2])/2.
lat = lat2[:,numpy.newaxis]*numpy.ones(lon2.shape)[numpy.newaxis,:]
lon = lon2[numpy.newaxis,:]*numpy.ones(lat2.shape)[:,numpy.newaxis]
elif grid is None:
## No grid info from data, making one up
data1=cdms2.asVariable(data1)
lon=data1.getAxis(-1)
lat=data1.getAxis(-2)
xm=lon[0]
xM=lon[-1]
ym=lat[0]
yM=lat[-1]
lat2 = numpy.zeros(len(lat)+1)
lon2 = numpy.zeros(len(lon)+1)
# Ok let's try to get the bounds
try:
blat = lat.getBounds()
blon = lon.GetBounds()
lat2[:len(lat)]=blat[:][0]
lat2[len(lat2)]=blat[-1][1]
lon2[:len(lon)]=blon[:][0]
lon2[len(lon2)]=blon[-1][1]
xm=blon[0][0]
xM=blon[-1][1]
ym=blat[0][0]
yM=blat[-1][1]
except:
## No luck we have to generate bounds ourselves
lat2[1:-1]=(lat[:-1]+lat[1:])/2.
lat2[0]=lat[0]-(lat[1]-lat[0])/2.
lat2[-1]=lat[-1]+(lat[-1]-lat[-2])/2.
lon2[1:-1]=(lon[:-1]+lon[1:])/2.
lon2[0]=lon[0]-(lon[1]-lon[0])/2.
lon2[-1]=lon[-1]+(lon[-1]-lon[-2])/2.
lat = lat2[:,numpy.newaxis]*numpy.ones(lon2.shape)[numpy.newaxis,:]
lon = lon2[numpy.newaxis,:]*numpy.ones(lat2.shape)[:,numpy.newaxis]
if grid is None:
vg.SetDimensions(lat.shape[1],lat.shape[0],1)
lon = numpy.ma.ravel(lon)
lat = numpy.ma.ravel(lat)
sh = list(lat.shape)
sh.append(1)
lon = numpy.ma.reshape(lon,sh)
lat = numpy.ma.reshape(lat,sh)
z = numpy.zeros(lon.shape)
m3 = numpy.concatenate((lon,lat),axis=1)
m3 = numpy.concatenate((m3,z),axis=1)
if xm is None:
try:
xm = lon[0]
xM = lon[-1]
ym = lat[0]
yM = lat[-1]
except:
xm=lon.min()
xM=lon.max()
ym=lat.min()
yM=lat.max()
if grid is None:
# First create the points/vertices (in vcs terms)
pts = vtk.vtkPoints()
## Convert nupmy array to vtk ones
ppV = numpy_to_vtk_wrapper(m3,deep=deep)
pts.SetData(ppV)
else:
xm,xM,ym,yM,tmp,tmp2 = grid.GetPoints().GetBounds()
projection = vcs.elements["projection"][gm.projection]
xm,xM,ym,yM = getRange(gm,xm,xM,ym,yM)
if grid is None:
geo, geopts = project(pts,projection,[xm,xM,ym,yM],geo)
## Sets the vertics into the grid
vg.SetPoints(geopts)
else:
vg=grid
out={"vtk_backend_grid":vg,
"xm":xm,
"xM":xM,
"ym":ym,
"yM":yM,
"continents":continents,
"wrap":wrap,
"geo":geo,
"cellData":cellData,
}
return out
def getRange(gm,xm,xM,ym,yM):
# Also need to make sure it fills the whole space
rtype= type(cdtime.reltime(0,"days since 2000"))
X1,X2 = gm.datawc_x1,gm.datawc_x2
if isinstance(X1,rtype) or isinstance(X2,rtype):
X1=X1.value
X2=X2.value
if not numpy.allclose([X1,X2],1.e20):
x1,x2 = X1,X2
else:
x1,x2 = xm,xM
Y1,Y2 = gm.datawc_y1,gm.datawc_y2
if isinstance(Y1,rtype) or isinstance(Y2,rtype):
Y1=Y1.value
Y2=Y2.value
if not numpy.allclose([Y1,Y2],1.e20):
y1,y2 = Y1,Y2
else:
y1,y2 = ym,yM
return x1,x2,y1,y2
## Continents first
## Try to save time and memorize these continents
vcsContinents= {}
def prepContinents(fnm):
""" This converts vcs continents files to vtkpolydata
Author: Charles Doutriaux
Input: vcs continent file name
"""
if vcsContinents.has_key(fnm):
return vcsContinents[fnm]
poly =vtk.vtkPolyData()
cells = vtk.vtkCellArray()
pts = vtk.vtkPoints()
f=open(fnm)
ln=f.readline()
while ln.strip().split()!=["-99","-99"]:
# Many lines, need to know number of points
N = int(ln.split()[0])
# Now create and store these points
n=0
npts = pts.GetNumberOfPoints()
while n<N:
ln=f.readline()
sp=ln.split()
sn = len(sp)
didIt = False
if sn%2 == 0:
try:
spts = []
for i in range(sn/2):
l,L = float(sp[i*2]),float(sp[i*2+1])
spts.append([l,L])
for p in spts:
pts.InsertNextPoint(p[1],p[0],0.)
n+=sn
didIt = True
except:
didIt = False
if didIt is False:
while len(ln)>2:
l,L=float(ln[:8]),float(ln[8:16])
pts.InsertNextPoint(L,l,0.)
ln=ln[16:]
n+=2
ln = vtk.vtkPolyLine()
ln.GetPointIds().SetNumberOfIds(N/2)
for i in range(N/2): ln.GetPointIds().SetId(i,i+npts)
cells.InsertNextCell(ln)
ln=f.readline()
poly.SetPoints(pts)
poly.SetLines(cells)
# The dataset has some duplicate lines that extend outside of x=[-180, 180],
# which will cause wrapping artifacts for certain projections (e.g.
# Robinson). Clip out the duplicate data:
box = vtk.vtkBox()
box.SetXMin(-180., -90., 0.)
box.SetXMax(180., 90., 1.)
clipper = vtk.vtkClipPolyData()
clipper.SetInputData(poly)
clipper.InsideOutOn()
clipper.SetClipFunction(box)
clipper.Update()
poly = clipper.GetOutput()
vcsContinents[fnm]=poly
return poly
#Geo projection
def project(pts,projection,wc,geo=None):
xm,xM,ym,yM= wc
if isinstance(projection,(str,unicode)):
projection = vcs.elements["projection"][projection]
if projection.type=="linear":
return None,pts
if geo is None:
geo = vtk.vtkGeoTransform()
ps = vtk.vtkGeoProjection()
pd = vtk.vtkGeoProjection()
names = ["linear","utm","state","aea","lcc","merc","stere","poly","eqdc","tmerc","stere","lcca","azi","gnom","ortho","vertnearper","sinu","eqc","mill","vandg","omerc","robin","somerc","alsk","goode","moll","imoll","hammer","wag4","wag7","oea"]
proj_dic = {"polar stereographic":"stere",
-3:"aeqd",
}
for i in range(len(names)):
proj_dic[i]=names[i]
pname = proj_dic.get(projection._type,projection.type)
projName = pname
pd.SetName(projName)
if projection.type == "polar (non gctp)":
if ym<yM:
pd.SetOptionalParameter("lat_0","-90.")
pd.SetCentralMeridian(xm)
else:
pd.SetOptionalParameter("lat_0","90.")
pd.SetCentralMeridian(xm+180.)
else:
setProjectionParameters(pd,projection)
geo.SetSourceProjection(ps)
geo.SetDestinationProjection(pd)
geopts = vtk.vtkPoints()
geo.TransformPoints(pts,geopts)
return geo,geopts
def setProjectionParameters(pd,proj):
if proj._type>200:
proj4 = proj.parameters
if numpy.allclose(proj4,1.e20):
proj4={}
else:
p=proj.parameters
proj4={}
if proj._type in [3,4]:
proj4["a"]=proj.smajor
proj4["b"]=proj.sminor
proj4["lat_1"]=proj.standardparallel1
proj4["lat_2"]=proj.standardparallel2
proj4["lon_0"]=proj.centralmeridian
proj4["lat_0"]=proj.originlatitude
proj4["x_0"]=proj.falseeasting
proj4["y_0"]=proj.falsenorthing
elif proj._type==5:
proj4["a"]=proj.smajor
proj4["b"]=proj.sminor
proj4["lon_0"]=proj.centralmeridian
proj4["lat_ts"]=proj.truescale
proj4["x_0"]=proj.falseeasting
proj4["y_0"]=proj.falsenorthing
elif proj._type==6:
proj4["a"]=proj.smajor
proj4["b"]=proj.sminor
proj4["lon_wrap"]=proj.centerlongitude # MAP NAME ?????
proj4["lat_ts"]=proj.truescale
proj4["x_0"]=proj.falseeasting
proj4["y_0"]=proj.falsenorthing
elif proj._type==7:
proj4["a"]=proj.smajor
proj4["b"]=proj.sminor
proj4["lon_0"]=proj.centralmeridian
proj4["lat_0"]=proj.originlatitude
proj4["x_0"]=proj.falseeasting
proj4["y_0"]=proj.falsenorthing
elif proj._type==8:
proj4["a"]=proj.smajor
proj4["b"]=proj.sminor
proj4["lon_0"]=proj.centralmeridian
proj4["lat_0"]=proj.originlatitude
proj4["x_0"]=proj.falseeasting
proj4["y_0"]=proj.falsenorthing
if (p[8]==0 or p[8]>9.9E19):
proj4["subtype"]=proj.subtype=0
proj4["lat_1"]=proj.standardparallel # MAP NAME ?????
proj4["lat_2"]=proj.standardparallel # MAP NAME ?????
proj4["lat_ts"]=proj.standardparallel # MAP NAME ?????
else:
proj4["subtype"]=proj.subtype=1
proj4["lat_1"]=proj.standardparallel1
proj4["lat_2"]=proj.standardparallel2
elif proj._type==9:
proj4["a"]=proj.smajor
proj4["b"]=proj.sminor
proj4["k_0"]=proj.factor
proj4["lon_0"]=proj.centralmeridian
proj4["lat_0"]=proj.originlatitude
proj4["x_0"]=proj.falseeasting
proj4["y_0"]=proj.falsenorthing
elif proj._type in [10,11,12,13,14]:
proj4["a"]=proj.sphere # MAP NAME ?????
proj4["b"]=proj.sphere # MAP NAME ?????
proj4["lon_0"]=proj.centerlongitude
proj4["lat_0"]=proj.centerlatitude
proj4["x_0"]=proj.falseeasting
proj4["y_0"]=proj.falsenorthing
elif proj._type==15:
proj4["a"]=proj.sphere # MAP NAME ?????
proj4["b"]=proj.sphere # MAP NAME ?????
proj4["height"]=proj.height # MAP NAME ?????
proj4["lon_0"]=proj.centerlongitude
proj4["lat_0"]=proj.centerlatitude
proj4["x_0"]=proj.falseeasting
proj4["y_0"]=proj.falsenorthing
elif proj._type in [16,18,21,25,27,28,29]:
proj4["a"]=proj.sphere # MAP NAME ?????
proj4["b"]=proj.sphere # MAP NAME ?????
proj4["lon_0"]=proj.centralmeridian
proj4["x_0"]=proj.falseeasting
proj4["y_0"]=proj.falsenorthing
elif proj._type==17:
proj4["a"]=proj.sphere
proj4["b"]=proj.sphere
proj4["lon_0"]=proj.centralmeridian
proj4["lat_ts"]=proj.truescale
proj4["x_0"]=proj.falseeasting
proj4["y_0"]=proj.falsenorthing
elif proj._type==19:
proj4["a"]=proj.sphere # MAP NAME ?????
proj4["b"]=proj.sphere # MAP NAME ?????
proj4["lon_0"]=proj.centralmeridian
proj4["lat_0"]=proj.originlatitude
proj4["x_0"]=proj.falseeasting
proj4["y_0"]=proj.falsenorthing
elif proj._type==20:
proj4["a"]=proj.smajor
proj4["b"]=proj.sminor
proj4["k_0"]=proj.factor
proj4["lat_0"]=proj.originlatitude
proj4["x_0"]=proj.falseeasting
proj4["y_0"]=proj.falsenorthing
if (p[12]==0 or p[12]>9.9E19):
proj4["subtype"]=proj.subtype
proj4["lon_0"]=proj.longitude1 # MAP NAME ?????
proj4["lat_1"]=proj.latitude1
proj4["lonc"]=proj.longitude2 # MAP NAME ?????
proj4["lat_2"]=proj.latitude2
else:
proj4["subtype"]=proj.subtype
proj4["azi"]=proj.azimuthalangle # MAP NAME ?????
proj4["lon_0"]=proj.azimuthallongitude # MAP NAME ?????
elif proj._type==22:
proj4["a"]=proj.smajor
proj4["b"]=proj.sminor
proj4["x_0"]=proj.falseeasting
proj4["y_0"]=proj.falsenorthing
if (p[12]==0 or p[12]>9.9E19):
proj4["subtype"]=proj.subtype
proj4["???"]=proj.orbitinclination # MAP NAME ?????
proj4["???"]=proj.orbitlongitude # MAP NAME ?????
proj4["???"]=proj.satelliterevolutionperiod # MAP NAME ?????
proj4["???"]=proj.landsatcompensationratio # MAP NAME ?????
proj4["???"]=proj.pathflag # MAP NAME ?????
else:
proj4["subtype"]=proj.subtype
proj4["???"]=proj.satellite # MAP NAME ?????
proj4["???"]=proj.path # MAP NAME ?????
elif proj._type==23:
proj4["a"]=proj.smajor
proj4["b"]=proj.sminor
proj4["x_0"]=proj.falseeasting
proj4["y_0"]=proj.falsenorthing
elif proj._type in [24,26]:
proj4["a"]=proj.sphere # MAP NAME ?????
proj4["b"]=proj.sphere # MAP NAME ?????
elif proj._type==30:
proj4["a"]=proj.sphere # MAP NAME ?????
proj4["b"]=proj.sphere # MAP NAME ?????
proj4["???"]=proj.shapem # MAP NAME ?????
proj4["???"]=proj.shapen # MAP NAME ?????
proj4["lon_0"]=proj.centerlongitude
proj4["lat_0"]=proj.centerlatitude
proj4["x_0"]=proj.falseeasting
proj4["y_0"]=proj.falsenorthing
if proj._type==6:
pd.SetOptionalParameter("lat_0","90")
for k in proj4:
if not numpy.allclose(proj4[k],1.e20):
if k=="lon_0":
pd.SetCentralMeridian(proj4[k])
elif k!="???":
pd.SetOptionalParameter(k,str(proj4[k]))
#Vtk dump
dumps={}
def dump2VTK(obj,fnm=None):
global dumps
if fnm is None:
fnm="foo.vtk" % dumps
if fnm[:-4].lower()!=".vtk":
fnm+=".vtk"
if fnm in dumps:
dumps[fnm]+=1
fnm=fnm[:-4]+"%.3i.vtk" % dumps[fnm]
else:
dumps[fnm]=0
dsw = vtk.vtkDataSetWriter()
dsw.SetFileName(fnm)
try:
dsw.SetInputData(obj)
except:
dsw.SetInputConnection(obj.GetOutputPort())
dsw.Write()
#Wrapping around
def doWrap(Act,wc,wrap=[0.,360], fastClip=True):
if wrap is None:
return Act
Mapper = Act.GetMapper()
data = Mapper.GetInput()
xmn=min(wc[0],wc[1])
xmx=max(wc[0],wc[1])
if numpy.allclose(xmn,1.e20) or numpy.allclose(xmx,1.e20):
xmx = abs(wrap[1])
xmn = -wrap[1]
ymn=min(wc[2],wc[3])
ymx=max(wc[2],wc[3])
if numpy.allclose(ymn,1.e20) or numpy.allclose(ymx,1.e20):
ymx = abs(wrap[0])
ymn = -wrap[0]
## Prepare MultiBlock and puts in oriinal data
appendFilter =vtk.vtkAppendPolyData()
appendFilter.AddInputData(data)
appendFilter.Update()
## X axis wrappping
Amn,Amx = Act.GetXRange()
if wrap[1]!=0.:
i=0
while Amn>xmn:
i+=1
Amn-=wrap[1]
Tpf = vtk.vtkTransformPolyDataFilter()
Tpf.SetInputData(data)
T=vtk.vtkTransform()
T.Translate(-i*wrap[1],0,0)
Tpf.SetTransform(T)
Tpf.Update()
appendFilter.AddInputData(Tpf.GetOutput())
appendFilter.Update()
i=0
while Amx<xmx:
i+=1
Amx+=wrap[1]
Tpf = vtk.vtkTransformPolyDataFilter()
Tpf.SetInputData(data)
T = vtk.vtkTransform()
T.Translate(i*wrap[1],0,0)
Tpf.SetTransform(T)
Tpf.Update()
appendFilter.AddInputData(Tpf.GetOutput())
appendFilter.Update()
# Y axis wrapping
Amn,Amx = Act.GetYRange()
if wrap[0]!=0.:
i=0
while Amn>ymn:
i+=1
Amn-=wrap[0]
Tpf = vtk.vtkTransformPolyDataFilter()
Tpf.SetInputData(data)
T = vtk.vtkTransform()
T.Translate(0,i*wrap[0],0)
Tpf.SetTransform(T)
Tpf.Update()
appendFilter.AddInputData(Tpf.GetOutput())
appendFilter.Update()
i=0
while Amx<ymx:
i+=1
Amx+=wrap[0]
Tpf = vtk.vtkTransformPolyDataFilter()
Tpf.SetInputData(data)
T = vtk.vtkTransform()
T.Translate(0,-i*wrap[0],0)
Tpf.SetTransform(T)
Tpf.Update()
appendFilter.AddInputData(Tpf.GetOutput())
appendFilter.Update()
# Clip the data to the final window:
clipBox = vtk.vtkBox()
clipBox.SetXMin(xmn, ymn, -1.0)
clipBox.SetXMax(xmx, ymx, 1.0)
if fastClip:
clipper = vtk.vtkExtractPolyDataGeometry()
clipper.ExtractInsideOn()
clipper.SetImplicitFunction(clipBox)
clipper.ExtractBoundaryCellsOn()
clipper.PassPointsOff()
else:
clipper = vtk.vtkClipPolyData()
clipper.InsideOutOn()
clipper.SetClipFunction(clipBox)
clipper.SetInputConnection(appendFilter.GetOutputPort())
clipper.Update()
Mapper.SetInputData(clipper.GetOutput())
return Act
def setClipPlanes(mapper, xmin, xmax, ymin, ymax):
clipPlaneCollection = vtk.vtkPlaneCollection()
if xmin != xmax:
clipPlaneXMin = vtk.vtkPlane()
clipPlaneXMin.SetOrigin(xmin, 0.0, 0.0)
clipPlaneXMin.SetNormal(1.0, 0.0, 0.0)
clipPlaneXMax = vtk.vtkPlane()
clipPlaneXMax.SetOrigin(xmax, 0.0, 0.0)
clipPlaneXMax.SetNormal(-1.0, 0.0, 0.0)
clipPlaneCollection.AddItem(clipPlaneXMin)
clipPlaneCollection.AddItem(clipPlaneXMax)
if ymin != ymax:
clipPlaneYMin = vtk.vtkPlane()
clipPlaneYMin.SetOrigin(0.0, ymin, 0.0)
clipPlaneYMin.SetNormal(0.0, 1.0, 0.0)
clipPlaneYMax = vtk.vtkPlane()
clipPlaneYMax.SetOrigin(0.0, ymax, 0.0)
clipPlaneYMax.SetNormal(0.0, -1.0, 0.0)
clipPlaneCollection.AddItem(clipPlaneYMin)
clipPlaneCollection.AddItem(clipPlaneYMax)
if clipPlaneCollection.GetNumberOfItems() > 0:
mapper.SetClippingPlanes(clipPlaneCollection)
# The code is replaced by the setClipPlanes above
# def doClip(data, xmin,xmax,ymin,ymax):
# if xmin!=xmax:
# xminClip = doClip1(data,xmin,1,0)
# xfullClip = doClip1(xminClip,xmax,-1,0)
# else:
# xfullClip = data
# if ymin!=ymax:
# yminClip = doClip1(xfullClip,ymin,1,1)
# xyClip = doClip1(yminClip,ymax,-1,1)
# else:
# xyClip = xfullClip
# return xyClip
# def doClip1(data,value,normal,axis=0):
# return data
# # We have the actor, do clipping
# clpf = vtk.vtkPlane()
# if axis == 0:
# clpf.SetOrigin(value,0,0)
# clpf.SetNormal(normal,0,0)
# else:
# clpf.SetOrigin(0,value,0)
# clpf.SetNormal(0,normal,0)
# clp = vtk.vtkClipPolyData()
# clp.SetClipFunction(clpf)
# clp.SetInputData(data)
# clp.Update()
# return clp.GetOutput()
def prepTextProperty(p,winSize,to="default",tt="default",cmap=None,
overrideColorIndex = None):
if isinstance(to,str):
to = vcs.elements["textorientation"][to]
if isinstance(tt,str):
tt = vcs.elements["texttable"][tt]
if cmap is None:
if tt.colormap is not None:
cmap = tt.colormap
else:
cmap = 'default'
if isinstance(cmap,str):
cmap = vcs.elements["colormap"][cmap]
colorIndex = overrideColorIndex if overrideColorIndex else tt.color
c=cmap.index[colorIndex]
p.SetColor([C/100. for C in c])
if to.halign in [0, 'left']:
p.SetJustificationToLeft()
elif to.halign in [2, 'right']:
p.SetJustificationToRight()
elif to.halign in [1,'center']:
p.SetJustificationToCentered()
p.SetOrientation(-to.angle)
if to.valign in [0,'top']:
p.SetVerticalJustificationToTop()
elif to.valign in [2, 'half']:
p.SetVerticalJustificationToCentered()
elif to.valign in [4,'bottom']:
p.SetVerticalJustificationToBottom()
elif to.valign in [1,'cap']:
warnings.warn("VTK does not support 'cap' align, using 'top'")
p.SetVerticalJustificationToTop()
elif to.valign in [3,'base']:
warnings.warn("VTK does not support 'base' align, using 'bottom'")
p.SetVerticalJustificationToBottom()
p.SetFontFamily(vtk.VTK_FONT_FILE)
p.SetFontFile(vcs.elements["font"][vcs.elements["fontNumber"][tt.font]])
p.SetFontSize(int(to.height*winSize[1]/800.))
def genTextActor(renderer,string=None,x=None,y=None,to='default',tt='default',cmap=None):
if isinstance(to,str):
to = vcs.elements["textorientation"][to]
if isinstance(tt,str):
tt = vcs.elements["texttable"][tt]
if tt.priority==0:
return []
if string is None:
string = tt.string
if x is None:
x = tt.x
if y is None:
y = tt.y
if x is None or y is None or string in [['',],[]]:
return []
n = max(len(x),len(y),len(string))
for a in [x,y,string]:
while len(a)<n:
a.append(a[-1])
sz = renderer.GetRenderWindow().GetSize()
actors=[]
pts = vtk.vtkPoints()
geo = None
if vcs.elements["projection"][tt.projection].type!="linear":
# Need to figure out new WC
Npts = 20
for i in range(Npts+1):
X = tt.worldcoordinate[0]+float(i)/Npts*(tt.worldcoordinate[1]-tt.worldcoordinate[0])
for j in range(Npts+1):
Y = tt.worldcoordinate[2]+float(j)/Npts*(tt.worldcoordinate[3]-tt.worldcoordinate[2])
pts.InsertNextPoint(X,Y,0.)
geo,pts = project(pts,tt.projection,tt.worldcoordinate,geo=None)
wc = pts.GetBounds()[:4]
#renderer.SetViewport(tt.viewport[0],tt.viewport[2],tt.viewport[1],tt.viewport[3])
renderer.SetWorldPoint(wc)
for i in range(n):
t = vtk.vtkTextActor()
p=t.GetTextProperty()
prepTextProperty(p,sz,to,tt,cmap)
pts = vtk.vtkPoints()
pts.InsertNextPoint(x[i],y[i],0.)
if geo is not None:
geo,pts = project(pts,tt.projection,tt.worldcoordinate,geo=geo)
X,Y,tz=pts.GetPoint(0)
X,Y = world2Renderer(renderer,X,Y,tt.viewport,wc)
else:
X,Y = world2Renderer(renderer,x[i],y[i],tt.viewport,tt.worldcoordinate)
t.SetPosition(X,Y)
t.SetInput(string[i])
#T=vtk.vtkTransform()
#T.Scale(1.,sz[1]/606.,1.)
#T.RotateY(to.angle)
#t.SetUserTransform(T)
renderer.AddActor(t)
actors.append(t)
return actors
def prepPrimitive(prim):
if prim.x is None or prim.y is None:
return 0
if not isinstance(prim.x[0],(list,tuple)):
prim.x = [prim.x,]
if not isinstance(prim.y[0],(list,tuple)):
prim.y = [prim.y,]
if vcs.isfillarea(prim):
atts = ["x","y","color","style","index"]
elif vcs.ismarker(prim):
atts = ["x","y","color","size","type"]
elif vcs.isline(prim):
atts = ["x","y","color","width","type"]
n=0
for a in atts:
n = max(n,len(getattr(prim,a)))
for a in atts:
v = getattr(prim,a)
while len(v)<n:
v.append(v[-1])
setattr(prim,a,v)
return n
def prepFillarea(renWin,farea,cmap=None):
n = prepPrimitive(farea)
if n==0:
return []
actors =[]
# Find color map:
if cmap is None:
if farea.colormap is not None:
cmap = farea.colormap
else:
cmap = 'default'
if isinstance(cmap,str):
cmap = vcs.elements["colormap"][cmap]
# Create data structures:
pts = vtk.vtkPoints()
polygons = vtk.vtkCellArray()
colors = vtk.vtkUnsignedCharArray()
colors.SetNumberOfComponents(3)
colors.SetNumberOfTuples(n)
polygonPolyData = vtk.vtkPolyData()
polygonPolyData.SetPoints(pts)
polygonPolyData.SetPolys(polygons)
polygonPolyData.GetCellData().SetScalars(colors)
# Reuse this temporary container to avoid reallocating repeatedly:
polygon = vtk.vtkPolygon()
# Iterate through polygons:
for i in range(n):
x = farea.x[i]
y = farea.y[i]
c = farea.color[i]
st = farea.style[i]
idx = farea.index[i]
N = max(len(x),len(y))
for a in [x,y]:
assert(len(a) == N)
# Add current polygon
pid = polygon.GetPointIds()
pid.SetNumberOfIds(N)
for j in range(N):
pid.SetId(j, pts.InsertNextPoint(x[j],y[j],0.))
cellId = polygons.InsertNextCell(polygon)
# Add the color to the color array:
color = cmap.index[c]
colors.SetTupleValue(cellId, [int((C/100.) * 255) for C in color])
# Transform points:
geo,pts = project(pts,farea.projection,farea.worldcoordinate)
# Setup rendering
m = vtk.vtkPolyDataMapper()
m.SetInputData(polygonPolyData)
a = vtk.vtkActor()
a.SetMapper(m)
actors.append((a,geo))
return actors
def genPoly(coords,pts,filled=True):
N = pts.GetNumberOfPoints()
if filled: