/
afim.py
executable file
·2680 lines (2411 loc) · 138 KB
/
afim.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
'''
This is a python module for functions and objects (classes) that are beneficial
to the Antarctica Fast Ice Modelling that I'm doing for my PhD.
author: dpath2o, daniel.atwater@utas.edu.au, May 2022
'''
import os
import re
import json
import pdb
import logging
import time
import pygmt
import numpy as np
import xarray as xr
import xesmf as xe
import pandas as pd
import metpy.calc as mpc
import cosima_cookbook as cc
import matplotlib.pyplot as plt
import cmocean as cm
import cartopy.crs as ccrs
import cartopy.feature as cft
import matplotlib.path as mpath
from datetime import datetime, timedelta, date
from dateutil.relativedelta import relativedelta
from dask.diagnostics import ProgressBar
from matplotlib.animation import FuncAnimation
############################################################################
# globals
ncrcat = os.path.join('/','apps','nco','5.0.5','bin','ncrcat')
##############################################################################################################################################
######################################################## NON-CLASS FUNCTIONS #################################################################
##############################################################################################################################################
def days_since_1601_to_date(days_since_1601):
"""
Converts a given number of days since January 1, 1601, to a human-readable date format.
Parameters:
days_since_1601 (int): The number of days since January 1, 1601.
Output:
Prints the calculated date in the YYYY-MM-DD format.
"""
start_date = date(1601, 1, 1)
offset = timedelta(days=days_since_1601)
result_date = start_date + offset
print(result_date.strftime("%Y-%m-%d"))
############################################################################
def plot_cartopy_pcolormesh(da=None, lon_name='longitude', lat_name='latitude',
figsize=(10,6), region=[0,360,-90,-50], t_str=None, projection=ccrs.SouthPolarStereo(),
cmap=cm.cm.ice, vmin=0, vmax=1, cbar_label='Sea Ice Concentration (%)',
title="", D_save=None, F_save=None, save=True, show=True):
fig, ax = plt.subplots(1,1, figsize=figsize, dpi=150, facecolor="w", subplot_kw=dict(projection=projection))
theta = np.linspace(0, 2*np.pi, 100)
center, radius = [0.5, 0.5], 0.5
verts = np.vstack([np.sin(theta), np.cos(theta)]).T
circle = mpath.Path(verts * radius + center)
ax.set_extent(region, ccrs.PlateCarree())
ax.set_boundary(circle, transform = ax.transAxes)
ax.add_feature(cft.LAND, color='darkgrey')
ax.add_feature(cft.COASTLINE, linewidth=.5)
pcm = ax.pcolormesh(da[lon_name], da[lat_name], da, cmap=cmap, vmin=vmin, vmax=vmax, transform=ccrs.PlateCarree())
plt.colorbar(pcm, label=cbar_label)
plt.title(title)
ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=1, color='gray', alpha=0.25, linestyle='--')
if save:
if not os.path.exists(D_save): os.makedirs(D_save)
plt.savefig(os.path.join(D_save,F_save))
if show:
plt.show()
plt.close()
############################################################################
def compute_nsdic_grid_cell_areas(ds, proj_str):
"""
Computes the area of each grid cell in a given dataset using a specific projection string.
Parameters:
ds (xarray.Dataset): The dataset containing grid information.
proj_str (str): The PROJ string describing the coordinate system.
Returns:
numpy.ndarray: 2D array containing the area of each grid cell.
"""
a = 6378273
b = 6356889.449
geod = Geod(a=a, b=b)
x_vals = ds['xgrid'].values
y_vals = ds['ygrid'].values
dx = ds['xgrid'].diff('x').fillna(0)
dx_vals = np.append(dx, dx[-1]) # Repeat the last value
dy = ds['ygrid'].diff('y').fillna(0)
dy_vals = np.append(dy, dy[-1]) # Repeat the last value
proj = pyproj.Proj(proj_str)
A = np.zeros((len(y_vals), len(x_vals)))
for i in range(len(y_vals)):
for j in range(len(x_vals)):
x = x_vals[j]
y = y_vals[i]
dx = dx_vals[j]
dy = dy_vals[i]
# Define the four corners of the cell
lon1, lat1 = proj(x, y, inverse=True)
lon2, lat2 = proj(x + dx, y, inverse=True)
lon3, lat3 = proj(x + dx, y + dy, inverse=True)
lon4, lat4 = proj(x, y + dy, inverse=True)
# Calculate the perimeter of the cell
perimeter = geod.line_length([lon1, lon2, lon3, lon4, lon1], [lat1, lat2, lat3, lat4, lat1])
# Calculate the area of the cell using Brahmagupta's formula
s = perimeter / 2
a, _, _ = geod.inv(lon1, lat1, lon2, lat2)
b, _, _ = geod.inv(lon2, lat2, lon3, lat3)
c, _, _ = geod.inv(lon3, lat3, lon4, lat4)
d, _, _ = geod.inv(lon4, lat4, lon1, lat1)
A[i,j] = np.sqrt((s - a) * (s - b) * (s - c) * (s - d))
return A
############################################################################
# Function to compare a CICE run with NSDIC
def compare_cice_nsdic(P_cice, NSDIC, grid_areas, proj_str, dt0='', dtN='', threshold=0.15, cice_reG_var='aice_m'):
"""
Compares CICE model output with NSIDC observations.
Parameters:
P_cice (str): Path to CICE model output files.
NSDIC (xarray.Dataset): NSIDC observation dataset.
grid_areas (numpy.ndarray): 2D array containing the area of each grid cell.
proj_str (str): The PROJ string describing the coordinate system.
dt0 (str): The start date for slicing time, format YYYY-MM-DD. Default is an empty string.
dtN (str): The end date for slicing time, format YYYY-MM-DD. Default is an empty string.
threshold (float): Threshold for masking ice concentration. Default is 0.15.
cice_reG_var (str): CICE variable name for regridding. Default is 'aice_m'.
Returns:
xarray.DataArray: Regridded CICE sea ice area extent data.
"""
CICE = xr.open_mfdataset(P_cice, decode_coords=False)
time_index = pd.DatetimeIndex(CICE['time'].values)
adjusted_time = time_index - pd.DateOffset(months=1)
CICE['time'] = adjusted_time.values
mask = (CICE['TLAT'] < 0).compute()
CICE = CICE.sel(time=slice(dt0,dtN))
CICE_SH = CICE.where(mask, drop=True)
#Convert xgrid and ygrid to latitude and longitude, and add the new coordinates to NSDIC Dataset
in_proj = pyproj.Proj(proj_str)
out_proj = pyproj.Proj(proj="latlong", datum="WGS84")
transformer = pyproj.Transformer.from_proj(in_proj, out_proj, always_xy=True)
xx, yy = np.meshgrid(NSDIC['xgrid'].values, NSDIC['ygrid'].values) # Make sure x_vals and y_vals are defined
lon_vals, lat_vals = transformer.transform(xx, yy)
NSDIC['latitude'] = (('y', 'x'), lat_vals)
NSDIC['longitude'] = (('y', 'x'), lon_vals)
# Define source grid from the subsetted CICE6 data
src_grid = xr.Dataset({'lat': (['nj', 'ni'], CICE_SH['TLAT'][0].values), 'lon': (['nj', 'ni'], CICE_SH['TLON'][0].values)})
# Define destination grid from NSIDC
dst_grid = xr.Dataset({'lat': (['y', 'x'], lat_vals), 'lon': (['y', 'x'], lon_vals)})
# Create regridder object
regridder = xe.Regridder(src_grid, dst_grid, method='bilinear', periodic=False)
# reG
reG_aice = regridder(CICE_SH[cice_reG_var])
# Maskthe concentration data based on threshold for CICE6. Then computing sea ice area extent of CICE6, which requires the above cell to be run first
mask_CICE = reG_aice > threshold
reG_aice['sea_ice_area_extent'] = (mask_CICE * reG_aice * grid_areas).sum(dim=['y', 'x'])/1e7
return reG_aice
############################################################################
def compute_cice_area(CICE='',
threshold=0.15,
hemisphere='sp',
monthly=True):
"""
Computes the total ice area based on a given threshold concentration and specified hemisphere.
Parameters:
CICE (xarray.Dataset): The dataset containing CICE model variables.
threshold (float): The threshold for ice concentration. Default is 0.15.
hemisphere (str): Specifies the hemisphere ('sp' for South Pole, 'np' for North Pole). Default is 'sp'.
monthly (bool): Indicates whether to use monthly ('aice_m') or general ('aice') variable. Default is True.
Returns:
float: The total area of ice in the specified hemisphere that exceeds the threshold concentration.
"""
if hemisphere=='sp':
lat_slice = (-90,-45)
elif hemisphere=='np':
nj_slice = (45,90)
if monthly:
var_name = 'aice_m'
else:
var_name = 'aice'
lons = CICE.TLON.isel(TLAT=slice(lat_slice))
lats = CICE.TLAT.isel(TLAT=slice(lat_slice))
aice_bool = CICE[var_name].isel(time=0,TLAT=slice(lat_slice)).where(ICE1.aice_m.isel(time=0,TLAT=slice(lat_slice)) >= threshold).values.flatten()
coords = list(zip(lons.values.flatten(), lats.values.flatten()))
n = len(coords)
coords = [(radians(lon), radians(lat)) for lon, lat in coords]
area = 0
for i in range(n):
if aice_bool[i]:
j = (i + 1) % n
x1, y1, z1 = np.cos(coords[i][1]) * np.cos(coords[i][0]), np.cos(coords[i][1]) * np.sin(coords[i][0]), np.sin(coords[i][1])
x2, y2, z2 = np.cos(coords[j][1]) * np.cos(coords[j][0]), np.cos(coords[j][1]) * np.sin(coords[j][0]), np.sin(coords[j][1])
area += (x1 * y2 - x2 * y1) * (y1 + y2 + z1 + z2)
return abs(area) / 2
############################################################################
def find_indices_within_region(LAT, LON, regn):
"""
Find the indices of grid cells within a specified geographical region.
This function takes in 2D arrays or DataArrays of latitude and longitude
coordinates, and a list representing the bounding box of a geographical
region. It returns the indices of the grid cells that are located within
the specified region.
Parameters:
LAT (np.array or xr.DataArray): 2D array representing the latitudes of the grid cells.
LON (np.array or xr.DataArray): 2D array representing the longitudes of the grid cells.
regn (list or tuple): A list or tuple containing the bounding box of the region
in the format [min_longitude, max_longitude, min_latitude, max_latitude].
Returns:
tuple: A tuple containing two arrays. The first array represents the row indices,
and the second array represents the column indices of the grid cells
within the specified region.
Example:
--------
LAT = np.array([[1, 2], [3, 4]])
LON = np.array([[5, 6], [7, 8]])
regn = [5, 7, 1, 3]
row_indices, col_indices = find_indices_within_region(LAT, LON, regn)
# row_indices = [0, 1]
# col_indices = [0, 1]
"""
ln_mn,ln_mx,lt_mn,lt_mx = regn
mask = (LAT >= lt_mn) & (LAT <= lt_mx) & (LON >= ln_mn) & (LON <= ln_mx)
return np.where(mask)
############################################################################
def compute_sfc_qsat(d2m, sp):
"""
Computes specific humidity at 2-meters based on dewpoint and surface pressure.
Parameters:
d2m (float): Dewpoint temperature at 2 meters.
sp (float): Surface pressure.
Returns:
float: Specific humidity at 2-meters.
"""
Rdry = 287.0597
Rvap = 461.5250
a1 = 611.21
a3 = 17.502
a4 = 32.19
T0 = 273.16
E = a1 * np.exp(a3 * (d2m-T0) / (d2m-a4) )
return (Rdry/Rvap) * E / (sp - ( (1-Rdry/Rvap) * E) )
############################################################################
def compute_ocn_sfc_slope(eta, dxdy_array, direction='x', grid_scale_factor=100):
"""
Computes sea surface slope in a specified direction.
Parameters:
eta (float or xarray.DataArray): Sea surface height.
dxdy_array (float or xarray.DataArray): Grid spacing array. Assumed to be in cm.
direction (str): The direction for which to compute the sea surface slope ('x' or 'y'). Default is 'x'.
grid_scale_factor (int): Scale factor to convert dxdy_array units to match eta. Default is 100.
Returns:
xarray.DataArray: Sea surface slope in the specified direction with appropriate units and attributes.
"""
if direction=='x':
dhdx = eta / (dxdy_array/grid_scale_factor)
dhdx.attrs['units'] = 'meters'
dhdx.attrs['long_name'] = 'sea surface slope in x-direction'
return dhdx
if direction=='y':
dhdy = eta / (dxdy_array/grid_scale_factor)
dhdy.attrs['units'] = 'meters'
dhdy.attrs['long_name'] = 'sea surface slope in y-direction'
return dhdy
############################################################################
def compute_ocn_heat_flux_at_depth(rho_D, cp_D, D, F_net, dTdt_D, time_unit_to_seconds=3600):
'''
Computes the ocean heat flux at a specific depth in W/m^2.
Parameters:
rho_D (float): Density at depth, in kg/m^3.
cp_D (float): Heat capacity at depth, in J/(kg*C).
D (float): Depth in meters.
F_net (float): Atmospheric heat flux at surface, in W/m^2.
dTdt_D (float): Time derivative of temperature at depth, in C/hr by default.
time_unit_to_seconds (int): Conversion factor for time derivative unit to seconds. Default is 3600 seconds.
Returns:
float: Ocean heat flux at specified depth in W/m^2.
Unit analysis on assumption of time derivative:
W/m^2 - (kg/m^3) * (J/(kg*C)) * m * (C/hr)
reduces to:
W/m^2 - J/(m^2 * hr)
or
(J * m^-2 * s^-1) - (J * m^-2 * 3600*s^-1)
'''
# cp_D is in J/(kg*C) and W is equal to J
return F_net - (rho_D*cp_D*D*dTdt_D)/time_unit_to_seconds
############################################################################
def compute_ocn_pressure_at_depth(D,latitude):
'''
Calculates the pressure at a specific depth in the ocean in dbars.
Parameters:
D (float): Depth in meters.
latitude (float): Latitude in degrees.
Returns:
float: Pressure in dbars.
REFERENCE:
Saunders, P.M. 1981
"Practical conversion of Pressure to Depth"
Journal of Physical Oceanography, 11, 573-574
'''
x = np.sin(abs(latitude)*np.pi/180)
c1 = 5.92E-3+(x**2)*5.25E-3;
return ((1-c1)-np.sqrt(((1-c1)**2)-(8.84E-6*D)))/4.42E-6;
############################################################################
def compute_ocn_secant_bulk_modulus(S,T,P):
'''
Computes the Secant Bulk Modulus (K) of sea water using Equation of State 1980 (UNESCO).
Parameters:
S (float): Salinity in PSU.
T (float): Temperature in Celsius.
P (float): Pressure in dbar.
Returns:
float: Secant Bulk Modulus in appropriate units.
REFERENCES:
Fofonoff, P. and Millard, R.C. Jr
Unesco 1983. Algorithms for computation of fundamental properties of
seawater, 1983. _Unesco Tech. Pap. in Mar. Sci._, No. 44, 53 pp.
Eqn.(15) p.18
Millero, F.J. and Poisson, A.
International one-atmosphere equation of state of seawater.
Deep-Sea Res. 1981. Vol28A(6) pp625-629.
'''
# pressure dbar to atmospheric
P = P/10
#--------------------------------------------------------------------
# Pure water terms of the secant bulk modulus at atmos pressure.
# UNESCO eqn 19 p 18
h3 = -5.77905e-7
h2 = 1.16092e-4
h1 = 1.43713e-3
h0 = 3.239908
AW = h0 + (h1 + (h2 + h3*T)*T)*T
k2 = 5.2787e-8
k1 = -6.12293e-6
k0 = 8.50935e-5
BW = k0 + (k1 + k2*T)*T;
e4 = -5.155288e-5
e3 = 1.360477e-2
e2 = -2.327105
e1 = 1.484206e2
e0 = 1.96522e4
KW = e0 + (e1 + (e2 + (e3 + e4*T)*T)*T)*T
#--------------------------------------------------------------------
# SEA WATER TERMS OF SECANT BULK MODULUS AT ATMOS PRESSURE.
j0 = 1.91075e-4
i2 = -1.6078e-6
i1 = -1.0981e-5
i0 = 2.2838e-3
SR = np.sqrt(S);
A = AW + (i0 + (i1 + i2*T)*T + j0*SR)*S
m2 = 9.1697e-10
m1 = 2.0816e-8
m0 = -9.9348e-7
#eqn.18
B = BW + (m0 + (m1 + m2*T)*T)*S
f3 = -6.1670e-5
f2 = 1.09987e-2
f1 = -0.603459
f0 = 54.6746
g2 = -5.3009e-4
g1 = 1.6483e-2
g0 = 7.944e-2
#eqn.16
K0 = KW + (f0 + (f1 + (f2 + f3*T)*T)*T + (g0 + (g1 + g2*T)*T)*SR)*S
#eqn.15
return K0 + (A + B*P)*P
############################################################################
def compute_ocn_density_standard_mean_ocean_water(T):
'''
Denisty of Standard Mean Ocean Water (Pure Water) using EOS 1980.
Returns kg/m^3
Requires input, T, temperature, in Celsius
REFERENCES:
Fofonoff, P. and Millard, R.C. Jr
Unesco 1983. Algorithms for computation of fundamental properties of
seawater, 1983. _Unesco Tech. Pap. in Mar. Sci._, No. 44, 53 pp.
UNESCO 1983 p17 Eqn(14)
Millero, F.J & Poisson, A.
International one-atmosphere equation of state for seawater.
Deep-Sea Research Vol28A No.6. 1981 625-629. Eqn (6)
'''
a0 = 9.99842594e2
a1 = 6.793952e-2
a2 = -9.095290e-3
a3 = 1.001685e-4
a4 = -1.120083e-6
a5 = 6.536332e-9
return a0 + (a1 + (a2 + (a3 + (a4 + a5*T)*T)*T)*T)*T
############################################################################
def compute_ocn_density_at_surface(S,T):
'''
Density of Sea Water at atmospheric pressure using UNESCO 1983 (EOS 1980) polynomial.
Returns kg/m^3
Requires, S (salinity) to be in practical salinity units (psu), and, T (temperature)
to be in Celsius
REFERENCES:
Unesco 1983. Algorithms for computation of fundamental properties of
seawater, 1983. _Unesco Tech. Pap. in Mar. Sci._, No. 44, 53 pp.
UNESCO 1983 p17
Millero, F.J & Poisson, A.
International one-atmosphere equation of state for seawater.
Deep-Sea Research Vol28A No.6. 1981 625-629.
'''
# UNESCO 1983 eqn(13) p17.
b0 = 8.24493e-1
b1 = -4.0899e-3
b2 = 7.6438e-5
b3 = -8.2467e-7
b4 = 5.3875e-9
c0 = -5.72466e-3
c1 = 1.0227e-4
c2 = -1.6546e-6
d0 = 4.8314e-4
d_smow = compute_ocn_density_standard_mean_ocean_water(T)
return d_smow + (b0 + (b1 + (b2 + (b3 + b4*T)*T)*T)*T)*S + (c0 + (c1 + c2*T)*T)*S*np.sqrt(S) + d0*(S**2)
############################################################################
def compute_ocn_density_at_depth(S,T,D,latitude):
'''
Density of Sea Water using UNESCO 1983 (EOS 80) polynomial.
Returns kg/m^3
Requires:
S (salinity) to be in practical salinity units (psu)
T (temperature) to be in Celsius
D (depth) to be in metres
latitude to be in degrees
REFERENCES:
Fofonoff, P. and Millard, R.C. Jr
Unesco 1983. Algorithms for computation of fundamental properties of
seawater, 1983. _Unesco Tech. Pap. in Mar. Sci._, No. 44, 53 pp.
UNESCO 1983 p17 Eqn(14)
Millero, F.J & Poisson, A.
International one-atmosphere equation of state for seawater.
Deep-Sea Research Vol28A No.6. 1981 625-629. Eqn (6)
'''
# compute pressure at depth and convert to bars
P = compute_ocn_pressure_at_depth(D,latitude)/10
rho0 = compute_ocn_density_at_surface(S,T)
K = compute_ocn_secant_bulk_modulus(S,T,P)
return rho0/(1-P/K)
############################################################################
def compute_ocn_heat_capacity_at_depth(S,T,D,latitude):
'''
Heat Capacity of Sea Water using UNESCO 1983 polynomial.
Returns [J kg^-1 C^-1]
Requires:
S (salinity) to be in practical salinity units (psu)
T (temperature) to be in Celsius
D (depth) to be in metres
latitude to be in degrees
REFERENCES:
Fofonoff, P. and Millard, R.C. Jr
Unesco 1983. Algorithms for computation of fundamental properties of
seawater, 1983. _Unesco Tech. Pap. in Mar. Sci._, No. 44, 53 pp.
UNESCO 1983 p17 Eqn(14)
Millero, F.J & Poisson, A.
International one-atmosphere equation of state for seawater.
Deep-Sea Research Vol28A No.6. 1981 625-629. Eqn (6)
'''
# compute pressure at depth and convert to bars
P = compute_ocn_pressure_at_depth(D,latitude)/10
#-----------------
# eqn.26, p.32
a0 = -7.64357
a1 = .1072763
a2 = -1.38385e-3
b0 = .1770383
b1 = -4.07718e-3
b2 = 5.148e-5
c0 = 4.2174e3
c1 = -3.720283
c2 = .1412855
c3 = -2.654387e-3
c4 = 2.093236e-5
A1 = c0 + c1*T + c2*T**2 + c3*T**3 + c4*T**4
A2 = (a0 + a1*T + a2*T**2)*S
A3 = (b0 + b1*T + b2*T**2)*S*np.sqrt(S)
Cp0 = A1 + A2 + A3
#-----------------
# eqn.28, p.33
d0 = -4.9592e-1
d1 = 1.45747e-2
d2 = -3.13885e-4
d3 = 2.0357e-6
d4 = 1.7168e-8
e0 = 2.4931e-4
e1 = -1.08645e-5
e2 = 2.87533e-7
e3 = -4.0027e-9
e4 = 2.2956e-11
f0 = -5.422e-8
f1 = 2.6380e-9
f2 = -6.5637e-11
f3 = 6.136e-13
B1 = (d0 + d1*T + d2*T**2 + d3*T**3 + d4*T**4)*P
B2 = (e0 + e1*T + e2*T**2 + e3*T**3 + e4*T**4)*P**2
B3 = (f0 + f1*T + f2*T**2 + f3*T**3)*P**3
dCp0 = B1 + B2 + B3
#-----------------
# eqn.29, p.34
d0 = 4.9247e-3
d1 = -1.28315e-4
d2 = 9.802e-7
d3 = 2.5941e-8
d4 = -2.9179e-10
e0 = -1.2331e-4
e1 = -1.517e-6
e2 = 3.122e-8
f0 = -2.9558e-6
f1 = 1.17054e-7
f2 = -2.3905e-9
f3 = 1.8448e-11
g0 = 9.971e-8
h0 = 5.540e-10
h1 = -1.7682e-11
h2 = 3.513e-13
j1 = -1.4300e-12
S_3 = S*np.sqrt(S)
C1 = ((d0 + d1*T + d2*T**2 + d3*T**3 + d4*T**4)*S + (e0 + e1*T + e2*T**2)*S_3)*P
C2 = ((f0 + f1*T + f2*T**2 + f3*T**3)*S + g0*S_3)*P**2
C3 = ((h0 + h1*T + h2*T**2)*S + j1*T*S_3)*P**3
dCp = C1 + C2 + C3
return (Cp0 + dCp0 + dCp)
############################################################################
def compute_ocn_density_at_depth_alternative_method(S,T,D,latitude):
'''
Calculate the density of seawater at a given depth, temperature, salinity, and latitude.
Parameters:
S (float) : Salinity (in PSU)
T (float) : Temperature (in degrees Celsius)
D (float) : Depth (in meters)
latitude (float) : Latitude (in degrees)
Returns:
float: Density of seawater (in kg/m^3)
'''
# depth to pressure
P = compute_ocn_pressure_at_depth(D,latitude)
# standar ocean water
a0 = 999.842594
a1 = 6.793953e-2
a2 = -9.095290e-3
a3 = 1.001685e-4
a4 = -1.120083e-6
a5 = 6.536332e-9
rho_SMOW = a0 + a1*T + a2*T**2 + a3*T**3 + a4*T**4 +a5*T**5
b0 = 8.2449e-1
b1 = -4.0899e-3
b2 = 7.6438e-5
b3 = -8.2467e-7
b4 = 5.3875e-9
c0 = -5.7246e-3
c1 = 1.0227e-4
c2 = -1.6546e-6
d0 = 4.8314e-4
B1 = b0 + b1*T + b2*T**2 + b3*T**3 + b4*T**4
C1 = c0 + c1*T + c2*T**2
rho_p0 = rho_SMOW + B1*S + C1*S**1.5 + d0*S**2
e0 = 19652.21
e1 = 148.4206
e2 = -2.327105
e3 = 1.360477e-2
e4 = -5.155288e-5
f0 = 54.674600
f1 = -0.603459
f2 = 1.099870e-2
f3 = -6.167e-5
g0 = 7.9440e-2
g1 = 1.6483e-2
g2 = -5.3009e-4
G1 = g0 + g1*T + g2*T**2
F1 = f0 + f1*T + f2*T**2 + f3*T**3
Kw = e0 + e1*T + e2*T**2 + e3*T**3 + e4*T**4
K0 = Kw + F1*S + G1*S**1.5
h0 = 3.23990
h1 = 1.43713e-3
h2 = 1.16092e-4
h3 = -5.77905e-7
i0 = 2.28380e-3
i1 = -1.09810e-5
i2 = -1.60780e-6
j0 = 1.91075e-4
k0 = 8.50935e-5
k1 = -6.12293e-6
k2 = 5.27870e-8
m0 = -9.9348e-7
m1 = 2.0816e-8
m2 = 9.1697e-10
Bw = k0 + k1*T + k2*T**2
B2 = Bw + (m0 + m1*T + m2*T**2)*S
Aw = h0 + h1*T + h2*T**2 + h3*T**3
A1 = Aw + (i0 + i1*T + i2*T**2)*S + j0*S**1.5
K = K0 + A1*P + B2*P**2
return ( rho_p0 / (1 - ( P / K )) )
############################################################################
def compute_diffuse_sfc_em(em_sfc, em_toa):
'''
Compute the diffuse electromagnetic radiation at the surface based on total radiation at surface and top of the atmosphere.
Parameters:
em_sfc (float) : Electromagnetic radiation at surface (W/m^2)
em_toa (float) : Electromagnetic radiation at top of atmosphere (W/m^2)
Returns:
float: Diffuse electromagnetic radiation at surface (W/m^2)
'''
k_t = em_sfc / em_toa
return 0.952 - 1.041 * np.exp(-np.exp((2.3 - 4.702*k_t)))
############################################################################
def compute_u2_from_u10(u10):
'''
Compute wind speed at 2 meters from reported wind speed at 10 meters.
Parameters:
u10 (float) : Wind speed at 10 meters (in m/s)
Returns:
float : Wind speed at 2 meters (in m/s)
'''
return (u10 * 4.87) / np.log((67.8 * 10) - 5.42)
############################################################################
def compute_sfc_airrho(t2m, d2m, sp):
'''
Compute air density at the surface based on temperature, dewpoint, and surface pressure.
Parameters:
t2m (float) : Temperature at 2 meters (in Kelvin)
d2m (float) : Dewpoint at 2 meters (in Kelvin)
sp (float) : Surface pressure (in Pascal)
Returns:
float : Air density at the surface (in kg/m^3)
'''
RH = mpc.relative_humidity_from_dewpoint(t2m,d2m)
r = mpc.mixing_ratio_from_relative_humidity(sp, t2m, RH)
return mpc.density(sp, t2m, r)
############################################################################
def compute_sfc_qsat(d2m, sp):
'''
Compute specific humidity at 2 meters based on dewpoint and surface pressure.
Parameters:
d2m (float) : Dewpoint at 2 meters (in Kelvin)
sp (float) : Surface pressure (in Pascal)
Returns:
float : Specific humidity at 2 meters (dimensionless)
'''
Rdry = 287.0597
Rvap = 461.5250
a1 = 611.21
a3 = 17.502
a4 = 32.19
T0 = 273.16
E = a1 * np.exp(a3 * (d2m-T0) / (d2m-a4) )
return (Rdry/Rvap) * E / (sp - ( (1-Rdry/Rvap) * E) )
############################################################################
def ocean_temp_from_theta(p0, p):
'''
Compute ocean temperature from potential temperature.
Parameters:
p0 (float) : Reference pressure in decibars (db)
p (float) : Pressure at the desired level in decibars (db)
Returns:
[Currently, this function doesn't return anything; you might want to implement this.]
Note:
This function currently calculates the pressure difference but doesn't compute the ocean temperature from potential temperature.
'''
dp = p0 - p
############################################################################
def update_frame(frame):
'''
Update the visualization frame for animation.
Parameters:
frame (int or float) : The frame index to update the visualization with.
Returns:
None
Note:
This function assumes that 'cax' and 'ds' are predefined. Make sure these variables are properly initialized before calling the function.
'''
cax.set_array( ds.isel(time=frame).values.flatten() )
############################################################################
def xesmf_regrid_dataset(DS_src, DS_dst, F_DS_na,
method='bilinear',
periodic=True,
reuse_weights=True,
F_weights='',
multi_file=False):
'''
Regrid a given dataset from source grid to destination grid using xESMF.
Parameters:
DS_src (xarray.Dataset) : Source dataset
DS_dst (xarray.Dataset) : Destination dataset
F_DS_na (str) : File name or path of the dataset to be regridded
method (str) : Regridding method; default is 'bilinear'
periodic (bool) : Whether the grid is periodic; default is True
reuse_weights (bool) : Whether to reuse weights; default is True
F_weights (str) : File name for saving/loading regridding weights; default is ''
multi_file (bool) : Whether to open multiple files; default is False
Returns:
xarray.Dataset : Regridded dataset
'''
print("regridding file: ",F_DS_na)
rg = xe.Regridder(DS_src, DS_dst,
method=method,
periodic=periodic,
filename=F_weights,
reuse_weights=reuse_weights)
if multi_file:
DS_na = xr.open_mfdataset(F_DS_na, parallel=True, chunks={'time':1})
else:
DS_na = xr.open_dataset(F_DS_na)
DS_rg = rg(DS_na)
return DS_rg
#####################################################################################################
############################################ CICE ANALYSIS ##########################################
#####################################################################################################
def read_json(filename):
'''Read a JSON file.
Parameters:
-----------
filename : str
Path to the JSON file.
Returns:
--------
dict
Dictionary containing the parsed JSON data.
'''
with open(filename, 'r') as file:
return json.load(file)
class cice_analysis:
'''
CICE (Community Ice CodE) Analysis Class.
Description:
------------
This class is designed to load and handle parameters and configurations for analyzing CICE datasets.
The class reads a JSON file containing necessary attributes and setups for the analysis, such as time frames,
thresholds, directories, titles, locations, and other specific parameters.
Attributes:
-----------
dt0 : str
Start date for the analysis period.
dtN : str
End date for the analysis period.
aice_thresh : float
Threshold value for the sea ice concentration.
FI_thresh : float
Threshold value for some feature of interest (e.g., flux or intensity).
aice_name : str
Variable name for sea ice concentration within the dataset.
proc_period : str
Processing period or frequency for the data (e.g., 'monthly').
P_nsdic : str
Path to some data directory or file, e.g., National Snow and Ice Data Center.
model_run_date : str
Date the model was run.
P_cices : str
Path to CICE data or files.
titles : list of str
List of titles for plots or analysis tasks.
olav_locs : list of lists
List of [longitude, latitude] locations related to the Olav region.
maws_locs : list of lists
List of [longitude, latitude] locations related to the Maws region.
spacing : str
Grid spacing for the GMT regular grid.
search_radius : str
Search radius for GMT's nearneighbor algorithm.
cmap_plot_cice : str
Color map for plotting CICE data.
cice_labels : list of str
Labels for CICE data plots.
region_names : list of str
Names of regions of interest.
regions_info : dict
Dictionary containing additional info about the regions of interest.
Methods:
--------
Currently, this class doesn't define extra methods, but future implementations might include
methods for data processing, plotting, and other analysis tasks.
Example:
--------
analysis = cice_analysis("config.json")
print(analysis.dt0) # Prints the start date from the JSON configuration.
'''
def __init__(self, filename):
'''Initialize the cice_analysis object by reading parameters from a JSON file.'''
data = read_json(filename)
self.D_afim_output = data['D_afim_output']
self.D_graphical = data["D_graphical"]
self.D_obs = data["D_obs"]
self.img_type = data["img_type"]
self.G_res = data["G_res"]
self.atm_frcg_name = data["atm_forcing"]
self.ocn_frcg_name = data["ocn_forcing"]
self.ic_source = data["ic_source"]
self.dt0 = data['dt0']
self.dtN = data['dtN']
self.aice_thresh = data['aice_thresh']
self.FI_thresh = data['FI_thresh']
self.frazil_thresh = data['frazil_thresh']
self.aice_name = data['aice_name']
self.spacing = data['spacing']
self.search_radius = data['search_radius']
self.proc_period = data['proc_period']
self.P_nsdic = data['P_nsdic']
self.afim_runs = data['afim_runs']
self.cmap_plot_cice = data['cmap_plot_cice']
self.region_names = data['region_names']
self.regions_info = data['regions_info']
self.plt_mo_dict = data['plt_mo_dict']
self.plt_stat_dict = data['plt_stat_dict']
self.GI_locations = ''
def build_data_path(self, model_run_dir, output_period, mf_switch=True, F_name=''):
'''
'''
if mf_switch:
self.P_afim = os.path.join(self.D_afim_output,model_run_dir,'history',output_period,"*.nc")
else:
self.P_afim = os.path.join(self.D_afim_output,model_run_dir,'history',output_period,F_name)
def load_run_and_time_convert(self, mf_switch=True, monthly=True):
'''
Load CICE datasets and apply a hemisphere mask based on latitude.
Parameters:
-----------
P_cice : str
Path to the CICE dataset.
mf_switch : bool, optional (default=True)
If True, use `xr.open_mfdataset` (multi-file dataset loading). If False, use `xr.open_dataset`.
which_hemisphere : str, optional (default='south')
Specifies the hemisphere for the masking. Can be 'south' or 'north'.
which_grid : str, optional (default='t')
Specifies the grid on which the mask will be applied. Can be 't' or 'u'.
daily_or_monthly : str, optional (default='monthly')
Specifies the frequency of the time data. Adjusts the time variable accordingly.
Returns:
--------
xarray.Dataset
The CICE dataset, subsetted by time and masked by hemisphere.
Description:
------------
The function loads a CICE dataset (either from a single file or multiple files), adjusts its time
coordinates based on the provided frequency, and applies a mask based on the given hemisphere
and grid type. The returned dataset contains only the data for the specified hemisphere.
'''
if mf_switch:
#from dask.distributed import Client, LocalCluster
#cluster = LocalCluster(n_workers=7, threads_per_worker=1)
#client = Client(cluster)
#chnk = {'nj': 108, 'ni': 144}
CICE = xr.open_mfdataset(self.P_afim)#,chunks=chnk)
# Open the dataset with Dask for parallel loading
#CICE = xr.open_mfdataset(self.P_afim, chunks=chnk, engine='netcdf4', parallel=True)
#client.close()
else:
CICE = xr.open_dataset(self.P_afim)
time_index = pd.DatetimeIndex(CICE['time'].values)
if monthly:
adjusted_time = time_index - pd.DateOffset(months=1)
else:
adjusted_time = time_index - pd.DateOffset(days=1)
CICE['time'] = adjusted_time.values
CICE = CICE.assign_coords(tlon_i=('ni', CICE['TLON'][0,:].values))
CICE = CICE.assign_coords(tlat_i=('nj', CICE['TLAT'][:,0].values))
CICE = CICE.assign_coords(ulon_i=('ni', CICE['ULON'][0,:].values))
CICE = CICE.assign_coords(ulat_i=('nj', CICE['ULAT'][:,0].values))
self.CICE = CICE.sel(time=slice(self.dt0,self.dtN))
def mask_hemisphere(self, which_hemisphere='south', which_grid='t'):
'''
Create a mask for either the northern or southern hemisphere based on specified grid points (either 't' or 'u').