forked from matthewhoffman/e3sm-cryo-analysis-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
weddell_mod2.py
2380 lines (2152 loc) · 102 KB
/
weddell_mod2.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
sys.path.append('/global/homes/c/cbegeman/e3sm-cryo-analysis-scripts/great_circle_calculator')
import os
import csv
import gsw
import netCDF4
import cartopy
import pyproj
import great_circle_calculator.great_circle_calculator as great_circle#import LatLon
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 *
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_nersc,
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_nersc):
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 = '',#region = '',
lat=-9999,lon=-9999,
zrange=[20,-9999],zeval = [-9999],zab=False,
ztop_pyc = [False],zbottom_pyc = [False],
overwrite=True, output_filename = '',
savepath=savepath_nersc):
if zab:
m = 'mab'
else:
m = 'm'
if len(zeval) < len(varlist):
zeval = [zeval[0] for i in varlist]
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 +
'_z{0:03d}-{1:03d}'.format(zrange[0], zrange[1]) + m +
'_t{0:03d}-{1:03d}'.format(year_range[0], year_range[1]) )
else:
filename = output_filename
print(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])])
if lat != -9999: #placename != '' or
#if lat == -9999: #if lon == -9999:
# 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]
else:
idx = pick_from_region(region=placename,run=runlist[0],plot_map=False)
data = np.zeros((len(runlist),len(varlist),nt))
kmax = fmesh.variables['maxLevelCell'][idx]
zmid,_,_ = zmidfrommesh(fmesh,cellidx=idx)
#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[i] != -9999:
header = header + '_z' + str(int(zeval[i]))
if ztop_pyc[i]:
header = header + '_abovepyc'
if zbottom_pyc[i]:
header = header + '_belowpyc'
colheadings.append(header)
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 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):
data[j,:,t] = math.nan
continue
f = netCDF4.Dataset(input_filename, 'r')
for i,var in enumerate(varlist):
if var in surfvar:
data[j,i,t] = f.variables[varname[vartitle.index(var)]][0,idx]
else:
if ztop_pyc[i] or zbottom_pyc[i]:
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,:]
var = f.variables[varname[vartitle.index(var)]][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 = np.argmin(np.abs(np.subtract(zmid[idx_i,:kmax[idx_i]],zpyc)))
if np.isnan(z_idx) or z_idx == 0 or z_idx == 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],
var[idx_i,idx_top:z_idx])),
np.sum(h[idx_i,idx_top:z_idx]))
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_bottom],
var [idx_i,z_idx:idx_bottom])),
np.sum(h[idx_i,z_idx:idx_bottom]))
data[j,i,t] = np.nanmean(zcol_mean[zcol_mean != -9999])
elif zrange[1] != -9999:
if zab:
zeval = np.add(zmid[0][-1],zrange)
else:
zeval = zrange
zidx = ([np.argmin(np.abs(np.subtract(zmid,zeval[0]))),
np.argmin(np.abs(np.subtract(zmid,zeval[1])))])
if zidx[1] == zidx[0]:
zidx[1] += 1
if zidx[1] < zidx[0]:
zidx = [zidx[1],zidx[0]]
data[j,i,t] = np.mean(f.variables[varname[vartitle.index(var)]]
[0,idx,zidx[0]:zidx[1]] )
elif zeval[i] != -9999:
if zab:
zeval[i] = np.add(zmid[0][-1],zeval[i])
zidx = np.argmin(np.abs(np.subtract(zmid,zeval[i])))
data[j,i,t] = f.variables[varname[vartitle.index(var)]][0,idx,zidx]
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,
apply_filter = False, cutoff = 0, #region = '',
varlim = [-9999,-9999],zrange=[20,-9999],zab=False,zeval=[-9999],
velocity_vector=False,
ztop_pyc = [False], zbottom_pyc = [False], diff_pyc = [False],
reference_run = '', ratio_barotropic = [False], input_filename = '',
shade_season = False, year_overlay=False,
print_to_file = True, create_figure = False,
overwrite=True, savepath=savepath_nersc):
linestyle = ['-' for i in runlist]
if zab:
m = 'mab'
else:
m = 'm'
nrow=len(varlist)
if velocity_vector:
nrow += -2
ncol=1
if len(zeval) < len(varlist):
zeval = [zeval[0] for i in varlist]
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 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)
for i,var in enumerate(varlist):
print(ztop_pyc[i])
if input_filename == '':
filename = ('_'.join(runlist) + '_' +
varlist[i] + '_' + placename)
#''.join(varlist) + '_' + placename)
if zeval[0] != -9999:
filename = filename + '_z{0:03d}_z{1:03d}'.format(zeval[0], zeval[1]) + m
if zrange[1] != -9999:
filename = filename + '_z{0:03d}-{1:03d}'.format(zrange[0], zrange[1]) + m
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])
else:
filename = input_filename
print(filename)
if not os.path.exists(savepath + filename + '.txt'):
print('extracting time series')
extract_tseries(runlist,varlist,year_range,
placename = placename,lat=lat,lon=lon,
ztop_pyc = ztop_pyc, zbottom_pyc = zbottom_pyc,
zrange=zrange,zab=zab, zeval=zeval,
output_filename = filename)#region=region,
if not create_figure:
continue
df = pandas.read_csv(savepath + filename + '.txt')
if len(varlist) == 1:
ax = axvar
else:
ax = axvar[i]
if i == nrow-1:
ax.set(xlabel=r'Year')
ymin = 9999.
ymax = -9999.
for j,run in enumerate(runlist):
times = df['decyear'][:]
print(run)
header = run+'_'+var
if zeval[i] != -9999:
header = header + '_z' + str(int(zeval[i]))
if ztop_pyc[i]:
header = header + '_abovepyc'
yaxislabel = r'$\rho_{ASW} \: - \: \rho_{ASW,CTRL} \: (kg \: m^{-3})$'
if zbottom_pyc[i]:
header = header + '_belowpyc'
yaxislabel = r'$\rho_{DSW} \: - \: \rho_{DSW,CTRL} \: (kg \: m^{-3})$'
data = df[header][:]
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))
print(np.nanmean(data))
yaxislabel = r'Baroclinic flux:Barotropic flux'
#else:
# yaxislabel = varlabel[vartitle.index(var)]
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 run == reference_run:
data_ref = data
linestyle[j] = '--'
if reference_run != '':
data = np.subtract(data,data_ref)
#if varlim[0] == -9999:
# varlim[0] = np.minimum(varlim[0],np.min(data))
# varlim[1] = np.maximum(varlim[1],np.max(data))
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:
pc = ax.plot(times,data,
'-',
label = runtitle[runname.index(run)],
linewidth = lw1,
linestyle = linestyle[j],
color = run_color[runname.index(run)])
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]],
[varlim[0],varlim[1],varlim[1],varlim[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]],
[varlim[0],varlim[1],varlim[1],varlim[0]],
facecolor=season_color[s], alpha=0.5,
linewidth=0)
if varlim[0] != -9999:
ax.set_ylim((varlim))
if any(ratio_barotropic):
ax.set_ylim([0,1])
ax.set_xlim((year_range))
ax.set(ylabel=yaxislabel)
plt.legend(loc=legloc,bbox_to_anchor=bboxanchor)
filename = ('_'.join(runlist) + '_' +
''.join(varlist) + '_' + placename)
if zeval[0] != -9999:
filename = filename + '_z{0:03d}_z{1:03d}'.format(zeval[0], zeval[1]) + m
if zrange[1] != -9999:
filename = filename + '_z{0:03d}-{1:03d}'.format(zrange[0], zrange[1]) + m
if any(ztop_pyc):
filename = filename + '_abovepyc'
if any(zbottom_pyc):
filename = filename + '_belowpyc'
if any(ratio_barotropic):
filename = filename + '_ratio'
if reference_run != '':
filename = filename + '_ref'+reference_run
filename = filename + '_t{0:03d}-{1:03d}'.format(year_range[0], year_range[1])
if apply_filter:
filename = filename + '_filter{:1.03f}'.format(cutoff)
print('save tseries figure', filename)
plt.savefig(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_nersc):
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 = ( runlist[0] + '_' + varlist[0] + '_' +
runlist[1] + '_' + varlist[1] + '_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):
input_filename = (
'{0}/mpaso.hist.am.timeSeriesStatsMonthly.'.format(
runpath[runname.index(runlist[i])])
+ datestr + '-01.nc')
f = netCDF4.Dataset(input_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(200)
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_nersc):
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])
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 = ['-','--',':','-.']
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'
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=c,linestyle=lineStyle[r])
axvar[k].set(xlabel=varlabel[vartitle.index(var)])
axvar[k].set_xlim([varmin[vartitle.index(var)],
varmax[vartitle.index(var)]])
axvar[k].set_ylim([maxDepth,0])
axvar[k].grid()
#plt.title(run + ': ' + datestr)
plt.savefig(savepath + filename + '.png',dpi=set_dpi)
plt.close()
#----------------------------------------------------------------------
# FLUXGATE
# -- Computes volumetric flux perpendicular to transect line and saves
# output to a csv file
#
# Inputs:
# transect_id
# yrrange
# optional variables:
# run runname, string
# runcmp if true, plot difference between variables of both entries in runname
# overwrite logical, if true, overwrite image file of same name TODO check
# plotting logical, if true, plot map of fluxgate location
# savepath path to save plot images
#----------------------------------------------------------------------
# TODO add option to define fluxgate across topography contour
# TODO add separate function to select transect points, which are then inputs to this function and others
def fluxgate(transect_id, yrrange = [50,51], morange = [1,13],
run_incr=['ISMF'], runcmp = False, runcmpname='ISMF-noEAIS',
mode = 'barotropic-baroclinic', overwrite=False,
plot_map = False, plot_transect=False,
savepath=savepath_nersc):
# import variables from file
fmesh = netCDF4.Dataset(meshpath[runname.index(run_incr[0])])
cellidx, idx, dist, transect_angle = pick_transect(#option='by_index',
run=run_incr[0],transect_name = transect_id,
overwrite=plot_map)
dv = fmesh.variables['dvEdge'][idx] # length of edge between vertices
angle = fmesh.variables['angleEdge'][idx] # angle in rad an edge normal vector makes with eastward
zh = fmesh.variables['layerThickness'][0,cellidx,:]
zmax = np.multiply(-1,fmesh.variables['bottomDepth'][cellidx])
zice = fmesh.variables['landIceDraft'][0,cellidx]
cell1 = np.subtract(fmesh.variables['cellsOnEdge'][idx,0],1)
cell2 = np.subtract(fmesh.variables['cellsOnEdge'][idx,1],1)
zmid,zbottom,ztop = zmidfrommesh(fmesh,cellidx=cellidx,vartype='scalar')
# Create depth vector for reporting cross-transect averaged
# baroclinic velocities
zu,idx_unique = np.unique(zbottom,return_index = True)
temp_idx = np.argsort(-1*zu)
zu = zu[temp_idx]
zh_temp = zh.flatten()[idx_unique]
zuh = zh_temp[temp_idx]
# angle the normal edge velocity makes with transect
dangle = angle - transect_angle
dangle[dangle>180] += -360
edgeSigns = np.divide(dangle,abs(dangle))
#mask = np.zeros(np.shape(depths),dtype=bool)
#for i,~ in enumerate(mask):
# if (depths[i] > zmax[i]) and (depths[i] < zice[i]):
# mask[i] = True
row,col = np.shape(zmid)
mask = np.zeros((row,col),dtype=bool)
for i in range(row):
for j in range(col):
if (zmid[i,j] > zmax[i]) and (zmid[i,j] < zice[i]):
mask[i,j] = True
F = np.multiply(zmid,0)
# compute face area
area = np.multiply(zmid,0)
for i in range(row):
for j in range(col):
area[i,j] = zh[i,j] * dv[i]
width_zsum = np.zeros((len(zu)))
for i,_ in enumerate(cellidx):
for j,_ in enumerate(zmid):
for k,_ in enumerate(zu):
if (zbottom[i,j] >= zu[k]) and (zbottom[i,j] < zu[k]+zuh[k]):
width_zsum[k] += dv[i]
width_zsum[width_zsum==0.] = math.nan
if plot_transect:
# create mesh variables for plotting
# distance along transect for plotting
xpt = fmesh.variables['xEdge'] [idx]
ypt = fmesh.variables['yEdge'] [idx]
n = np.sqrt( np.square(ypt- ypt[0]) +
np.square(xpt- xpt[0]) )
yline = np.divide(n,1e3)
temp,ymesh= np.meshgrid(np.zeros((col,)),n)
# initialize text files for saving output
if overwrite:
flag='w+'
else:
flag='a+'
col_headings = ['year','month','decyear']
#if runcmp:
# wr.writerow(['year','month','decyear',
# run+'_flux_pos',run+'_flux_neg',run+'_flux_total',
# runcmpname+'_flux_pos',runcmpname+'_flux_neg',runcmpname+'_flux_total'])
#else:
# wr.writerow(['year','month','decyear',
# run+'_flux_pos',run+'_flux_neg',run+'_flux_total'])