-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpycfsr2frc.py
2464 lines (1990 loc) · 98.2 KB
/
pycfsr2frc.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 pycfsr2frc.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 forcing file based on CFSR monthly data
===========================================================================
'''
import netCDF4 as netcdf
import matplotlib.pyplot as plt
import matplotlib.dates as dt
import numpy as np
import numexpr as ne
from scipy import io
import scipy.interpolate as si
import scipy.ndimage as nd
import scipy.spatial as sp
#import matplotlib.nxutils as nx
import time
import scipy.interpolate.interpnd as interpnd
from mpl_toolkits.basemap import Basemap
from collections import OrderedDict
#from datetime import datetime
import calendar as ca
from py_roms2roms import horizInterp
from py_roms2roms import ROMS, debug0, debug1
from py_roms2roms import RomsGrid, RomsData
class RomsGrid(RomsGrid):
'''
Modify the RomsGrid class
'''
def create_frc_nc(self, frcfile, sd, ed, nr, cl, madeby, bulk):
'''
Create a new forcing file based on dimensions from grdobj
frcfile : path and name of new frc file
sd : start date2num
ed : end date
nr : no. of records
cl : cycle length
madeby : name of this file
'''
if bulk:
try:
frcfile = frcfile.replace('frc_', 'blk_')
except Exception:
pass
else:
try:
frcfile = frcfile.replace('blk_', 'frc_')
except Exception:
pass
self.frcfile = frcfile
print 'Creating new CFSR forcing file:', frcfile
# Global attributes
''' The best choice should be format='NETCDF4', but it will not work with
Sasha's 2008 code (not tested with Roms-Agrif). Therefore I use
format='NETCDF3_64BIT; the drawback is that it is very slow'
'''
#nc = netcdf.Dataset(frcfile, 'w', format='NETCDF3_64BIT')
#nc = netcdf.Dataset(frcfile, 'w', format='NETCDF3_CLASSIC')
nc = netcdf.Dataset(frcfile, 'w', format='NETCDF4')
nc.created = dt.datetime.datetime.now().isoformat()
nc.type = 'ROMS interannual forcing file produced by %s.py' %madeby
nc.grd_file = self.romsfile
nc.start_date = sd
nc.end_date = ed
# Dimensions
nc.createDimension('xi_rho', self.lon().shape[1])
nc.createDimension('xi_u', self.lon().shape[1] - 1)
nc.createDimension('eta_rho', self.lon().shape[0])
nc.createDimension('eta_v', self.lon().shape[0] - 1)
if bulk:
nc.createDimension('bulk_time', nr)
else:
nc.createDimension('sms_time', nr)
nc.createDimension('shf_time', nr)
nc.createDimension('swf_time', nr)
nc.createDimension('sst_time', nr)
nc.createDimension('srf_time', nr)
nc.createDimension('sss_time', nr)
nc.createDimension('one', 1)
# Dictionary for the variables
frc_vars = OrderedDict()
if bulk:
frc_vars['bulk_time'] = ['time',
'bulk_time',
'bulk formulation execution time',
'days']
else:
frc_vars['sms_time'] = ['time',
'sms_time',
'surface momentum stress time',
'days']
frc_vars['shf_time'] = ['time',
'shf_time',
'surface heat flux time',
'days']
frc_vars['swf_time'] = ['time',
'swf_time',
'surface freshwater flux time',
'days']
frc_vars['sst_time'] = ['time',
'sst_time',
'sea surface temperature time',
'days']
frc_vars['sss_time'] = ['time',
'sss_time',
'sea surface salinity time',
'days']
frc_vars['srf_time'] = ['time',
'srf_time',
'solar shortwave radiation time',
'days']
# Note this could be problematic if scale_cfsr_coads.py adjusts variables
# with different frequencies...
frc_vars['month'] = ['time',
'sst_time',
'not used by ROMS; useful for scale_cfsr_coads.py',
'month of year']
# Bulk formaulation
if bulk:
frc_vars['tair'] = ['rho',
'bulk_time',
'surface air temperature',
'Celsius']
frc_vars['rhum'] = ['rho',
'bulk_time',
'relative humidity',
'fraction']
frc_vars['prate'] = ['rho',
'bulk_time',
'precipitation rate',
'cm day-1']
frc_vars['wspd'] = ['rho',
'bulk_time',
'wind speed 10m',
'm s-1']
frc_vars['radlw'] = ['rho',
'bulk_time',
'net outgoing longwave radiation',
'Watts meter-2',
'upward flux, cooling water']
frc_vars['radlw_in'] = ['rho',
'bulk_time',
'downward longwave radiation',
'Watts meter-2',
'downward flux, warming water']
frc_vars['radsw'] = ['rho',
'bulk_time',
'shortwave radiation',
'Watts meter-2',
'downward flux, warming water']
frc_vars['sustr'] = ['u',
'bulk_time',
'surface u-momentum stress',
'Newton meter-2']
frc_vars['svstr'] = ['v',
'bulk_time',
'surface v-momentum stress',
'Newton meter-2']
frc_vars['uwnd'] = ['u',
'bulk_time',
'10m u-wind',
'm s-1']
frc_vars['vwnd'] = ['v',
'bulk_time',
'10m v-wind',
'm s-1']
# dQdSST
else:
frc_vars['sustr'] = ['u',
'sms_time',
'surface u-momentum stress',
'Newton meter-2']
frc_vars['svstr'] = ['v',
'sms_time',
'surface v-momentum stress',
'Newton meter-2']
frc_vars['shflux'] = ['rho',
'shf_time',
'surface net heat flux',
'Watts meter-2']
frc_vars['swflux'] = ['rho',
'swf_time',
'surface freshwater flux (E-P)',
'centimeters day-1',
'net evaporation',
'net precipitation']
frc_vars['SST'] = ['rho',
'sst_time',
'sea surface temperature',
'Celsius']
frc_vars['SSS'] = ['rho',
'sss_time',
'sea surface salinity',
'PSU']
frc_vars['dQdSST'] = ['rho',
'sst_time',
'surface net heat flux sensitivity to SST',
'Watts meter-2 Celsius-1']
frc_vars['swrad'] = ['rho',
'srf_time',
'solar shortwave radiation',
'Watts meter-2',
'downward flux, heating',
'upward flux, cooling']
for key, value in zip(frc_vars.keys(), frc_vars.values()):
#print key, value
if 'time' in value[0]:
dims = (value[1])
elif 'rho' in value[0]:
dims = (value[1], 'eta_rho', 'xi_rho')
elif 'u' in value[0]:
dims = (value[1], 'eta_rho', 'xi_u')
elif 'v' in value[0]:
dims = (value[1], 'eta_v', 'xi_rho')
else:
error
#print 'key, dims = ',key, dims
nc.createVariable(key, 'f4', dims, zlib=True)
nc.variables[key].long_name = value[2]
nc.variables[key].units = value[3]
if 'time' in key and nr is not None:
nc.variables[key].cycle_length = cl
if 'swrad' in key:
nc.variables[key].positive = value[4]
nc.variables[key].negative = value[5]
if 'swflux' in key:
nc.variables[key].positive = value[4]
nc.variables[key].negative = value[5]
if 'radlw' in key:
nc.variables[key].positive = value[4]
if 'radlw_in' in key:
nc.variables[key].positive = value[4]
if 'radsw' in key:
nc.variables[key].positive = value[4]
nc.close()
def gc_dist(self, lon1, lat1, lon2, lat2):
'''
Use Haversine formula to calculate distance
between one point and another
!! lat and lon in radians !!
'''
r_earth = self.r_earth # Mean earth radius in metres (from scalars.h)
dlat = lat2 - lat1
dlon = lon2 - lon1
dang = 2. * np.arcsin(np.sqrt(np.power(np.sin(0.5 * dlat), 2) + \
np.cos(lat2) * np.cos(lat1) * np.power(np.sin(0.5 * dlon), 2)))
return r_earth * dang # distance
#def get_runoff(self, swflux_data, dai_file, mon):
def get_runoff(self, dai_file, mon):
'''
This needs to be speeded up. Separate into 2 parts:
1 def runoff_setup() to do one-time tasks
2 get_runoff() to do variable tasks
'''
mon -= 1
area = 1.
area /= (self.pm() * self.pn())
dx = 1.
dx /= np.mean(self.pm())
roms_dir = self.romsfile.replace(self.romsfile.split('/')[-1], '')
cdist = io.loadmat(roms_dir + 'coast_distances.mat')
mask = self.maskr()
# Exponential decay, runoff forced towards coast. 75km ?
#mult = np.exp(-cdist['cdist'] / 150.e4)
mult = np.exp(-cdist['cdist'] / 60.e4)
np.place(mult, mask > 1., 0)
# Read in river data and set data trim
lon0 = np.round(self.lon().min() - 1.0)
lon1 = np.round(self.lon().max() + 1.0)
lat0 = np.round(self.lat().min() - 1.0)
lat1 = np.round(self.lat().max() + 1.0)
nc = netcdf.Dataset(dai_file)
lon_runoff = nc.variables['lon'][:]
lat_runoff = nc.variables['lat'][:]
i0 = np.nonzero(lon_runoff > lon0)[0].min()
i1 = np.nonzero(lon_runoff < lon1)[0].max() + 1
j0 = np.nonzero(lat_runoff > lat0)[0].min()
j1 = np.nonzero(lat_runoff < lat1)[0].max() + 1
flux_unit = 1.1574e-07 # (cm/day)
surf_ro = np.zeros(self.lon().shape)
lon_runoff = lon_runoff[i0:i1]
lat_runoff = lat_runoff[j0:j1]
runoff = nc.variables['runoff'][mon, j0:j1, i0:i1]
nc.close()
lon_runoff, lat_runoff = np.meshgrid(lon_runoff, lat_runoff)
lon_runoff = lon_runoff[runoff >= 1e-5]
lat_runoff = lat_runoff[runoff >= 1e-5]
runoff = runoff[runoff >= 1e-5]
n_runoff = runoff.size
for idx in np.arange(n_runoff):
#print idx, n_runoff
# Find suitable unmasked grid points to distribute run-off
dist = self.gc_dist(np.deg2rad(self.lon()),
np.deg2rad(self.lat()),
np.deg2rad(lon_runoff[idx]),
np.deg2rad(lat_runoff[idx]))
if dist.min() <= 5. * dx:
#scale = 150. * 1e3 # scale of Dai data is at 1 degree
scale = 60. * 1e3 # scale of Dai data is at 1 degree
bool_mask = (dist < scale) * (mask > 0)
int_are = area[bool_mask].sum()
ave_wgt = mult[bool_mask].mean()
surface_flux = 1e6 * runoff[idx]
#print 'surface_flux, int_are', surface_flux, int_are
surface_flux /= np.array([int_are, np.spacing(2)]).max()
#print 'surface_flux',surface_flux
surf_ro[bool_mask] = (surf_ro[bool_mask] + surface_flux /
flux_unit * mult[bool_mask] / ave_wgt)
#return (swflux_data * mask) - (surf_ro * mask) comment Sep 2013
return surf_ro * mask
def get_runoff_index_weights(self, dtnum):
'''
Get indices and weights for Dai river climatology
Input: dt - datenum for current month
Output: dai_ind_min
dai_ind_max
weights
'''
dtdate = dt.num2date(dtnum)
day_plus_hr = np.float(dtdate.day + dtdate.hour / 24.)
x_monrange = ca.monthrange(dtdate.year, dtdate.month)[-1]
x_half_monrange = 0.5 * x_monrange
if dtdate.day > x_half_monrange:
# Second half of month, use present and next months
dai_ind_min = dtdate.month - 1
dai_ind_max = dtdate.month
if dai_ind_max == 12:
dai_ind_max = 0
y_monrange = ca.monthrange(dtdate.year + 1, 1)[-1]
else:
y_monrange = ca.monthrange(dtdate.year, dtdate.month)[-1]
x = day_plus_hr - x_half_monrange
y = 0.5 * y_monrange
y += x_monrange
y -= day_plus_hr
w1, w2 = y, x
else:
# First half of month, use previous and present months
dai_ind_min = dtdate.month - 2
dai_ind_max = dtdate.month - 1
if dai_ind_min < 0:
dai_ind_min = 11
y_monrange = ca.monthrange(dtdate.year - 1, 12)[-1]
else:
y_monrange = ca.monthrange(dtdate.year, dtdate.month - 1)[-1]
x = x_half_monrange - day_plus_hr
y = 0.5 * y_monrange
y += day_plus_hr
w1, w2 = x, y
xpy = x + y
weights = [w1 / xpy, w2 / xpy]
return dai_ind_min, dai_ind_max, weights
class CfsrGrid(ROMS):
'''
CFSR grid class (inherits from RomsGrid class)
'''
def __init__(self, filename, model_type):
'''
'''
super(CfsrGrid, self).__init__(filename, model_type)
print 'Initialising CfsrGrid', filename
self._lon = self.read_nc('lon', indices='[:]')
self._lat = self.read_nc('lat', indices='[:]')
self._lon, self._lat = np.meshgrid(self._lon,
self._lat[::-1])
def lon(self):
return self._lon
def lat(self):
return self._lat
def metrics(self):
'''
Return array of metrics unique to this grid
(lonmin, lonmax, lon_res, latmin, latmax, lat_res)
where 'res' is resolution in degrees
'''
self_shape = self.lon().shape
lon_range = self.read_nc_att('lon', 'valid_range')
lon_mean = self.lon().mean().round(2)
lat_mean = self.lat().mean().round(2)
res = np.diff(lon_range) / self.lon().shape[1]
met = np.hstack((self_shape[0], self_shape[1], lon_mean, lat_mean, res))
return met
#def get_mask(self):
#'''
#Return a land sea mask
#'''
#try:
#result = self.read_nc('LAND_L1', '[0,::-1]')
#except Exception:
#try:
#result = self.read_nc('LAND_L1_Avg', '[0,::-1]')
#except Exception:
#try:
#result = self.read_nc('SALTY_L160', '[0,::-1]')
#except Exception:
#raise
#return np.abs(result - 1.)
#def select_mask(self, masks):
#'''
#Loop over list of masks to find which one
#has same grid dimensions as self
#'''
#for each_ind, each_mask in enumerate(masks):
#if np.alltrue(each_mask.metrics() == self.metrics()):
#self.mask = each_mask.get_mask()
#try:
#self.mask
#except Exception:
##print 'No suitable mask found masks'
#raise
###to_do__make_routine_to_add_new_grid_on_the_fly
#else:
#return self
def resolution(self):
'''
Return the resolution of the data in degrees
'''
return self.metrics()[-1]
#def get_points(self, roms_M):
#'''
#get points
#'''
#return self.proj2gnom(roms_M)
#def get_points_kdetree(self, roms_points, roms_M):
#'''
#Check that no ROMS data points lie outside of the
#CFSR domain. If this occurs pycfsr2frc cannot function;
#the solution is to obtain a new CFSR file making sure that it
#covers the child grid...
#'''
#cfsr_points_all = self.get_points(roms_M) # must use roms_M
#cfsr_tri = sp.Delaunay(cfsr_points_all) # triangulate full parent
#tn = cfsr_tri.find_simplex(roms_points)
#assert not np.any(tn == -1), 'ROMS data points outside CFSR domain detected'
## Create cfsr grid KDE tree...
#cfsr_tree = sp.KDTree(cfsr_points_all)
## ... in order to get minimum no. indices for interpolation.
#return cfsr_tree, cfsr_points_all
def assert_resolution(self, cfsrgrd_tmp, key):
'''
'''
assert self.metrics()[2] <= cfsrgrd_tmp.metrics()[2], \
'Resolution of %s is lower than previous grids, move up in dict "cfsr_files"' %key
class CfsrData(RomsData):
'''
CFSR data class (inherits from RomsData class)
'''
def __init__(self, filename, varname, model_type, romsgrd, masks=None):
'''
'''
super(CfsrData, self).__init__(filename, model_type)
#print 'bbbbbbbbbbbbb'
#classname = str(self.__class__).partition('.')[-1].strip("'>")
#print '\n--- Instantiating *%s* instance from' %classname, filename
self.varname = varname
self._check_product_description()
self.needs_time_averaging = False
if 'mask' not in (str(type(self)).lower()):
self._set_averaging_weights()
self._set_start_end_dates('ref_date_time')
self._lon = self.read_nc('lon', indices='[:]')
self._lat = self.read_nc('lat', indices='[:]')
self._lon, self._lat = np.meshgrid(self._lon,
self._lat[::-1])
self._get_metrics()
if masks is not None:
self._select_mask(masks)
self._maskr = self.cfsrmsk._maskr
self.fillmask_cof = self.cfsrmsk.fillmask_cof
else:
self.cfsrmsk = None
self.fillmask_cof = None
self.romsgrd = romsgrd
self.datain = np.ma.empty(self.lon().shape)
self.datatmp = np.ma.empty(self.lon().shape)
self.dataout = np.ma.empty(self.romsgrd.lon().size)
self._datenum = self._get_time_series()
self.tind = None
self.tri = None
self.tri_all = None
self.dt = None
self.to_be_downscaled = False
self.needs_all_point_tri = False
def lon(self):
return self._lon
def lat(self):
return self._lat
def maskr(self):
''' Returns mask on rho points
'''
return self._maskr
'''----------------------------------------------------------------------------------
Methods to detect if CFSR instance data are forecasts, forecast averages or
analyses. If a forecast of either type, a second field at tind-1 must be read and
averaged appropriately to ensure all fields are at either 00, 06, 12, 18 hours.
'''
def _check_product_description(self):
''' Returns appropriate string
'''
self.product = self.read_nc_att(self.varname, 'product_description')
def _set_averaging_weights(self):
'''
Order: call after self._check_product_description()
'''
def _calc_weights(frcst_hr, delta_hr):
return np.array([frcst_hr, delta_hr - frcst_hr]) / delta_hr
self.forecast_hour = self.read_nc('forecast_hour', indices='[0]').astype('float')
if 'Forecast' in self.product:
self.needs_time_averaging = True
self.delta_hours = np.diff(self.read_nc('time', indices='[:2]')).astype('float')
self.time_avg_weights = _calc_weights(self.forecast_hour, self.delta_hours)
elif 'Average (reference date/time to valid date/time)' in self.product:
self.needs_time_averaging = True
self.delta_hours = np.diff(self.read_nc('time', indices='[:2]')).astype('float')
self.time_avg_weights = _calc_weights(0.5 * self.forecast_hour, self.delta_hours)
else:
Exception, 'Undefined_product'
return self
def _get_data_time_average(self):
'''
Order: call after self._set_averaging_weights()
'''
np.add(self.time_avg_weights[0] * self.datatmp,
self.time_avg_weights[1] * self.datain, out=self.datain)
return self
def print_weights(self):
'''
'''
print '------ averaging weights for *%s* product: %s' %(self.product, self.time_avg_weights)
'''----------------------------------------------------------------------------------
'''
def _select_mask(self, masks):
'''Loop over list of masks to find which one
has same grid dimensions as self
'''
for each_mask in masks:
if np.alltrue(each_mask.metrics == self.metrics):
self.cfsrmsk = each_mask
#self._maskr = each_mask._get_landmask()
return self
return None
def fillmask(self):
'''Fill missing values in an array with an average of nearest
neighbours
From http://permalink.gmane.org/gmane.comp.python.scientific.user/19610
Order: call after self.get_fillmask_cof()
'''
dist, iquery, igood, ibad = self.fillmask_cof
weight = dist / (dist.min(axis=1)[:,np.newaxis] * np.ones_like(dist))
np.place(weight, weight > 1., 0.)
xfill = weight * self.datain[igood[:,0][iquery], igood[:,1][iquery]]
xfill = (xfill / weight.sum(axis=1)[:,np.newaxis]).sum(axis=1)
self.datain[ibad[:,0], ibad[:,1]] = xfill
return self
def _set_start_end_dates(self, varname):
'''
'''
#print 'varname', varname
self._start_date = self.read_nc(varname, '[0]')
#print 'fff',self._start_date.dtype
#print self._start_date
#aaaa
try:
self._end_date = self.read_nc(varname, '[-1]')
except Exception:
self._end_date = self._start_date
return self
def datenum(self):
return self._datenum
def _date2num(self, date):
'''
Convert CFSR 'valid_date_time' to datenum
Input: date : ndarray (e.g., "'2' '0' '1' '0' '1' '2' '3' '1' '1' '8'")
'''
#print 'dateee',date, date.size
assert (isinstance(date, np.ndarray) and
date.size == 10), 'date must be size 10 ndarray'
return dt.date2num(dt.datetime.datetime(np.int(date.tostring()[:4]),
np.int(date.tostring()[4:6]),
np.int(date.tostring()[6:8]),
np.int(date.tostring()[8:10])))
def _get_time_series(self):
'''
'''
#print 'self._start_date', self._start_date
date0 = self._date2num(self._start_date)
date1 = self._date2num(self._end_date)
datelen = self.read_dim_size('time')
datenum = np.linspace(date0, date1, datelen)
return datenum
#if np.unique(np.diff(datenum)).size == 1:
#return datenum
#else:
#raise 'dsdsdsd'
def get_delaunay_tri(self):
'''
'''
self.points_all = np.copy(self.points)
self.tri_all = sp.Delaunay(self.points_all)
self.points = np.array([self.points[:,0].flat[self.cfsrmsk.cfsr_ball],
self.points[:,1].flat[self.cfsrmsk.cfsr_ball]]).T
self.tri = sp.Delaunay(self.points)
return self
def reshape2roms(self):
'''
Following interpolation with horizInterp() we need to
include land points and reshape
'''
self.dataout = self.dataout.reshape(self.romsgrd.lon().shape)
return self
def _check_for_nans(self):
'''
'''
flat_mask = self.romsgrd.maskr().ravel()
assert not np.any(np.isnan(self.dataout[np.nonzero(flat_mask)])
), 'Nans in self.dataout sea points'
self.dataout[:] = np.nan_to_num(self.dataout)
return self
def _interp2romsgrd(self):
'''
'''
ball = self.cfsrmsk.cfsr_ball
interp = horizInterp(self.tri, self.datain.flat[ball])
self.dataout[self.romsgrd.idata()] = interp(self.romsgrd.points)
return self
def interp2romsgrd(self, fillmask=False):
'''
'''
if fillmask:
self.fillmask()
self._interp2romsgrd()
self._check_for_nans()
return self
def check_interp(self):
'''
'''
fac = 5
cmap = plt.cm.gist_ncar
rlonmin, rlonmax = self.romsgrd.lon().min(), self.romsgrd.lon().max()
rlatmin, rlatmax = self.romsgrd.lat().min(), self.romsgrd.lat().max()
cfsri0, cfsri1 = (np.argmin(np.abs(self.lon()[0] - rlonmin)) - fac,
np.argmin(np.abs(self.lon()[0] - rlonmax)) + fac)
cfsrj0, cfsrj1 = (np.argmin(np.abs(self.lat()[:,0] - rlatmin)) - fac,
np.argmin(np.abs(self.lat()[:,0] - rlatmax)) + fac)
cfsr = np.ma.masked_where(self.maskr() == 0, self.datain.copy())
try:
roms = np.ma.masked_where(self.romsgrd.maskr() == 0,
self.dataout.copy())
except Exception:
roms = np.ma.masked_where(self.romsgrd.maskr() == 0,
self.dataout.reshape(self.romsgrd.maskr().shape))
cmin, cmax = roms.min(), roms.max()
plt.figure()
plt.pcolormesh(self.lon()[cfsrj0:cfsrj1, cfsri0:cfsri1],
self.lat()[cfsrj0:cfsrj1, cfsri0:cfsri1],
cfsr[cfsrj0:cfsrj1, cfsri0:cfsri1], cmap=cmap, edgecolors='w')
plt.clim(cmin, cmax)
plt.pcolormesh(self.romsgrd.lon(), self.romsgrd.lat(), roms, cmap=cmap)
plt.clim(cmin, cmax)
plt.axis('image')
plt.colorbar()
plt.show()
def get_date_index(self, other, ind):
'''
'''
return np.nonzero(self.datenum() == other.datenum()[ind])[0][0]
def _get_metrics(self):
'''Return array of metrics unique to this grid
(lonmin, lonmax, lon_res, latmin, latmax, lat_res)
where 'res' is resolution in degrees
'''
self_shape = self._lon.shape
lon_range = self.read_nc_att('lon', 'valid_range')
lon_mean, lat_mean = (self._lon.mean().round(2),
self._lat.mean().round(2))
res = np.diff(lon_range) / self._lon.shape[1]
self.metrics = np.hstack((self_shape[0], self_shape[1], lon_mean, lat_mean, res))
return self
def _read_cfsr_frc(self, var, ind):
''' Read CFSR forcing variable (var) at record (ind)
'''
return self.read_nc(var, '[' + str(ind) + ']')[::-1]
def _get_cfsr_data(self, varname):
''' Get CFSR data with explicit variable name
'''
# Fill the mask
#outvar = self.fillmask(outvar, self.outmask, flags[cfsr_key])
return self._read_cfsr_frc(varname, self.tind)
def _get_cfsr_datatmp(self):
''' Get CFSR data with implicit variable name
'''
self.datatmp[:] = self._read_cfsr_frc(self.varname, self.tind-1)
return self
def get_cfsr_data(self):
''' Get CFSR data with implicit variable name
'''
self.datain[:] = self._read_cfsr_frc(self.varname, self.tind)
if self.needs_time_averaging:
self._get_cfsr_datatmp()
self._get_data_time_average()
return self
def set_date_index(self, dt):
try:
self.tind = np.nonzero(self.datenum() == dt)[0][0]
except Exception:
raise # dt out of range in CFSR file
else:
return self
def vd_time(self):
'''
Valid date and time as YYYYMMDDHH
'''
return self.read_nc('valid_date_time')
def time(self):
'''
Hours since 1979-01-01 00:00:00.0 +0:00
'''
return self.read_nc('time')
def check_vars_for_downscaling(self, var_instances):
'''Loop over list of grids to find which have
dimensions different from self
'''
for ind, each_grid in enumerate(var_instances):
if np.any(each_grid.metrics != self.metrics):
each_grid.to_be_downscaled = True
return self
def dQdSST(self, sst, sat, rho_air, U, qsea):
'''
Compute the kinematic surface net heat flux sensitivity to the
the sea surface temperature: dQdSST.
Q_model ~ Q + dQdSST * (T_model - SST)
dQdSST = - 4 * eps * stef * T^3 - rho_air * Cp * CH * U
- rho_air * CE * L * U * 2353 * ln (10 * q_s / T^2)
Input parameters:
sst : sea surface temperature (Celsius)
sat : sea surface atmospheric temperature (Celsius)
rho_air : atmospheric density (kilogram meter-3)
U : wind speed (meter s-1)
qsea : sea level specific humidity (kg/kg)
Output:
dqdsst : kinematic surface net heat flux sensitivity to the
the sea surface temperature (Watts meter-2 Celsius-1)
From Roms_tools of Penven etal
'''
# SST (Kelvin)
sst = np.copy(sst)
sst += self.Kelvin
# Latent heat of vaporisation (J.kg-1)
L = np.ones(sat.shape)
L *= self.L1
L -= (self.L2 * sat)
# Infrared contribution
q1 = -4.
# Multiply by Stefan constant
q1 *= self.Stefan
q1 *= np.power(sst, 3)
# Sensible heat contribution
q2 = -rho_air
q2 *= self.Cp
q2 *= self.Ch
q2 *= U
# Latent heat contribution
dqsdt = 2353.
dqsdt *= np.log(10.)
dqsdt *= qsea
dqsdt /= np.power(sst, 2)
q3 = -rho_air
# Multiply by Ce (Latent heat transfer coefficient, stable condition)
q3 *= self.Ce
q3 *= L
q3 *= U
q3 *= dqsdt
dQdSST = q1
dQdSST += q2
dQdSST += q3
return dQdSST
class CfsrMask(CfsrData):
'''Mask class (inherits from CfsrData class)
'''
def __init__(self, cfsr_dir, mask_file, romsgrd, balldist):
super(CfsrMask, self).__init__(cfsr_dir + mask_file[0], mask_file[1], 'CFSR', romsgrd)
self.tind = 0
self.get_cfsr_data()
self.balldist = balldist
self.romsgrd = romsgrd
self._maskr = np.abs(self.datain - 1)
#self.maskr()
self.proj2gnom(ignore_land_points=False, M=romsgrd.M)
self.make_kdetree()
self.has_ball = False
self.get_kde_ball()
self.cfsrmsk = None
self.get_fillmask_cof(self.maskr())
def get_kde_ball(self):
'''
'''
self.cfsr_ball = self.kdetree.query_ball_tree(self.romsgrd.kdetree, self.balldist)
self.cfsr_ball = np.array(self.cfsr_ball).nonzero()[0]
self.has_ball = True