-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathrectgrid.py
More file actions
4607 lines (3538 loc) · 155 KB
/
rectgrid.py
File metadata and controls
4607 lines (3538 loc) · 155 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 work is licensed under the Creative Commons
Attribution-Noncommercial-ShareAlike 3.0 Unported License.
To view a copy of this license, visit
http://creativecommons.org/licenses/by-nc-sa/3.0/
or send a letter to Creative Commons, 444 Castro Street,
Suite 900, Mountain View, California, 94041, USA.
===============================
These are REQUIRED packages. If any of these are not present, you
need to install into your current version of Python. (* == Optional but recommended )
URLS:
http://code.google.com/p/netcdf4-python/
*http://www.scipy.org/
"""
import pickle as pickle
import resource as resource
import numpy as numpy
import netCDF4 as netCDF4
import datetime as datetime
from midas.utils import *
from midas.rectgrid_utils import *
from midas.rectgrid_gen import *
from midas.wright_eos import *
# Optional packages
try:
import scipy as scipy
HAVE_SCIPY=True
except:
HAVE_SCIPY=False
pass
try:
import matplotlib.pyplot as plt
except:
pass
# Constants
epsln = 1.e-20
Omega=7.295e-5
PI_180 = numpy.pi/180.
R_earth = 6371.e3
###
### THE FOLLOWING SUBROUTINES WERE EXTRACTED FROM THE (deprecated) BASEMAP package
### Contact: Jeff Whitaker <jeffrey.s.whitaker@noaa.gov>
###
### BEGIN>>
###
def interp(datain,xin,yin,xout,yout,checkbounds=False,masked=False,order=1):
"""
Interpolate data (``datain``) on a rectilinear grid (with x = ``xin``
y = ``yin``) to a grid with x = ``xout``, y= ``yout``.
.. tabularcolumns:: |l|L|
============== ====================================================
Arguments Description
============== ====================================================
datain a rank-2 array with 1st dimension corresponding to
y, 2nd dimension x.
xin, yin rank-1 arrays containing x and y of
datain grid in increasing order.
xout, yout rank-2 arrays containing x and y of desired output grid.
============== ====================================================
.. tabularcolumns:: |l|L|
============== ====================================================
Keywords Description
============== ====================================================
checkbounds If True, values of xout and yout are checked to see
that they lie within the range specified by xin
and xin.
If False, and xout,yout are outside xin,yin,
interpolated values will be clipped to values on
boundary of input grid (xin,yin)
Default is False.
masked If True, points outside the range of xin and yin
are masked (in a masked array).
If masked is set to a number, then
points outside the range of xin and yin will be
set to that number. Default False.
order 0 for nearest-neighbor interpolation, 1 for
bilinear interpolation, 3 for cublic spline
(default 1). order=3 requires scipy.ndimage.
============== ====================================================
.. note::
If datain is a masked array and order=1 (bilinear interpolation) is
used, elements of dataout will be masked if any of the four surrounding
points in datain are masked. To avoid this, do the interpolation in two
passes, first with order=1 (producing dataout1), then with order=0
(producing dataout2). Then replace all the masked values in dataout1
with the corresponding elements in dataout2 (using numpy.where).
This effectively uses nearest neighbor interpolation if any of the
four surrounding points in datain are masked, and bilinear interpolation
otherwise.
Returns ``dataout``, the interpolated data on the grid ``xout, yout``.
"""
# xin and yin must be monotonically increasing.
if xin[-1]-xin[0] < 0 or yin[-1]-yin[0] < 0:
raise ValueError('xin and yin must be increasing!')
if xout.shape != yout.shape:
raise ValueError('xout and yout must have same shape!')
# check that xout,yout are
# within region defined by xin,yin.
if checkbounds:
if xout.min() < xin.min() or \
xout.max() > xin.max() or \
yout.min() < yin.min() or \
yout.max() > yin.max():
raise ValueError('yout or xout outside range of yin or xin')
# compute grid coordinates of output grid.
delx = xin[1:]-xin[0:-1]
dely = yin[1:]-yin[0:-1]
if max(delx)-min(delx) < 1.e-4 and max(dely)-min(dely) < 1.e-4:
# regular input grid.
xcoords = (len(xin)-1)*(xout-xin[0])/(xin[-1]-xin[0])
ycoords = (len(yin)-1)*(yout-yin[0])/(yin[-1]-yin[0])
else:
# irregular (but still rectilinear) input grid.
xoutflat = xout.flatten(); youtflat = yout.flatten()
ix = (numpy.searchsorted(xin,xoutflat)-1).tolist()
iy = (numpy.searchsorted(yin,youtflat)-1).tolist()
xoutflat = xoutflat.tolist(); xin = xin.tolist()
youtflat = youtflat.tolist(); yin = yin.tolist()
xcoords = []; ycoords = []
for n,i in enumerate(ix):
if i < 0:
xcoords.append(-1) # outside of range on xin (lower end)
elif i >= len(xin)-1:
xcoords.append(len(xin)) # outside range on upper end.
else:
xcoords.append(float(i)+(xoutflat[n]-xin[i])/(xin[i+1]-xin[i]))
for m,j in enumerate(iy):
if j < 0:
ycoords.append(-1) # outside of range of yin (on lower end)
elif j >= len(yin)-1:
ycoords.append(len(yin)) # outside range on upper end
else:
ycoords.append(float(j)+(youtflat[m]-yin[j])/(yin[j+1]-yin[j]))
xcoords = numpy.reshape(xcoords,xout.shape)
ycoords = numpy.reshape(ycoords,yout.shape)
# data outside range xin,yin will be clipped to
# values on boundary.
if masked:
xmask = numpy.logical_or(numpy.less(xcoords,0),numpy.greater(xcoords,len(xin)-1))
ymask = numpy.logical_or(numpy.less(ycoords,0),numpy.greater(ycoords,len(yin)-1))
xymask = numpy.logical_or(xmask,ymask)
xcoords = numpy.clip(xcoords,0,len(xin)-1)
ycoords = numpy.clip(ycoords,0,len(yin)-1)
# interpolate to output grid using bilinear interpolation.
if order == 1:
xi = xcoords.astype(numpy.int32)
yi = ycoords.astype(numpy.int32)
xip1 = xi+1
yip1 = yi+1
xip1 = numpy.clip(xip1,0,len(xin)-1)
yip1 = numpy.clip(yip1,0,len(yin)-1)
delx = xcoords-xi.astype(numpy.float32)
dely = ycoords-yi.astype(numpy.float32)
dataout = (1.-delx)*(1.-dely)*datain[yi,xi] + \
delx*dely*datain[yip1,xip1] + \
(1.-delx)*dely*datain[yip1,xi] + \
delx*(1.-dely)*datain[yi,xip1]
elif order == 0:
xcoordsi = numpy.around(xcoords).astype(numpy.int32)
ycoordsi = numpy.around(ycoords).astype(numpy.int32)
dataout = datain[ycoordsi,xcoordsi]
elif order == 3:
try:
from scipy.ndimage import map_coordinates
except ImportError:
raise ValueError('scipy.ndimage must be installed if order=3')
coords = [ycoords,xcoords]
dataout = map_coordinates(datain,coords,order=3,mode='nearest')
else:
raise ValueError('order keyword must be 0, 1 or 3')
if masked and isinstance(masked,bool):
dataout = ma.masked_array(dataout)
newmask = ma.mask_or(ma.getmask(dataout), xymask)
dataout = ma.masked_array(dataout,mask=newmask)
elif masked and is_scalar(masked):
dataout = numpy.where(xymask,masked,dataout)
return dataout
def shiftgrid(lon0,datain,lonsin,start=True,cyclic=360.0):
"""
Shift global lat/lon grid east or west.
.. tabularcolumns:: |l|L|
============== ====================================================
Arguments Description
============== ====================================================
lon0 starting longitude for shifted grid
(ending longitude if start=False). lon0 must be on
input grid (within the range of lonsin).
datain original data with longitude the right-most
dimension.
lonsin original longitudes.
============== ====================================================
.. tabularcolumns:: |l|L|
============== ====================================================
Keywords Description
============== ====================================================
start if True, lon0 represents the starting longitude
of the new grid. if False, lon0 is the ending
longitude. Default True.
cyclic width of periodic domain (default 360)
============== ====================================================
returns ``dataout,lonsout`` (data and longitudes on shifted grid).
"""
if numpy.fabs(lonsin[-1]-lonsin[0]-cyclic) > 1.e-4:
# Use all data instead of raise ValueError, 'cyclic point not included'
start_idx = 0
else:
# If cyclic, remove the duplicate point
start_idx = 1
if lon0 < lonsin[0] or lon0 > lonsin[-1]:
raise ValueError('lon0 outside of range of lonsin')
i0 = numpy.argmin(numpy.fabs(lonsin-lon0))
i0_shift = len(lonsin)-i0
if ma.isMA(datain):
dataout = ma.zeros(datain.shape,datain.dtype)
else:
dataout = numpy.zeros(datain.shape,datain.dtype)
if ma.isMA(lonsin):
lonsout = ma.zeros(lonsin.shape,lonsin.dtype)
else:
lonsout = numpy.zeros(lonsin.shape,lonsin.dtype)
if start:
lonsout[0:i0_shift] = lonsin[i0:]
else:
lonsout[0:i0_shift] = lonsin[i0:]-cyclic
dataout[...,0:i0_shift] = datain[...,i0:]
if start:
lonsout[i0_shift:] = lonsin[start_idx:i0+start_idx]+cyclic
else:
lonsout[i0_shift:] = lonsin[start_idx:i0+start_idx]
dataout[...,i0_shift:] = datain[...,start_idx:i0+start_idx]
return dataout,lonsout
def addcyclic(arrin,lonsin):
"""
``arrout, lonsout = addcyclic(arrin, lonsin)``
adds cyclic (wraparound) point in longitude to ``arrin`` and ``lonsin``,
assumes longitude is the right-most dimension of ``arrin``.
"""
nlons = arrin.shape[-1]
newshape = list(arrin.shape)
newshape[-1] += 1
if ma.isMA(arrin):
arrout = ma.zeros(newshape,arrin.dtype)
else:
arrout = numpy.zeros(newshape,arrin.dtype)
arrout[...,0:nlons] = arrin[:]
arrout[...,nlons] = arrin[...,0]
if ma.isMA(lonsin):
lonsout = ma.zeros(nlons+1,lonsin.dtype)
else:
lonsout = numpy.zeros(nlons+1,lonsin.dtype)
lonsout[0:nlons] = lonsin[:]
lonsout[nlons] = lonsin[-1] + lonsin[1]-lonsin[0]
return arrout,lonsout
###
# <<END
###
# Turn on for more verbose output
DEBUG = 0
class quadmesh(object):
"""A quadmesh object is a horizontal lattice on
a sphere or plane. When instantiating from a file, a quadmesh
is constructed by reading the lat-lon list associated
with (var) from file (path) . Additionally, a grid can be
constructed using a FMS supergrid object (see midas.rectgrid_gen).
Additional lattice points are needed to define the
cell perimeters. The primary lattice of (T) cell centers,
and the perimeter lattice of (Q) points are located at coordinates
(y_T,x_T) and (y_T_bounds,x_T_bounds) respectively.
There are (jm,im) H cell points and (jm+1,im+1) perimeter
locations.
X_T_bounds
V
+-------+-------+-------+
: : : :
: : : :
: : : :
+-------+-------Q-------:
: : : :
: : T : :< Y_T
: : : :
+-------Q-------+-------+< Y_T_bounds
^ ^
X_T
Cell metrics are sometimes available, depending on the way in which the
quadmesh was constructed.
"""
def __init__(self,path=None,cyclic=False,tripolar_n=False,var=None,simple_grid=False,supergrid=None,lon=None,lat=None,lonb=None,latb=None,is_latlon=True,is_cartesian=False,grid_type='generic',):
"""
>>> grid=quadmesh('http://data.nodc.noaa.gov/thredds/dodsC/woa/WOA09/NetCDFdata/temperature_annual_1deg.nc',var='t_an',cyclic=True)
>>> print(grid.lonh[0],grid.lonh[-1])
0.5 359.5
>>> print(grid.lath[0],grid.lath[-1])
-89.5 89.5
>>> print(grid.lonq[0],grid.lonq[-1])
0.0 360.0
>>> print(grid.latq[0],grid.latq[-1])
-90.0 90.0
>>> x=numpy.linspace(0.,360,361);y=numpy.linspace(-90.,90,181)
>>> X,Y=numpy.meshgrid(x,y)
>>> grid=quadmesh(lonb=X,latb=Y,cyclic=True)
>>> print(grid.lonh[0],grid.lonh[-1])
0.5 359.5
>>> print(grid.lath[0],grid.lath[-1])
-89.5 89.5
>>> print(grid.lonq[0],grid.lonq[-1])
0.0 360.0
>>> print(grid.latq[0],grid.latq[-1])
-90.0 90.0
"""
self.is_latlon=is_latlon
self.is_cartesian=is_cartesian
self.have_metrics = False
self.simple_grid=simple_grid
if numpy.logical_and(is_cartesian,is_latlon):
print('Select either is_latlon or is_cartesian, not both')
return None
self.yDir=1
self.cyclic_x = cyclic
self.tripolar_n = tripolar_n
if supergrid is not None:
var_dict = {}
x=supergrid.x; y=supergrid.y
grid_x=supergrid.grid_x; grid_y=supergrid.grid_y
self.lonh=grid_x[1::2]
self.lath=grid_y[1::2]
self.lonq=grid_x[0::2]
self.latq=grid_y[0::2]
self.x_T=x[1::2,1::2]
self.y_T=y[1::2,1::2]
self.x_T_bounds=x[0::2,0::2]
self.y_T_bounds=y[0::2,0::2]
self.jm = self.x_T.shape[0]
self.im = self.x_T.shape[1]
self.wet = numpy.ones((self.jm,self.im))
self.cyclic_x=supergrid.dict['cyclic_x']
self.tripolar_n=supergrid.dict['tripolar_n']
if supergrid.have_metrics:
dx=supergrid.dx
dy=supergrid.dy
dxh = dx[:,::2]+dx[:,1::2]
self.dxh=0.5*(dxh[:-1:2,:]+dxh[2::2,:])
dyh = dy[::2,:]+dy[1::2,:]
self.dyh=0.5*(dyh[:,:-1:2]+dyh[:,2::2])
self.Ah = self.dxh*self.dyh
self.angle_dx=supergrid.angle_dx[1::2,1::2]
self.have_metrics=True
else:
self.have_metrics=False
return
if path is not None:
if type(path) == 'netCDF4.Dataset':
f=path
else:
f=netCDF4.Dataset(path)
if grid_type == 'gold_geometry':
self.x_T = f.variables['geolon'][:]
self.x_T_bounds = f.variables['geolonb'][:]
xtb0=2.0*self.x_T_bounds[:,0]-self.x_T_bounds[:,1]
xtb0=xtb0[:,numpy.newaxis]
self.x_T_bounds = numpy.hstack((xtb0,self.x_T_bounds))
xtb0=self.x_T_bounds[0,:]
self.x_T_bounds = numpy.vstack((xtb0,self.x_T_bounds))
self.y_T = f.variables['geolat'][:]
self.y_T_bounds = f.variables['geolatb'][:]
ytb0=2.0*self.y_T_bounds[0,:]-self.y_T_bounds[1,:]
self.y_T_bounds = numpy.vstack((ytb0,self.y_T_bounds))
ytb0=self.y_T_bounds[:,0]
ytb0=ytb0[:,numpy.newaxis]
self.y_T_bounds = numpy.hstack((ytb0,self.y_T_bounds))
self.lonh = f.variables['lonh'][:]
self.lath = f.variables['lath'][:]
self.lonq = f.variables['lonq'][:]
self.lonq = numpy.hstack((self.lonq[0]-(self.lonq[1]-self.lonq[0]),self.lonq))
self.latq = f.variables['latq'][:]
self.latq = numpy.hstack((self.latq[0]-(self.latq[1]-self.latq[0]),self.latq))
self.D = f.variables['D'][:]
self.f = f.variables['f'][:]
try:
self.dxh = f.variables['dxh'][:]
except:
self.dxh = f.variables['dxT'][:]
try:
self.dyh = f.variables['dyh'][:]
except:
self.dyh = f.variables['dyT'][:]
self.Ah = f.variables['Ah'][:]
self.wet = f.variables['wet'][:]
self.im = numpy.shape(self.lonh)[0]
self.jm = numpy.shape(self.lath)[0]
self.have_metrics=True
return
if grid_type == 'mom4_gridspec':
self.x_T = f.variables['geolon_t'][:]
self.x_T_bounds = f.variables['geolon_e'][:]
xtb0=2.0*self.x_T_bounds[:,0]-self.x_T_bounds[:,1]
xtb0=xtb0[:,numpy.newaxis]
self.x_T_bounds = numpy.hstack((xtb0,self.x_T_bounds))
xtb0=self.x_T_bounds[0,:]
self.x_T_bounds = numpy.vstack((xtb0,self.x_T_bounds))
self.y_T = f.variables['geolat_t'][:]
self.y_T_bounds = f.variables['geolat_n'][:]
ytb0=2.0*self.y_T_bounds[0,:]-self.y_T_bounds[1,:]
self.y_T_bounds = numpy.vstack((ytb0,self.y_T_bounds))
ytb0=self.y_T_bounds[:,0]
ytb0=ytb0[:,numpy.newaxis]
self.y_T_bounds = numpy.hstack((ytb0,self.y_T_bounds))
self.lonh = f.variables['gridlon_t'][:]
self.lath = f.variables['gridlat_t'][:]
self.lonq = f.variables['gridlon_c'][:]
self.lonq = numpy.hstack((self.lonq[0]-(self.lonq[1]-self.lonq[0]),self.lonq))
self.latq = f.variables['gridlat_c'][:]
self.latq = numpy.hstack((self.latq[0]-(self.latq[1]-self.latq[0]),self.latq))
self.D = f.variables['ht'][:]
self.f = 2.0*Omega*numpy.sin(self.y_T*numpy.pi/180.)
self.dxh = f.variables['dxt'][:]
self.dyh = f.variables['dyt'][:]
self.Ah = self.dxh*self.dyh
self.wet = f.variables['wet'][:]
self.im = numpy.shape(self.lonh)[0]
self.jm = numpy.shape(self.lath)[0]
self.have_metrics=True
return
f = None
self.x_T = None; self.y_T = None; self.x_T_bounds = None; self.y_T_bounds = None
self.lonq = None; self.latq = None
if lon is not None and lat is not None:
self.x_T=lon.copy()
self.y_T=lat.copy()
self.lonh=self.x_T[0,:]
self.lath=self.y_T[:,0]
if lonb is not None and latb is not None:
self.x_T_bounds=lonb.copy()
self.y_T_bounds=latb.copy()
self.lonq = self.x_T_bounds[0,:]
self.latq = self.y_T_bounds[:,0]
self.lonh = 0.5*(self.lonq[0:-1]+self.lonq[1:])
self.lath = 0.5*(self.latq[0:-1]+self.latq[1:])
if lon is None and lat is None and lonb is None and latb is None:
f=netCDF4.Dataset(path)
if var is None and f is not None:
print(""" Need to specify a variable from which to create a
dummy grid since a valid grid option was not
specified """)
raise
else:
var_dict = {}
var_dict['X']=None
var_dict['Y']=None
var_dict['Z']=None
var_dict['T']=None
var_dict['type'] = 'T'
if f is not None:
for n in range(0,f.variables[var].ndim):
dimnam = f.variables[var].dimensions[n]
dim = f.variables[dimnam]
cart = get_axis_cart(dim,dimnam)
if cart is not None:
var_dict[cart]=dimnam
if var_dict['X'] is not None and lon is None:
lon_axis = f.variables[var_dict['X']]
dir=get_axis_direction(lon_axis)
self.lonh = sq(f.variables[var_dict['X']][:])
if dir == -1:
self.lonh=self.lonh[::-1]
elif lon is not None:
self.lonh = sq(lon[0,:])
else:
self.lonh=[0.]
print("Longitude axis not detected ")
if var_dict['Y'] is not None and lat is None:
lat_axis = f.variables[var_dict['Y']]
dir=get_axis_direction(lat_axis)
self.lath = sq(f.variables[var_dict['Y']][:])
if dir == -1:
self.yDir=-1
self.lath=self.lath[::-1]
elif lat is not None:
self.lath=sq(lat[:,0])
else:
self.lath=[0.]
print("Latitude axis not detected ")
if self.lonq is None:
self.lonq = 0.5*(self.lonh + numpy.roll(self.lonh,-1))
if numpy.isscalar(self.lonq):
self.lonq=numpy.array([self.lonq])
if numpy.size(self.lonq) > 2:
self.lonq[-1] = 2.0*self.lonq[-2] -self.lonq[-3]
if numpy.size(self.lonq) > 1:
lon0=2.0*self.lonh[0]-self.lonq[0]
else:
lon0 = self.lonq[0]
self.lonq=numpy.hstack(([lon0],self.lonq))
if self.latq is None:
self.latq = 0.5*(self.lath + numpy.roll(self.lath,-1))
if numpy.isscalar(self.latq):
self.latq=numpy.array([self.latq])
if numpy.size(self.latq) > 2:
self.latq[-1] = 2.0*self.lath[-1]-self.latq[-2]
if numpy.size(self.latq) > 1:
lat0=2.0*self.lath[0]-self.latq[0]
else:
lat0 = self.latq[0]
self.latq=numpy.concatenate(([lat0],self.latq))
try:
self.im = len(self.lonh)
except:
self.lonh = numpy.array([self.lonh])
self.im = 1
try:
self.jm = len(self.lath)
except:
self.lath = numpy.array([self.lath])
self.jm = 1
if simple_grid is True:
self.simple_grid = True
self.cyclic_x = cyclic
self.jm = len(self.lath)
self.im = len(self.lonh)
return
if self.x_T is None:
self.x_T,self.y_T = numpy.meshgrid(self.lonh,self.lath)
if self.im > 1 and self.x_T_bounds is None:
xtb=0.5*(self.x_T + numpy.roll(self.x_T,shift=1,axis=1))
xtb0=2.0*xtb[:,-1]-xtb[:,-2]
xtb0=xtb0[:,numpy.newaxis]
xtb=numpy.hstack((xtb,xtb0))
xtb0=2.0*xtb[:,1]-xtb[:,2]
xtb[:,0]=xtb0
self.x_T_bounds=xtb.copy()
xtb0=self.x_T_bounds[-1,:]
self.x_T_bounds = numpy.vstack((self.x_T_bounds,xtb0))
if self.jm > 1 and self.y_T_bounds is None:
ytb=0.5*(self.y_T + numpy.roll(self.y_T,shift=1,axis=0))
ytb0=2.0*ytb[-1,:]-ytb[-2,:]
ytb0=ytb0[numpy.newaxis,:]
ytb=numpy.vstack((ytb,ytb0))
ytb0=2.0*ytb[1,:]-ytb[2,:]
ytb[0,:]=ytb0
self.y_T_bounds=ytb.copy()
ytb0=self.y_T_bounds[:,-1]
ytb0=ytb0[:,numpy.newaxis]
self.y_T_bounds = numpy.hstack((self.y_T_bounds,ytb0))
if self.im> 1 and self.jm > 1:
dx = (self.x_T_bounds - numpy.roll(self.x_T_bounds,axis=1,shift=1))
dx=0.5*(dx[0:-1,1:]+dx[1:,1:])
dx=dx*numpy.pi/180.
self.dxh = dx*R_earth*numpy.cos(self.y_T*numpy.pi/180.)
dy = (self.y_T_bounds - numpy.roll(self.y_T_bounds,axis=0,shift=1))
dy=0.5*(dy[1:,0:-1]+dy[1:,1:])
dy = dy*numpy.pi/180.
self.dyh = dy*R_earth
self.Ah=self.dxh*self.dyh
self.have_metrics=True
else:
self.x_T=self.lonh; self.y_T=self.lath
self.cyclic_x = cyclic
if self.cyclic_x:
self.xmod_len = self.x_T_bounds[0,-1] - self.x_T_bounds[0,0]
self.wet = numpy.ones((self.jm,self.im))
def find_geo_bounds(self,x=None,y=None):
"""
Returns the bounds of the grid. Currently this is of limited use
for generalized horizontal coordinates (based on lonh/lath).
>>> from midas import *
>>> x=numpy.linspace(0.,360,361);y=numpy.linspace(-90.,90.,181)
>>> X,Y=numpy.meshgrid(x,y)
>>> grid=quadmesh(lonb=X,latb=Y,cyclic=True)
>>> xs,xe,ys,ye=grid.find_geo_bounds(x=(20.,50.),y=(-10.,10.))
>>> print(xs,xe,grid.lonq[xs],grid.lonq[xe])
20 50 20.0 50.0
>>> print(ys,ye,grid.latq[ys],grid.latq[ye])
80 100 -10.0 10.0
"""
xs=0; xe=self.im
ys=0; ye=self.jm
if x is not None:
[xs,xe]=find_axis_bounds(self.lonq,x=x,modulo_360=self.cyclic_x)
if y is not None:
[ys,ye]=find_axis_bounds(self.latq,x=y)
return xs,xe,ys,ye
def geo_region(self,y=None,x=None,name=None):
"""
Returns a dictionary for sampling a contiguous region
based on geographical boundaries.
Currently this is of limited use for generalized horizontal
coordinates (based on lonh/lath).
>>> from midas import *
>>> x=numpy.linspace(0.,360.,361);y=numpy.linspace(-90.,90.,181)
>>> X,Y=numpy.meshgrid(x,y)
>>> grid=quadmesh(lonb=X,latb=Y,cyclic=True)
>>> section=grid.geo_region(x=(-30.,20.),y=(-10.,10.))
>>> print(section['xax_data'][0],section['xax_data'][-1])
330.5 379.5
>>> print(section['yax_data'][0],section['yax_data'][-1])
-9.5 9.5
"""
section={}
xs,xe,ys,ye = self.find_geo_bounds(x=x,y=y)
section['y']=numpy.arange(ys,max(ye,ys+1))
section['yax_data']= self.lath[section['y']]
section['yax_data']=numpy.asarray(section['yax_data'])
if xe>=xs:
section['x']=numpy.arange(xs,max(xe,xs+1))
section['x_read']=section['x']
section['xax_data']=self.lonh[section['x']]
else:
section['x_read']=[numpy.arange(xs,self.im)]
section['x_read'].append(numpy.arange(0,xe))
xind = numpy.hstack((section['x_read'][0],section['x_read'][1]))
section['x'] = xind
section['xax_data']=self.lonh[xind]
lonh=section['xax_data'].copy()
if not numpy.isscalar(lonh):
lon0=lonh[0]
else:
lon0=lonh
if self.cyclic_x:
lonh[lonh<lon0]=lonh[lonh<lon0]+360.
section['xax_data']=lonh
section['xax_data']=numpy.asarray(section['xax_data'])
section['lon0']=lon0
section['name'] = name
section['parent_grid'] = self
return section
def indexed_region(self,i=None,j=None,name=None):
"""
Returns a \"section\" dictionary for sampling a contiguous region.
based on index coordinates.
>>> from midas import *
>>> x=numpy.linspace(0.5,359.5,360);y=numpy.linspace(-89.5,89.5,180)
>>> X,Y=numpy.meshgrid(x,y)
>>> grid=quadmesh(lon=X,lat=Y,cyclic=True)
>>> section=grid.indexed_region(i=(20,20))
>>> print(section['xax_data'][0],section['xax_data'][-1])
20.5 20.5
>>> print(section['yax_data'][0],section['yax_data'][-1])
-89.5 89.5
"""
section={}
if j is not None:
ys=j[0];ye=j[1]
section['y']=numpy.arange(ys,ye+1)
section['yax_data']= self.lath[section['y']]
else:
section['y']=None
section['yax_data']= self.lath
if i is not None:
xs=i[0];xe=i[1]
if xe>=xs:
section['x']=numpy.arange(xs,xe+1)
else:
section['x']=numpy.hstack((numpy.arange(xs,self.im),numpy.arange(0,xe)))
section['xax_data']= self.lonh[section['x']]
else:
section['x']=None
section['x_read']=section['x']
section['name'] = name
section['parent_grid'] = self
return section
def extract(self,geo_region=None):
"""
Returns new grid object using a \"section\" dictionary
created using the \"geo_region\" or \"indexed_region\"
method.
>>> from midas.rectgrid import *
>>> import hashlib
>>> x=numpy.linspace(0.,360.,361);y=numpy.linspace(-90.,90.,181)
>>> X,Y=numpy.meshgrid(x,y)
>>> grid=quadmesh(lonb=X,latb=Y,cyclic=True)
>>> section=grid.geo_region(x=(-30.,20.),y=(-10.,10.))
>>> new_grid = grid.extract(section)
>>> print(new_grid.lonq[0],new_grid.lonq[-1])
330.0 380.0
>>> print(new_grid.latq[0],new_grid.latq[-1])
-10.0 10.0
>>> hash=hashlib.md5(new_grid.x_T)
>>> hash.update(new_grid.y_T)
>>> print(hash.hexdigest())
c26e431bd6c9ae8753c91c163168cf39
"""
if geo_region is None:
grid=copy.copy(self)
return grid
else:
grid = copy.copy(self)
x_section = geo_region['x']
y_section = geo_region['y']
if x_section is not None:
xb_section = numpy.hstack((x_section,x_section[-1]+1))
if y_section is not None:
yb_section = numpy.hstack((y_section,y_section[-1]+1))
grid.lath = numpy.take(self.lath,y_section,axis=0)
grid.latq = numpy.take(self.latq,yb_section,axis=0)
grid.lonh=numpy.take(self.lonh,x_section,axis=0)
grid.lonq=numpy.take(self.lonq,xb_section,axis=0)
lon0=grid.lonq[0]
grid.lonh[grid.lonh<lon0]=grid.lonh[grid.lonh<lon0]+360.
grid.lonq[grid.lonq<lon0]=grid.lonq[grid.lonq<lon0]+360.
if not grid.simple_grid:
grid.x_T = numpy.take(numpy.take(self.x_T,y_section,axis=0),x_section,axis=1)
# grid.x_T[grid.x_T<lon0]=grid.x_T[grid.x_T<lon0]+360.
grid.x_T_bounds = numpy.take(numpy.take(self.x_T_bounds,yb_section,axis=0),xb_section,axis=1)
# grid.x_T_bounds[grid.x_T_bounds<lon0]=grid.x_T_bounds[grid.x_T_bounds<lon0]+360.
grid.y_T = numpy.take(numpy.take(self.y_T,y_section,axis=0),x_section,axis=1)
grid.y_T_bounds = numpy.take(numpy.take(self.y_T_bounds,yb_section,axis=0),xb_section,axis=1)
if hasattr(grid,'D'):
grid.D = numpy.take(numpy.take(self.D,y_section,axis=0),x_section,axis=1)
if hasattr(grid,'f'):
grid.f = numpy.take(numpy.take(self.f,y_section,axis=0),x_section,axis=1)
if hasattr(grid,'wet'):
grid.wet = numpy.take(numpy.take(self.wet,y_section,axis=0),x_section,axis=1)
if grid.have_metrics:
grid.dxh = numpy.take(numpy.take(self.dxh,y_section,axis=0),x_section,axis=1)
grid.dyh = numpy.take(numpy.take(self.dyh,y_section,axis=0),x_section,axis=1)
grid.Ah = numpy.take(numpy.take(self.Ah,y_section,axis=0),x_section,axis=1)
if hasattr(grid,'angle_dx'):
grid.angle_dx = numpy.take(numpy.take(self.angle_dx,y_section,axis=0),x_section,axis=1)
if hasattr(grid,'mask'):
grid.mask = numpy.take(numpy.take(self.mask,y_section,axis=0),x_section,axis=1)
grid.im = numpy.shape(grid.lonh)[0]
grid.jm = numpy.shape(grid.lath)[0]
return grid
def add_mask(self,field,path=None):
"""
Add a 2-D mask to the grid. The mask can have any values, e.g.
a different number for each ocean basin. This can be used to
defne other masked arrays using mask_where, for instance.
"""
if path is not None:
f=netCDF4.Dataset(path)
if field in f.variables:
self.mask = f.variables[field][:]
else:
print(' Field ',field,' is not present in file ',path)
return None
return None
class state(object):
"""Returns a model state of (fields). The default is
to extract the entire data domain at all time levels from (path). Use
(geo_region) to store a section of the horizontal grid. Use
(time_indices) or (date_bounds) to extract along the record dimension.
(z_indices) can be used to read a contiguous number of vertical layers or
levels.
stagger:
11 - centered at grid tracer (T) points, (lath,lonh)
21 - centered on north face of tracer cell
12 - centered on east face of tracer cell
22 - centered on north-east corner of tracer cell
01 - centered on south face of tracer cell
10 - centered on west face of tracer cell
00 - centered on south-west corner of tracer cell
NOTE:The layer (interfaces) variable must be stored in order to calculate
accurate finite volume integrals.
"""
def __init__(self,path=None,grid=None,geo_region=None,time_indices=None,date_bounds=None,z_indices=None,z_bounds=None,fields=None,default_calendar=None,MFpath=None,interfaces=None,path_interfaces=None,MFpath_interfaces=None,stagger=None,verbose=True,z_orientation=None,memstats=False):
"""
>>> from midas import *
>>> import hashlib
>>> grid=quadmesh('http://data.nodc.noaa.gov/thredds/dodsC/woa/WOA09/NetCDFdata/temperature_annual_1deg.nc',var='t_an',cyclic=True)
>>> IO = grid.geo_region(x=(30,120.),y=(-30.,25.))
>>> S=state('http://data.nodc.noaa.gov/thredds/dodsC/woa/WOA09/NetCDFdata/temperature_annual_1deg.nc',grid=grid,geo_region=IO,fields=['t_an'],verbose=False)
>>> hash=hashlib.md5(S.t_an)
>>> print(hash.hexdigest())
9c7abd5fddd0f64439a027f662a3c7c7
"""
if path is not None:
f=netCDF4.Dataset(path)
self.path = path
self.is_MFpath = False
elif MFpath is not None:
f=netCDF4.MFDataset(MFpath)
self.path = MFpath
self.is_MFpath = True
else:
f=None
self.rootgrp = f
self.variables = {}
self.var_dict = {}
if fields is None:
if grid is not None:
new_grid = grid.extract(geo_region)
self.grid = new_grid
self.geo_region=geo_region
return
if stagger is None:
stagger = {}
for v in fields:
stagger[v]='00'
else:
var_stagger = stagger.copy()
if len(var_stagger) != len(fields):
print(""" Need to provide stagger for each field """)
return
stagger = {}
n=0
for v in fields:
stagger[v]=var_stagger[n]
n=n+1
if grid is None:
if path is not None:
try:
grid = quadmesh(path,var=fields[0])
except:
print('No X-Y grid detected, proceeding with no grid information')
grid=None
pass
else:
try:
grid = quadmesh(self.rootgrp,var=fields[0])
except:
print('No X-Y grid detected, proceeding with no grid information')
grid=None
pass