-
Notifications
You must be signed in to change notification settings - Fork 1
/
mapper.py
executable file
·1930 lines (1747 loc) · 68 KB
/
mapper.py
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
#!/usr/bin/env python
import string
import re
import sys
from mylib_save import *
from mylib_text import *
from mylib_axis import *
from mylib_grid import *
from mylib_equator import *
from mylib_boundaries import *
from mylib_continents import *
from mylib_misc import *
from mylib_lut import *
import vtk
import os.path
import numpy
import netCDF4
import pickle
license = """
Copyright Patrick Brockmann (CEA / LSCE)
This software is a computer program whose purpose is to
display variables from model output with regular, curvilinear
or generic grid description. Those grid are described by respecting
the Climate and Forecast (CF) Metadata Convention of the netCDF format.
This software is governed by the CeCILL license under French law and
abiding by the rules of distribution of free software. You can use,
modify and/ or redistribute the software under the terms of the CeCILL
license as circulated by CEA, CNRS and INRIA at the following URL
http://www.cecill.info.
As a counterpart to the access to the source code and rights to copy,
modify and redistribute granted by the license, users are provided only
with a limited warranty and the software's author, the holder of the
economic rights, and the successive licensors have only limited
liability.
In this respect, the user's attention is drawn to the risks associated
with loading, using, modifying and/or developing or reproducing the
software by the user in light of its specific status of free software,
that may mean that it is complicated to manipulate, and that also
therefore means that it is reserved for developers and experienced
professionals having in-depth computer knowledge. Users are therefore
encouraged to load and test the software's suitability as regards their
requirements in conditions enabling the security of their systems and/or
data to be ensured and, more generally, to use and operate it in the
same conditions as regards security.
The fact that you are presently reading this means that you have had
knowledge of the CeCILL license and that you accept its terms.
"""
credits = """######################################################
VTK_Mapper : A mapping application using netCDF4, NumPy, VTK, Qt
######################################################
"""
#
##################################
PATHROOT = os.path.dirname(sys.argv[0])
##################################
usage = """######################################################
Usage: mapper.py [-h]
[-p projection] [-a actor]
[-n levels_nb] [-l min:max:delta]
[--bg r,g,b] [--fg r,g,b]
[--camera camera_object_file] [--color spectrum_color_file]
[--kindex index] [--lindex index]
[--continents] [--continents_file file] [--continents_color r,g,b] [--continents_width width]
[--boundaries] [--boundaries_color r,g,b] [--boundaries_width width]
[--equator] [--equator_color r,g,b] [--equator_width width]
[--grid] [--grid_color r,g,b] [--grid_width width] [--grid_delta delta]
[--label_format format]
[--verbose] [--prefix prefixfilename] [--offscreen] [-x] [--interface]
[--gridfile gridCF_file]
var_file var
"""
options = """######################################################
Options:
-h, -?, --help, -help
Print this manual
-x, --interface
Run the application with the GUI interface
-p, --projection
Projection to choose in (linear,orthographic)
-a, --actor
Actor to choose in :
isofill,cell,cellbounds,isoline1,isoline2
Other accepted syntax are:
isofilled,cells,,cellsbounds,isolines1,isolines2
-v, --verbose
Verbose mode
-n, --levels_nb
Number of levels should be in [3:100]
-l, --levels
Levels expressed as minimum:maximum:delta
Example: -l 2:32:4 from 2 to 32 by step of 4
-l 0:0:4 from min to max by step of 4
--bg, --background
Background color expressed as red, green, blue values in [0:1]
Example: --bg 0.3,0.3,0.3
--fg, --foreground
Foreground color expressed as red, green, blue values in [0:1]
Example: --fg 1.0,1.0,1.0
--op, --operation
Operation to apply on variable (use quote)
Example: --op 'var*86400'
--op '(var*100)+273.15'
--camera
Camera object file
--color
Spectrum color file
This file follows the coding of the ferret percent method which
defines points along an abstract path in RGB color space that runs
from 0 to 100 percent. Search Palette/by_percent in
http://ferret.wrc.noaa.gov/Ferret/Documentation
--kindex
Index for the 3th dimension (vertical axis)
of the variable to plot [1:n]
--lindex
Index for the 4th dimension (time axis)
of the variable to plot [1:n]
--boundaries, --continents, --equator, --grid
Drawn if this option is present
--boundaries_color, --continents_color, --equator_color, --grid_color
Color expressed as red, green, blue values in [0:1]
Example: --boundaries_color 0.,0.,0.3
--boundaries_width, --continents_width, --equator_width, --grid_width
Lines width expressed in [1:5]
--continents_file
NetCDF continents file (CONT_LON,CONT_LAT variables)
--grid_delta
Delta for grid lines (default=30)
--label_format
format (default="%6.2g")
--prefix
Filename prefix used when PNG and PDF file
are saved (default=picture)
--gridfile
NetCDF file at the CF convention from where the grid is read.
If present, the "mask" variable is read and used in combinaison
with the mask deduced from the variable.
If gridfile not present, use only self descriptions of the variable.
--ratioxy
Set the ratio between height and width
for linear projection (default=1.0)
--offscreen
Produce a PNG and a PDF file in a offscreen mode
"""
interactions = """######################################################
Interactions:
---------------------
* Press e to quit
---------------------
* Press u to save the renderwindow as a PNG image
---------------------
* Press p to pick a cell and get its indices and its value
(available only with actors cell or cellbounds)
---------------------
* Press c to capture camera position and save a camera.sty file
---------------------
* Press , to move backward on k dimension
* Press ; to move forward on k dimension
---------------------
* Press - or : to move backward on l dimension
* Press + or ! to move forward on l dimension
---------------------
* Press v to save the renderwindow as a PDF file
---------------------
* Press c to init or re-init size of the renderwindow
---------------------
* Press o to save the object as a VTK object
(explore use of Paraview by loading this object file)
---------------------
* Press 1 to switch between different actors
isolines1-->isolines2-->cells-->cellbounds-->isofill-->isolines1
---------------------
* Press 2 to activate/inactivate display of boundaries
---------------------
* Press 4 to activate/inactivate display of continents
---------------------
* Press 5 to activate/inactivate display of equator
---------------------
* Press 6 to activate/inactivate display of grid
---------------------
* Press 7 to load the camera file
---------------------
* Press ? to get this help
######################################################
"""
##################################
command = {}
command['argprogram'] = "mapper.py"
##################################
option_projection = 'linear'
option_actor = 'cells'
option_levels_nb = 15
option_levels_nb_specified = 1
option_verbose = 0
option_bg = [1, 1, 1]
option_fg = [0, 0, 0]
option_op = None
kindex = 0
lindex = 0
camera_filename = None
color_filename = PATHROOT+'/colors/grads.spk'
option_boundaries_active = 0
option_boundaries_color_user = [1, 0, 1]
option_boundaries_width = 2
option_continents_active = 0
option_continents_file = None
option_continents_color_user = [0, 0, 1]
option_continents_width = 1
option_grid_delta = 10
option_grid_active = 0
option_grid_color_user = [1, 0, 0]
option_grid_width = 1
option_equator_active = 0
option_equator_color_user = [0, 0, 0]
option_equator_width = 2
option_label_format = '%6.2g'
option_prefix = 'picture'
option_gridfile = 0
option_ratioxy = 1.0
option_offscreen = 0
option_interface = 0
while len(sys.argv[1:]) != 0:
if sys.argv[1] in ('-h', '--help'):
del(sys.argv[1])
print(usage + options)
sys.exit(1)
elif sys.argv[1] in ('-p', '--projection'):
command['--projection'] = sys.argv[2]
option_projection = sys.argv[2]
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] in ('-a', '--actor'):
command['--actor'] = sys.argv[2]
option_actor = sys.argv[2]
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] in ('-v', '--verbose'):
command['--verbose'] = ''
option_verbose = 1
del(sys.argv[1])
elif sys.argv[1] in ('-x', '--interface'):
command['--interface'] = ''
option_interface = 1
del(sys.argv[1])
elif sys.argv[1] in ('-n', '--levels_nb'):
command['--levels_nb'] = sys.argv[2]
option_levels_nb = int(sys.argv[2])
option_levels_nb_specified = 1
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] in ('-l', '--levels'):
command['--levels'] = sys.argv[2]
option_levels = sys.argv[2].split(':')
option_levels_nb_specified = 0
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] in ('--bg', '--background'):
command['--background'] = sys.argv[2]
option_bg = sys.argv[2].split(',')
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] in ('--fg', '--foreground'):
command['--foreground'] = sys.argv[2]
option_fg = sys.argv[2].split(',')
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] in ('--op', '--operation'):
command['--operation'] = sys.argv[2]
option_op = sys.argv[2]
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] == '--kindex':
command['--kindex'] = sys.argv[2]
kindex = int(sys.argv[2])-1
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] == '--lindex':
command['--lindex'] = sys.argv[2]
lindex = int(sys.argv[2])
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] == '--camera':
command['--camera'] = sys.argv[2]
camera_filename = sys.argv[2]
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] == '--color':
command['--color'] = sys.argv[2]
color_filename = sys.argv[2]
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] == '--continents':
command['--continents'] = ''
option_continents_active = 1
del(sys.argv[1])
elif sys.argv[1] == '--continents_file':
command['--continents_file'] = sys.argv[2]
option_continents_active = 1
option_continents_file = sys.argv[2]
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] == '--continents_color':
command['--continents_color'] = sys.argv[2]
option_continents_color_user = sys.argv[2].split(',')
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] == '--continents_width':
command['--continents_width'] = sys.argv[2]
option_continents_width = int(sys.argv[2])
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] == '--boundaries':
command['--boundaries'] = ''
option_boundaries_active = 1
del(sys.argv[1])
elif sys.argv[1] == '--boundaries_color':
command['--boundaries_color'] = sys.argv[2]
option_boundaries_active = 1
option_boundaries_color_user = sys.argv[2].split(',')
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] == '--boundaries_width':
command['--boundaries_width'] = sys.argv[2]
option_boundaries_active = 1
option_boundaries_width = int(sys.argv[2])
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] == '--equator':
command['--equator'] = ''
option_equator_active = 1
del(sys.argv[1])
elif sys.argv[1] == '--equator_color':
command['--equator_color'] = sys.argv[2]
option_equator_active = 1
option_equator_color_user = sys.argv[2].split(',')
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] == '--equator_width':
command['--equator_width'] = sys.argv[2]
option_equator_active = 1
option_equator_width = int(sys.argv[2])
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] == '--grid':
command['--grid'] = ''
option_grid_active = 1
del(sys.argv[1])
elif sys.argv[1] == '--grid_delta':
command['--grid_delta'] = sys.argv[2]
option_grid_active = 1
option_grid_delta = int(sys.argv[2])
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] == '--grid_color':
command['--grid_color'] = sys.argv[2]
option_grid_active = 1
option_grid_color_user = sys.argv[2].split(',')
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] == '--grid_width':
command['--grid_width'] = sys.argv[2]
option_grid_active = 1
option_grid_width = int(sys.argv[2])
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] == '--label_format':
command['--label_format'] = sys.argv[2]
option_label_format = sys.argv[2]
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] == '--prefix':
command['--prefix'] = sys.argv[2]
option_prefix = sys.argv[2]
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] == '--gridfile':
command['--gridfile'] = sys.argv[2]
option_gridfile = 1
gridfilename = sys.argv[2]
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] == '--ratioxy':
command['--ratioxy'] = sys.argv[2]
option_ratioxy = float(sys.argv[2])
del(sys.argv[1])
del(sys.argv[1])
elif sys.argv[1] == '--offscreen':
command['--offscreen'] = ''
option_offscreen = 1
option_interface = 0
del(sys.argv[1])
elif re.match('-', sys.argv[1]):
print('option inconnu')
break
else:
break
if len(sys.argv[1:]) != 2:
print(usage + options)
sys.exit(1)
command['argvarfile'] = sys.argv[1]
command['argvarname'] = sys.argv[2]
################################################################
# Transform and verify arguments
# -------------------------
if option_actor not in ('isofill', 'isofilled',
'cell', 'cells',
'cellbounds', 'cellsbounds',
'isoline1', 'isolines1',
'isoline2', 'isolines2'):
print(usage + options)
sys.exit(1)
# -------------------------
if option_projection not in ('linear', 'orthographic'):
print(usage + options)
sys.exit(1)
# -------------------------
if option_levels_nb_specified:
if not(2 < option_levels_nb < 101):
print(usage + options)
sys.exit(1)
else:
levels_nb = option_levels_nb
else:
if len(option_levels) != 3:
print(usage + options)
sys.exit(1)
else:
for i in range(len(option_levels)):
option_levels[i] = float(option_levels[i])
levels_min = option_levels[0]
levels_max = option_levels[1]
levels_delta = abs(option_levels[2])
if (levels_max < levels_min) or (levels_delta == 0):
print(usage + options)
sys.exit(1)
# -------------------------
if len(option_bg) != 3:
print(usage + options)
sys.exit(1)
else:
colorbg = []
for i in range(len(option_bg)):
colorbg.append(float(option_bg[i]))
# -------------------------
if len(option_fg) != 3:
print(usage + options)
sys.exit(1)
else:
colorfg = []
for i in range(len(option_fg)):
colorfg.append(float(option_fg[i]))
# -------------------------
if len(option_continents_color_user) != 3:
print(usage + options)
sys.exit(1)
else:
option_continents_color = []
for i in range(len(option_continents_color_user)):
option_continents_color.append(
float(option_continents_color_user[i]))
# -------------------------
if len(option_boundaries_color_user) != 3:
print(usage + options)
sys.exit(1)
else:
option_boundaries_color = []
for i in range(len(option_boundaries_color_user)):
option_boundaries_color.append(
float(option_boundaries_color_user[i]))
# -------------------------
if len(option_grid_color_user) != 3:
print(usage + options)
sys.exit(1)
else:
option_grid_color = []
for i in range(len(option_grid_color_user)):
option_grid_color.append(float(option_grid_color_user[i]))
# -------------------------
if len(option_equator_color_user) != 3:
print(usage + options)
sys.exit(1)
else:
option_equator_color = []
for i in range(len(option_grid_color_user)):
option_equator_color.append(float(option_equator_color_user[i]))
################################################################
axisxticknb = axisyticknb = 7
################################################################
my_print(option_verbose, '----------------------------')
my_print(option_verbose, 'VTK Version', vtk.vtkVersion().GetVTKVersion())
################################################################
# Limit excursion of the vertex of the cell according to
# its center position
def limit_lon(blon, clon):
clon = (clon+360*10) % 360
clon = numpy.where(numpy.greater(clon, 180), clon-360, clon)
clon = numpy.where(numpy.less(clon, -180), clon+360, clon)
clon1 = numpy.zeros(blon.shape, numpy.float32)
clon1 = numpy.ones(blon.shape, numpy.float32)*clon[..., None]
blon = (blon+360*10) % 360
blon = numpy.where(numpy.greater(blon, 180), blon-360, blon)
blon = numpy.where(numpy.less(blon, -180), blon+360, blon)
blon = numpy.where(numpy.greater(
abs(blon-clon1), abs(blon+360-clon1)), blon+360, blon)
blon = numpy.where(numpy.greater(
abs(blon-clon1), abs(blon-360-clon1)), blon-360, blon)
return blon
################################################################
def read_var_fromfile(file, varname, verbose=1):
global varlongname, varunits, varshape
global listvarname, listvarlongname, listvarunits, listvarshape, listvaraxis
global dictvarsatt
global kindex, lindex, lindex_max, kindex_max
my_print(verbose, '----------------------------')
my_print(verbose, 'Reading var: ', varname, ' from: ', file)
my_print(verbose, 'Args: ', varname, file, kindex, lindex, option_op)
listvarname = []
listvarlongname = []
listvarunits = []
listvarshape = []
listvaraxis = []
dictvarsatt = {}
try:
f1 = netCDF4.Dataset(file)
varobject = f1.variables[varname]
try:
varlongname = varobject.long_name
except:
varlongname = varname
try:
varunits = varobject.units
except:
varunits = ""
try:
varshape = str(varobject.shape)
except:
varshape = ""
try:
varaxis = str(varobject.axis)
except:
varaxis = ""
listvarname = f1.variables.keys()
for varname_item in listvarname:
var_item = f1.variables[varname_item]
try:
varlongname_item = var_item.long_name
except:
varlongname_item = ""
listvarlongname.append(varlongname_item)
try:
varunits_item = var_item.units
except:
varunits_item = ""
listvarunits.append(varunits_item)
try:
varshape_item = str(var_item.shape)
except:
varshape_item = ""
listvarshape.append(varshape_item)
try:
varaxis_item = str(var_item.dimension)
except:
varaxis_item = ""
listvaraxis.append(varaxis_item)
try:
listvaratt_item = []
for att in var_item.attributes.keys():
attribut_value = var_item.attributes.get(att)
# To get attribut presented as 1800. and not as an array [ 1800.,]
if str(type(attribut_value)) == "<type 'array'>":
listvaratt_item.append(
att+" : "+str(attribut_value[0]))
else:
listvaratt_item.append(att+" : "+str(attribut_value))
except:
listvaratt_item = []
dictvarsatt[varname_item] = listvaratt_item
my_print(verbose, 'var name: ', varname)
my_print(verbose, 'var long name: ', varlongname)
my_print(verbose, 'var units: ', varunits)
my_print(verbose, 'var shape: ', varshape)
vardimensions = varobject.dimensions
my_print(verbose, 'var dimensions: ', vardimensions)
var = varobject
# ---------------------------------------
vartype = ""
for vardimension in vardimensions:
try:
vardimname = f1.variables[vardimension]
if vardimname.axis == 'X':
vartype = vartype+"X"
elif vardimname.axis == 'Y':
vartype = vartype+"Y"
elif vardimname.axis == 'Z':
vartype = vartype+"Z"
elif vardimname.axis == 'T' or re.search("since", vardimname.units.lower()):
vartype = vartype+"T"
else:
raise
except:
if re.search("depth", vardimension.lower()) or re.match("^z", vardimension.lower()):
vartype = vartype+"Z"
elif re.search("time", vardimension.lower()):
vartype = vartype+"T"
else:
vartype = vartype+"-"
my_print(verbose, 'var type: ', vartype)
# ---------------------------------------
if re.match("^TZ", vartype):
kindex_max = var.shape[1]-1
if kindex > var.shape[1]-1:
kindex = var.shape[1]-1
if kindex < 0:
kindex = 0
lindex_max = var.shape[0]-1
if lindex > var.shape[0]-1:
lindex = var.shape[0]-1
if lindex < 0:
lindex = 0
var = var[lindex, kindex, ...]
# ---------------------------------------
elif re.match("^T", vartype):
kindex = 0
kindex_max = 0
lindex_max = var.shape[0]-1
if lindex > var.shape[0]-1:
lindex = var.shape[0]-1
if lindex < 0:
lindex = 0
var = var[lindex, ...]
# ---------------------------------------
elif re.match("^Z", vartype):
lindex = 0
lindex_max = 0
kindex_max = var.shape[0]-1
if kindex > var.shape[0]-1:
kindex = var.shape[0]-1
if kindex < 0:
kindex = 0
var = var[kindex, ...]
# ---------------------------------------
else:
kindex = 0
lindex = 0
kindex_max = 0
lindex_max = 0
var = var[...]
except:
my_print(verbose, 'Error in var file processing')
try:
my_print(verbose, 'Variables available are: ', f1.variables.keys())
except:
my_print(verbose, 'Cannot read file', file)
sys.exit(1)
f1.close()
return var
################################################################
def read_grid_fromfile(file, varname, verbose=1):
global clon, blon, blat
global nvertex
my_print(verbose, '----------------------------')
my_print(verbose, 'Reading grid')
try:
my_print(verbose, 'Get longitudes, latitudes from', file)
f1 = netCDF4.Dataset(file)
v1 = f1.variables[varname]
# Try first non regular grid
try:
listcoord = v1.coordinates
my_print(verbose, 'found', varname,
'coordinates attribut:', listcoord)
for coordvarname in listcoord.split():
var = f1.variables[coordvarname]
varattrdict = var.__dict__
print(varattrdict)
# ajouter gestion attribut axis X,Y,Z,T
if "units" in varattrdict or "UNITS" in varattrdict:
varunits = var.units.lower()
my_print(verbose, 'found units attribut for :', coordvarname)
if varunits == "degrees_east":
clon = f1.variables[coordvarname]
clonvarname = coordvarname
elif varunits == "degrees_north":
clat = f1.variables[coordvarname]
clatvarname = coordvarname
elif "axis" in varattrdict or "AXIS" in varattrdict:
my_print(verbose, 'found axis attribut for :', coordvarname)
varaxis = var.axis.upper()
if varaxis == "X":
clon = f1.variables[coordvarname]
clonvarname = coordvarname
elif varaxis == "Y":
clat = f1.variables[coordvarname]
clatvarname = coordvarname
else:
my_print(verbose, 'no units or axis attribut for',
coordvarname)
sys.exit(1)
try:
my_print(
verbose, 'found longitude coordinate variable:', clonvarname)
my_print(
verbose, 'found latitude coordinate variable:', clatvarname)
except:
my_print(
verbose, 'no coordinate variables for longitude and/or latitude')
sys.exit(1)
try:
blon = f1.variables[clon.bounds]
my_print(
verbose, 'found longitude bounds coordinates variable:', clon.bounds)
except:
my_print(verbose, 'no bounds attribut for', clonvarname)
sys.exit(1)
try:
blat = f1.variables[clat.bounds]
my_print(
verbose, 'found latitude bounds coordinates variable:', clat.bounds)
except:
my_print(verbose, 'no bounds attribut for', clatvarname)
sys.exit(1)
nvertex = blon.shape[-1]
clon = clon[:]
clat = clat[:]
blon = blon[:]
blat = blat[:]
# Now look to regular grid
except:
lon1D = f1.variables[v1.dimensions[-1]]
lat1D = f1.variables[v1.dimensions[-2]]
clon, clat = numpy.meshgrid(lon1D, lat1D)
try:
blon1D = f1.variables[lon1D.bounds]
# shape of bounds variable is dim,2
my_print(
verbose, 'found longitude bounds coordinates variable:', lon1D.bounds)
blon1D_low = blon1D[..., 0]
blon1D_up = blon1D[..., 1]
except:
my_print(verbose, 'no bounds for',
v1.dimensions[-1], ', create it with mid-points')
blon1D_low = []
blon1D_up = []
for i in range(len(lon1D)-1):
d = abs(lon1D[i+1]-lon1D[i])/2.
if i == 0:
blon1D_low.append(lon1D[i]-d)
blon1D_low.append(lon1D[i]+d)
blon1D_up.append(lon1D[i]+d)
if i == (len(lon1D)-2):
blon1D_up.append(lon1D[i+1]+d)
try:
blat1D = f1.variables[lat1D.bounds]
# shape of bounds variable is dim,2
my_print(
verbose, 'found longitude bounds coordinates variable:', lat1D.bounds)
blat1D_low = blat1D[..., 0]
blat1D_up = blat1D[..., 1]
except:
my_print(verbose, 'no bounds for',
v1.dimensions[-2], ', create it with mid-points')
blat1D_low = []
blat1D_up = []
for i in range(len(lat1D)-1):
d = abs(lat1D[i+1]-lat1D[i])/2.
if i == 0:
blat1D_low.append(lat1D[i]-d)
blat1D_low.append(lat1D[i]+d)
blat1D_up.append(lat1D[i]+d)
if i == (len(lat1D)-2):
blat1D_up.append(lat1D[i+1]+d)
blon_LL, blat_LL = numpy.meshgrid(blon1D_low, blat1D_low)
blon_LR, blat_LR = numpy.meshgrid(blon1D_up, blat1D_low)
blon_UR, blat_UR = numpy.meshgrid(blon1D_up, blat1D_up)
blon_UL, blat_UL = numpy.meshgrid(blon1D_low, blat1D_up)
blon = numpy.dstack((blon_LL, blon_LR, blon_UR, blon_UL))
blat = numpy.dstack((blat_LL, blat_LR, blat_UR, blat_UL))
del blon_LL
del blon_LR
del blon_UR
del blon_UL
del blat_LL
del blat_LR
del blat_UR
del blat_UL
nvertex = 4
my_print(verbose, 'number of vertex: ', nvertex)
npoints = clon.size
clon = numpy.reshape(clon, (npoints))
clat = numpy.reshape(clat, (npoints))
blon = numpy.reshape(blon, (npoints, nvertex))
blat = numpy.reshape(blat, (npoints, nvertex))
except:
my_print(verbose, 'Error while extracting grid')
sys.exit(1)
################################################################
def read_mask_fromgridfile(file, kindex, verbose=1):
my_print(verbose, '----------------------------')
my_print(verbose, 'Reading grid file: ', file)
try:
f2 = netCDF4.Dataset(file)
mask = f2.variables['mask'][kindex, :]
my_print(verbose, 'mask shape: ', mask.shape)
except:
my_print(verbose, 'Error in grid file processing')
my_print(verbose, 'Trying to read variable mask')
sys.exit(1)
return mask
################################################################
def get_and_combine_masks():
global var, mask
my_print(option_verbose, '----------------------------')
my_print(option_verbose, 'Get and combine mask(s)')
var = numpy.ravel(var)
mask = numpy.ravel(mask)
selection_fromvar = numpy.ma.getmask(var)
mask_var = numpy.ma.masked_not_equal(mask, 1)
selection_frommask = numpy.ma.getmask(mask_var)
selection_both = numpy.ma.mask_or(selection_frommask, selection_fromvar)
return selection_both
################################################################
def compress_var(var, selection_both):
my_print(option_verbose, '----------------------------')
my_print(option_verbose, 'Mask and compress var')
my_print(option_verbose, 'Before: ', var.shape)
var_1 = numpy.ma.masked_array(var, selection_both)
var_1 = var_1.compressed()
my_print(option_verbose, 'After: ', var_1.shape)
return var_1
################################################################
varfilename = sys.argv[1]
varname = sys.argv[2]
var = read_var_fromfile(varfilename, varname, verbose=option_verbose)
my_print(option_verbose, '----------------------------')
if option_gridfile != 0:
my_print(option_verbose, 'Grid file specified: ', gridfilename)
mask = read_mask_fromgridfile(gridfilename, kindex, verbose=option_verbose)
my_print(option_verbose, 'Will read grid from grid file')
read_grid_fromfile(gridfilename, 'mask', verbose=option_verbose)
else:
my_print(option_verbose, 'No Grid file specified')
my_print(option_verbose, 'Will read grid from variable file')
read_grid_fromfile(varfilename, varname, verbose=option_verbose)
mask = var*0+1
################################################################
if option_op != None:
var = eval(option_op)
selection_both = get_and_combine_masks()
var_1 = compress_var(var, selection_both)
################################################################
var_scalefactor = 1.0
def scale_var(var, verbose=option_verbose):
global var_scalefactor
var_scalefactor = scalefactor(var)
my_print(verbose, '----------------------------')
my_print(verbose, 'Scaling var')
my_print(verbose, 'min,max (initial): ', min(var), max(var))
my_print(verbose, 'Scale factor: ', var_scalefactor)
# ym var=var*var_scalefactor
my_print(verbose, 'min,max (scaled): ', min(var), max(var))
return var
################################################################
if option_op == None:
var_1 = scale_var(var_1)
################################################################
def compute_projection(projection):
global blon, blat, x, y, z
my_print(option_verbose, '----------------------------')
my_print(option_verbose, 'Projection:', projection)
if projection == 'linear':
my_print(option_verbose, 'Limit longitude excursion')
blon = limit_lon(blon, clon)
x = blon
y = blat
z = blon*0
my_print(option_verbose, 'Ratio X/Y: ', option_ratioxy)
y = y*option_ratioxy
else:
# Limit latitude to 90 and -90 (some model grids give some!)
blat = numpy.where(numpy.greater(blat, 90), 90., blat)
blat = numpy.where(numpy.less(blat, -90), -90., blat)
deg2rad = numpy.pi/180.
x = numpy.cos(blat*deg2rad)*numpy.cos(blon*deg2rad)
y = numpy.cos(blat*deg2rad)*numpy.sin(blon*deg2rad)
z = numpy.sin(blat*deg2rad)
# Limit precision
x = numpy.rint(x*10000)/10000
y = numpy.rint(y*10000)/10000
z = numpy.rint(z*10000)/10000
################################################################
compute_projection(option_projection)
################################################################
def compress_pos():
global selection_both, x, y, z, x_1, y_1, z_1, index_i_1
my_print(option_verbose, '----------------------------')
my_print(option_verbose, 'Mask and compress positions')
if selection_both.all() != None:
selection_both1 = numpy.ones(
x.shape, numpy.int8)*selection_both[..., None]
else:
selection_both1 = None
x_0 = numpy.ma.masked_array(x, selection_both1)
x_1 = x_0.compressed()
x_1 = numpy.reshape(x_1, [var_1.shape[0], nvertex])
y_0 = numpy.ma.masked_array(y, selection_both1)
y_1 = y_0.compressed()
y_1 = numpy.reshape(y_1, [var_1.shape[0], nvertex])
z_0 = numpy.ma.masked_array(z, selection_both1)
z_1 = z_0.compressed()
z_1 = numpy.reshape(z_1, [var_1.shape[0], nvertex])
# Create var indices (FORTRAN notations)
var_indices = numpy.indices(var.shape)
index_i = var_indices[0]+1
index_i_1 = numpy.ma.masked_array(index_i, selection_both)
index_i_1 = index_i_1.compressed()
################################################################