-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNorESM_utils.py
2876 lines (2728 loc) · 141 KB
/
NorESM_utils.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
#import ESMF
#from esmf_utils import grid_create, grid_create_periodic
import xarray as xr
import dask
import numpy as np
from matplotlib.colors import from_levels_and_colors
import matplotlib as mpl
#
import numpy as np
import numpy.ma as ma
#import math as math
#import scipy.io.netcdf as nio
#import scipy.io as io
from scipy.interpolate import griddata
from scipy import interpolate
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
from shapely.geometry.polygon import LinearRing
import os
#
import cartopy.crs as ccrs
#
#from mpl_toolkits.basemap import Basemap
import sys
#import dist
from scipy import stats
import calendar
# Some locally installed stuff
#import h5py
#import gsw
#import seawater as sw
#from netCDF4 import Dataset
#import math
#
#
#######################
#
def distance(origin, destination, radius = 6371):
'''
'''
lat1, lon1 = origin
lat2, lon2 = destination
dlat = np.radians(lat2-lat1)
dlon = np.radians(lon2-lon1)
a = np.sin(dlat/2) * np.sin(dlat/2) + np.cos(np.radians(lat1))* np.cos(np.radians(lat2)) * np.sin(dlon/2) * np.sin(dlon/2)
c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1-a))
d = radius * c
#
return d
def circular_boundary(rad=0.5):
'''
Create a circular path for cartopy polar stereographic plots
see https://scitools.org.uk/cartopy/docs/latest/gallery/always_circular_stereo.html#custom-boundary-shape
'''
theta = np.linspace(0, 2*np.pi, 100)
center, radius = [0.5, 0.5], rad
verts = np.vstack([np.sin(theta), np.cos(theta)]).T
return mpl.path.Path(verts * radius + center)
def discrete_cmap(levels,cmap0=mpl.cm.viridis,extend='both'):
'''
Create a discrete colormap
'''
cmlist=[];
if extend in ['max','min']:
rgb_levels = np.linspace(0,252,len(levels))
elif extend in ['both']:
rgb_levels = np.linspace(0,252,len(levels)+1)
else:
rgb_levels = np.linspace(0,252,len(levels)-1)
#
for cl in rgb_levels: cmlist.append(int(cl))
#
cmap1, norm1 = from_levels_and_colors(levels,cmap0(cmlist),extend=extend)
#
return cmap1, norm1
def read_sections_old(filename):
'''Read the section indeces defined on NorESM grid. Note that these indeces are defined for Fortran 1 based system so one needs to substract one to get the correct python 0 based indeces'''
f=open(filename)
data=f.readlines()
f.close()
datanames=[]
c=0
for j in range(len(data)+1):
if j==len(data) or data[j][0:4]=='Name':
#save the old data
if (j!=0):
exec(datanames[c]+'=np.ones((len(dummy),len(dummy[0])))')
for k in range(len(dummy)):
exec(datanames[c]+'[k,:]=dummy[k]')
c=c+1
if (j!=len(data)):
#intialize the new variables
exec('datanames.append("'+data[j][6:-1].strip()+'")')
dummy=[]
else:
dummy.append(np.array(data[j].strip().split(),dtype=int))
#
#Put everything into a dictionary and return that
output={}
for dataname in datanames:
exec('output.update({"'+dataname+'": '+dataname+'})')
#
return output
def read_sections(filename):
'''
Read the section indeces defined on NorESM grid.
Note that these indeces are defined for Fortran 1 based system
so one needs to substract one to get the correct python 0 based indeces
'''
#
data=open(filename).readlines()
titles = [name for name in data if 1+name.find('Name')]
indices = [data.index(title) for title in titles] #indices of the titles
indices.append(len(data)) # last index
#
output={}
for ii,ind in enumerate(indices[:-1]):
dum=[]
for jj in range(ind+1,indices[ii+1]):
dum.append(np.array(data[jj].strip().split(),dtype=int)-1)
output[titles[ii][6:-1].strip()]=np.array(dum)
return output
def read_section_data(fpath,model,ens,files):
"""Read section transports from CMIP5 models. MFO is the standard output."""
filenames=[]
for fil in files:
filenames.append(fpath+model+'/'+ens+'/'+fil)
#Read the passage names
f=nio.netcdf_file(filenames[0])
passages=f.variables['passage']
dummy=[]
#print model
for passage in passages:
dummy.append(passage.tostring().replace('\0','').strip())
#
#print dummy
f.close()
#read the files and construct time and data arrays
#this is needed because some of the models have more than one file per ensemble
time_size=[] #length of each file (how many time steps)
time_size.append(0)
for c in range(len(filenames)):
exec('f'+str(c)+'=nio.netcdf_file(filenames[c])')
exec('time_size.append(len(f'+str(c)+'.variables["time"][:]))')
#After checking how many files there are create arrays for the mfo and time
mfo=np.ones((sum(time_size),len(dummy)))*np.nan
timeaxis=np.ones(sum(time_size))*np.nan
time_size=np.cumsum(time_size)
#read the data
for c in range(len(filenames)):
exec('mfo[time_size[c]:time_size[c+1],:]=f'+str(c)+'.variables["mfo"][:,:]')
exec('timeaxis[time_size[c]:time_size[c+1]]=f'+str(c)+'.variables["time"][:].squeeze()')
exec('f'+str(c)+'.close()')
#Create the output dictionary
output={}
#output.update({"passage_names": dummy})
output.update({"time": timeaxis})
c=0
for passage in dummy:
exec('output.update({"'+passage+'": mfo[:,c]})')
c=c+1
#
return output, dummy
def section_data():
#Read the mfo data, start by checking which models and ensembles are available
fpath='/Data/skd/share/ModData1/CMIP5/ocean/rcp85/mfo/mon/'
models=os.listdir(fpath)
ens_num=np.zeros(len(models))
c=0
for model in models:
exec('ens_num[c]=len(os.listdir("'+fpath+model+'/"))')
c=c+1
#use the read_section_data for the actual reading
data={}
p=0
for model in models:
for j in range(int(ens_num[p])):
exec('mfo_'+model.replace('-','_')+'_r'+str(j+1)+', passage_names=read_section_data(fpath,model,"r'+str(j+1)+'i1p1",os.listdir("'+fpath+model+'/r'+str(j+1)+'i1p1/"))')
exec('data.update({"mfo_'+model.replace('-','_')+'_r'+str(j+1)+'":mfo_'+model.replace('-','_')+'_r'+str(j+1)+'})')
p=p+1
#
data.update({"passage_names": passage_names})
data.update({"models": models})
#
return data
def PAGO_sections(sections,modelname,fname):
#READ IN SECTIONS DEFINED IN PAGO AND PUT THEM INTO A NICE FORMAT
#sections=['brw','brn','be1','be2','fst','lan','nrs','BER','baf','dso','ifo','fso']
#note the corrections, somehow PAGO assumes that v to be on the north face so have to change v or u points up or down depending on the direction of the turn
model_sections=io.loadmat("/Data/skd/users/anu074/CMIP_PAGO/"+modelname+fname)
veci=[]; vecj=[]; udir=[]; vdir=[];
for s, section in enumerate(sections):
j=np.where(model_sections["MODEL_sections"]["name"][0][:]==section)[0][0]
dir1=model_sections["MODEL_sections"][0][j][3].copy()
dir2=model_sections["MODEL_sections"][0][j][4][0].copy()
jj=[]; ii=[]; carryover1=False; carryover2=False
ii.append(int(model_sections["MODEL_sections"][0][j][1][0][0].copy()))
jj.append(int(model_sections["MODEL_sections"][0][j][2][0][0].copy()))
for k in range(1,len(model_sections["MODEL_sections"][0][j][1][0])):
i1=int(model_sections["MODEL_sections"][0][j][1][0][k].copy())
j1=int(model_sections["MODEL_sections"][0][j][2][0][k].copy())
if (dir1[k]!=dir1[k-1] and dir1[k-1]=='W' and ((int(dir2[k-1])==1 and int(dir2[k])==-1) or (int(dir2[k-1])==-1 and int(dir2[k])==1)) ) or (j1<jj[k-1] and carryover1): #from west face to north face
ii.append(i1)
jj.append(j1+1) #v should be read from north face
carryover1=True
if carryover2:
carryover2=False
elif (dir1[k]!=dir1[k-1] and dir1[k-1]=='N' and ((int(dir2[k-1])==1 and int(dir2[k])==1) or (int(dir2[k-1])==-1 and int(dir2[k])==-1)) ) or (j1>jj[k-1] and carryover2): #from north face to west face
ii.append(i1)
jj.append(j1-1) #u should be read from the cell below the previous one
carryover2=True
if carryover1:
carryover1=False
else:
ii.append(i1)
jj.append(j1)
veci.append(ii)#(model_sections["MODEL_sections"][0][j][1][0].copy())
vecj.append(jj)#(model_sections["MODEL_sections"][0][j][2][0].copy())
#dir1=model_sections["MODEL_sections"][0][j][3].copy()
#dir2=model_sections["MODEL_sections"][0][j][4][0].copy()
diru=dir2.copy(); dirv=dir2.copy()
diru[list(np.where(dir1=='N')[0])]=0; udir.append(diru);
dirv[list(np.where(dir1=='W')[0])]=0; vdir.append(dirv);
model={"names": sections, "veci": veci, "vecj": vecj, "udir": udir, "vdir":vdir}
return model
def fix_PAGO(s_v,s_u,data):
""" Since the PAGO follows the vertices there can be a checkboard pattern in the velocity. This function is attempt to fix that by adding one velocity to the other"""
if ma.sum(abs(s_v))>=ma.sum(abs(s_u)):
ind1=ma.where(s_v)[0]
ind2=ma.where(s_u)[0]
else:
ind1=ma.where(s_u)[0]
ind2=ma.where(s_v)[0]
if len(data.shape)>1:
for i in ind2: #add to the 2 closest points - almost work, maybe should be added to all the points in the vicinity
i1=ma.where(abs(ind1-i)==ma.min(abs(ind1-i)))[0]
i1=ind1[i1]
if len(i1)==1:
data[:,i1[0]]=ma.masked_array(data[:,i1[0]].data+data[:,i].data,mask=data[:,i1[0]].mask)
else:
data[:,i1[0]]=ma.masked_array(data[:,i1[0]].data+.5*data[:,i].data,mask=data[:,i1[0]].mask)
data[:,i1[1]]=ma.masked_array(data[:,i1[1]].data+.5*data[:,i].data,mask=data[:,i1[1]].mask)
dataout=data[:,ind1]
else:
for i in ind2: #add to the 2 closest points - almost work, maybe should be added to all the points in the vicinity
i1=ma.where(abs(ind1-i)==ma.min(abs(ind1-i)))[0]
i1=ind1[i1]
if len(i1)==1:
data[i1[0]]=ma.masked_array(data.data[i1[0]]+data.data[i],mask=data.mask[i1[0]])
else:
data[i1[0]]=ma.masked_array(data.data[i1[0]]+.5*data.data[i],mask=data.mask[i1[0]])
data[i1[1]]=ma.masked_array(data.data[i1[1]]+.5*data.data[i],mask=data.mask[i1[1]])
dataout=data[ind1]
return ind1,dataout
def find_bottompatch(x,y,maxd):
#Note that hear we assume that we want to have a patch starting from
#lower left corner and moving over with maximum depth maxd to the lower rigth corner
#From there we move to the upper left corner with depths at y
#This works for interpolated data
b_patch=np.zeros((len(x)*2,2))
for k in range(len(x)):
b_patch[k,1]=maxd; b_patch[k+len(x),1]=y[len(x)-k-1];
b_patch[k,0]=x[k]; b_patch[k+len(x),0]=x[len(x)-k-1];
#
#If we want follow the grid lines then we do the following
b_patch2=np.zeros((len(x)*2+4,2))
#bottom part
b_patch2[0:2,1]=maxd; b_patch2[0,0]=min(x); b_patch2[1,0]=max(x);
#surface part
imid=int(len(x)/2.); imid2=imid*2
b_patch2[2:imid2+2:2,0]=x[imid-1:-1][::-1]; #from left to middle
b_patch2[3:imid2+2:2,0]=x[imid-1:-1][::-1]; #from left to middle
b_patch2[imid2+3:-1:2,0]=x[:imid][::-1]; #from rigth to middle
b_patch2[imid2+4:-1:2,0]=x[:imid][::-1]; #from rigth to middle
b_patch2[imid2+2,0]=x[imid-1]; b_patch2[imid*2+2]=x[imid-1];
b_patch2[2,0]=x[-1]; b_patch[-1,0]=x[0]
#
b_patch2[2,1]=y[-1]; b_patch2[-1,1]=y[0] #First surface points
b_patch2[3:imid2+3:2,1]=y[imid-1:-1][::-1]; #from left to middle
b_patch2[4:imid2+4:2,1]=y[imid-1:-1][::-1]; #from left to middle
b_patch2[imid2+2:-2:2,1]=y[:imid][::-1]; #from rigth to middle
b_patch2[imid2+3:-2:2,1]=y[:imid][::-1]; #from rigth to middle
return b_patch, b_patch2
def point_inside_polygon(x,y,poly):
""" As it says, find out if points x,y are inside polygon poly """
#Determine if a point is inside a given polygon or not
#Polygon is a list of (x,y) pairs.
#Note that this does not work in lon,lat coordinates -> use basemap to convert lon,lat to some map projection coordinates
#Adapted from http://www.ariel.com.au/a/python-point-int-poly.html
n = len(poly)
inside =False
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x,p1y = p2x,p2y
return inside
#def insphpoly(lon,lat,lonv,latv,lon0,lat0):
# """ INSPHPOLY True for points inside or on a polygonal region. INSIDE = INSPHPOLY(LON,LAT,LONV,LATV,LON0,LAT0) returns a matrix INSIDE the size of LON and LAT. INSIDE(p,q) = 1 if the point (LON(p,q), LAT(p,q)) is either strictly inside or on the edge of the spherical polygonal region whose vertices are specified by the vectors LONV and LATV; otherwise INSIDE(p,q) = 0. All positions are stereographically projected onto a plane with (LON0, LAT0) in origo before polygon testing is done."""
# #
# #rad=pi/180;
# #w=np.tan((90-lat0)*rad/2).*np.exp(np.i*lon0*rad);
# #z=np.tan((90-lat)*rad/2).*np.exp(np.i*lon*rad);
# #z=(z-w)./(np.conj(w).*z+1);
# #zv=np.tan((90-latv)*rad/2).*np.exp(np.i*lonv*rad);
# #zv=np.(zv-w)./(conj(w).*zv+1);
# #
# #inside=inpolygon(real(z),imag(z),real(zv),imag(zv));
# #return inside
def basin_coords(x,y,basin_name):
""" Determine the basins based on the basin name and create the polygon """
if basin_name=='nansen':
#xp=[20.5, 20.5, 70, 100, 80, 50, 20.5]
#yp=[82, 84, 85.5, 84, 83.5, 83.5, 82]
xp=[350.,20.,20.,70.,110.,115.,125.,115.,70.,20.,350.,350.]
yp=[81.,81.,81.,82.,80.,77.,77.,82.5,85.5,85.,85.,81.]
elif basin_name=='amundsen':
#xp=[330,160,110,135,125.5,100,80.5,0.5,330]
#yp=[86.5, 89.5,88,84,83.5,87,88,86.5,86.5]
xp=[350.,10.,70.,90.,115.,125.,126.,140.,140.,150.,140.,300.,300.,350.]
yp=[85.5,85.5,85.5,85.,82.5,80.,78.,79.5,82.5,85.,87.5,87.5,85.5,85.5]
elif basin_name=='makarov':
#xp=[165, 165, 280, 280, 165]
#yp=[86, 88, 88, 86, 86]
xp=[300.,60.,145.,180.,180.,240.,285,300.]
yp=[85.5,89.5,80.,79.,85.,86.,86.,85.5]
elif basin_name=='canada':
#xp=[220, 215, 210, 205, 208, 210, 225, 230, 230, 225, 225,220.5,220]
#yp=[73, 72, 73, 74, 77, 81, 82, 82, 78, 77, 73,73,73]
#xp=[200.,210.,220.,227.,227.,240.,250.,210.,185.,185.,205,205.,200.]
#yp=[73.,71.5,71.5,72.5,77.5,80.,82.5,84.,84.,80.,80.,75.,73.]
xp=[-103.84775688995,-132.426110480092,-146.32851987161,-157.129445685198,-165.289764266082,-174.948859566318,-169.908721619095,-153.99152252417,-153.654033773183,-155.991549118887,-157.264115189183,-158.99374858648,-156.200224800736,-149.147691533142,-146.758355108426,-144.575059890815,-142.121921555256,-140.683340702781,-138.653559249327,-137.204255767801,-134.56804180152,-129.946421652944,-127.799470427715,-127.884540272314,-127.978284839156,-127.025389763871,-120.96578199099,-110.556210660899,-109.124896536309,-108.367743820184,-105.94954447772,-103.84775688995]
yp=[83.1681125452104,83.7662334620532,83.8235854688569,83.8506192123663,83.5387740470199,81.0961814080998,79.63568188243,77.4297453757112,76.9425777887249,76.1151804105261,74.9362263809805,73.5789329669126,72.8750577746576,71.4351508667292,71.0889175071879,71.0180792528114,70.7030506843364,70.6869725167624,70.4111375153443,70.4316926024079,70.6888027417022,71.8499446192718,72.9555979284964,73.7334233896998,74.5127217931511,75.3222606599783,77.8864195154148,80.0342652352252,80.3858803567825,81.84979009224,82.139759675712,83.1681125452104]
elif basin_name=='eurasia':
xp=[27.2474628708497,36.5447032085722,48.5214896162041,60.7001380803934,77.9434238049383,94.8206611280039,107.876624193844,114.76253701556,121.721644200227,134.412781688966,140.650432725167,141.964704250335,145.155248340791,149.246374638137,132.143273251575,149.76109018589,-79.6880622455017,-55.18591213471,-43.4591200137502,-22.0049915144465,-20.6758818057775,-17.5930251981611,-9.73692516655174,5.28638472739742,27.2474628708497]
yp=[81.2047365447009,81.5007859895957,82.2436675361916,82.721919243158,82.4532187163616,81.6658524321853,80.1201616988957,78.868040305759,77.3745806589471,78.343810419039,79.2198008825623,81.0361747596064,82.8850251870597,84.6970166179212,88.170272215848,88.5112003265041,89.0201530656119,86.82607324433,85.3307236364029,85.7137862915936,84.4424860812103,83.6275436815664,82.8313390219846,82.2610471668164,81.2047365447009]
elif basin_name=='arctic':
xp=[20.0,66.0,67.0,59.0,54,63.0,95.0,150.0,-175.0,-164, -127, -127,-124,-122.9,-122,-110.4,-95.2,-88.4, -62.3, -56.5, -40,-20]
yp=[80.0,80.0,76.5,75.0,72,69.0,66.0, 66.0, 66.5,65.5, 65.5, 70,72.2, 74.1,76.1, 78.6, 80.4, 81.8, 82.4, 81.6, 79, 80]
elif basin_name=='arctic_mediterranean':
xp=[-32,-20,-14,-7,-1.5,14,20,30,63.0,95.0,150.0,-175.0,-164,-110.0,-72.0,-40.]
yp=[ 68, 65, 65,62,60.5,61,68,66,69.0,66.0,66.0 , 66.5,65.5, 66.0, 80.0,80.]
elif basin_name=='eurasian_shelves':
xp=[60,60,100,120,130,160,180,180,140,120,90,60]
yp=[70,80,80,77,77,77,72,70,70,70,70,70]
elif basin_name=='fram_strait':
xp=[0.0, 10., 10., 0.0, 0.0]
yp=[78., 78., 80., 80., 78.]
elif basin_name=='AW_inflow1':
xp=[20., 30., 30., 20., 20.]
yp=[81., 81., 85., 85., 81.]
elif basin_name=='AW_inflow2':
xp=[80., 90., 90., 80., 80.]
yp=[83., 83., 85., 85., 83.]
elif basin_name=='mediterranean':
xp=[-5,-5,12,56,59,40,33,22,-5,-5]
yp=[36,40,50,50,33,32,29,29,31,35]
elif basin_name=='siberia':
xp=[30,180,180,30,30]
yp=[60,60,70,70,60]
elif basin_name=='namerica':
xp=[180,290,290,180,180]
yp=[60,60,70,70,60]
elif basin_name=='icemelt':
xp=[93,100,110,115,120,82,65,93] #
yp=[82,82,81,81,85,86,85,82]
elif basin_name=='nordic_seas':
xp=[-32,-20,-14,-7,-1.5,14,20,17,-32,-32]
yp=[68,65,65,62,60.5,61,69,79,79,68]
elif basin_name=='nordic_seas_e': #Norwegian Sea
xp=[-14,-7,-1.5,14,20,17,7,8,-8,-2,-6.5,-14]
yp=[65,62,60.5,61,69,79,78,74,71,68,65,65]
elif basin_name=='nordic_seas_w': #Greenland and Iceland Seas
xp=[-32,-20,-14,-6.5,-2,-8,8,7,17,-32,-32]
yp=[68,65,65,65,68,71,74,78,79,79,68]
elif basin_name=='north_atlantic': #Region in the north_atlantic
xp=[-60,-45,-45,-60,-60]
yp=[37,37,41,41,37]
elif basin_name=='subpolar_gyre': #Region in the subpolar_gyre
xp=[-50,-60,-45,-40,-30,-30,-40,-50]
yp=[ 50, 60, 59, 60, 65, 50, 50, 50]
elif basin_name=='natlantic':
xp=[-10.0,-20.0,-30.0,-40.0,-50.0,-60.0,-76.0,-77.0,-78.0,-82.0,-91.0,-101.0,-130.0,-164.0,-175.0,150.0,95.0,36.0,20.0,11.0, 9.0, 9.0,-5.5,-5.5,-10.0]
yp=[ 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 7.0, 8.5, 9.5, 9.0, 17.0, 21.0, 65.6, 65.5, 66.5, 66.0,66.0,62.0,68.0,60.0,55.0,49.0,36.0,35.0, 10.0]
elif basin_name=='atlantic':
xp=[-65.0,-76.0,-77.0,-78.0,-82.0,-91.0,-101.0,-130.0,-164.0,-175.0,150.0,95.0,36.0,20.0,11.0, 9.0, 9.0,-5.5,-5.5,25.0, 19.5, 10.0, 0.0,-13.0,-20.0,-30.0,-40.0,-50.0,-60.0,-70.0,-60.0,-65.0]
yp=[ 9.0, 7.0, 8.5, 9.5, 9.0, 17.0, 21.0, 65.6, 65.5, 66.5, 66.0,66.0,62.0,68.0,60.0,55.0,49.0,36.0,35.0, 0.0,-34.5,-40.0,-45.0,-50.0,-50.0,-50.0,-50.0,-50.0,-50.0,-50.0,-20.0, 9.0]
return xp,yp
def basin_mask_old(x,y,basin_name,is_basin=True,xp=None,yp=None):
"""
THIS FUNCTION IS DEPRECATED IN FAVOR OF USING CARTOPY BASED
FUNCTION basin_mask instead!
Find out whether lon, lat coordinated are inside a polygon """
#if the basin polygon is not given find it based on the name
if is_basin:
xp,yp=basin_coords(x,y,basin_name)
m=Basemap(projection='npstere', boundinglat=20, lon_0=0)
xp,yp=m(xp,yp)
poly=[]
for j in range(len(xp)):
poly.append((xp[j],yp[j]))
if(len(x.shape)==2):
inside=np.ones(x.shape)*np.nan
for i in range(x.shape[0]):
for j in range(x.shape[1]):
xx,yy=m(x[i,j],y[i,j])
inside[i,j]=point_inside_polygon(xx,yy,poly)
elif(len(x.shape)==1):
inside=np.ones((y.shape[0],x.shape[0]))*np.nan
for j in range(y.shape[0]):
for i in range(x.shape[0]):
xx,yy=m(x[i],y[j])
inside[j,i]=point_inside_polygon(xx,yy,poly)
return inside
def basin_mask(x,y,basin_name=None,xp=None,yp=None):
"""
Find out whether lon, lat coordinated are inside a polygon.
If the basin polygon is not given find it based on the name.
x : longitude in degrees, can be either 1D or 2D (will be converted to 2D)
y : latitude in degrees, can be either 1D or 2D (will be converted to 2D)
basin_name : str, optional, default is None. If basin_name is given then
basin_coords needs to have a corresponding entry. If basin_name is not give,
then one needs to specify the coordinates xp, yp
xp, yp : lon,lat coordinates in degrees defining a polygon.
"""
#
if np.all(xp==None) and np.all(yp==None):
xp, yp = basin_coords(x,y,basin_name)
xp, yp = np.array(xp),np.array(yp)
# transfrom coordinates to polar strereographic so don't have to deal with the polar singularity
proj = ccrs.NorthPolarStereo(central_longitude=0.0)
tcoords1 = proj.transform_points(ccrs.PlateCarree(), xp, yp)
xp, yp = tcoords1[:,0], tcoords1[:,1]
tcoords2 = proj.transform_points(ccrs.PlateCarree(), x, y)
#
poly=[]
for j in range(len(xp)):
poly.append((xp[j],yp[j]))
if(len(x.shape)==2):
print('2d')
xx, yy = tcoords2[:,:,0], tcoords2[:,:,1]
inside = np.ones(xx.shape)*np.nan
for j in range(xx.shape[0]):
for i in range(xx.shape[1]):
inside[j,i]=point_inside_polygon(xx[j,i],yy[j,i],poly)
elif(len(x.shape)==1):
xx, yy = tcoords2[:,0], tcoords2[:,1]
xx, yy = np.meshgrid(xx,yy)
inside = np.ones((y.shape[0], x.shape[0]))*np.nan
for j in range(yy.shape[0]):
for i in range(xx.shape[0]):
inside[j,i]=point_inside_polygon(xx[j,i],yy[j,i],poly)
return inside
def woa_basins(lon,lat,basin_name):
""" READ WOA BASINS AND DEFINE BASIN MASK"""
data=np.loadtxt('WOA_ocean_basins.txt',delimiter=',',skiprows=2,usecols=(0,1,2))
lonwoa=data[:,1]; latwoa=data[:,0]; datawoa=data[:,2]
mask=griddata((lonwoa,latwoa),datawoa,(lon,lat),method='nearest',fill_value=99)
if basin_name=='arctic':
mask[mask!=11]=0; mask[mask!=0]=1
return mask
def drainage_basin(x,y,regime):
data=np.loadtxt('Budgeteers_Arctic_Ocean_Drainage_Basin_Mask_plus_Bugeteers_Ocean_Mask_v1.0.txt',skiprows=6)
lat=np.loadtxt('latitude_budgeteers.txt',skiprows=6)
lon=np.loadtxt('longitude_budgeteers.txt',skiprows=6)
data[data==-9999]=0.0
if regime=='lnd':
data[data==2]=0.0
elif regime=='ocn':
data[data==1]=0.0
data[data==2]=1
jj,ii=np.where(data<=2)
mask=griddata((lon[jj,ii],lat[jj,ii]),data[jj,ii],(x,y),method='nearest',fill_value=0.0)
return mask
def NorESM_masks(basin_name,iinds,jinds,barents=False,secfile='secindex.dat',grid='bipolar',lon=None,lat=None, baltic=True):
'''NorESM_masks(basin,iinds,jinds,barents)
Basin is either 'arctic' or 'nordic seas'. Barents is a flag, whether or not to include it to the 'arctic'. For the most parts we are following the gates defined in the secindex file. Note that in that file the indices are in Fortran 1 based format, that is why there is -1 in this function. Note that the difference to the above functions is that this is very NorESM specific and wont work with any other model while the functions above are able to figure out the points inside polygon in any model.'''
inds_all=read_sections(secfile)
coords=[]
if basin_name=='atlantic':
#Atlantic+Arctic
if grid in ['bipolar']:
coords.extend([[300,0],[295,46],[293,50],[293,220],[282,220],[282,225],[280,225],[280,243],[273,250],[267,250],[267,333],[70,333],[70,350],[60,350],[48,340],[48,335],[48,315],[32,300],[32,289],[32,250],[54,250],[54,0]])
elif grid in ['tripolar']:
lons=[-109,-100,-91,-84,-84,-81,-80,-77,-59,-59,20,20,-5.5,-5.5,8.5,94]
lats=[63,21,17,14,11,9.5,9.5,8,-5,-34,-34,10,34,39,51,64]
for j in range(len(lons)):
j_out,i_out=lonlat_index(lon,lat,lons[j],lats[j],inc=1)
coords.extend([[i_out,j_out]])
coords.extend((inds_all.get('bering_strait')[:,:2]-1).tolist())
lons=[-160,-115]
lats=[66,66]
for j in range(len(lons)):
j_out,i_out=lonlat_index(lon,lat,lons[j],lats[j],inc=0.5)
coords.extend([[i_out,j_out]])
coords.extend([[coords[-1][0],lat.shape[0]]])
coords.extend([[coords[0][0],lat.shape[0]]])
if basin_name=='nordic_seas':
if grid in ['bipolar']:
coords.extend([[6,384]]) #first point
elif grid in ['tripolar']:
j_out,i_out=lonlat_index(lon,lat,-40,70,inc=0.5)
coords.extend([[i_out,j_out]])
coords.extend((inds_all.get('denmark_strait')[:,:2]-1).tolist())
coords.extend((inds_all.get('iceland_faroe_channel')[:,:2]-1).tolist())
coords.extend((inds_all.get('faroe_scotland_channel')[:,:2]-1).tolist())
if grid in ['bipolar']:
coords.extend([[36,340], [47,340]]) #from scotland to norway
elif grid in ['tripolar']: #this is a bit different, take the North Sea and Baltic into account
if baltic:
coords.extend((inds_all.get('english_channel')[:,:2]-1).tolist())
coords.extend([[coords[-1][0],coords[-1][1]-1]])
j_out,i_out=lonlat_index(lon,lat,42,48.5,inc=0.5)
coords.extend([[i_out,j_out]])
j_out,i_out=lonlat_index(lon,lat,42,58.5,inc=0.5)
coords.extend([[i_out,j_out]])
else:
coords.extend([[coords[-1][0],coords[-1][1]-1]])
j_out,i_out=lonlat_index(lon,lat,15,62,inc=0.5)
coords.extend([[i_out,j_out]])
coords.extend((inds_all.get('barents_opening')[::-1,:2]-1).tolist())
coords.extend((inds_all.get('fram_strait')[::-1,:2]-1).tolist())
if grid in ['bipolar']:
coords.extend([[115,384]]) #last point
elif grid in ['tripolar']:
j_out,i_out=lonlat_index(lon,lat,-40,75,inc=0.5)
coords.extend([[i_out,j_out]])
if basin_name=='arctic':
if grid in ['bipolar']:
coords.extend([[112,384]])
elif grid in ['tripolar']:
coords.extend((inds_all.get('canadian_archipelago')[22:,:2]-1).tolist())
j_out,i_out=lonlat_index(lon,lat,-37.5,79.5,inc=0.5)
coords.extend([[i_out,j_out]])
coords.extend((inds_all.get('fram_strait')[:,:2]-1).tolist())
if barents:
#include barents sea
coords.extend((inds_all.get('barents_opening')[:,:2]-1).tolist())
if grid in ['bipolar']:
coords.extend([[68,333]]) #
elif grid in ['tripolar']:
j_out,i_out=lonlat_index(lon,lat,42,58.5,inc=0.5)
coords.extend([[i_out,j_out]])
else:
#don't include barents sea
coords.extend([[96,369],[99,369],[99,367],[103,367],[115,361],[117,359],[114,352],[104,352],[104,351],[101,351],[101,350],[98,350],[98,349],[96,349],[94,344],[94,333]])
coords.extend((inds_all.get('bering_strait')[:,:2]-1).tolist())
if grid in ['bipolar']:
coords.extend([[245,333]])
coords.extend([[245,355]])
elif grid in ['tripolar']:
#add points between Bering Strait and CAA
j_out,i_out=lonlat_index(lon,lat,-155.5,66.0,inc=0.5)#,58.5,inc=0.5)
coords.extend([[i_out,j_out]])
j_out,i_out=lonlat_index(lon,lat,-127,66.0,inc=0.5); coords.extend([[i_out,j_out]])
j_out,i_out=lonlat_index(lon,lat,-125,69.5,inc=0.5); coords.extend([[i_out,j_out]])
if grid in ['bipolar']:
coords.extend((inds_all.get('canadian_archipelago')[:2,:2]-1).tolist())
coords.extend([[226,359],[232,362],[234,363],[236,366],[236,374],[204,375]])
coords.extend((inds_all.get('canadian_archipelago')[2:,:2]-1).tolist())
coords.extend([[199,384]])
elif grid in ['tripolar']:
coords.extend((inds_all.get('canadian_archipelago')[:22,:2]-1).tolist())
coords.extend([[coords[-1][0],lat.shape[0]]])
coords.extend([[coords[0][0],lat.shape[0]]])
#j_out,i_out=lonlat_index(lon,lat,-37.5,79.5,inc=0.5)
#coords.extend([[i_out,j_out]])
#Then the actual mask
ring=LinearRing(coords)
area = Polygon(ring)
if grid in ['bipolar']:
mask=np.zeros((384,320))
elif grid in ['tripolar']:
mask=np.zeros(lat.shape)
for j in range(len(iinds)):
mask[jinds[j],iinds[j]]=area.contains(Point(iinds[j],jinds[j]))
return mask
def lonlat_index(lon,lat,lon_p,lat_p,inc=0.5):
"""Find the closest - or at least pretty close indeces from 2D lon,lat arrays that correspond to point lon_p,lat_p. 'inc' should be in order of the grid size"""
j1,i1=ma.where(ma.logical_and(lat<lat_p+inc,lat>lat_p-inc))
j2=ma.where(ma.logical_and(lon[j1,i1]<lon_p+inc,lon[j1,i1]>lon_p-inc))[0]
j_out,i_out=ma.where(ma.logical_and(lat==lat[j1,i1][j2][0],lon==lon[j1,i1][j2][0]))
return j_out,i_out
def lonlatfix(lon,lat):
"""Make Longitudes to be in between -180 and 180, and output 2D lon, lat"""
norm_grid=False
if ma.min(lon)<-180:
lon[lon<0.0]=lon[lon<0.0]+360
lon[lon>180]=lon[lon>180]-360
elif ma.min(lon)>=0.:
lon[lon>180.0]=lon[lon>180.0]-360
norm_grid=True
if len(lon.shape)<2:
lon,lat=np.meshgrid(lon, lat)
norm_grid=False
if ma.max(lon)>180 or ma.min(lon)<-180:
print('something is wrong max(lon)='+str(ma.max(lon))+', min(lon)='+ma.min(lon))
#
return lon, lat, norm_grid
def enable_global(tlon,tlat,data):
"""Fix NorESM/CCSM4 (only works with these models) data in such a way that it can to be plotted on a global projection on its native grid"""
tlon = np.where(np.greater_equal(tlon,min(tlon[:,0])),tlon-360,tlon)
tlon=tlon+abs(ma.max(tlon)); tlon=tlon+360
# stack grids side-by-side (in longitiudinal direction), so
# any range of longitudes may be plotted on a world map.
tlon = np.concatenate((tlon,tlon+360),1)
tlat = np.concatenate((tlat,tlat),1)
data = ma.concatenate((data,data),1)
tlon = tlon-360.
return tlon, tlat, data
def NorESM_add_cyclic(lon,lat,data,dim=1):
'''Add a cyclic point to NorESM data. Note that here we assume that data has the same size as lon and lat (so 2D). dim is the dimension in which the cyclic point is to be added. For most cases this would be the default option dim=1, but for generality the possibility is given for arbitrary dimension. If the variable is 3D with time as first variable then dim should most likely be 2'''
#create the new shape
dims=list(data.shape)
dims[dim]=dims[dim]+1
dims=tuple(dims)
#creat the new arrays and assign the data - copy the first column/row to the end of the array
for v in ['lon','lat','data']:
if len(dims)<3 or v in ['lon','lat']:
if len(dims)>2:
exec('d'+v+'=ma.zeros((dims[1],dims[2]))')
else:
exec('d'+v+'=ma.zeros(dims)')
if dim==1:
exec('d'+v+'[:,:-1]='+v+'')
exec('d'+v+'[:,-1]='+v+'[:,0]')
elif dim==0:
exec('d'+v+'[:-1,:]='+v+'')
exec('d'+v+'[-1,:]='+v+'[0,:]')
elif len(dims)>2 and v in ['data']:
exec('d'+v+'=ma.zeros(dims)')
if dim==2:
exec('d'+v+'[:,:,:-1]='+v+'')
exec('d'+v+'[:,:,-1]='+v+'[:,:,0]')
elif dim==1:
exec('d'+v+'[:,:-1,:]='+v+'')
exec('d'+v+'[:,-1,:]='+v+'[:,0,:]')
return dlon, dlat, ddata
#def make_dist_grid(lon,lat):
# ''' THIS IS TOO SLOW, THINK ABOUT AWAY TO AVOID THE LOOPS '''
# if len(lon.shape)>1:
# dx=np.zeros(lon.shape)
# dy=np.zeros(lon.shape)
# for i in range(1,lon.shape[0]):
# for j in range(1,lon.shape[1]):
# d=gsw.earth.distance([0,lon[i,j]],[0,lat[i,j]])
# dy[i,j]=d*np.sin(np.radians(lat[i,j]));dx[i,j]=d*np.cos(np.radians(lon[i,j]))
def across_line(lon,lat,u,v,lon_line,lat_line,FirstTime=True,iind=None,jind=None,dxout=None,dyout=None,dxin=None,dyin=None):
"""Line is a list of lon,lat points defining the line, with a straight line only start and end points are iven. U and V should be the eastward and northward transport (velocity) components. One can use the vecrotc to rotate the components if they are initially on a model grid."""
#
#First we find a smaller area around the line to speed up the interpolation
if FirstTime:
dx=2.;dy=2.;
xp=[min(lon_line)-dx,max(lon_line)+dx,max(lon_line)+dx,min(lon_line)-dx,min(lon_line)-dx]
yp=[min(lat_line)-dy,min(lat_line)-dy,max(lat_line)+dy,max(lat_line)+dy,min(lat_line)-dy]
inside=basin_mask(lon,lat,'',is_basin=False,xp=xp,yp=yp)
jind,iind=np.where(inside!=0.0)
#find a equidistant map projection
#m=Basemap(projection='aeqd',lon_0=min(lon_line),lat_0=np.min(lat_line))
#xin,yin=m(lon,lat)
#xout,yout=m(lon_line,lat_line)
#Make a distance 'grid', check how far everything is from the equator (0,0)
lo=lon[jind,iind]; la=lat[jind,iind]
dxin=np.zeros(len(lo));dyin=np.zeros(len(la))
dxout=np.zeros(len(lon_line)); dyout=np.zeros(len(lat_line))
for j in range(len(dxin)):
din=gsw.earth.distance([0,lo[j]],[0,la[j]])
dxin[j]=din*np.cos(np.radians(lo[j]));dyin[j]=din*np.sin(np.radians(la[j]))
for j in range(len(dxout)):
dout=gsw.earth.distance([0,lon_line[j]],[0,lat_line[j]])
dxout[j]=dout*np.cos(np.radians(lon_line[j])); dyout[j]=dout*np.sin(np.radians(lat_line[j]))
#d=gsw.earth.distance(lon,lat)
#distx=np.cumsum(d,axis=0);disty=np.cumsum(d,axis=1)
#dist=np.sqrt(distx**2+disty**2)
#Then we interpolate to get the northward and eastward components along the line
#tx=griddata((xin[jind,iind],yin[jind,iind]),u[jind,iind],(xout,yout),method='linear',fill_value=0.0)
#ty=griddata((xin[jind,iind],yin[jind,iind]),v[jind,iind],(xout,yout),method='linear',fill_value=0.0)
tx=griddata((dxin,dyin),u[jind,iind],(dxout,dyout),method='linear',fill_value=0.0)
ty=griddata((dxin,dyin),v[jind,iind],(dxout,dyout),method='linear',fill_value=0.0)
phi=np.arctan2(np.gradient(lat_line),(np.gradient(lon_line)*np.cos(np.radians(lat_line))))
#Finally we rotate the components to get the transports accross the line
txr=tx*np.cos(phi)-ty*np.sin(phi)
tyr=tx*np.sin(phi)+ty*np.cos(phi)
#
return txr,tyr,phi,iind,jind,dxout,dyout,dxin,dyin
def across_line2(x_line,y_line,lon_line,lat_line,u_line,v_line):
''' Transport across line without interpolation. Note that now lon,lat,u,v are the model variables along the line given by indices i_line and j_line. Since the line is defined along the indices we can rotate the indices just once i.e. phi is both the angle of the line and angle of the gridcells. The function above is more general and can be used to interpolate transports along any line whether or not it follows the model grid indices. However, this is probably more accurate. '''
#phi=np.arctan2(np.gradient(lat_line),(np.gradient(lon_line)*np.cos(np.radians(lat_line))))
phi=np.arctan2(np.gradient(y_line),np.gradient(x_line))
#t_across=u_line*np.cos(phi)*(lon_line/np.abs(lon_line))+v_line*np.sin(phi)*(lat_line/np.abs(lat_line))
t_across=u_line*np.cos(phi)+v_line*np.sin(phi)
t_along=u_line*np.sin(phi)+v_line*np.cos(phi) #this is probably wrong
return t_across,t_along,phi
def vecrotc(lon,lat,u,v,scalar=True):
""" VECROTC rotate vector components [UR,VR] = VECROT(LON,LAT,U,V) rotate the vector components U and V defined at Arakawa C grid velocity points to zonal (UR) and meridional (VR) components defined at scalar points, or optionally at their respective points. LON and LAT defines the geographic location of the scalar points. Points near the pole singularities are set to NaN."""
# Centered latitude and longitude differences in one direction
dlat=np.zeros(lat.shape); dlon=np.zeros(lon.shape)
dlat[:,0]=lat[:,1]-lat[:,0]; dlat[:,1:-1]=(lat[:,2:]-lat[:,0:-2])*.5; dlat[:,-1]=lat[:,-1]-lat[:,-2]
dlon[:,0]=lon[:,1]-lon[:,0]; dlon[:,1:-1]=(lon[:,2:]-lon[:,0:-2])*.5; dlon[:,-1]=lon[:,-1]-lon[:,-2]
dlon[dlon>180]=dlon[dlon>180]-360
dlon[dlon<-180]=dlon[dlon<-180]+360
dlon[dlon>90]=dlon[dlon>90]-180
dlon[dlon<-90]=dlon[dlon<-90]+180
# Compute rotation angle
rad=np.pi/180
phi=np.arctan2(dlat,(dlon*np.cos(np.radians(lat))))
#
us=u.copy();vs=v.copy()
if scalar==True:
if len(u.shape)==2:
# Get velocity components at scalar point
us[:,:-1]=ma.sum([u[:,:-1],u[:,1:]],0)*.5
#us[:,-1]=u[:,-1]
vs[:-1,:]=ma.sum([v[:-1,:],v[1:,:]],0)*.5
#vs[-1,:]=v[-1,:];
elif len(u.shape)==3:
# Get velocity components at scalar point
us[:,:,:-1]=ma.sum([u[:,:,:-1],u[:,:,1:]],0)*.5
#us[:,-1]=u[:,-1]
vs[:,:-1,:]=ma.sum([v[:,:-1,:],v[:,1:,:]],0)*.5
#vs[-1,:]=v[-1,:];
# Rotate the vector components
ur=us*np.cos(phi)-vs*np.sin(phi)
vr=us*np.sin(phi)+vs*np.cos(phi)
# Set points near pole singularities to NaN
#ind=find(lat>88|lat<-88);
#ur(ind)=nan;
#vr(ind)=nan;
return ur, vr, phi
def noresm2WOA(datain,shift=False, grid='gx1v6',dest='1deg'):
'''noresm2WOA(datain,shift=False, grid='gx1v6')
Interpolate from the 2D datain field (choose grid to be one of the following: 'gx1v6', 'tnx1v1', 'tnx0.25v1') to WOA09 cartesian grid using a predefined weights defined in sparse matrix S'''
#load the data
if grid in ['gx1v6']:
mapping_data=io.loadmat('/Home/siv22/anu074/NorESM/map_noresm_gx1v6_to_woa09_1deg_aave.mat')
#S=mapping_data['S'].copy()
#these two don't work, maybe something wrong with the way data is written in mat file
elif grid in ['tnx1v1']:
mapping_data=io.loadmat('/Data/skd/users/anu074/norstore/map_noresm_tnx1v1_to_woa09_1deg_aave_v2.mat')
#S=mapping_data["S"].values()[0][:]
elif grid in ['tnx0.25v1']:
if dest in ['1deg']:
mapping_data=io.loadmat('/Data/skd/users/anu074/norstore/map_noresm_tnx0.25v1_to_woa09_1deg_aave_v2.mat')
elif dest in ['0.25deg']:
mapping_data=io.loadmat('/Data/skd/users/anu074/norstore/map_noresm_tnx0.25v1_to_woa09_0_25deg_aave_v2.mat')
S=mapping_data['S'][:]
lon_b=mapping_data['lon_b'][:].squeeze()
lat_b=mapping_data['lat_b'][:].squeeze()
nx_b=mapping_data['nx_b'][:].squeeze()
ny_b=mapping_data['ny_b'][:].squeeze()
#
s_a=datain.flatten()
if False:
ind=ma.where(1-datain.mask.flatten())[0]
S2=S[:,ind]
s_a2=s_a[ind]
s_b=ma.reshape(S2*s_a2,(int(ny_b), int(nx_b)))#(int(nx_b),int(ny_b)))
else:
s_b=ma.reshape(S*s_a,(int(ny_b), int(nx_b)))
#
if shift:
j=nx_b/2
s_c=s_b.copy(); s_c[:,:j]=s_b[:,j:]; s_c[:,j:]=s_b[:,:j]; s_b=s_c
lon_c=lon_b.copy(); lon_c[:j]=lon_b[j:]; lon_c[j:]=lon_b[:j]; lon_b=lon_c
return lon_b, lat_b, s_b
def noresm2scalar(u,v):
"""Interpolate the velocity components to scalar points on NorESM C grid """
us=u.copy();vs=v.copy()
if len(u.shape)==2:
# Get velocity components at scalar point
us[:,:-1]=ma.sum([u[:,:-1],u[:,1:]],0)*.5
vs[:-1,:]=ma.sum([v[:-1,:],v[1:,:]],0)*.5
elif len(u.shape)==3:
# Get velocity components at scalar point
us[:,:,:-1]=ma.sum([u[:,:,:-1],u[:,:,1:]],0)*.5
vs[:,:-1,:]=ma.sum([v[:,:-1,:],v[:,1:,:]],0)*.5
return us,vs
def scalar2u(S,dp=None,area=None):
""" Linearly interpolate scalar S to u point on NorEsm C grid"""
Sout=S.copy()
if type(dp)==type(None):
dp=np.ones(S.shape)
if type(area)==type(None):
area=np.ones(S.shape)
if len(S.shape)==3 and len(area.shape)==2:
np.tile(area,(S.shape[0],1,1))
if len(S.shape)==3:
Sout[:,:,1:]=ma.sum([(area*dp*S)[:,:,:-1],(area*dp*S)[:,:,1:]],0)/ma.sum([(area*dp)[:,:,:-1],(area*dp)[:,:,1:]],0)#0.5*(S[:,:,:-1]+S[:,:,1:])
Sout[:,:,0]=ma.sum([(area*dp*S)[:,:,-1],(area*dp*S)[:,:,0]],0)/ma.sum([(area*dp)[:,:,-1],(area*dp)[:,:,0]],0) #0.5*(S[:,:,-1]+S[:,:,0])
elif len(S.shape)==2:
Sout[:,1:]=ma.sum([(area*S)[:,:-1],(area*S)[:,1:]],0)/ma.sum([area[:,:-1],area[:,1:]],0) #0.5*(S[:,:-1]+S[:,1:])
Sout[:,0]=ma.sum([(area*S)[:,-1],(area*S)[:,0]],0)/ma.sum([area[:,-1],area[:,0]],0) #0.5*(S[:,-1]+S[:,0])
#
return Sout
def scalar2v(S,dp=None,area=None):
""" Linearly interpolate scalar S to v point on NorEsm C grid"""
Sout=S.copy()
if type(dp)==type(None):
dp=np.ones(S.shape)
if type(area)==type(None):
area=np.ones(S.shape)
if len(S.shape)==3 and len(area.shape)==2:
np.tile(area,(S.shape[0],1,1))
if len(S.shape)==3:
Sout[:,:-1,:]=ma.sum([(area*dp*S)[:,1:,:],(area*dp*S)[:,:-1,:]],0)/ma.sum([(area*dp)[:,1:,:],(area*dp)[:,:-1,:]],0) #0.5*(S[:,1:,:]+S[:,:-1,:])
elif len(S.shape)==2:
Sout[:-1,:]=ma.sum([(area*dp*S)[1:,:],(area*dp*S)[:-1,:]],0)/ma.sum([(area*dp)[1:,:],(area*dp)[:-1,:]],0) #0.5*(S[1:,:]+S[:-1,:])
#
return Sout
def runningMean(x, N, axis=None):
"""Fast running mean using convolve. x is the variable and N is the window size"""
if len(x.shape)==1:
runmean=np.convolve(x, np.ones((N,))/N)[(N-1):]
elif len(x.shape)==2:
runmean=np.zeros(x.shape)
if axis==None: axis=0
if axis==1: x=x.T; runmean=runmean.T;
for j in range(x.shape[1]):
runmean[:,j]=np.convolve(x[:,j].squeeze(), np.ones((N,))/N)[(N-1):]
if axis==1: runmean=runmean.T
return runmean
def timeMean(x,year0,inds=None,xtype='monthly',dt=None):
"""Make averages over time up to a year from annual daily data (i.e. there is 365+ entries). If longer time mean is required then calculate monthly means with this script and annual/longer averages from that. It's suggested not to give the indices, but to use 'monthly' flag or dt for all the rest."""
dim=x.shape
n1=365
if type(inds)==type(None):
if xtype in ['monthly']:
inds=np.cumsum([0,31,28,31,30,31,30,31,31,30,31,30,31])
else:
inds=np.arange(0,n1+1,dt)
inds[-1]=n1
n=len(inds)-1
if dt!=None and dim[0]%int(dt)==0:
if len(dim)==1:
y=np.nanmean(np.reshape(x,(dim[0]/dt,dt)),1)
elif len(dim)==2:
y=np.nanmean(np.reshape(x,(dim[0]/dt,dt,dim[1])),1)
elif len(dim)==3:
y=np.nanmean(np.reshape(x,(dim[0]/dt,dt,dim[1],dim[2])),1)
else:
years=int(x.shape[0]/365.) #how many years
if len(dim)==1:
y=np.zeros(years*(len(inds)-1)) #initialize the output
for year in range(year0,year0+years): #loop over the years
if year==year0:
inds1=inds.copy() #if the first year then just copy the inds
else:
inds1=inds+inds1[-1] #if not the first years, then increase the indicaes
if calendar.isleap(year):
if n==12: #if monthly then add the leap day to february
inds1[2:]=inds1[2:]+1
else: #if not monthly then just use the additional day in the very end
inds1[-1]=inds1[-1]+1
for j in range(n-1): #loop over the time discretization (months,weeks,etc)
y[j]=np.nanmean(x[inds1[j]:inds1[j+1]])
else:
y=np.zeros(list([years*(len(inds)-1)])+list(dim[1:]))
c=0
for year in range(year0,year0+years): #loop over the years
if year==year0:
inds1=inds.copy() #if the first year then just copy the inds
else:
inds1=inds+inds1[-1] #if not the first years, then increase the indicaes
if calendar.isleap(year):
if n==12: #if monthly then add the leap day to february
inds1[2:]=inds1[2:]+1
else: #if not monthly then just use the additional day in the very end
inds1[-1]=inds1[-1]+1
for j in range(n): #loop over the time discretization (months,weeks,etc)
y[c,:]=np.nanmean(x[inds1[j]:inds1[j+1],:],0)
c=c+1
return y
def AnnualMean(x,w=None):
"""mean=AnnualMean(x,w=None)
Calculate the annual mean from monthly timeseries, time is assumed to be the zero dimension.
If months are of different length then use w for weights"""
dim=x.shape
###############
if len(dim)==1:
m=ma.zeros(dim[0]/12.)
if type(w)==type(None):
for j in range(x.shape[0]/12):
m[j]=ma.mean(x[j*12:(j+1)*12])
else:
for j in range(x.shape[0]/12):
m[j]=ma.sum(w[j*12:(j+1)*12]*x[j*12:(j+1)*12])/ma.sum(w[j*12:(j+1)*12])
#################
elif len(dim)==2:
m=ma.zeros((dim[0]/12.,dim[1]))
if type(w)==type(None):
for j in range(dim[0]/12):
m[j,:]=ma.mean(x[j*12:(j+1)*12,:],0)
else:
w=np.tile(w,(dim[1],1)).T
for j in range(dim[0]/12):
m[j,:]=ma.sum(w[j*12:(j+1)*12,:]*x[j*12:(j+1)*12,:],0)/ma.sum(w[j*12:(j+1)*12,:],0)
#################
elif len(dim)==3:
m=ma.zeros((dim[0]/12.,dim[1],dim[2]))
if type(w)==type(None):
for j in range(dim[0]/12):
m[j,:,:]=ma.mean(x[j*12:(j+1)*12,:,:],0)
else:
w=np.tile(w,(dim[2],dim[1],1)).T
for j in range(dim[0]/12):
m[j,:,:]=ma.sum(w[j*12:(j+1)*12,:,:]*x[j*12:(j+1)*12,:,:],0)/ma.sum(w[j*12:(j+1)*12,:,:],0)
#################
elif len(dim)==4:
m=ma.zeros((dim[0]/12.,dim[1],dim[2],dim[3]))
if type(w)==type(None):
for j in range(dim[0]/12):
m[j,:,:,:]=ma.mean(x[j*12:(j+1)*12,:,:,:],0)
else:
w=np.tile(w,(dim[3],dim[2],dim[1],1)).T
for j in range(dim[0]/12):
m[j,:,:,:]=ma.sum(w[j*12:(j+1)*12,:,:,:]*x[j*12:(j+1)*12,:,:,:],0)/ma.sum(w[j*12:(j+1)*12,:,:,:],0)
#
return m
def centered_diff(t,xaxis):
""" Use a 1D polynomial method to calculate centered difference on a irregularly spaced grid. t=input data (2D) dx=grid spacing"""
#Initialize the data
dx=np.diff(xaxis) #dx
dxaxis=np.cumsum(dx) #new x-axis
dtout=np.ones((t.shape[0],t.shape[1]-1))*np.nan #output data
#