forked from matthewhoffman/e3sm-cryo-analysis-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
weddell_mod.py
2550 lines (2322 loc) · 111 KB
/
weddell_mod.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 7 13:56:52 2019
@author: cbegeman
"""
import sys
import os
import csv
import gsw
import netCDF4
import cartopy
import pyproj
import numpy as np
import numpy.ma as ma
import cmocean
import pandas
from shapely.geometry import Point,Polygon
import math
import matplotlib as pltlib
from matplotlib import ticker,rc#import datetime
import matplotlib.pyplot as plt
import matplotlib.cm as cmx
import matplotlib.colors as colors
from matplotlib.colors import LogNorm,Normalize
from matplotlib.colors import SymLogNorm
import scipy.signal
from scipy.signal import butter,filtfilt
import scipy.interpolate as interp
from scipy.stats import linregress
# my libraries
from extract_depths import zmidfrommesh
from pick_from_mesh import *
from plot_config import *
from data_config import *
global bad_data, bad_data2, deg2rad, lat_N, runname, runpath, meshpath, vartitle, varname, varmin, varmax, varcmap, surfvar, dvar
def TS_diagram(runlist,year_range,
placename = '',lat=-9999,lon=-9999,
z=-9999,zab=False,zall=True,plot_lines=True,
seasonal=False,runcmp=False,savepath=savepath,
pyc_polygon = TSpolygon_Hattermann2018_edit):
S_limits = np.array([32.5,35.0])
T_limits = np.array([-2.1,1.5])
years = np.arange(year_range[0],year_range[1]+1,1)
months = np.arange(1,13,1)
nt = len(years)*len(months)
times = np.zeros((nt,))
if placename == '':
idx,placename = pick_point(run=run_list[0],lat=lat,lon=lon)
idx = [idx]
else:
idx = pick_from_region(region=placename,run=runlist[0],plot_map=False)
fmesh = netCDF4.Dataset(meshpath[runname.index(run_list[0])])
nz = len(fmesh.variables['layerThickness'][0,idx,:])
filename = run_list[0] + '_TS_' + placename + '_'
if z != -9999:
filename += str(z) + 'm_'
filename += str(year_range[0]) + '-' + str(year_range[1])
if seasonal:
filename += '_seasonal'
print(filename)
T = np.zeros((nt,len(run_list),nz))
S = np.zeros((nt,len(run_list),nz))
#if z != -9999:
# zmid,_,_ = zmidfrommesh(fmesh,cellidx=idx)
# if zab:
# zeval = np.add(zmid[0][-1],z)
# m = 'mab'
# else:
# zeval = -1*z
# m = 'm'
# zidx = np.argmin(np.abs(np.subtract(zmid,zeval)))
for j,run in enumerate(run_list):
t=0
for yr in years:
for mo in months:
times[t] = yr+(mo-1.0)/12.0
datestr = '{0:04d}-{1:02d}'.format(yr, mo)
input_filename = '{0}/mpaso.hist.am.timeSeriesStatsMonthly.'.format(
runpath[runname.index(run)]) + datestr + '-01.nc'
f = netCDF4.Dataset(input_filename, 'r')
T[t,j,:] = f.variables[varname[vartitle.index('T')]][0,idx,:]
S[t,j,:] = f.variables[varname[vartitle.index('S')]][0,idx,:]
f.close()
t=t+1
fig = plt.figure(1, facecolor='w')
axTS = fig.add_subplot()
if seasonal:
cNorm = Normalize(vmin=0, vmax=1)
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap='twilight')
cbtitle = r'Time of Year'
else:
cNorm = Normalize(vmin=year_range[0], vmax=year_range[1]+ 1)
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap='cmo.deep')
cbtitle = r'Simulated Year'
for j,run in enumerate(run_list):
if zall:
sc=axTS.scatter(S[:,j,:], T[:,j,:], s=1,
c = run_color[runname.index(run)])
#if z != -9999:
# if plot_lines:
# for i,ti in enumerate(times):
# if i > 0:
# if seasonal:
# colorVal = scalarMap.to_rgba(np.subtract(ti,np.floor(ti)))
# else:
# colorVal = scalarMap.to_rgba(ti)
# #scz=axTS.plot([S[i-1,zidx],S[i,zidx]], [T[i-1,zidx],T[i,zidx]],
# # '-', color=colorVal,linewidth=1)
# Sline = [S[i-1,j,zidx],S[i,j,zidx]]
# Tline = [T[i-1,j,zidx],T[i,j,zidx]]
# scz=axTS.arrow(Sline[0], Tline[0],
# Sline[1]-Sline[0], Tline[1]-Tline[0],
# color=colorVal,linewidth=1)
# plt.colorbar(scalarMap,label=cbtitle)
# else:
# scz=axTS.scatter(S[:,j,zidx], T[:,j,zidx],
# s = 30,edgecolor='k', cmap='twilight')
# plt.colorbar(scalarMap,label=cbtitle)
# show pycnocline bounds
S_polygon = np.zeros([5],dtype='float')
S_polygon[:-1] = [pyc_polygon[i][0] for i in np.arange(0,4)]
S_polygon[-1] = S_polygon[0]
T_polygon = np.zeros([5],dtype='float')
T_polygon[:-1] = [pyc_polygon[i][1] for i in np.arange(0,4)]
T_polygon[-1] = T_polygon[0]
for i in np.arange(0,4):
axTS.plot([S_polygon[i],S_polygon[i+1]],
[T_polygon[i],T_polygon[i+1]],
color='k',linewidth=1)
#axTS.fill(S_polygon, T_polygon,closed=True,
# fill = False,edgecolor='k')
# plot water mass bounds
lncolor = 'black'
lw1 = 1
#plt.plot([34.0, 34.0], [-1.85, 0.2], ':', color=lncolor, linewidth=lw1)
#plt.plot([34.5, 34.5], [-1.86, -1.5], ':', color=lncolor, linewidth=lw1)
#plt.plot([34.0, 35.0], [-1.5, -1.5], ':', color=lncolor, linewidth=lw1)
#plt.plot([34.0, 35.0], [0.0, 0.0], ':', color=lncolor, linewidth=lw1)
plt.plot(S_limits, S_limits*m_Tfreezing + b_Tfreezing,
':', color=lncolor, linewidth=lw1)
axTS.set_ylim(T_limits)
axTS.set_xlim(S_limits)
axTS.set_ylabel(varlabel[vartitle.index('T')])
axTS.set_xlabel(varlabel[vartitle.index('S')])
plt.savefig(savepath + filename +'.png')
plt.clf()
#----------------------------------------------------------------------
# Z_PYCNOCLINE
# -- compute the depth of the pycnocline
#
# Inputs:
# z vector of depths
# T vector of temperature of length z
# S vector of temperature of length z
# pyc_polygon list of points defining T,S polygon within which the
# pycnocline must fall
# Output:
# z depth of pycnocline
#----------------------------------------------------------------------
def z_pycnocline(z,T,S,diags=False,cellidx=0,zmin=-9999,
pyc_polygon = TSpolygon_Hattermann2018_edit,
plot_TS = False, savepath=savepath):
TS_polygon = Polygon(pyc_polygon)
polygon_mask = np.zeros(len(z),dtype=bool)
for zidx in range(len(z)):
polygon_mask[zidx] = TS_polygon.contains(Point((S[zidx],T[zidx])))
if np.sum(polygon_mask) == 0 and len(z) > 1:
dz = 5.#dz = np.min([5.,np.min(z[:-1]-z[1:])])
zi = np.arange(np.max(z),
np.max([np.min(z),zmin]),
-1*dz)
polygon_mask = np.zeros(len(zi),dtype=bool)
Sfunc = interp.interp1d(z, S) #, kind='cubic')
Si = Sfunc(zi)
Tfunc = interp.interp1d(z, T) #, kind='cubic')
Ti = Tfunc(zi)
for zidx in range(len(zi)):
polygon_mask[zidx] = TS_polygon.contains(Point((Si[zidx],Ti[zidx])))
if np.sum(polygon_mask) == 0:
dz = 0.1#dz = np.min([5.,np.min(z[:-1]-z[1:])])
zi = np.arange(np.max(z),
np.max([np.min(z),zmin]),
-1*dz)
polygon_mask = np.zeros(len(zi),dtype=bool)
Sfunc = interp.interp1d(z, S) #, kind='cubic')
Si = Sfunc(zi)
Tfunc = interp.interp1d(z, T) #, kind='cubic')
Ti = Tfunc(zi)
for zidx in range(len(zi)):
polygon_mask[zidx] = TS_polygon.contains(Point((Si[zidx],Ti[zidx])))
if np.sum(polygon_mask) == 0:
if plot_TS:
filename = 'TS_polygon_'+str(cellidx)
fig = plt.figure(1, facecolor='w')
axTS = fig.add_subplot()
sc=axTS.plot(S, T, 'k', marker='.',linestyle='-')
sc=axTS.scatter(Si, Ti, s=1, c='grey')
S_polygon = np.zeros([5],dtype='float')
S_polygon[:-1] = [pyc_polygon[i][0] for i in np.arange(0,4)]
S_polygon[-1] = S_polygon[0]
T_polygon = np.zeros([5],dtype='float')
T_polygon[:-1] = [pyc_polygon[i][1] for i in np.arange(0,4)]
T_polygon[-1] = T_polygon[0]
for i in np.arange(0,4):
axTS.plot([S_polygon[i],S_polygon[i+1]],
[T_polygon[i],T_polygon[i+1]],
color='k')
plt.savefig(savepath + filename +'.png')
plt.clf()
return nan
else:
return np.median(zi[polygon_mask])
else:
return np.median(zi[polygon_mask])
if diags and np.sum(polygon_mask) != 0:
print(S[polygon_mask],T[polygon_mask])
return np.median(z[polygon_mask])
#----------------------------------------------------------------------
# TSERIES1
# -- plot timeseries of variable at a given depth and geographic location
# -- plot geographic location on an area map with bathymetry
#
# Inputs:
# run runname, string
# varlist variables to plot, list of strings
# latS latitude, always in Southern Hem, positive, real
# lonW longitude, always in Western Hem, positive, real
# startyr lower limit on simulated year to plot, real
# endyr upper limit on simulated year to plot, real
# z depth value, real
# zab true if z denotes m above sea level, false if m below surface
# runcmp if true, plot both entries in runname
# savepath path to save plot images
#----------------------------------------------------------------------
def extract_tseries(runlist,varlist,year_range,
placename = '', land_ice_mask=False,
lat=-9999,lon=-9999,
zrange=None, zeval=-9999, zab=False,
ztop_pyc = [False],zbottom_pyc = [False],
operation = 'mean',
overwrite=True, output_filename = '',
savepath=savepath):
if zab:
m = 'mab'
else:
m = 'm'
if len(ztop_pyc)<len(varlist):
ztop_pyc = [False for i in varlist]
if len(zbottom_pyc)<len(varlist):
zbottom_pyc = [False for i in varlist]
if output_filename == '':
filename = ('_'.join(runlist) + '_' +
''.join(varlist) + '_' + placename)
if zrange is not None:
filename = filename + '_z{0:03d}-{1:03d}'.format(zrange[0], zrange[1]) + m
filename = filename + '_t{0:03d}-{1:03d}'.format(year_range[0], year_range[1])
else:
filename = output_filename
print('extract tseries',savepath + filename + '.txt')
years = np.arange(year_range[0],year_range[1],1)
months = np.arange(1,13,1)
nt = len(years)*len(months)
times = np.zeros((nt,))
fmesh = netCDF4.Dataset(meshpath[runname.index(runlist[0])])
data = np.zeros((len(runlist),len(varlist),nt))
if placename in region_is_point:
lat = region_coordbounds[region_name.index(placename)][1,1]
lon = region_coordbounds[region_name.index(placename)][0,0]
idx,_ = pick_point(lat=lat,lon=lon,run=runlist[0],
plot_map=False,savepath=savepath)
idx = [idx]
elif lat != -9999:
idx,_ = pick_point(lat=lat,lon=lon,run=runlist[0],
plot_map=False,savepath=savepath)
idx = [idx]
else:
idx = pick_from_region(region=placename, run=runlist[0],
land_ice_mask = land_ice_mask,
plot_map=False)
#if 'unormal' in varlist:
# _,_,_,transect_angle = pick_transect(option='by_index',
# run=run,transect_name = 'trough_shelf')
t=0
colheadings = ['decyear']
for j,run in enumerate(runlist):
for i,var in enumerate(varlist):
header = run+'_'+var
if zeval != -9999:
header = header + '_z' + str(int(zeval))
if ztop_pyc[i]:
header = header + '_abovepyc'
if zbottom_pyc[i]:
header = header + '_belowpyc'
colheadings.append(header)
if zrange is not None:
kmax = fmesh.variables['maxLevelCell'][idx]
zmid,_,_ = zmidfrommesh(fmesh,cellidx=idx)
zidx = np.zeros((len(idx),2),dtype=int)
for i in range(0,len(idx)):
if zrange[1] != -9999:
if zab:
zeval = np.add(zmid[0][-1],zeval)
zidx[i,:] = ([np.argmin(np.abs(np.subtract(zmid,zeval[0]))),
np.argmin(np.abs(np.subtract(zmid,zeval[1])))])
if zidx[i,1] == zidx[i,0]:
zidx[i,1] += 1
if zidx[i,1] < zidx[i,0]:
zidx[i,:] = [zidx[i,1],zidx[i,0]]
elif zeval != -9999:
if zab:
zeval = np.add(zmid[0][-1],zeval)
else:
zeval = -1.*zeval
zidx[i,0] = np.argmin(np.abs(np.subtract(zmid[0],zeval)))
for yr in years:
print(yr)
for mo in months:
times[t] = yr+(mo-1.0)/12.0
datestr = '{0:04d}-{1:02d}'.format(yr, mo)
for j,run in enumerate(runlist):
input_filename = ('{0}/mpaso.hist.am.timeSeriesStatsMonthly.'.format(
runpath[runname.index(run)])
+ datestr + '-01.nc')
if not os.path.exists(input_filename):
print('Output file for {} does not exist'.format(run))
data[j,:,t] = math.nan
continue
f = netCDF4.Dataset(input_filename, 'r')
if any(ztop_pyc) or any(zbottom_pyc):
z_idx = np.zeros((len(idx)),dtype=int)
zcol_mean = np.zeros((len(idx)))# make idx a list
T = f.variables[varname[vartitle.index('T')]][0,idx,:]
S = f.variables[varname[vartitle.index('S')]][0,idx,:]
h = fmesh.variables['layerThickness'][0,idx,:]
for idx_i,_ in enumerate(idx):
zpyc = z_pycnocline(zmid[idx_i,:kmax[idx_i]],
T [idx_i,:kmax[idx_i]],
S [idx_i,:kmax[idx_i]],
zmin = -500.,cellidx=idx[idx_i])
z_idx[idx_i] = int(np.argmin(np.abs(np.subtract(zmid[idx_i,:kmax[idx_i]],zpyc))))
for i,var in enumerate(varlist):
if var in surfvar:
if operation == 'mean':
data[j,i,t] = np.mean(f.variables[varname[vartitle.index(var)]][0,idx])
elif operation == 'area_sum':
data[j,i,t] = np.sum(np.multiply(f.variables[varname[vartitle.index(var)]][0,idx],
fmesh.variables['areaCell'][idx]))
else:
data[j,i,t] = f.variables[varname[vartitle.index(var)]][0,idx]
else:
if ztop_pyc[i] or zbottom_pyc[i]:
var = f.variables[varname[vartitle.index(var)]][0,idx,:]
for idx_i,_ in enumerate(idx):
if np.isnan(z_idx[idx_i]) or z_idx[idx_i] == 0 or z_idx[idx_i] == kmax[idx_i]:
zcol_mean[idx_i] = -9999
else:
if ztop_pyc[i]:
idx_top = 0
#idx_top = np.minimum(z_idx-1,
# np.argmin(np.abs(np.subtract(zmid[idx_i,:kmax[idx_i]],zrange[0]))))
zcol_mean[idx_i] = np.divide(
np.sum(np.multiply(
h[idx_i,idx_top:z_idx[idx_i]],
var[idx_i,idx_top:z_idx[idx_i]])),
np.sum(h[idx_i,idx_top:z_idx[idx_i]]))
elif zbottom_pyc[i]:
idx_bottom = kmax[idx_i]
#idx_bottom = np.minimum(kmax[idx_i],
# np.argmin(np.abs(np.subtract(zmid[idx_i,:kmax[idx_i]],zrange[1]))))
zcol_mean[idx_i] = np.divide(
np.sum(np.multiply(
h [idx_i,z_idx[idx_i]:idx_bottom],
var [idx_i,z_idx[idx_i]:idx_bottom])),
np.sum(h[idx_i,z_idx[idx_i]:idx_bottom]))
data[j,i,t] = np.nanmean(zcol_mean[zcol_mean != -9999])
elif zrange[1] != -9999:
data[j,i,t] = np.mean(f.variables[varname[vartitle.index(var)]]
[0,idx,zidx[:,0]:zidx[:,1]] )
elif zeval != -9999:
data[j,i,t] = f.variables[varname[vartitle.index(var)]][0,idx,zidx[:,0]]
f.close()
t += 1
if overwrite:
flag='w+'
else:
flag='a+'
table_file = open(savepath + filename + '.txt',flag)
wr = csv.writer(table_file,dialect='excel')
wr.writerow(colheadings)
rowentries = np.zeros((len(varlist)*len(runlist)+1))
for i,t in enumerate(times):
rowentries[0] = t
rowentries[1:] = data[:,:,i].flatten()
wr.writerow(rowentries)
return
def butter_lowpass_filter(data, cutoff, fs, order):
normal_cutoff = (2. * cutoff) / fs
# Get the filter coefficients
b, a = butter(order, normal_cutoff, btype='low', analog=False)
y = filtfilt(b, a, data)
return y
def tseries1(runlist, varlist, year_range,
placename=[''], lat=-9999, lon=-9999,
operation='mean', apply_filter=False, cutoff=0, #region = '',
varlim=True, show_tipping=False,
zrange=[-9999,-9999], zab=[False], zeval=[-9999],
flip_y=False, velocity_vector=False, tav=0,
ztop_pyc=[False], zbottom_pyc=[False], diff_pyc=[False],
reference_run='', ratio_barotropic=[False],
input_filename=[''], input_filename2='', var2='',
shade_season=False, year_overlay=False, year_minmax=False,
print_to_file=True, create_figure=True,
show_legend=True, show_obs='', obs=[],
linestyle=None, overwrite=False, savepath=savepath):
if linestyle == None:
linestyle = ['-' for i in runlist]
if zab[0]:
m = 'mab'
else:
m = 'm'
nrow=len(varlist)
if velocity_vector:
nrow += -2
ncol=1
if len(zab)<len(varlist):
zab = [zab[0] for i in varlist]
if len(zeval)<len(varlist):
zeval = [zeval[0] for i in varlist]
if len(ztop_pyc)<len(runlist):
ztop_pyc = [False for i in runlist]
if len(zbottom_pyc)<len(runlist):
zbottom_pyc = [False for i in runlist]
if len(diff_pyc)<len(varlist):
diff_pyc = [False for i in varlist]
if len(ratio_barotropic)<len(varlist):
ratio_barotropic = [False for i in varlist]
#if lat != -9999:
# idx,placename = pick_point(run=runlist[0],lat=lat,lon=lon)
fig,axvar = plt.subplots(nrow,ncol,sharex=True)
years = np.arange(year_range[0],year_range[1],1)
t_season.append(1)
filename = ('_'.join(runlist) + '_' +
'_'.join(varlist))
if placename[0] != '':
filename = filename + '_' + placename[0]
if zeval[0] != -9999:
filename = filename + '_z{0:03f}'.format(int(zeval[0])) + m
if zrange[1] != -9999:
filename = filename + '_z{0:03d}-{1:03d}'.format(zrange[0], zrange[1]) + m
for i,var in enumerate(varlist):
if ztop_pyc[i]:
filename = filename + '_abovepyc'
if zbottom_pyc[i]:
filename = filename + '_belowpyc'
filename = filename + '_t{0:03d}-{1:03d}'.format(year_range[0], year_range[1])
if input_filename[0] == '' and not print_to_file:
input_filename[0] = filename
if (not os.path.exists(f'{savepath}/{input_filename[0]}.txt') or overwrite) and print_to_file:
print('extracting time series')
extract_tseries(runlist,varlist,year_range,
placename = placename[0], lat=lat,lon=lon,
operation = operation,
ztop_pyc = ztop_pyc, zbottom_pyc = zbottom_pyc,
zrange=zrange,zab=zab[0], zeval=zeval[0],
savepath=savepath,output_filename = filename)
if not create_figure:
return
df = pandas.read_csv(f'{savepath}/{input_filename[0]}.txt')
times = df['decyear'][:]
if input_filename2 != '':
df2 = pandas.read_csv(f'{savepath}/{input_filename2}.txt')
for i,var in enumerate(varlist):
if len(varlist) == 1:
ax = axvar
else:
ax = axvar[i]
if i == nrow-1:
ax.set(xlabel='Year')
if show_obs=='fill':
ax.fill([year_range[0],year_range[0],year_range[1],year_range[1]],
[obs[0],obs[1],obs[1],obs[0]], facecolor='lightblue',
alpha=0.25, linewidth=None, label='Observed')
if show_obs=='line':
ax.plot([np.min(years),np.max(years)],[obs[0],obs[0]],'--k',linewidth=lw1)
ax.plot([np.min(years),np.max(years)],[obs[1],obs[1]],'--k',linewidth=lw1, label='Wang et al. (2012)')
yaxislabel=varlabel[vartitle.index(var)]
#yaxislabel = yaxislabel +', '+region_title[region_name.index(placename[0])]
ymin = 9999.
ymax = -9999.
for j,run in enumerate(runlist):
if len(input_filename) > 1:
df = pandas.read_csv(f'{savepath}/{input_filename[j]}.txt')
times = df['decyear'][:]
header = '_'+var
if zeval[0] != -9999:
header = header + '_z' + str(int(zeval[0]))
if ztop_pyc[j]:
header = header + '_abovepyc'
rholabel=r'$\sigma_{AASW}$'
if reference_run != '':
yaxislabel = r'$\sigma_{AASW} \: - \: \sigma_{AASW,CTRL} \: (kg \: m^{-3})$'
else:
yaxislabel = r'$\sigma_{AASW} \: (kg \: m^{-3})$'
if zbottom_pyc[j]:
header = header + '_belowpyc'
rholabel=r'$\sigma_{DSW}$'
if reference_run != '':
yaxislabel = r'$\sigma_{DSW} \: - \: \sigma_{DSW,CTRL} \: (kg \: m^{-3})$'
else:
yaxislabel = r'$\sigma_{DSW} \: (kg \: m^{-3})$'
if any(zbottom_pyc) and any(ztop_pyc):
yaxislabel = r'$\sigma \: (kg \: m^{-3})$'
print(f'getting data from {run}{header} in {savepath}/{input_filename[j]})')
data = df[run+header][:]
print(run,np.min(data),np.max(data))
if input_filename2 != '':
data2 = df2[var2+header][:]
yaxislabel = r'$\rho(trough) - \rho(WDW) \: (kg \: m^{-3})$'
if diff_pyc[i]:
data2 = df[run+'_'+var+'_belowpyc'][:]
data = np.subtract(data2,data)
yaxislabel = r'$\Delta \rho \: (kg \: m^{-3})$'
if diff_pyc[i] and reference_run != '':
yaxislabel = r'$\Delta \rho \: - \: \Delta \rho_{CTRL} \: (kg \: m^{-3})$'
elif ratio_barotropic[i]:
data2 = df[run+'_F_barotropic'][:]
data = np.divide(data,np.abs(data2))
yaxislabel = r'Baroclinic flux:Barotropic flux'
if var == 'rho':
data = np.subtract(data, 1000)
#else:
# yaxislabel = varlabel[vartitle.index(var)]
if year_minmax:
data_min = np.zeros((len(years)))
data_max = np.zeros((len(years)))
for idx, yr in enumerate(years):
idx_time = (times>=yr) * (times < yr+1)
data_min[idx] = np.min(data[idx_time])
data_max[idx] = np.max(data[idx_time])
ax.fill_between(years, data_min, y2=data_max, facecolor=run_color[runname.index(run)], alpha=0.2)
#data_min = data.copy()
#data_max = data.copy()
#for idx in range(len(times)):
# data_min[idx] = np.min(data[max(0, idx - 6):min(len(times)-1, idx + 6)])
# data_max[idx] = np.max(data[max(0, idx - 6):min(len(times)-1, idx + 6)])
# #print(f'min,max between {max(0, idx - 6)},{min(len(times)-1, idx + 6)} = {data_min[idx]},{data_min[idx]}')
#ax.fill_between(times, data_min, y2=data_max, facecolor=run_color[runname.index(run)], alpha=0.5)
if apply_filter:
fs = 12 # sampling frequency in 1/years
order = 4
times = times[~np.isnan(data)]
data = data[~np.isnan(data)]
data = butter_lowpass_filter(data, cutoff, fs, order)
if tav > 0:
tav1 = int(tav/2)
data[0:tav1] = math.nan
for t in range(tav1,len(times)-tav1):
data[t] = np.nanmean(data[t-tav1:t+tav1])
data[len(times)-tav1:] = math.nan
if run == reference_run:
data_ref = data
linestyle[j] = '--'
if reference_run != '':
data = np.subtract(data,data_ref)
if year_overlay:
for yr in years:
idx_time = (times>=yr) * (times < yr+1)
pc = ax.plot(times[idx_time]-yr,data[idx_time],
'-', color = run_color[runname.index(run)],
alpha = 0.5)
else:
if input_filename2 != '':
pc = ax.plot(times,np.subtract(data2,data),
'-',
label = runtitle[runname.index(run)],
linewidth = lw1,
color = run_color[runname.index(run)])
#pc = ax.plot(times,data2,
# ':',
# label = runtitle[runname.index(run)],
# linewidth = lw1,
# color = run_color[runname.index(run)])
else:
pc = ax.plot(times,data,
#label = fr'{runtitle[runname.index(run)]}, {rholabel}',
label = fr'{runtitle[runname.index(run)]}',
linewidth = lw1,
linestyle = linestyle[j],
color = run_color[runname.index(run)])
yl = ax.get_ylim()
if show_tipping:
ax.plot([run_tipping_year[runname.index(run)],
run_tipping_year[runname.index(run)]],
#[-100, 2000],
yl,
':', color=run_color[runname.index(run)],
linewidth=lw1)
ax.set_ylim(yl)
if varlim:
ylim = [varmin[vartitle.index(var)], varmax[vartitle.index(var)]]
ax.set_ylim(ylim)
if any(ratio_barotropic):
ylim = [0,1]
ax.set_ylim(ylim)
if shade_season:
if year_overlay:
for s,_ in enumerate(season):
ax.fill([t_season[s],t_season[s],t_season[s+1],t_season[s+1]],
[ylim[0],ylim[1],ylim[1],ylim[0]],
facecolor=season_color[s], alpha=0.5,
linewidth='none')
else:
for yr in years:
for s,_ in enumerate(season):
ax.fill([yr + t_season[s],yr + t_season[s],
yr + t_season[s+1], yr + t_season[s+1]],
[ylim[0],ylim[1],ylim[1],ylim[0]],
facecolor=season_color[s], alpha=0.5,
linewidth=0)
if not varlim:
ax.autoscale()
ax.set_xlim((year_range))
ax.set(ylabel=yaxislabel)
if flip_y:
ax.invert_yaxis()
plt.tight_layout()
if show_legend:
#plt.legend(loc=legloc, frameon=False, bbox_to_anchor=bboxanchor)
plt.legend(loc=legloc, frameon=False)
if tav > 0:
filename = filename + '_tav{:1.03f}'.format(int(tav))
if apply_filter:
filename = filename + '_filter{:1.03f}'.format(cutoff)
if year_minmax:
filename = filename + '_yearminmax'
if year_overlay:
filename = filename + '_yearoverlay'
if reference_run != '':
filename = filename + '_ref' + reference_run
if input_filename2 != '':
filename = filename + '_diff' + var2
if show_obs:
filename = filename + '_obs'
print(f'save tseries figure {savepath}/{filename}.png')
plt.savefig(f'{savepath}/{filename}.png', bbox_inches='tight')
plt.close(fig)
#if velocity_vector:
# i = len(varlist)-2
# plt_aspect = 1/(6*len(years))
# print(plt_aspect)
# width = 10
# fig = plt.figure(figsize=(width,width*plt_aspect*2))
# ax = fig.add_subplot(111)
# ax.set(xlabel='year',ylabel='U (m/s)')
# Umax = np.max(np.sqrt(np.add(np.square(data[i,:]),np.square(data[i+1,:]))))
# y_scalefactor = 1/(12*Umax)
# print(Umax)
# if year_overlay:
# for yr in years:
# idx_time = (times>=yr) * (times < yr+1)
# time = times[idx_time]
# d = data[:,idx_time]
# if runcmp:
# d2 = data2[:,idx_time]
# for ti,t in enumerate(time):
# plt.plot([t-yr,t-yr+d[i,ti]],[0,d[i+1,ti]],'-k',alpha=0.5)
# if runcmp:
# plt.plot([t-yr,t-yr+d2[i,ti]],[0,d2[i+1,ti]],'-b',alpha=0.5)
# else:
# for ti,t in enumerate(times):
# plt.plot([t,t+data[i,ti]],[0,data[i+1,ti]],'-k')
# plt.ylim([-1*Umax,Umax])
# ax.set_aspect(plt_aspect/(2*Umax),adjustable='box')
# filename = ( run + '_U_t_' + str(z) + m + '_' + placename + '_' +
# str(year_range[0]) + '-' + str(year_range[1]) )
# print(filename)
# plt.savefig(savepath + '/' + filename + '.png')
#----------------------------------------------------------------------
# HOVMOLLER
# -- color plot of variable vs. depth and time
#
# Inputs:
# run runname, string
# latS latitude, always in Southern Hem, positive, real
# lonW longitude, always in Western Hem, positive, real
# startyr lower limit on simulated year to plot, real
# endyr upper limit on simulated year to plot, real
# varlist variables to plot, list of strings
# maxDepth maximum depth of plots
# savepath path to save plot images
#----------------------------------------------------------------------
def hovmoller(runlist,year_range,
option = 'coord', coord=[-76,330],
transect_id = '',
varlist = ['T','S','rho','u','v'],zlim = [0,-9999],
limTrue = False, plot_pycnocline = False,
input_filename = '',
savepath=savepath):
if len(runlist) < len(varlist):
runlist = [runlist[0] for i in varlist]
if option == 'coord':
idx,locname = pick_point(run=runlist[0],lat=coord[0],lon=coord[1])
elif option == 'transect':
locname = transect_id
filename = ''
for i,run in enumerate(runlist):
filename = filename + run + '_' + varlist[i] + '_'
filename = ( filename + 'hovmoller_' +
locname + '_' + str(year_range[0]) + '-' + str(year_range[1]) )
print(filename)
if option == 'coord':
years = np.arange(year_range[0],year_range[1],1)
months = np.arange(1,13,1)
nt = len(years)*len(months)
times = np.zeros((nt,))
fmesh = netCDF4.Dataset(meshpath[runname.index(runlist[0])])
# calculate z from depths
zmid,ztop,zbottom = zmidfrommesh(fmesh,cellidx=[idx],vartype='scalar')
z = np.zeros((len(zmid[0,:])+1))
#zh = fmesh.variables['layerThickness'][0,idx,:]
#zbottom = np.subtract(zmid[0,:],0.5*zh)
z[0] = ztop[0,0]#zmid[0,0]+zh[0]
z[1:] = zbottom[0,:]
#z = z[0:fmesh.variables['maxLevelCell'][idx]]
nz = len(z)
data = np.zeros((len(varlist),nz,len(times)))
z_pyc = np.zeros((len(varlist),len(times)+1))
t=0
for yr in years:
for mo in months:
times[t] = yr+(mo-1.0)/12.0
datestr = '{0:04d}-{1:02d}'.format(yr, mo)
for i,var in enumerate(varlist):
mpas_filename = (
'{0}/mpaso.hist.am.timeSeriesStatsMonthly.'.format(
runpath[runname.index(runlist[i])])
+ datestr + '-01.nc')
f = netCDF4.Dataset(mpas_filename, 'r')
data[i,1:,t] = (f.variables[varname[vartitle.index(var)]]
[0,idx,:nz-1])
if plot_pycnocline:
#for ti in range(start_time_idx,end_time_idx-2):
z_pyc[i,t] = z_pycnocline(zmid,
f.variables[varname[vartitle.index('T')]][0,idx,:nz-1],
f.variables[varname[vartitle.index('S')]][0,idx,:nz-1])
f.close()
t += 1
times = np.append(times,np.max(times)+(1/12))
z_pyc[:,-1] = z_pyc[:,-2]
start_time_idx = 0
end_time_idx = len(times)+1
elif option == 'transect':
if not os.path.exists(savepath + input_filename):
print(input_filename,' does not exist')
return
df = pandas.read_csv(savepath+input_filename)
t = df['decyear'][:]
times = t.to_numpy(dtype='float32')
start_time_idx = np.argmin(np.abs(times - year_range[0]))
end_time_idx = np.argmin(np.abs(times - year_range[1]))
times = np.append(times,np.max(times)+(1/12))
# one more time point is needed to specify the right points of quadrilateral
zbottom = np.zeros(270)
zcol = []
i = 0
# ztop is already written to specify the upper points of quadrilateral
for col in df.columns:
if col[0] == '-':
zcol.append(col)
zbottom[i] = float(col)
i += 1
zbottom = zbottom[zbottom != 0]
zmid = zbottom[1:] - (zbottom[1:]-zbottom[:-1])/2
z = zbottom
nz = len(z)
data = np.zeros((len(varlist),nz,len(times)))
#for i in range(start_time_idx,end_time_idx):
# data[0,:,i] = df['u_barotropic_sum'][i]
for i,_ in enumerate(z):
data[1,i,:-1] = df[zcol[i][:]][:]
locname = transect_id
zlim[0] = min(zlim[0],np.max(z))
zlim[1] = max(zlim[1],np.min(z[~np.isnan(data[1,:,0])])) #zlim[1] = np.min(z)
nrow=len(varlist)
ncol=1
data[np.isnan(data)] = 0
fig,axvar = plt.subplots(nrow,ncol,sharex=True)
for i,var in enumerate(varlist):
cm = plt.get_cmap(varcmap[vartitle.index(var)])
if limTrue:
cNorm = colors.Normalize(vmin=varmin[vartitle.index(var)],
vmax=varmax[vartitle.index(var)])
elif var[0] == 'u' or var[0] == 'v':
vlim = np.max(np.abs(data[i,:,:]))
cNorm = colors.Normalize(vmin=-1*vlim, vmax=vlim)
else:
cNorm = colors.Normalize(vmin=np.min(np.abs(data[i,:,:])),
vmax=np.max(np.abs(data[i,:,:])))
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)
if plot_pycnocline:# and (var == 'T' or var == 'S' or var == 'rho'):
#print(times)
#print(z_pyc[i,:])
pypyc = axvar[i].plot(times,z_pyc[i,:],'-k')
#for ti in range(start_time_idx,end_time_idx-2):
# pypyc = axvar[varlist.index('T')].plot(
# [times[ti],times[ti+1]],
# [z_pyc[ti],z_pyc[ti]],'-k')
pc = axvar[i].pcolormesh(times[start_time_idx:end_time_idx+1], z,
data[i,1:,start_time_idx:end_time_idx],
cmap = cm, norm=cNorm)
if i == nrow-1:
axvar[i].set(xlabel='Simulated year')
axvar[i].set(ylabel=varlabel[vartitle.index('z')])
axvar[i].set_ylim((zlim))
axvar[i].invert_yaxis()
cbar = fig.colorbar(scalarMap,ax=axvar[i])
cbar.set_label(varlabel[vartitle.index(var)])
axvar[i].set(title = runtitle[runname.index(runlist[i])])# + ': ' + locname)
plt.savefig(savepath + filename + '.png')#,dpi=set_dpi)
plt.close()
#----------------------------------------------------------------------
# PROFILE
# -- variable vs. depth at a given geographic location
#
# Inputs:
# varlist variables to plot, list of strings
# run runname, string
# startyr lower limit on simulated year to plot, real
# endyr upper limit on simulated year to plot, real
# latS latitude, always in Southern Hem, positive, real
# lonW longitude, always in Western Hem, positive, real
# maxDepth maximum depth of plots
# runcmp if true, plot both entries in runname
# mo month to plot data from, if 0 then plot all months of data
# savepath path to save plot images
#----------------------------------------------------------------------
def profile(runlist,varlist,year_range,
lat=-9999,lon=-9999,placename = '',
maxDepth = -500.,mo = 0,
savepath=savepath):
varmin[vartitle.index('T')] = -2.2
varmax[vartitle.index('T')] = 2
varmin[vartitle.index('S')] = 32.8
varmax[vartitle.index('S')] = 34.8
varmin[vartitle.index('rho')] = 1026.7
varmax[vartitle.index('rho')] = 1027.8
varmin[vartitle.index('u')] = -0.03
varmax[vartitle.index('u')] = 0.03
varmin[vartitle.index('v')] = -0.03
varmax[vartitle.index('v')] = 0.03
fmesh = netCDF4.Dataset(meshpath[runname.index(runlist[0])])
idx,placename = pick_point(lat=lat,lon=lon,placename = placename)
zmid,_,_ = zmidfrommesh(fmesh,cellidx=[idx])
zmid = zmid[0,:]
datestr=str(year_range[0]) + '-' + str(year_range[1])
if mo != 0:
datestr= datestr+'_mo'+str(mo)
filename = ('_'.join(runlist) + '_' +
''.join(varlist) + '_profiles_' + placename +
'_' + datestr )
print(filename)
#latCell = fmesh.variables['latCell'][:]
#lonCell = fmesh.variables['lonCell'][:]
#xCell = fmesh.variables['xCell'][:]
#yCell = fmesh.variables['yCell'][:]
#depths = fmesh.variables['refBottomDepth'][:]
#zmax = np.multiply(-1,fmesh.variables['bottomDepth'][:])
#zice = fmesh.variables['landIceDraft'][0,:]
#logical_N = (latCell < lat_N*deg2rad) & (xCell > 0)
#locname = str(latS) + 'S' + str(lonW) + 'W'
#latplt = -1.*latS*deg2rad
#lonplt = (360.-lonW)*deg2rad
#idx = np.argmin( (latCell-latplt)**2 + (lonCell-lonplt)**2) #122901-1
years = np.arange(year_range[0],year_range[1]+1,1)
if mo == 0:
months = np.arange(1,13,1)
else:
months = [mo]
nt = len(years)*len(months)
times = np.zeros((nt,))
colors = [ cmx.jet(x) for x in np.linspace(0.0, 1.0, 13)]
lineStyle = ['-' for i in runlist]
#lineStyle = ['-','--',':','-.']
nrow=1
ncol=len(varlist)
fig,axvar = plt.subplots(nrow,ncol,sharey=True)
axvar[0].set(ylabel='depth (m)')
t = 0
for r,run in enumerate(runlist):
for i,yr in enumerate(years):
for j,mo in enumerate(months):
c = colors[j]
# lat = region_coordbounds[region_name.index(placename)][1,1]
# lon = region_coordbounds[region_name.index(placename)][0,0]
datestr = '{0:04d}-{1:02d}'.format(yr, mo)
input_filename = '{0}/mpaso.hist.am.timeSeriesStatsMonthly.'.format(runpath[runname.index(run)]) + datestr + '-01.nc'
if not os.path.exists(input_filename):
continue
f = netCDF4.Dataset(input_filename, 'r')
for k,var in enumerate(varlist):
data = f.variables[varname[vartitle.index(var)]]
axvar[k].plot(data[0,idx,:], zmid,
color = run_color[runname.index(run)],
#color=c,
linestyle=lineStyle[r])
axvar[k].set(xlabel=varlabel[vartitle.index(var)])
axvar[k].set_xlim([varmin[vartitle.index(var)],
varmax[vartitle.index(var)]])