-
Notifications
You must be signed in to change notification settings - Fork 1
/
grid_set.py
1858 lines (1692 loc) · 72.7 KB
/
grid_set.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
# here is the class that holds all the data days/months
# it has all the gridding scripts needed
# it will save load all the data/days/months as needed
import numpy as np
import datetime
import shutil
import os
import copy
from netCDF4 import Dataset
# from numba import jit
from scipy import stats
from scipy import sparse
from scipy.ndimage.filters import gaussian_filter
# from mpl_toolkits.basemap import Basemap
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import shapely.vectorized
proj_cart = ccrs.PlateCarree()
class grid_set:
# will make one of these at a time point (as a datetime) defined by timestart
def __init__(self,mplot):
# print(type(mplot))
if 'crs' in str(type(mplot)):
### need lon/lat to x,y
# def mtemp(x,y):
# inshape = x.shape
# if np.shape()
def tempm(x,y):
if type(x) == list:
x = np.array(x)
y = np.array(y)
inshape = np.shape(x)
if inshape == ():
x = np.array(x)
y = np.array(y)
inshape = np.shape(x)
xy = mplot.transform_points(proj_cart,x,y)
if np.shape(inshape)[0] == 0: ### 0d input:
x = xy[0,0]
y = xy[0,1]
elif np.shape(inshape)[0] == 1: ### 1d input:
x = xy[:,0]
y = xy[:,1]
else:
x = xy[:,:,0]
y = xy[:,:,1]
return x, y
self.mplot = tempm
def tempm(x,y,lon,lat):
x, y = mplot.transform_vectors(proj_cart,lon,lat,x,y)
return x, y
self.rotate_vector = tempm
self.ccrs = mplot
### need
else:
self.mplot = mplot
self.rotate_vector = lambda x,y,lon,lat: mplot.rotate_vector(x,y,lon,lat)
self.proj = True
self.files = False
self.saved = False
self.grid = False
self.gridinfo = False
self.masked = False
self.data = False
@property
def shape(self):
return (self.m,self.n)
def reproject(self,mplot):
if 'crs' in str(type(mplot)):
### need lon/lat to x,y
def tempm(x,y):
if type(x) == list:
x = np.array(x)
y = np.array(y)
inshape = np.shape(x)
if inshape == ():
# print('reshaping')
x = np.array(x)
y = np.array(y)
inshape = np.shape(x)
xy = mplot.transform_points(proj_cart,x,y)
if np.shape(inshape)[0] == 0: ### 0d input:
x = xy[0,0]
y = xy[0,1]
elif np.shape(inshape)[0] == 1: ### 1d input:
x = xy[:,0]
y = xy[:,1]
else:
x = xy[:,:,0]
y = xy[:,:,1]
return x, y
self.mplot = tempm
def tempm(x,y,lon,lat):
x, y = mplot.transform_vectors(proj_cart,lon,lat,x,y)
return x, y
self.rotate_vector = tempm
self.ccrs = mplot
else:
self.mplot = mplot
### need
self.xpts, self.ypts = self.mplot(self.lons,self.lats)
for a in dir(self):
if a == 'xptp':
self.get_ptp()
break
@property
def ll_extent(self):
x1 = self.lons.min()
x2 = self.lons.max()
y1 = self.lats.min()
y2 = self.lats.max()
return [x1,x2, y1,y2]
@property
def x_extent(self):
x1 = self.xpts.min()
x2 = self.xpts.max()
y1 = self.ypts.min()
y2 = self.ypts.max()
return [x1,x2, y1,y2]
@property
def x_corners(self): # Input array : arr
xlist=[self.xpts[0,0],
self.xpts[0,-1], self.xpts[-1,-1],
self.xpts[-1,0], self.xpts[0,0]]
ylist=[self.ypts[0,0],
self.ypts[0,-1], self.ypts[-1,-1],
self.ypts[-1,0], self.ypts[0,0]]
return [[x,y] for x,y in zip(xlist,ylist)]
@property
def ll_corners(self): # Input array : arr
xlist=[self.lons[0,0],
self.lons[0,-1], self.lons[-1,-1],
self.lons[-1,0], self.lons[0,0]]
ylist=[self.lats[0,0],
self.lats[0,-1], self.lats[-1,-1],
self.lats[-1,0], self.lats[0,0]]
return [[x,y] for x,y in zip(xlist,ylist)]
@property
def x_border(self): # Input array : arr
xlist=border(self.xpts)
ylist=border(self.ypts)
return np.vstack((xlist,ylist)).T
@property
def ll_border(self): # Input array : arr
xlist=border(self.lons)
ylist=border(self.lats)
return np.vstack((xlist,ylist)).T
def lims_from_lonlat(self,points,for_extent = False):
x,y = self.mplot(points[0][0],points[0][1])
x1,x2 = copy.copy(x),copy.copy(x)
y1,y2 = copy.copy(y),copy.copy(y)
if len(points) < 2:
print('We need more than one point to create limits')
for p in points[1:]:
x,y = self.mplot(p[0],p[1])
x1 = np.minimum(x1,x)
x2 = np.maximum(x2,x)
y1 = np.minimum(y1,y)
y2 = np.maximum(y2,y)
if for_extent:
return [x1,x2, y1,y2]
else:
return (x1,x2), (y1,y2)
def set_grid_lon_lat(self,lons,lats,grid_list = False,fill_lonlat = False):
# creates a grid depending on wanted resolution
if fill_lonlat:
lons,lats = np.meshgrid(lons,lats)
lons = lons.T
lats = lats.T
if self.proj:
xpts, ypts = self.mplot(lons,lats)
self.lons = lons
self.lats = lats
self.xpts = xpts
self.ypts = ypts
if grid_list:
print("Linear grid list. Following grid_set methods won't apply, though Gs2Gs regridding will")
print("Zero values set for saving")
self.dxRes = 1.0
self.dyRes = 1.0
self.m = 1
self.n = 1
self.ang_c = 1.0
self.ang_s = 1.0
self.xdist = 1.0
self.ydist = 1.0
self.gridinfo = True
self.grid = True
else:
self.dxRes = np.mean(np.diff(xpts[0,:]))
self.dyRes = np.mean(np.diff(ypts[:,0]))
self.m,self.n = np.shape(lons)
self.grid = True
print("Got a grid res = ",self.m," x ",self.n)
print("Note that all grid info is in nx x ny grids, whilst data is in nx x ny")
else: print("Projection not defined yet, do that first")
def set_grid_dxy(self,dxRes,dyRes,ax=None):
# creates a grid depending on wanted resolution
if hasattr(self,'ccrs'):
self.xmin, self.xmax = ax.get_xlim()
self.ymin, self.ymax = ax.get_ylim()
nx = np.abs(int((self.xmax-self.xmin)/dxRes)+1)
ny = np.abs(int((self.ymax-self.ymin)/dyRes)+1)
xpts,ypts = np.meshgrid(
np.linspace(self.xmin,self.xmax,nx),
np.linspace(self.ymin,self.ymax,ny),indexing = 'ij')
lonlat = proj_cart.transform_points(self.ccrs,xpts,ypts)
self.lons = lonlat[:,:,0]
self.lats = lonlat[:,:,1]
else:
nx = int((self.mplot.xmax-self.mplot.xmin)/dxRes)+1
ny = int((self.mplot.ymax-self.mplot.ymin)/dyRes)+1
lons, lats, xpts, ypts = self.mplot.makegrid(nx, ny, returnxy=True)
self.lons = lons
self.lats = lats
self.xpts = xpts
self.ypts = ypts
self.dxRes = dxRes
self.dyRes = dyRes
self.grid = True
self.m = nx
self.n = ny
print("Got a grid res = ",nx," x ",ny)
print("Note that all grid info is in nx x ny grids, whilst data is in nx x ny")
def set_grid_mn(self,nx,ny,ax=None):
# creates a grid depending on wanted no. of points
if hasattr(self,'ccrs'):
self.xmin, self.xmax = ax.get_xlim()
self.ymin, self.ymax = ax.get_ylim()
xpts,ypts = np.meshgrid(
np.linspace(self.xmin,self.xmax,nx),
np.linspace(self.ymin,self.ymax,ny),indexing = 'ij')
lonlat = proj_cart.transform_points(self.ccrs,xpts,ypts)
self.lons = lonlat[:,:,0]
self.lats = lonlat[:,:,1]
self.dxRes = (self.xmax-self.xmin)/(nx - 1)
self.dyRes = (self.ymax-self.ymin)/(ny - 1)
else:
lons, lats, xpts, ypts = self.mplot.makegrid(nx, ny, returnxy=True)
self.lons = lons
self.lats = lats
self.dxRes = (self.mplot.xmax-self.mplot.xmin)/(nx - 1)
self.dyRes = (self.mplot.ymax-self.mplot.ymin)/(ny - 1)
self.xpts = xpts
self.ypts = ypts
self.grid = True
self.m = nx
self.n = ny
print("Got a grid res = ",nx," x ",ny)
def set_gate_grid(self,lonG,latG,npoints=100,aspect=100,res=None):
# creates a grid depending on wanted resolution
"""
set_gate_grid method, creates a 2xn gate grid to view flow between two points
gate is two points wide in order to get the normal direction across it correct
Parameters
---------
lonG
[lon point 1, lon point 2] list or tuple of the longitude of the two points
latG
[lat point 1, lat point 2] list or tuple of the latitude of the two points
npoints: int, optional
the number of points across the gate, default = 100
aspect: float, optional
the ratio between the gate length and the two point width, default = 100
res: float, optional
alternatively we can select a distance here in meteres to space the points by approximate this distance. Here npoints will be equal to point1->point2/res + 1. Default = None
"""
if res is not None:
### (long1, lat1, long2, lat2,deg=False,eps=1e-10)
gate_dist = ellipsoidal_distance(lonG[0],latG[0],lonG[1],latG[1],deg=True)
npoints = int(gate_dist/res)+1
print('Setting npoints from res, npoints = '+str(npoints))
x,y = self.mplot(np.array(lonG),np.array(latG))
xpts = np.linspace(x[0],x[1],npoints)
ypts = np.linspace(y[0],y[1],npoints)
ystep = (xpts[-1]- xpts[0])/aspect
xstep = (ypts[-1]- ypts[0])/aspect
xpts = np.vstack([xpts,xpts - xstep]).T
ypts = np.vstack([ypts,ypts + ystep]).T
if hasattr(self,'ccrs'):
lonlat = proj_cart.transform_points(self.ccrs,xpts,ypts)
self.lons = lonlat[:,:,0]
self.lats = lonlat[:,:,1]
else:
lons,lats = self.mplot(xpts,ypts,inverse=True)
self.lons = lons
self.lats = lats
self.xpts = xpts
self.ypts = ypts
self.dxRes = np.abs(ystep)
self.dyRes = np.abs(xstep)
self.grid = True
self.m = npoints
self.n = 2
print("Got a gate res = ",self.m," ({:g} m)".format(self.dxRes),
" x ",self.n)
def get_grid_info(self,av_dist = True, av_ang = True):
# creates a grid depending on wanted no. of points
# print( self.grid and (not self.gridinfo))
if self.grid and (not self.gridinfo):
#iterate over the grid to get dimensions and angles
# first iterate all x dimensions - m-1/n array
# then iterate all y dimensions - m/n-1 array
lon_pad = np.pad(self.lons, (1,1), 'linear_ramp', end_values=(np.nan))
lat_pad = np.pad(self.lats, (1,1), 'linear_ramp', end_values=(np.nan))
tempf = lambda x1,y1,x2,y2: ellipsoidal_distance(x1,y1,x2,y2,deg=True)
xdims = np.vectorize(tempf)(
lon_pad[ :-1,1:-1],lat_pad[ :-1,1:-1],
lon_pad[1: ,1:-1],lat_pad[1: ,1:-1])
ydims= np.vectorize(tempf)(
lon_pad[1:-1, :-1],lat_pad[1:-1, :-1],
lon_pad[1:-1,1: ],lat_pad[1:-1,1: ])
# then average the available distances i-1,i j-1,j
if av_dist:
self.xdist = np.nanmean([xdims[1:,:],xdims[:-1,:]],axis=0)
self.ydist = np.nanmean([ydims[:,1:],ydims[:,:-1]],axis=0)
else:
self.xdist = np.ones([self.m,self.n])*np.nan
self.ydist = np.ones([self.m,self.n])*np.nan
self.xdist[:-1,:] = xdims[1:-1,:]
self.xdist[-1,:] = xdims[-1,:]
self.ydist[:,:-1] = ydims[:,1:-1]
self.ydist[:,-1] = ydims[:,-1]
print("Grid distances calculated: ",np.nanmean(self.xdist)," x ",np.nanmean(self.ydist))
# then iterate all angles - this is all points plus the extra possible angles
# pad the lon lat arrays for iteration
tempf = lambda x1,y1,x2,y2: lon_lat_angle(x1,y1,x2,y2,
return_trig = True,deg=True)
yPlus_c,yPlus_s = np.vectorize(tempf)(
lon_pad[1:-1,1:-1],lat_pad[1:-1,1:-1],
lon_pad[1:-1,2: ],lat_pad[1:-1,2: ])
if av_ang:
# xplus xPlus_c, -xPlus_s
xPlus_c,xPlus_s = np.vectorize(tempf)(
lon_pad[1:-1,1:-1],lat_pad[1:-1,1:-1],
lon_pad[2: ,1:-1],lat_pad[2: ,1:-1])
# xmin -xPlus_c, xPlus_s
xMins_c,xMins_s = np.vectorize(tempf)(
lon_pad[1:-1,1:-1],lat_pad[1:-1,1:-1],
lon_pad[ :-2,1:-1],lat_pad[ :-2,1:-1])
# ymin -yMins_s, -yMins_c
yMins_c,yMins_s = np.vectorize(tempf)(
lon_pad[1:-1,1:-1],lat_pad[1:-1,1:-1],
lon_pad[1:-1, :-2],lat_pad[1:-1, :-2])
# average all the components first checking the orientation
# if j == 20 and i ==12:
# print([xPlus_c,xMins_c,yPlus_c,yMins_c])
# print([xPlus_s,xMins_s,yPlus_s,yMins_s])
if av_ang:
self.ang_c = np.nanmean([-xPlus_s, xMins_s, yPlus_c,-yMins_c],axis=0)
self.ang_s = np.nanmean([ xPlus_c,-xMins_c, yPlus_s,-yMins_s],axis=0)
# mag = np.hypot(self.ang_c,self.ang_s)
# self.ang_c /= mag
# self.ang_s /= mag
else:
self.ang_c = yPlus_c
self.ang_s = yPlus_s
print('Angles calculated')
self.gridinfo = True
else: print("Grid not defined yet, do that first")
def get_grid_info_old(self,av_dist = True, av_ang = True):
# creates a grid depending on wanted no. of points
# print( self.grid and (not self.gridinfo))
if self.grid and (not self.gridinfo):
#iterate over the grid to get dimensions and angles
# first iterate all x dimensions - m-1/n array
# then iterate all y dimensions - m/n-1 array
xdims = np.empty([self.m-1,self.n])
ydims = np.empty([self.m,self.n-1])
self.xdist = np.empty([self.m,self.n])
self.ydist = np.empty([self.m,self.n])
self.ang_c = np.empty([self.m,self.n])
self.ang_s = np.empty([self.m,self.n])
for i in range(self.m):
for j in range(self.n-1):
try:
ydims[i,j] = ellipsoidal_distance(
self.lons[i,j ],self.lats[i,j ],
self.lons[i,j+1],self.lats[i,j+1],deg=True)
except ZeroDivisionError:
ydims[i,j] = 0.0
for i in range(self.m-1):
for j in range(self.n):
try:
xdims[i,j] = ellipsoidal_distance(
self.lons[i ,j],self.lats[i ,j],
self.lons[i+1,j],self.lats[i+1,j],deg=True)
except ZeroDivisionError:
xdims[i,j] = 0.0
# then average the available distances i-1,i j-1,j
if av_dist:
for i in range(self.m):
for j in range(self.n):
self.xdist[i,j] = np.nanmean(xdims[:i+1,j][-2:])
self.ydist[i,j] = np.nanmean(ydims[i,:j+1][-2:])
else:
self.xdist[:-1,:] = xdims
self.xdist[-1,:] = xdims[-1,:]
self.ydist[:,:-1] = ydims
self.ydist[:,-1] = ydims[:,-1]
print("Grid distances calculated: ",np.nanmean(self.xdist)," x ",np.nanmean(self.ydist))
# then iterate all angles - this is all points plus the extra possible angles
# pad the lon lat arrays for iteration
lon_pad = np.pad(self.lons, (1,1), 'linear_ramp', end_values=(np.nan))
lat_pad = np.pad(self.lats, (1,1), 'linear_ramp', end_values=(np.nan))
for i in range(self.m):
for j in range(self.n):
# i + angle
yPlus_c,yPlus_s = lon_lat_angle(lon_pad[i+1,j+1],lat_pad[i+1,j+1],
lon_pad[i+1,j+2],lat_pad[i+1,j+2],
return_trig = True,deg=True)
if av_ang:
xPlus_c,xPlus_s = lon_lat_angle(lon_pad[i+1,j+1],lat_pad[i+1,j+1],
lon_pad[i+2,j+1],lat_pad[i+2,j+1],
return_trig = True,deg=True)
xMins_c,xMins_s = lon_lat_angle(lon_pad[i+1,j+1],lat_pad[i+1,j+1],
lon_pad[i ,j+1],lat_pad[i ,j+1],
return_trig = True,deg=True)
yMins_c,yMins_s = lon_lat_angle(lon_pad[i+1,j+1],lat_pad[i+1,j+1],
lon_pad[i+1,j ],lat_pad[i+1,j ],
return_trig = True,deg=True)
# average all the components first checking the orientation
# if j == 20 and i ==12:
# print([xPlus_c,xMins_c,yPlus_c,yMins_c])
# print([xPlus_s,xMins_s,yPlus_s,yMins_s])
if av_ang:
self.ang_c[i,j] = np.nanmean([-xPlus_s, xMins_s, yPlus_c,-yMins_c])
self.ang_s[i,j] = np.nanmean([ xPlus_c,-xMins_c, yPlus_s,-yMins_s])
mag = np.hypot(self.ang_c[i,j],self.ang_s[i,j])
self.ang_c[i,j] /= mag
self.ang_s[i,j] /= mag
else:
self.ang_c[i,j] = yPlus_c
self.ang_s[i,j] = yPlus_s
print('Angles calculated')
self.gridinfo = True
else: print("Grid not defined yet, do that first")
@property
def limits(self):
return [
np.min(self.xpts),np.max(self.xpts),
np.min(self.ypts),np.max(self.ypts),
]
#### these are midpoints for plotting
@property
def xptp(self):
if not hasattr(self,'_xptp'):
self.get_ptp()
return self._xptp
@property
def yptp(self):
if not hasattr(self,'_yptp'):
self.get_ptp()
return self._yptp
def get_ptp(self):
"""
Generates pts arrays for pcolor and pcolormesh - midpoitns for grid areas
"""
if self.grid:
# extend longitude by 2
xpt_pad = np.pad(self.xpts, ((1,0),(0,0)), 'edge')
ypt_pad = np.pad(self.ypts, ((0,0),(1,0)), 'edge')
self._xptp = xpt_pad[:-1,:]+0.5*(np.diff(xpt_pad,axis=0))
self._yptp = ypt_pad[:,:-1]+0.5*(np.diff(ypt_pad,axis=1))
# xpt_pad = np.pad(self.xpts, ((0,0),(1,0)), 'edge')
# ypt_pad = np.pad(self.ypts, ((1,0),(0,0)), 'edge')
# self.xptp = xpt_pad[:,:-1]+0.5*(np.diff(xpt_pad,axis=0))
# self.yptp = ypt_pad[:-1,:]+0.5*(np.diff(ypt_pad,axis=1))
#### these are square points for plotting
@property
def xsq(self):
if not hasattr(self,'_xsq'):
self.get_square_points()
return self._xsq
@property
def ysq(self):
if not hasattr(self,'_ysq'):
self.get_square_points()
return self._ysq
def get_square_points(self):
"""
makes the xsq,ysq fields that will let you plot on a square grid
uses np.meshgrid to make location arrasy statring lower left at (0,0)
"""
self._xsq,self._ysq = np.meshgrid(np.linspace(0,1,self.m),np.linspace(0,1,self.n),indexing = 'ij')
@property
def area(self):
return self.xdist*self.ydist
def check_angles(self,point=False,scale=1.0,project = False):
# return np.hypot of con/sin, min/max and mean
check_ang = np.hypot(self.ang_c,self.ang_s)**2
print('mean ='+str(np.nanmean(check_ang)))
print('max ='+str(np.nanmax(check_ang)))
print('min ='+str(np.nanmin(check_ang)))
# if a point is given return a vector to north and x positive
# so it can be plotted on projection
if (type(point) == list and project):
# do it using the projection
i = point[0]
j = point[1]
# vector is due up (0,1)
Out1 = (self.xpts[i,j],self.ypts[i,j])
# due north (easy)
xrot = np.array(0.0) #-self.ang_s[i,j]
yrot = np.array(1.0) # self.ang_c[i,j]
u,v = self.rotate_vector(xrot,yrot,self.lons[i,j],self.lats[i,j])
# vertical on grid (0,1)
xrot = -self.ang_c[i,j]
yrot = -self.ang_s[i,j]
# # horizontal on grid (1,0)
# xrot = -self.ang_s[i,j]
# yrot = self.ang_c[i,j]
u1,v1 = self.rotate_vector(xrot,yrot,self.lons[i,j],self.lats[i,j])
return u,v,u1,v1,Out1[0],Out1[1]
elif type(point) == list:
# returns two normalised vectors
i = point[0]
j = point[1]
# line1 starts at point
# goes in direction to j+1 (+ve x)
xvec = self.xpts[i,j+1] - self.xpts[i,j]
yvec = self.ypts[i,j+1] - self.ypts[i,j]
# print(xvec,yvec)
# angles are between positive x and due north clockwise
# xrot = self.ang_c[i,j]*xvec + self.ang_s[i,j]*yvec
# yrot = self.ang_c[i,j]*yvec - self.ang_s[i,j]*xvec
# rotation is -pi/4 + rotation xrot = xyvec, yrot = -xvec
xrot = self.ang_c[i,j]*yvec - self.ang_s[i,j]*xvec
yrot = -self.ang_c[i,j]*xvec - self.ang_s[i,j]*yvec
# print(xrot,yrot)
print(np.rad2deg(np.arctan2(self.ang_s[i,j],self.ang_c[i,j])))
Out1 = (self.xpts[i,j],self.ypts[i,j])
Out2 = (Out1[0] + xvec*scale,Out1[1] + yvec*scale)
Out3 = (Out1[0] + xrot*scale,Out1[1] + yrot*scale)
# return the list of x,y's needed for plot
return ([Out1[0],Out2[0]],
[Out1[1],Out2[1]]),([Out1[0],Out3[0]],
[Out1[1],Out3[1]])
# line2 starts at point
# goes in direction - j+1 plus rotation
def rotate_vectors_to_plot(self,xvec,yvec):
"""
utilises the ang_c and ang_s arrays along with the associated projection
"""
# ur,vr will be in lon/lat
# ur = xvec*self.ang_c + yvec*self.ang_s
# vr = yvec*self.ang_c - xvec*self.ang_s
# test
ur = -yvec*self.ang_c - xvec*self.ang_s
vr = xvec*self.ang_c - yvec*self.ang_s
urr,vrr = self.rotate_vector(ur,vr,self.lons,self.lats)
return urr,vrr
def blank_grid_info(self):
if not self.gridinfo:
self.ang_c = np.zeros_like(self.lons,dtype=bool)
self.ang_s = np.zeros_like(self.lons,dtype=bool)
self.xdist = np.zeros_like(self.lons,dtype=bool)
self.ydist = np.zeros_like(self.lons,dtype=bool)
self.gridinfo = True
def save_grid(self,file):
if self.grid and self.gridinfo:
# save lat/lon pts
np.savez(file,
lats = self.lats,
lons = self.lons,
xpts = self.xpts,
ypts = self.ypts,
dxRes = self.dxRes,
dyRes = self.dyRes,
m = self.m,
n = self.n,
ang_c = self.ang_c,
ang_s = self.ang_s,
xdist = self.xdist,
ydist = self.ydist)
print("Grid saved in "+file)
else:
print("No grid to save - run get_grid_info")
def save_grid_nc(self,file,notes=''):
if self.grid and self.gridinfo:
# save lat/lon pts
NC_f = Dataset(file, 'w', format='NETCDF4')
NC_f.description = 'python grid_set grid file'+notes
# dimensions
NC_f.createDimension('x', self.m)
NC_f.createDimension('y', self.n)
# variables
# time = NC_f.createVariable('time', 'f8', ('time',))
x = NC_f.createVariable('x', 'f4', ('x',))
y = NC_f.createVariable('y', 'f4', ('y',))
lons = NC_f.createVariable('lons', 'f8', ('x', 'y',))
lats = NC_f.createVariable('lats', 'f8', ('x', 'y',))
ang_c = NC_f.createVariable('ang_c', 'f8',('x', 'y',))
ang_s = NC_f.createVariable('ang_s', 'f8',('x', 'y',))
xdist = NC_f.createVariable('xdist', 'f8',('x', 'y',))
ydist = NC_f.createVariable('ydist', 'f8',('x', 'y',))
NC_f.setncattr_string('dxRes',self.dxRes)
NC_f.setncattr_string('dyRes',self.dyRes)
lons[:,:] = self.lons
lats[:,:] = self.lats
ang_c[:,:] = self.ang_c
ang_s[:,:] = self.ang_s
xdist[:,:] = self.xdist
ydist[:,:] = self.ydist
NC_f.close()
def load_grid(self,file):
npzfile = np.load(file)
self.lats = npzfile["lats"]
self.lons = npzfile["lons"]
# self.xpts = npzfile["xpts"]
# self.ypts = npzfile["ypts"]
self.dxRes = npzfile["dxRes"]
self.dyRes = npzfile["dyRes"]
self.m = npzfile["m"]
self.n = npzfile["n"]
if type(self.m) == np.ndarray: self.m = self.m[()]
if type(self.n) == np.ndarray: self.n = self.n[()]
self.ang_c = npzfile["ang_c"]
self.ang_s = npzfile["ang_s"]
self.xdist = npzfile["xdist"]
self.ydist = npzfile["ydist"]
self.grid = True
self.gridinfo = True
self.reproject(self.mplot)
print("Loaded a grid: "+file)
def check_grid(self):
# makes sure the projection and loaded grid are consistent
if self.proj and self.grid and self.gridinfo:
proj_dim = self.mplot.xmax - self.mplot.xmin
proj_dim = proj_dim/self.m
print("Projection av xdim = ",proj_dim)
print("dxRes = ",self.dxRes)
print("xdist av = ",np.mean(self.xdist))
def get_grid_mask(self,inflate = 0.0):
# makes a land mask for each point then inflates by a distance m
# makes a land mask for each point then inflates by a distance m
if hasattr(self,'ccrs'):
Tlons = self.lons.copy()
Tlons[Tlons>180] -= 360
ocean = cfeature.OCEAN
allocean = list(ocean.geometries())
mask = np.sum([shapely.vectorized.contains(c, Tlons, self.lats)
for c in allocean],axis=0)
self.mask = np.ones([self.m,self.n])*np.nan
self.mask[mask==1] = 1.0
self.masked =True
self.mask_inflate = 0.0
else:
self.mask = np.ones([self.m,self.n])
for i in range(self.m):
for j in range(self.n):
if self.mplot.is_land(self.xpts[i,j],self.ypts[i,j]):
self.mask[i,j] = np.nan
self.masked =True
self.mask_inflate = 0.0
inf_mask = np.ones([self.m,self.n])
if (inflate>0.0) and self.gridinfo:
self.inflate_mask(inflate)
def inflate_mask(self,inflate = 0.0):
# makes a land mask for each point then inflates by a distance m
# makes a land mask for each point then inflates by a distance m
if self.masked and self.gridinfo:
inf_mask = np.ones([self.m,self.n])
if (inflate>0.0) and self.gridinfo:
if hasattr(self,'mask_inflate'):
self.mask_inflate += inflate
else:
self.mask_inflate = inflate
for i in range(self.m):
for j in range(self.n):
if np.isnan(self.mask[i,j]):
inf_p = int(inflate/np.hypot(self.xdist[i,j],self.ydist[i,j]))
inf_mask[i-inf_p:i+inf_p+1,j-inf_p:j+inf_p+1] = np.nan
self.mask = inf_mask
elif self.gridinfo:
self.mask_inflate = inflate
else:
print("Not masked so can't inflate")
def mask_point(self,lon,lat,inflate = 0):
x,y = np.unravel_index(np.argmin(
np.abs(self.lons - lon) +
np.abs(self.lats - lat)),
np.shape(self.lons))
if (inflate>0.0) and self.gridinfo:
inf_p = int(inflate/np.hypot(self.xdist[x,y],self.ydist[x,y]))
self.mask[x-inf_p:x+inf_p+1,y-inf_p:y+inf_p+1] = np.nan
else:
self.mask[x,y] = np.nan
def save_mask(self,file):
if self.masked:
# save lat/lon pts
np.savez(file,
mask = self.mask,
mask_inflate = self.mask_inflate,
m = self.m,
n = self.n)
print("Mask saved in "+file)
else:
print("No mask to save - run get_grid_mask")
def load_mask(self,file):
if self.masked:
print("Masked already!")
elif self.gridinfo:
# save lat/lon pts
npzfile = np.load(file)
self.mask = npzfile["mask"]
self.mask_inflate = npzfile["mask_inflate"]
m_check = npzfile["m"]
n_check = npzfile["n"]
if (m_check == self.m)&(n_check == self.n):
print("Loaded mask, ",m_check," x ",n_check," inflated by ",self.mask_inflate)
self.masked = True
else:
print("Gird and mask dimensins inconsistent, check them")
print("Mask",m_check," x ",n_check," Grid, ",self.m," x ",self.n)
def generate_mask_lonlat(self,lon_r,lat_r,add_mask = True,out='bool'):
"""
give a lon_r = [l1,l2] range of lons to keep within the mask
give a lat_r = [l1,l2] range of lats to keep within the mask
makes a np array that keeps the given range unmaksed.
add_mask keeps the new mask true to the original GS mask, ie, keeps a land mask
out = 'bool' makes the out array a logical, T = unmaskes, F = masked
out = 'float' makes the out array a float, 1.0 unmasked, np.nan = masked
"""
new_mask = np.ones_like(self.mask)
new_mask[self.lats<lat_r[0]] =np.nan
new_mask[self.lats>lat_r[1]] =np.nan
new_mask[self.lons<lon_r[0]] =np.nan
new_mask[self.lons>lon_r[1]] =np.nan
if add_mask:
new_mask[np.isnan(self.mask)] =np.nan
if out == 'Float':
return new_mask
elif out == 'bool':
out_mask = np.ones_like(self.mask,dtype=bool)
out_mask[np.isnan(new_mask)] = False
return out_mask
def GS2track(self,arr,lon,lat,method='linear',save_array = False):
"""
Give this function an array and lon/lat of a 1d track
You'll get the array regridded onto the track
Saves the regridding methods for efficiency
method = 'linear','nearest','cubic' is the scipy interpolator used
"""
from scipy.spatial import Delaunay
from scipy.interpolate import LinearNDInterpolator
from scipy.interpolate import NearestNDInterpolator
from scipy.interpolate import CloughTocher2DInterpolator
# get the tri angulation
### check if the regridding terms exist
### make
if not hasattr(self, 'tri'):
xyorig = np.vstack((self.xpts.ravel(),self.ypts.ravel())).T
self.tri = Delaunay(xyorig) # Compute the triangulation
mesh_new = self.mplot(lon,lat)
try:
arrout = arr(mesh_new)
return arrout
except TypeError:
if method == 'linear':
interpolator = LinearNDInterpolator(self.tri, arr.ravel())
elif method == 'nearest':
interpolator = NearestNDInterpolator(self.tri, arr.ravel())
elif method == 'cubic':
interpolator = CloughTocher2DInterpolator(self.tri, arr.ravel())
arrout = interpolator(mesh_new)
if save_array:
return arrout, interpolator
else:
return arrout
def GS2track_vecs(self,x,y,lon,lat,method='linear',save_array = False):
"""
Give this function an array and lon/lat of a 1d track
You'll get the array regridded onto the track
Saves the regridding methods for efficiency
method = 'linear','nearest','cubic' is the scipy interpolator used
"""
from scipy.spatial import Delaunay
from scipy.interpolate import LinearNDInterpolator
from scipy.interpolate import NearestNDInterpolator
from scipy.interpolate import CloughTocher2DInterpolator
# get the tri angulation
### check if the regridding terms exist
### make
if not hasattr(self, 'tri'):
xyorig = np.vstack((self.xpts.ravel(),self.ypts.ravel())).T
self.tri = Delaunay(xyorig) # Compute the triangulation
mesh_new = self.mplot(lon,lat)
try:
xout = x(mesh_new)
yout = y(mesh_new)
return xout,yout
except TypeError:
xr = -y*self.in_ang_c - x*self.in_ang_s
yr = x*self.in_ang_c - y*self.in_ang_s
if method == 'linear':
interpolatorX = LinearNDInterpolator(self.tri, xr.ravel())
interpolatorY = LinearNDInterpolator(self.tri, yr.ravel())
elif method == 'nearest':
interpolatorX = NearestNDInterpolator(self.tri, xr.ravel())
interpolatorY = NearestNDInterpolator(self.tri, yr.ravel())
elif method == 'cubic':
interpolatorX = CloughTocher2DInterpolator(self.tri, xr.ravel())
interpolatorY = CloughTocher2DInterpolator(self.tri, yr.ravel())
xout = interpolatorX(mesh_new)
yout = interpolatorY(mesh_new)
if save_array:
return xout,yout, interpolatorX,interpolatorY
else:
return xout,yout
def bin_list(self,data_list,lons,lats,bin_func = 'mean',
ret_count = False,xy_order = 0,append = False,verbos=False):
from scipy import stats
"""
uses the grid_set to bin data points
will only work well with grids and projections that are 'squarish'
If the grid is too distorted then this won't be accurate
If the gird is say diagonally orientated to the projection
again this won't work
Uses the scipy.stats.binned_statistics
data_list = list of data points (list np.array data_frame column)
lon/lat = the same as data_list but lon/lat
bin_func, the statistic we want, as with binned_statistics
this can be a function
xy_order is for intialising the grid_bin
default = 0, expecting xpts to increase in the x direction
set to = 1, for xpts increasing in the y direction (odd grid)
"""
stat_append = False
if append is not False: stat_append = True
if not hasattr(self, 'edges_x') or xy_order!=self.xy_order:
dims = np.shape(self.xpts)
self.xy_order = xy_order
if xy_order == 0:
self.edges_x = np.zeros(dims[0]+1)
self.edges_y = np.zeros(dims[1]+1)
self.edges_x[0:-1] = self.xpts[:,0]
self.edges_y[0:-1] = self.ypts[0,:]
elif xy_order == 1:
self.edges_x = np.zeros(dims[1]+1)
self.edges_y = np.zeros(dims[0]+1)
self.edges_x[0:-1] = self.xpts[0,:]
self.edges_y[0:-1] = self.ypts[:,0]
xshift = np.mean(np.diff(self.edges_x))
yshift = np.mean(np.diff(self.edges_y))
self.edges_x[-1] = 2*self.edges_x[-2] - self.edges_x[-3]
self.edges_y[-1] = 2*self.edges_y[-2] - self.edges_y[-3]
self.edges_x = self.edges_x - xshift
self.edges_y = self.edges_y - yshift
#### we can't have dcreasing bins so let's shift them
self.descx = False
self.descy = False
if np.sum(np.diff(self.edges_x))<0.0:
self.edges_x = np.flip(self.edges_x)
self.descx = True
if np.sum(np.diff(self.edges_y))<0.0:
self.edges_y = np.flip(self.edges_y)
self.descy = True
x,y = self.mplot(lons,lats)
msk = np.isfinite(data_list) & np.isfinite(lons) & np.isfinite(lats)
# return [self.edges_x-xshift,self.edges_y-yshift]
ret = stats.binned_statistic_2d(x[msk],y[msk],
data_list[msk],statistic=bin_func,
bins=[self.edges_x,self.edges_y])
#### now return array
if self.xy_order == 1:
outarr = ret.statistic.T
else:
outarr = ret.statistic
### flip outputs if needed
if ((self.xy_order == 0 and self.descx)
or (self.xy_order == 1 and self.descy)):
outarr = np.fliplr(outarr)
if verbos: print('flipping lr')
if ((self.xy_order == 0 and self.descy)
or (self.xy_order == 1 and self.descx)):
outarr = np.flipud(outarr)
if verbos: print('flipping ud')
### count for accumulation
if ret_count or stat_append:
ret = stats.binned_statistic_2d(x[msk],y[msk],
data_list[msk],statistic='count',
bins=[self.edges_x,self.edges_y])
if self.xy_order == 1:
outcount = ret.statistic.T
else:
outcount = ret.statistic
if ((self.xy_order == 0 and self.descx)
or (self.xy_order == 1 and self.descy)):
outcount = np.fliplr(outcount)
if ((self.xy_order == 0 and self.descy)
or (self.xy_order == 1 and self.descx)):
outcount = np.flipud(outcount)
### again flip if needed
#### or accumulate the count
if stat_append:
### weighted av
count_weight = append[1] + outcount
w_old = append[0]*append[1]/count_weight
w_new = outarr*outcount/count_weight
w_old[np.isnan(w_old)] = 0.0
w_new[np.isnan(w_new)] = 0.0
newarr = w_old + w_new
newarr[count_weight<1] = np.nan
outarr = newarr
outcount = count_weight
if ret_count:
return outarr,outcount
else:
return outarr
def hist_bin_list(self,data_list,lons,lats,hist_bins,
xy_order = 0,append = False,verbos=False):
from scipy import stats