forked from evanmason/pyroms2roms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpycfsr2frc.py.orig
1637 lines (1254 loc) · 63.2 KB
/
pycfsr2frc.py.orig
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
'''
Create a forcing file based on CFSR data
E. Mason IMEDEA 2012
'''
import netCDF4 as netcdf
import pylab as plt
import numpy as np
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
#import collections
from mpl_toolkits.basemap import Basemap
from collections import OrderedDict
from datetime import datetime
import calendar as ca
from pyroms2roms import horizInterp
from pyroms2roms import ROMS, debug0, debug1
from pyroms2roms import RomsGrid, RomsData
class RomsGrid(RomsGrid):
'''
Modify the RomsGrid class
'''
def create_frc_nc(self, frcfile, sd, ed, nr, cl, madeby):
'''
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
'''
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 = 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)
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()
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']
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, 'f8', dims)
nc.variables[key].long_name = value[2]
nc.variables[key].units = value[3]
if 'time' in key:
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]
nc.close()
def gc_dist(self, lon1, lat1, lon2, lat2):
'''
Use Haversine formula to calculate distance
between one point and another
'''
r_earth = 6371315. # 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):
'''
'''
mon -= 1
area = 1. / (self.pm() * self.pn())
dx = 1. / np.mean(self.pm())
cdist = io.loadmat(self.roms_dir + 'coast_distances.mat')
mask = self.mask()
# Exponential decay, runoff forced towards coast. 75km ?
mult = np.exp(-cdist['cdist'] / 150e4)
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
bool_mask = np.logical_and(dist < scale, mask > 0)
int_are = np.sum(area[bool_mask])
ave_wgt = np.mean(mult[bool_mask])
surface_flux = 1e6 * runoff[idx] / int_are
surf_ro[bool_mask] = surf_ro[bool_mask] + surface_flux / \
flux_unit * mult[bool_mask] / ave_wgt
return (swflux_data * mask) - (surf_ro * mask)
class CfsrGrid(RomsGrid):
'''
CFSR grid class (inherits from RomsGrid class)
'''
def _lonlat(self):
lon = self.read_nc('lon', indices='[:]')
lat = self.read_nc('lat', indices='[:]')
return np.meshgrid(lon, lat[::-1])
def lon(self):
return self._lonlat()[0]
def lat(self):
return self._lonlat()[1]
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
'''
met = np.array([])
lon_range = self.read_nc_att('lon', 'valid_range')
lat_range = self.read_nc_att('lat', 'valid_range')
lon_res = np.diff(lon_range) / self.lon().shape[1]
lat_res = np.diff(lat_range) / self.lat().shape[0]
met = np.concatenate((lon_range, lon_res, lat_range, lat_res))
return met
def select_mask(self, grids, masks):
'''
'''
for gind, grid in enumerate(grids):
if np.alltrue(grid.metrics() == self.metrics()):
mask = masks[gind]
try:
return mask.get_mask()
except Exception, err:
print 'Unspecified grid in method "select_mask"'
to_do__make_routine_to_add_new_grid_on_the_fly
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_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 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 frc_emp(self, ind):
'''
evaporation minus precipitation in cm/day
'''
return self.read_nc('EMNP_L1', '[' + str(ind) + ']')[::-1]
def frc_sat(self, ind):
'''
air temperature (K)
'''
try:
return self.read_nc('TMP_L103_Avg', '[' + str(ind) + ']')[::-1]
except Exception:
return self.read_nc('TMP_L103', '[' + str(ind) + ']')[::-1]
def frc_sap(self, ind):
'''
surface air pressure (Pa)
'''
try:
return self.read_nc('PRES_L1', '[' + str(ind) + ']')[::-1]
except Exception:
return self.read_nc('PRES_L1_Avg', '[' + str(ind) + ']')[::-1]
def frc_sss(self, ind):
'''
sea surface salinity (kg kg-1)
'''
return self.read_nc('SALTY_L160', '[' + str(ind) + ']')[::-1]
def frc_sst(self, ind):
'''
sea surface temperature (K)
'''
return self.read_nc('TMP_L1', '[' + str(ind) + ']')[::-1]
def frc_uspd(self, ind):
'''
u 10-m wind speed (m s-1)
'''
return self.read_nc('U_GRD_L103_Avg', '[' + str(ind) + ']')[::-1]
def frc_vspd(self, ind):
'''
v 10-m wind speed (m s-1)
'''
return self.read_nc('V_GRD_L103_Avg', '[' + str(ind) + ']')[::-1]
def frc_shf(self, ind):
'''
net surface heat flux (W m-2)
'''
return self.read_nc('LHTFL_L1', '[' + str(ind) + ']')[::-1]
def frc_shflux_SW_up(self, ind):
'''
upward shortwave radiation flux (W m-2)
'''
return self.read_nc('USWRF_L1', '[' + str(ind) + ']')[::-1]
def frc_shflux_SW_down(self, ind):
'''
downward shortwave radiation flux (W m-2)
'''
return self.read_nc('DSWRF_L1', '[' + str(ind) + ']')[::-1]
def frc_shflux_LW_up(self, ind):
'''
upward longwave radiation flux (W m-2)
'''
return self.read_nc('ULWRF_L1', '[' + str(ind) + ']')[::-1]
def frc_shflux_LW_down(self, ind):
'''
downward longwave radiation flux (W m-2)
'''
return self.read_nc('DLWRF_L1', '[' + str(ind) + ']')[::-1]
def frc_shflux_LH(self, ind):
'''
latent heat (W m-2)
'''
return self.read_nc('LHTFL_L1', '[' + str(ind) + ']')[::-1]
def frc_shflux_SH(self, ind):
'''
sensible heat (W m-2)
'''
return self.read_nc('SHTFL_L1', '[' + str(ind) + ']')[::-1]
def frc_qair(self, ind):
'''
sea level specific humidity (kg kg-1)
'''
return self.read_nc('SPF_H_L103', '[' + str(ind) + ']')[::-1]
def frc_rel_hum(self, ind):
'''
relative humidity (%)
'''
return self.read_nc('R_H_L103', '[' + str(ind) + ']')[::-1]
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 get_mask(self):
'''
Return a land sea mask
'''
try:
result = self.read_nc('LAND_L1', '[0,::-1]')
return np.abs(result - 1.)
except Exception:
try:
result = self.read_nc('LAND_L1_Avg', '[0,::-1]')
return np.abs(result - 1.)
except Exception:
try:
result = self.read_nc('SALTY_L160', '[0,::-1]')
return np.abs(result.mask - 1.)
except Exception, err:
print 'undefined grid'
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
'''
# Specific heat of atmosphere.
Cp = 1004.8
# Sensible heat transfer coefficient (stable condition)
Ch = 0.66e-3
# Latent heat transfer coefficient (stable condition)
Ce = 1.15e-3
# Emissivity coefficient
eps = 0.98
# Stefan constant
stef = 5.6697e-8
# SST (Kelvin)
SST = sst + 273.15
# Latent heat of vaporisation (J.kg-1)
L = 2.5008e6 - 2.3e3 * sat
# Infrared contribution
q1 = -4. * stef * np.power(SST, 3)
# Sensible heat contribution
q2 = -rho_air * Cp * Ch * U
# Latent heat contribution
dqsdt = 2353. * np.log(10.) * qsea / np.power(SST, 2)
q3 = -rho_air * Ce * L * U * dqsdt
dQdSST = q1 + q2 + q3
return dQdSST
"""
def get_W3(self, roms_tools_W3, uspd_pts, uspd_mask):
'''
Get monthly point means of Roms_tools W3 over the CFSR domain
'''
"""
class AirSea(object):
'''
'''
def __init__(self):
'''
Constants from:
http://woodshole.er.usgs.gov/operations/sea-mat/air_sea-html/as_consts.html
'''
# ------- physical constants
self.g = 9.8 # acceleration due to gravity [m/s^2]
self.eps_air = 0.62197 # molecular weight ratio (water/air)
self.CtoK = 273.15 # conversion factor for [C] to [K]
self.gas_const_R = 287.04 # gas constant for dry air [J/kg/K]
# ------- meteorological constants
self.z = 10. # default measurement height [m]
self.kappa = 0.4 # von Karman's constant
self.Charnock_alpha = 0.011 # Charnock constant (for determining roughness length
''' at sea given friction velocity), used in Smith
formulas for drag coefficient and also in Fairall
and Edson. use alpha=0.011 for open-ocean and
alpha=0.018 for fetch-limited (coastal) regions.'''
self.R_roughness = 0.11 # limiting roughness Reynolds # for aerodynamically
''' smooth flow'''
# ------ defaults suitable for boundary-layer studies
self.cp = 1004.7 # heat capacity of air [J/kg/K]
self.rho_air = 1.22 # air density (when required as constant) [kg/m^2]
self.Ta = 10. # default air temperature [C]
self.Pa = 1020. # default air pressure for Kinneret [mbars]
self.psych_default = 'screen' # default psychmometer type (see relhumid.m)
# satur. specific humidity coefficient reduced by 2% over salt water
self.Qsat_coeff = 0.98
def viscair(self):
'''
vis=VISCAIR(Ta) computes the kinematic viscosity of dry air as a
function of air temperature following Andreas (1989), CRREL Report
89-11.
INPUT: Ta - air temperature [C]
OUTPUT: vis - air viscosity [m^2/s]
'''
return 1.326e-5 * (1 + 6.542e-3 * self.Ta + 8.301e-6 * np.power(self.Ta, 2) -
4.84e-9 * np.power(self.Ta, 3))
def cdntc(self, sp):
'''
cd, u10 = cdntc(sp, z ,Ta) computes the neutral drag coefficient and
wind speed at 10m given the wind speed and air temperature at height z
following Smith (1988), J. Geophys. Res., 93, 311-326.
INPUT: sp - wind speed [m/s]
self.z - measurement height [m]
self.Ta - air temperature (optional) [C]
OUTPUT: cd - neutral drag coefficient at 10m
u10 - wind speed at 10m [m/s]
'''
sp = np.asarray(sp)
# iteration endpoint
tol = np.asarray(.00001)
visc = self.viscair()
# remove any sp==0 to prevent division by zero
np.place(sp, sp == 0, 0.1)
# initial guess
ustaro = np.zeros(sp.shape)
ustarn = .036 * sp
# iterate to find z0 and ustar
ii = np.abs(ustarn - ustaro) > tol
while np.any(ii):
ustaro = ustarn
z0 = self.Charnock_alpha * np.power(ustaro, 2) / self.g + \
self.R_roughness * visc / ustaro
ustarn = sp * (self.kappa / np.log(self.z / z0))
ii = np.abs(ustarn - ustaro) > tol
sqrcd = self.kappa / np.log((10.) / z0)
cd = np.power(sqrcd, 2)
u10 = ustarn / sqrcd
return cd, u10
def stresstc(self, u, v, Ta=None, rho_air=None):
'''
taux, tauy = stresstc(u, v) computes the neutral wind stress given the
wind speed and air temperature at height z following Smith (1988),
J. Geophys. Res., 93, 311-326. Air temperature and density are optional
inputs.
INPUT: u, v - wind speed components [m/s]
z - measurement height [m]
Ta - air temperature (optional) [C]
rho_air - air density (optional) [kg/m^3]
OUTPUT: taux, tauy - wind stress components [N/m^2]
Adapted from http://woodshole.er.usgs.gov/operations/sea-mat/air_sea-html/as_consts.html
'''
sp = np.hypot(u, v)
if Ta is not None:
self.Ta = Ta
cd, u10 = self.cdntc(sp)
if rho_air is None:
taux = self.rho_air * cd * u * u10
tauy = self.rho_air * cd * v * u10
else:
taux = rho_air * cd * u * u10
tauy = rho_air * cd * v * u10
return taux, tauy
def air_dens(self, Ta, RH, Pa=None, Q=None):
'''
rhoa=AIR_DENS(Ta,RH,Pa) computes the density of moist air.
Air pressure is optional.
INPUT: Ta - air temperature Ta [C]
RH - relative humidity [%]
Pa - air pressure (optional) [mb]
OUTPUT: rhoa - air density [kg/m^3]
'''
if Pa is not None:
self.Pa = Pa # pressure in mb
if Q is None:
Q = (0.01 * RH) * self.qsat(Ta, Pa) # specific humidity of air [kg/kg]
o61 = 1. / self.eps_air - 1. # 0.61 (moisture correction for temp.)
T = Ta + self.CtoK # convert to K
Tv = T * (1. + o61 * Q) # air virtual temperature
rhoa = (100. * self.Pa) / (self.gas_const_R * Tv) # air density [kg/m^3]
return rhoa
def qsat(self, Ta, Pa=None):
'''
QSAT: computes specific humidity at saturation.
q=QSAT(Ta) computes the specific humidity (kg/kg) at saturation at
air temperature Ta (deg C). Dependence on air pressure, Pa, is small,
but is included as an optional input.
INPUT: Ta - air temperature [C]
Pa - (optional) pressure [mb]
OUTPUT: q - saturation specific humidity [kg/kg]
Version 1.0 used Tetens' formula for saturation vapor pressure
from Buck (1981), J. App. Meteor., 1527-1532. This version
follows the saturation specific humidity computation in the COARE
Fortran code v2.5b. This results in an increase of ~5% in
latent heat flux compared to the calculation with version 1.0.
'''
if Pa is not None:
self.Pa = Pa # pressure in mb
# as in Fortran code v2.5b for COARE
ew = 6.1121 * (1.0007 + 3.46e-6 * self.Pa) * np.exp((17.502 * Ta) / \
(240.97 + Ta)) # in mb
q = 0.62197 * (ew / (self.Pa - 0.378 * ew)) # mb -> kg/kg
return q
def delq(self, Ts, Ta, rh, Pa=None):
'''
dq=DELQ(Ts,Ta,rh) computes the specific humidity (kg/kg) difference
between the air (as determined by relative humidty rh and air
temperature Ta measurements) and the sea surface (where q is
assumed to be at 98% saturation at the sea surface temperature Ts).
DELQ uses QSAT based on Tetens' formula for saturation vapor
pressure from Buck (1981), J. App. Meteor., 1527-1532. The
dependence of QSAT on pressure is small (<0.5%) and has been
removed using a mean pressure of 1020 mb.
INPUT: Ts - sea surface temperature [C]
Ta - air temperature [C]
rh - relative humidity [%]
Pa - (optional) pressure [mb]
OUTPUT: dq - air-sea specific humidity difference [kg/kg]
'''
if Pa is not None:
self.Pa = Pa # pressure in mb
dq = 0.01 * rh * self.qsat(Ta, self.Pa) - \
self.Qsat_coeff * self.qsat(Ts, self.Pa)
return dq
if __name__ == '__main__':
'''
pycfsr2frc
Prepare interannual ROMS surface forcing with CFSR data from
http://rda.ucar.edu/pub/cfsr.html
CFSR surface data for ROMS forcing are global but subgrids can be
selected. User must supply a list of the files available, pycfsr2frc
will loop through the list, sampling and interpolating each variable.
ROMS needs the following variables:
EP : evaporation - precipitation
Net heat flux
Qnet = SW - LW - LH - SH
where SW denotes net downward shortwave radiation,
LW net downward longwave radiation,
LH latent heat flux,
and SH sensible heat flux
Note that there are dependencies for:
dQdSS <-
CFSR grids, for info see http://rda.ucar.edu/datasets/ds093.2/docs/moly_filenames.html
Horizontal resolution indicator, 4th character of filename:
h - high (0.5-degree) resolution
a - high (0.5-degree) resolution, spl type only
f - full (1.0-degree) resolution
l - low (2.5-degree) resolution
But some files labelled 'l' are in fact 0.3-degree, eg, UWND, VWND...
Notes about the data quality:
1) The 0.3deg flxf06.gdas.DSWRF.SFC.grb2.nc is ugly
Evan Mason, IMEDEA, 2012
'''
#_USER DEFINED VARIABLES_______________________________________
# CFSR information_________________________________
#cfsr_dir = '/Users/emason/toto/'
#cfsr_dir = '/shared/emason/NCEP-CFSR/'
cfsr_dir = '/shared/emason/NCEP-CFSR/S-14_N56__W-63_E12/'
# Filenames of needed CFSR variables
SSS = 'ocnh01.gdas.SALTY.5m.grb2.nc'
swflux = 'ocnh01.gdas.EMNP.SFC.grb2.nc'
shflux_SW_down = 'flxl01.gdas.DSWRF.SFC.grb2.nc'
shflux_SW_up = 'flxl01.gdas.USWRF.SFC.grb2.nc'
shflux_LW_down = 'flxl01.gdas.DLWRF.SFC.grb2.nc'
shflux_LW_up = 'flxl01.gdas.ULWRF.SFC.grb2.nc'
shflux_LH = 'flxl01.gdas.LHTFL.SFC.grb2.nc'
shflux_SH = 'flxl01.gdas.SHTFL.SFC.grb2.nc'
#sustr = 'flxf01.gdas.UWND.10m.grb2.nc' # use for MedSea
#svstr = 'flxf01.gdas.VWND.10m.grb2.nc' # use for MedSea
sustr = 'flxf01.gdas.WND.10m.grb2.nc' # use for NEA
svstr = 'flxf01.gdas.WND.10m.grb2.nc' # use for NEA
#SST = 'pgbh01.gdas.TMP.SFC.grb2.nc' # use for MedSea
SST = 'ocnh01.gdas.TMP.SFC.grb2.nc' # use for NEA
# Surface air temperature
# file 'flxf01.gdas.TMP.2m.grb2.nc' compares well with Roms_tools sat.cdf
#sat = 'flxf01.gdas.TMP.2m.grb2.nc' # use for MedSea
sat = 'pgbh01.gdas.TMP.2m.grb2.nc' # use for NEA
# Relative humidity
# file 'pgbh01.gdas.R_H.2m.grb2.nc' compares well with Roms_tools rh.cdf
rel_hum = 'pgbh01.gdas.R_H.2m.grb2.nc'
#sap = 'pgbhnl.gdas.PRES.SFC.grb2.nc' # use for MedSea
sap = 'flxf01.gdas.PRES.SFC.grb2.nc' # use for NEA
qair = 'flxf01.gdas.SPF_H.2m.grb2.nc'
# Filenames of masks for the 1.0, 0.5 and 0.3 degree grids
mask10 = 'pgbl01.gdas.LAND.SFC.grb2.nc'
mask05 = 'pgbh01.gdas.LAND.SFC.grb2.nc'
mask03 = 'flxf01.gdas.LAND.SFC.grb2.nc'
mask1_8 = 'flxl01.gdas.LAND.SFC.grb2.nc'
maskocn = 'ocnh01.gdas.SALTY.5m.grb2.nc'
# ROMS configuration information_________________________________
#roms_dir = '/marula/emason/runs2012/MedSea15/'
#roms_dir = '/shared/emason/marula/emason/runs2012/MedSea5/'
#roms_dir = '/home/emason/runs2012_tmp/MedSea5_R2.5/'
#roms_dir = '/marula/emason/runs2013/na_7pt5km_intann_5day/'
#roms_dir = '/Users/emason/toto/'
roms_dir = '/marula/emason/runs2013/cb_3km_2013_intann/'
#roms_grd = 'grd_MedSea5_R2.5.nc'
#roms_grd = 'roms_grd_NA2009_7pt5km.nc'
roms_grd = 'cb_2009_3km_grd_smooth.nc'
# Forcing file
#frc_filename = 'frc_intann_MedSea5.nc' # ini filename
#frc_filename = 'frc_CFSR_NA_7pt5km.nc'
frc_filename = 'frc_2013_cb3km_CFSR.nc'
# True if the frc file being prepared is for a downscaled simulation
downscaled = True
if downscaled:
# Point to parent directory, where pyccmp2frc expects to find
# start_date.mat (created by set_ROMS_interannual_start.py)
par_dir = '/marula/emason/runs2013/na_7pt5km_intann_5day/'
# Start and end dates of the ROMS simulation
# must be strings, format 'YYYYMMDDHH'
#start_date = '1985010100'
#end_date = '2010010100'
start_date = '1997010100'
end_date = '2000123100'
# Flag to 360-day years
make360 = False
cycle_length = 0
# Option for river runoff climatology
# Note, a precomputed *coast_distances.mat* must be available
# in roms_dir; this is computed using XXXXXX.py
add_dai_runoff = True # True of False
if add_dai_runoff:
dai_file = '/home/emason/matlab/runoff/dai_runoff_mon_-180+180.nc'
#dai_file = '/home/emason/matlab/runoff/dai_runoff_mon_0_360.nc'
# interpolation / processing parameters_________________________________
balldist = 250000. # distance (m) for kde_ball (should be 2dx at least?)
# Filling of landmask options
# Set to True to extrapolate sea data over land
wind_fill_mask = False # 10 m
sat_fill_mask = True # 2 m
rel_hum_fill_mask = True # 2 m
qair_fill_mask = True # 2 m
windspd_fill_mask = True # surface
"""
# Use climatological scalar wind from Roms_tools for dQdSST calculation
use_roms_tools_W3 = True
if use_roms_tools_W3:
roms_tools_W3 = '/home/emason/roms/Roms_tools/COADS05/w3.cdf'
"""
#_END USER DEFINED VARIABLES_______________________________________
plt.close('all')
# This dictionary of CFSR files needs to supply some or all of the surface
# forcing variables variables:
cfsr_files = OrderedDict([
('SSS', SSS),
('swflux', swflux),
('shflux', OrderedDict([
('shflux_SW_down', shflux_SW_down),
('shflux_SW_up', shflux_SW_up),
('shflux_LW_down', shflux_LW_down),
('shflux_LW_up', shflux_LW_up),
('shflux_LH', shflux_LH),
('shflux_SH', shflux_SH)])),
('dQdSST', OrderedDict([
('sustr', sustr),
('svstr', svstr),
('SST', SST),
('sat', sat),
('rel_hum', rel_hum),
('sap', sap),
('qair', qair)]))])
'''cfsr_files = OrderedDict([
('SSS', SSS),
('dQdSST', OrderedDict([
('sustr', sustr),
('svstr', svstr),
('SST', SST),
('sat', sat),
('rel_hum', rel_hum),
('sap', sap),
('qair', qair)]))])'''
# masks for the 1.0, 0.5 and 0.3 degree grids
cfsr_masks = OrderedDict([
('mask10', mask10),
('mask05', mask05),
('mask03', mask03),