forked from evanmason/pyroms2roms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
py_roms2roms.py
2265 lines (1817 loc) · 79.1 KB
/
py_roms2roms.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
# -*- coding: utf-8 -*-
# %run py_roms2roms.py
'''
===========================================================================
This file is part of py-roms2roms
py-roms2roms is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
py-roms2roms is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with py-roms2roms. If not, see <http://www.gnu.org/licenses/>.
Version 1.0.1
Copyright (c) 2014 by Evan Mason, IMEDEA
Email: [email protected]
===========================================================================
Create a ROMS boundary file based on ROMS data
===========================================================================
'''
import netCDF4 as netcdf
import matplotlib.pyplot as plt
import numpy as np
import numexpr as ne
import scipy.interpolate as si
import scipy.ndimage as nd
import scipy.spatial as sp
import glob as glob
#import matplotlib.nxutils as nx
import time
import scipy.interpolate.interpnd as interpnd
from scipy.interpolate import RectBivariateSpline as rbs
import collections
from mpl_toolkits.basemap import Basemap
from collections import OrderedDict
from datetime import datetime
class vertInterp(object):
'''Vertical interpolation object based on scipy.ndimage.map_coordinates()
http://www.scipy.org/SciPyPackages/Ndimage
http://docs.scipy.org/doc/scipy/reference/ndimage.html
'''
def __init__(self, vweights):
'''
Input parameter:
vweights : input; computed by method get_map_coordinate_weights()
Makes hweights : same size as vweights, columns correspond to
x-axis indices
'''
self.vweights = vweights
self.hweights = np.tile(np.arange(vweights.shape[1], dtype=np.float64),
(vweights.shape[0], 1))
def vert_interp(self, par_var):
'''
par_var is 2d (depth, dist) parent variable
'''
return nd.map_coordinates(par_var, np.array([self.vweights,
self.hweights]),
order=1,
mode='nearest',
prefilter=False,
cval=999999)
class horizInterp(interpnd.CloughTocher2DInterpolator):
'''
'''
def __init__(self, tri, values, fill_value=np.nan,
tol=1e-6, maxiter=400):
interpnd.NDInterpolatorBase.__init__(self, tri.points, values, ndim=2,
fill_value=fill_value)
self.tri = tri
self.grad = interpnd.estimate_gradients_2d_global(self.tri, self.values,
tol=tol, maxiter=maxiter)
class horizInterpRbs(rbs):
"""
"""
def __init__(self, datalon, datalat, data, kx=1, ky=1):
self.coeffs = rbs(datalat, datalon, data, kx=kx, ky=ky)
def rbs_interp(self, romslon, romslat):
return self.coeffs.ev(romslat, romslon)
class bcolors:
"""
See http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python
"""
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
class ROMS(object):
'''
ROMS class
'''
def __init__(self, datafile, model_type):
'''
Initialise the ROMS object
'''
thetype = str(type(self)).split('.')[-1].split("'")[0]
msg = '--- instantiating *%s*, %s' % (thetype, datafile)
#with bcolors.FAIL as col_:
print(bcolors.OKGREEN + msg + bcolors.ENDC)
self.romsfile = datafile
self.indices = '[self.j0:self.j1, self.i0:self.i1]'
self.i0 = 0
self.i1 = None
self.j0 = 0
self.j1 = None
self.k = 0 # to be used as a z index
self.t = 0 # to be used as a time index
self.r_earth = 6371315. # Mean earth radius in metres (from scalars.h)
# Flag indicating ROMS, SODA, CFSR, etc.
assert isinstance(model_type, str), 'model_type must be a string'
assert model_type in ('ROMS', 'CFSR', 'SODA', 'Mercator', 'Ecco'
), "model_type must be one of 'ROMS', 'CFSR', 'SODA', 'Mercator'"
self.model_type = model_type
# To be used for handling a grid that crosses
# zero degree meridian
self.zero_crossing = False
self.fix_zero_crossing = False
# An index along either x or y dimension
self.ij = None
# Used by CfsrData class
# Values taken from Roms_tools ("get_dqdsst.m")
# Specific heat of atmosphere.
self.Cp = 1004.8
# Sensible heat transfer coefficient (stable condition)
self.Ch = 0.66e-3
# Latent heat transfer coefficient (stable condition)
self.Ce = 1.15e-3
# Emissivity coefficient
self.eps = 0.985 # see Roms_tools function "as_consts.m"
# Stefan constant
self.Stefan = 5.6697e-8
# Latent heat of vaporisation (J.kg-1)
self.L1 = 2.5008e6
self.L2 = 2.3e3
# Kelvin
self.Kelvin = 273.15
def read_nc(self, varname, indices="[:]"):
'''
Read data from netcdf file
varname : variable ('temp', 'mask_rho', etc) to read
indices : string of index ranges, eg. '[0,:,0]'
'''
#print self.romsfile
try:
with netcdf.Dataset(self.romsfile) as nc:
var = eval(''.join(("nc.variables[varname]", indices)))
except Exception:
try:
with netcdf.Dataset(self.romsfile[0]) as nc:
var = eval(''.join(("nc.variables[varname]", indices)))
except Exception:
raise
if 'float32' in var.dtype.name:
return var.astype(np.float64)
else:
return var
def read_nc_mf(self, varname, indices="[:]"):
'''
Read data from multi-file netcdf file
varname : variable ('temp', 'mask_rho', etc) to read
indices : string of index ranges, eg. '[0,:,0]'
'''
try:
try:
with netcdf.MFDataset(self.filenames) as nc:
var = eval(''.join(("nc.variables[varname]", indices)))
except Exception:
with netcdf.MFDataset(self.filenames, aggdim='TIME') as nc:
var = eval(''.join(("nc.variables[varname]", indices)))
except Exception:
raise
if 'float32' in var.dtype.name:
return var.astype(np.float64)
else:
return var
def read_nc_at_index(self, varname, ind):
'''
Read data from multi-file netcdf file
varname : variable ('temp', 'mask_rho', etc) to read
indices : string of index ranges, eg. '[0,:,0]'
'''
try:
with netcdf.Dataset(self.romsfile) as nc:
return eval(''.join(("nc.variables[varname]", indices)))
except Exception:
try:
with netcdf.Dataset(self.romsfile[0]) as nc:
return eval(''.join(("nc.variables[varname]", indices)))
except Exception:
raise Exception
def read_nc_att(self, varname, att):
'''
Read data attribute from netcdf file
varname : variable ('temp', 'mask_rho', etc) to read
att : string of attribute, eg. 'valid_range'
'''
try:
with netcdf.Dataset(self.romsfile) as nc:
return eval(''.join(("nc.variables[varname].", att)))
except Exception:
try:
with netcdf.Dataset(self.romsfile[0]) as nc:
return eval(''.join(("nc.variables[varname].", att)))
except Exception:
raise Exception
def read_dim_size(self, dim):
'''
Read dimension size from netcdf file
dim : dimension ('time', 'lon_u', etc) to read
'''
try:
with netcdf.Dataset(self.romsfile) as nc:
#return len(eval("nc.dimensions[dim]"))
return len(nc.dimensions[dim])
except Exception:
raise
def list_of_variables(self):
'''
'''
datafile = self.romsfile
if isinstance(datafile, list):
datafile = datafile[0]
not_done = True
while not_done:
try:
#print datafile
with netcdf.Dataset(datafile) as nc:
not_done = False
keys = nc.variables.keys()
except:
#print 'sleeping'
time.sleep(0.5)
return keys
@staticmethod
def half_interp(h_one, h_two):
'''
Speed up frequent operations of type 0.5 * (arr[:-1] + arr[1:])
'''
return ne.evaluate('0.5 * (h_one + h_two)')
@staticmethod
def rho2u_2d(rho_in):
'''
Convert a 2D field at rho points to a field at u points
'''
def _r2u(rho_in, Lp):
u_out = rho_in[:, :Lp - 1]
u_out += rho_in[:, 1:Lp]
u_out *= 0.5
return u_out.squeeze()
assert rho_in.ndim == 2, 'rho_in must be 2d'
Mshp, Lshp = rho_in.shape
return _r2u(rho_in, Lshp)
@staticmethod
def rho2u_3d(rho_in):
'''
Convert a 3D field at rho points to a field at u points
Calls rho2u_2d
'''
def levloop(rho_in):
Nlevs, Mshp, Lshp = rho_in.shape
rho_out = np.zeros((Nlevs, Mshp, Lshp-1))
for k in xrange(Nlevs):
rho_out[k] = ROMS.rho2u_2d(rho_in[k])
return rho_out
assert rho_in.ndim == 3, 'rho_in must be 3d'
return levloop(rho_in)
@staticmethod
def rho2v_2d(rho_in):
'''
Convert a 2D field at rho points to a field at v points
'''
def _r2v(rho_in, Mp):
v_out = rho_in[:Mp - 1]
v_out += rho_in[1:Mp]
v_out *= 0.5
return v_out.squeeze()
assert rho_in.ndim == 2, 'rho_in must be 2d'
Mshp, Lshp = rho_in.shape
return _r2v(rho_in, Mshp)
@staticmethod
def rho2v_3d(rho_in):
'''
Convert a 3D field at rho points to a field at v points
Calls rho2v_2d
'''
def levloop(rho_in):
Nlevs, Mshp, Lshp = rho_in.shape
rho_out = np.zeros((Nlevs, Mshp-1, Lshp))
for k in xrange(Nlevs):
rho_out[k] = ROMS.rho2v_2d(rho_in[k])
return rho_out
assert rho_in.ndim == 3, 'rho_in must be 3d'
return levloop(rho_in)
@staticmethod
def u2rho_2d(u_in):
'''
Convert a 2D field at u points to a field at rho points
'''
def _uu2ur(uu_in, Mp, Lp):
L, Lm = Lp - 1, Lp - 2
u_out = np.zeros((Mp, Lp))
u_out[:, 1:L] = 0.5 * (u_in[:, 0:Lm] + \
u_in[:, 1:L])
u_out[:, 0] = u_out[:, 1]
u_out[:, L] = u_out[:, Lm]
return u_out.squeeze()
assert u_in.ndim == 2, 'u_in must be 2d'
Mp, Lp = u_in.shape
return _uu2ur(u_in, Mp, Lp+1)
@staticmethod
def u2rho_3d(u_in):
'''
Convert a 3D field at u points to a field at rho points
Calls u2rho_2d
'''
def _levloop(u_in):
Nlevs, Mshp, Lshp = u_in.shape
u_out = np.zeros((Nlevs, Mshp, Lshp+1))
for Nlev in xrange(Nlevs):
u_out[Nlev] = ROMS.u2rho_2d(u_in[Nlev])
return u_out
assert u_in.ndim == 3, 'u_in must be 3d'
return _levloop(u_in)
@staticmethod
def v2rho_2d(v_in):
'''
Convert a 2D field at v points to a field at rho points
'''
def _vv2vr(v_in, Mp, Lp):
M, Mm = Mp - 1, Mp - 2
v_out = np.zeros((Mp, Lp))
v_out[1:M] = 0.5 * (v_in[:Mm] + \
v_in[1:M])
v_out[0] = v_out[1]
v_out[M] = v_out[Mm]
return v_out.squeeze()
assert v_in.ndim == 2, 'v_in must be 2d'
Mp, Lp = v_in.shape
return _vv2vr(v_in, Mp+1, Lp)
@staticmethod
def v2rho_3d(v_in):
'''
Convert a 3D field at v points to a field at rho points
Calls v2rho_2d
'''
def levloop(v_in):
Nlevs, Mshp, Lshp = v_in.shape
v_out = np.zeros((Nlevs, Mshp+1, Lshp))
for Nlev in xrange(Nlevs):
v_out[Nlev] = ROMS.v2rho_2d(v_in[Nlev])
return v_out
assert v_in.ndim == 3, 'v_in must be 3d'
return levloop(v_in)
def rotate(self, u_in, v_in, **kwargs):
"""
Rotate velocity vectors
'angle' from gridfile
"""
if kwargs.has_key('ob'):
if kwargs['ob'] in 'east':
angle = self.angle()[:,-1]
elif kwargs['ob'] in 'west':
angle = self.angle()[:,0]
elif kwargs['ob'] in 'north':
angle = self.angle()[-1]
elif kwargs['ob'] in 'south':
angle = self.angle()[0]
else:
raise Exception
else:
angle = self.angle()
cosa = np.cos(kwargs['sign'] * angle)
sina = np.sin(kwargs['sign'] * angle)
u_out = (u_in * cosa) + (v_in * sina)
v_out = (v_in * cosa) - (u_in * sina)
return u_out, v_out
def get_fillmask_cof(self, mask):
'''Create (i, j) point arrays for good and bad data.
# Bad data are marked by the fill_value, good data elsewhere.
'''
# CHANGED Jan 14 to include *mask* argument
igood = np.vstack(np.where(mask == 1)).T
ibad = np.vstack(np.where(mask == 0)).T
tree = sp.cKDTree(igood)
# Get the k closest points to the bad points
# distance is squared
try:
dist, iquery = tree.query(ibad, k=4, p=2)
except:
try:
dist, iquery = tree.query(ibad, k=3, p=2)
except:
try:
dist, iquery = tree.query(ibad, k=2, p=2)
except:
dist, iquery = tree.query(ibad, k=1, p=2)
self.fillmask_cof = np.array([dist, iquery, igood, ibad])
return self
def fillmask(self, x, mask, weights=False):
'''
Fill missing values in an array with an average of nearest
neighbours
From http://permalink.gmane.org/gmane.comp.python.scientific.user/19610
Input:
x : 2-d array to be filled
mask : 2-d mask (0s & 1s) same shape as x
Output:
x : filled x
self.fillmask_cof is set
'''
assert x.ndim == 2, 'x must be a 2D array.'
fill_value = 9999.99
x[mask == 0] = fill_value
if isinstance(weights, np.ndarray):
dist, iquery, igood, ibad = weights
else:
self.get_fillmask_cof(mask)
dist, iquery, igood, ibad = self.fillmask_cof
# Create a normalised weight, the nearest points are weighted as 1.
# Points greater than one are then set to zero
weight = dist / (dist.min(axis=1)[:, np.newaxis] * np.ones_like(dist))
weight[weight > 1.] = 0.
# Multiply the queried good points by the weight, selecting only
# the nearest points. Divide by the number of nearest points
# to get average
xfill = weight * x[igood[:,0][iquery], igood[:,1][iquery]]
xfill = (xfill / weight.sum(axis=1)[:, np.newaxis]).sum(axis=1)
# Place average of nearest good points, xfill, into bad point locations
x[ibad[:,0], ibad[:,1]] = xfill
if not isinstance(weights, bool):
return x
else:
return x, np.array([dist, iquery, igood, ibad])
def proj2gnom(self, ignore_land_points=False, gtype='rho', index_str=None, M=None):
'''
Use premade Basemap instance for Gnomonic projection
of lon, lat.
ignore_land_points : if True returns only lon, lat from sea points.
gtype : grid type, one of 'rho', 'u' or 'v'
index_str : specifies a boundary.
M : Child basemap obj must be passed in for parent projection
'''
def remove_masked_points(lon, lat, mask):
lon, lat = lon[mask == True], lat[mask == True]
return lon, lat
if index_str is not None:
glon = eval(''.join(('self.lon()', index_str)))
glat = eval(''.join(('self.lat()', index_str)))
if ignore_land_points:
if 'rho' in gtype:
glon, glat = remove_masked_points(glon, glat,
eval(''.join(('self.maskr()', index_str))))
elif 'u' in gtype:
glon, glat = remove_masked_points(glon, glat,
eval(''.join(('self.umask()', index_str))))
elif 'v' in gtype:
glon, glat = remove_masked_points(glon, glat,
eval(''.join(('self.vmask()', index_str))))
elif index_str is None and ignore_land_points is True: # exclude masked points
glon, glat = remove_masked_points(self.lon(), self.lat(), self.maskr())
else:
glon, glat = self.lon(), self.lat()
if M is None:
glon, glat = self.M(glon, glat)
else:
#print 'dddd'
glon, glat = M(glon, glat)
self.points = np.array([glon.ravel(),glat.ravel()]).T
return self
def make_kdetree(self):
''' Make a parent kde tree that will enable selection
minimum numbers of indices necessary to parent grid for
successful interpolation to child grid
Requires self.points from def proj2gnom
'''
self.kdetree = sp.cKDTree(self.points)
if not hasattr(sp.ckdtree.cKDTree, "query_ball_tree"):
print '------ cKDTree.query_ball_tree not found (update of scipy recommended)'
self.kdetree = sp.KDTree(self.points)
return self
def make_gnom_transform(self):
'''
Create Basemap instance for Gnomonic projection
Return the transformation, M
'''
self.M = Basemap(projection = 'gnom',
lon_0=self.lon().mean(), lat_0=self.lat().mean(),
llcrnrlon=self.lon().min(), llcrnrlat=self.lat().min(),
urcrnrlon=self.lon().max(), urcrnrlat=self.lat().max())
return self
def child_contained_by_parent(self, child_grid):
'''
Check that no child data points lie outside of the
parent domain.
'''
tri = sp.Delaunay(self.points) # triangulate full parent
tn = tri.find_simplex(child_grid.points)
assert not np.any(tn == -1), 'Error: detected child data points outside parent domain'
print '------ parent domain suitable for interpolation'
return self
def set_subgrid(self, other, k=4):
'''
Set indices to parent subgrid
Parameter:
other : another (child) RomsGrid instance
'''
def kdt(lon, lat, limits):
ppoints = np.array([lon.ravel(), lat.ravel()]).T
ptree = sp.cKDTree(ppoints)
#print limits
pindices = ptree.query(limits, k=k)[1]
iind, jind = np.array([], dtype=int), np.array([], dtype=int)
for pind in pindices.ravel():
j, i = np.unravel_index(pind, lon.shape)
iind = np.r_[iind, i]
jind = np.r_[jind, j]
return iind, jind
if self.zero_crossing is True and 'ROMS' not in self.model_type:
'''
Used by pysoda2roms when there is a zero crossing,
eg. at western Med.
'''
def half_limits(lon, lat):
return np.array([np.array([lon.min(), lon.max(),
lon.max(), lon.min()]),
np.array([lat.min(), lat.min(),
lat.max(), lat.max()])]).T
# Get bounds for -ve part of grid
lat = other.lat()[other.lon() < 0.]
lon = other.lon()[other.lon() < 0.] + 360.
limits = half_limits(lon, lat)
iind, jind = kdt(self._lon, self._lat, limits)
self.i1 = iind.min()
j10, j11 = jind.min(), jind.max()
# Get bounds for +ve part of grid
lat = other.lat()[other.lon() >= 0.]
lon = other.lon()[other.lon() >= 0.]
limits = half_limits(lon, lat)
iind, jind = kdt(self._lon, self._lat, limits)
self.i0 = iind.max()
j20, j21 = jind.min(), jind.max()
self.j0 = np.min([j10, j20])
self.j1 = np.max([j11, j21])
#self.fix_zero_crossing = True
else:
''' Used for pyroms2roms, and pysoda2roms when
there is no zero crossing
'''
if np.alltrue(other.lon() < 0.) and np.alltrue(self._lon >= 0.):
self._lon -= 360.
iind, jind = kdt(self._lon, self._lat, other.limits())
self.i0, self.i1 = iind.min(), iind.max()
self.j0, self.j1 = jind.min(), jind.max()
return self
def _get_barotropic_velocity(self, baroclinic_velocity, cell_depths):
'''
'''
sum_baroclinic = (baroclinic_velocity * cell_depths).sum(axis=0)
total_depth = cell_depths.sum(axis=0)
sum_baroclinic /= total_depth
return sum_baroclinic
def get_barotropic_velocity(self, baroclinic_velocity, cell_depths):
'''
Input:
baroclinic_velocity
cell_depths
'''
return self._get_barotropic_velocity(baroclinic_velocity, cell_depths)
def set_barotropic(self): #, open_boundary):
'''
'''
self.barotropic = self._get_barotropic_velocity(self.dataout,
self.romsgrd.scoord2dz())
return self
class RomsGrid (ROMS):
'''
RomsGrid class (inherits from ROMS class)
'''
def __init__(self, filename, sigma_params, model_type):
'''
'''
super(RomsGrid, self).__init__(filename, model_type)
#self.indices = '[self.j0:self.j1, self.i0:self.i1]'
self.grid_file = filename
self._lon = self.read_nc('lon_rho')#, indices=self.indices)
self._lat = self.read_nc('lat_rho')#, indices=self.indices)
self._pm = self.read_nc('pm')#, indices=self.indices)
self._pn = self.read_nc('pn')#, indices=self.indices)
self._maskr = self.read_nc('mask_rho')#, indices=self.indices)
self._angle = self.read_nc('angle')#, indices=self.indices)
self._h = self.read_nc('h')#, indices=self.indices)
self._hraw = self.read_nc('hraw')#, indices=self.indices)
self._f = self.read_nc('f')#, indices=self.indices)
self._uvpmask()
self.theta_s = np.double(sigma_params['theta_s'])
self.theta_b = np.double(sigma_params['theta_b'])
self.hc = np.double(sigma_params['hc'])
self.N = np.double(sigma_params['N'])
self.sc_r = None
def lon(self): return self._lon[self.j0:self.j1, self.i0:self.i1]
def lat(self): return self._lat[self.j0:self.j1, self.i0:self.i1]
def pm(self): return self._pm[self.j0:self.j1, self.i0:self.i1]
def pn(self): return self._pn[self.j0:self.j1, self.i0:self.i1]
def maskr(self): return self._maskr[self.j0:self.j1, self.i0:self.i1]
def angle(self): return self._angle[self.j0:self.j1, self.i0:self.i1]
def h(self): return self._h[self.j0:self.j1, self.i0:self.i1]
def hraw(self): return self._hraw[self.j0:self.j1, self.i0:self.i1]
def f(self): return self._f[self.j0:self.j1, self.i0:self.i1]
def idata(self):
return np.nonzero(self.maskr().ravel() == 1.)[0]
def imask(self):
return np.nonzero(self.maskr().ravel() == 0.)[0]
def _uvpmask(self):
'''
Get mask at u, v, psi points
'''
try:
self._umask = self.read_nc('mask_u')
except:
#Mp, Lp = self.maskr().shape
#print 'Mp',Mp,' Lp',Lp
#Mp -= 1
#Lp -= 1
#M = Mp - 1
#L = Lp - 1
self._umask = self.maskr()[:, :-1] * self.maskr()[:, 1:]
self._vmask = self.maskr()[:-1] * self.maskr()[1:]
self._pmask = self._umask[:-1] * self._umask[1:]
else:
self._vmask = self.read_nc('mask_v')
self._pmask = self.read_nc('mask_psi')
return self
def umask(self):
return self._umask
# Not sure about all below (29/12/2017) BUT indices needed
# for tiled grids...
# added '-1' 1/9/2016 cos problem in py_mercator_ini line ~385
'''try:
return self._umask[self.j0:self.j1, self.i0:self.i1-1]
except:
return self._umask[self.j0:self.j1, self.i0:-2]'''
def vmask(self):
return self._vmask
# Not sure about all below (29/12/2017)
# added '-1' 1/9/2016 cos problem in py_mercator_ini line ~385
'''try:
return self._vmask[self.j0:self.j1-1, self.i0:self.i1]
except:
return self._vmask[self.j0:-2, self.i0:self.i1]'''
def pmask(self):
print 'fix me'
return self._pmask
def mask3d(self):
'''
3d stack of mask same size as N
'''
return np.tile(self.maskr(), (np.int(self.N), 1, 1))
def umask3d(self):
'''
3d stack of umask same size as N
'''
return np.tile(self.umask(), (np.int(self.N), 1, 1))
def vmask3d(self):
'''
3d stack of vmask same size as N
'''
return np.tile(self.vmask(), (np.int(self.N), 1, 1))
def boundary(self):
'''
Return lon,lat of perimeter around a ROMS grid
'''
lon = np.hstack((self.lon()[0:, 0], self.lon()[-1, 1:-1],
self.lon()[-1::-1, -1], self.lon()[0, -2::-1]))
lat = np.hstack((self.lat()[0:, 0], self.lat()[-1, 1:-1],
self.lat()[-1::-1, -1], self.lat()[0, -2::-1]))
return lon, lat
def VertCoordType(self):
nc = netcdf.Dataset(self.grdfile, 'r')
var = nc.VertCoordType
nc.close()
return var
def title(self):
nc = netcdf.Dataset(self.grdfile, 'r')
var = nc.title
nc.close()
return var
def check_zero_crossing(self):
if np.logical_and(np.any(self.lon() < 0.),
np.any(self.lon() >= 0.)):
self.zero_crossing = True
def _scoord2z(self, point_type, zeta, alpha, beta):
"""
z = scoord2z(h, theta_s, theta_b, hc, N, point_type, scoord, zeta)
scoord2z finds z at either rho or w points (positive up, zero at rest surface)
h = array of depths (e.g., from grd file)
theta_s = surface focusing parameter
theta_b = bottom focusing parameter
hc = critical depth
N = number of vertical rho-points
point_type = 'r' or 'w'
scoord = 'new2008' :new scoord 2008, 'new2006' : new scoord 2006,
or 'old1994' for Song scoord
zeta = sea surface height
message = set to False if don't want message
"""
def CSF(self, sc):
'''
Allows use of theta_b > 0 (July 2009)
'''
one64 = np.float64(1)
if self.theta_s > 0.:
csrf = ((one64 - np.cosh(self.theta_s * sc))
/ (np.cosh(self.theta_s) - one64))
else:
csrf = -sc ** 2
sc1 = csrf + one64
if self.theta_b > 0.:
Cs = ((np.exp(self.theta_b * sc1) - one64)
/ (np.exp(self.theta_b) - one64) - one64)
else:
Cs = csrf
return Cs
#
try:
self.scoord
except:
self.scoord = 'new2008'
N = np.float64(self.N.copy())
cff1 = 1. / np.sinh(self.theta_s)
cff2 = 0.5 / np.tanh(0.5 * self.theta_s)
sc_w = (np.arange(N + 1, dtype=np.float64) - N) / N
sc_r = ((np.arange(1, N + 1, dtype=np.float64)) - N - 0.5) / N
#sc_w = np.arange(-1., 1. / N, 1. / N, dtype=np.float64)
#sc_r = 0.5 * (sc_w[1:] + sc_w[:-1])
if 'w' in point_type:
sc = sc_w
N += 1. # add a level
else:
sc = sc_r
#Cs = (1. - self.theta_b) * cff1 * np.sinh(self.theta_s * sc) \
#+ self.theta_b * (cff2 * np.tanh(self.theta_s * (sc + 0.5)) - 0.5)
z = np.empty((int(N),) + self.h().shape, dtype=np.float64)
if self.scoord in 'new2008':
Cs = CSF(self, sc)
if self.scoord in 'new2006' or self.scoord in 'new2008':
hinv = 1. / (self.h() + self.hc)
cff = self.hc * sc
cff1 = Cs
for k in np.arange(N, dtype=int):
z[k] = zeta + (zeta + self.h()) * (cff[k] + cff1[k] * self.h()) * hinv
elif self.scoord in 'old1994':
hinv = 1. / self.h()
cff = self.hc * (sc - Cs)
cff1 = Cs
cff2 = sc + 1
for k in np.arange(N) + 1:
z0 = cff[k-1] + cff1[k-1] * self.h()
z[k-1, :] = z0 + zeta * (1. + z0 * hinv)
else:
raise Exception("Unknown scoord, should be 'new2008' or 'old1994'")
if self.sc_r is None:
self.sc_r = sc_r
return z.squeeze(), np.float32(Cs)
def scoord2z_r(self, zeta=0., alpha=0., beta=1.):
'''
Depths at vertical rho points
'''
return self._scoord2z('r', zeta=zeta, alpha=alpha, beta=beta)[0]
def Cs_r(self, zeta=0., alpha=0., beta=1.):
'''
S-coordinate stretching curves at rho points
'''
return self._scoord2z('r', zeta=zeta, alpha=alpha, beta=beta)[1]
def scoord2z_w(self, zeta=0., alpha=0., beta=1.):
'''
Depths at vertical w points
'''
return self._scoord2z('w', zeta=zeta, alpha=alpha, beta=beta)[0]
def Cs_w(self, zeta=0., alpha=0., beta=1.):
'''
S-coordinate stretching curves at w points
'''
return self._scoord2z('w', zeta=zeta, alpha=alpha, beta=beta)[1]
def _set_dz_rho_points(self, zeta=0., alpha=0., beta=1):
"""
Set depths of sigma layers at rho points, 3d matrix.
"""
dz = self._scoord2z('w', zeta=zeta, alpha=alpha, beta=beta)[0]
self._dz_rho_points = dz[1:] - dz[:-1]
def scoord2dz(self, zeta=0., alpha=0., beta=1.):
"""
dz at rho points, 3d matrix, depths of sigma layers
"""
dz = self._scoord2z('w', zeta=zeta, alpha=alpha, beta=beta)[0]
return dz[1:] - dz[:-1]
def scoord2dz_u(self, zeta=0., alpha=0., beta=1.):
'''
dz at u points, 3d matrix, depths of sigma layers
'''
dz = self.scoord2dz(zeta=0., alpha=0., beta=1.)
return self.rho2u_3d(dz)
def scoord2dz_v(self, zeta=0., alpha=0., beta=1.):
'''
dz at v points, 3d matrix, depths of sigma layers
'''
dz = self.scoord2dz(zeta=0., alpha=0., beta=1.)
return self.rho2v_3d(dz)
def set_bry_dx(self):
'''
Set dx for all 4 boundaries
'''
self.set_dx_east()
self.set_dx_west()
self.set_dx_north()
self.set_dx_south()
return self
def set_dx_east(self):
'''
Set dx in m along eastern boundary
'''
self.dx_east = np.reciprocal(0.5 * (self._pn[:,-1] + self._pn[:,-2]))
return self
def set_dx_west(self):
'''
Set dx in m along western boundary
'''
self.dx_west = np.reciprocal(0.5 * (self._pn[:, 0] + self._pn[:, 1]))
return self
def set_dx_south(self):
'''
Set dx in m along southern boundary
'''
self.dx_south = np.reciprocal(0.5 * (self._pm[0] + self._pm[1]))
return self
def set_dx_north(self):
'''
Set dx in m along northern boundary
'''
self.dx_north = np.reciprocal(0.5 * (self._pm[-1] + self._pm[-2]))
return self
def set_bry_maskr(self):
'''
Set mask for all 4 boundaries
'''