forked from ihesp/IPART
/
river_tracker1_funcs.py
1172 lines (942 loc) · 39.6 KB
/
river_tracker1_funcs.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
'''Functions used in river_tracker1.py
Author: guangzhi XU (xugzhi1987@gmail.com; guangzhi.xu@outlook.com)
Update time: 2019-05-10 11:03:36.
'''
from __future__ import print_function
import numpy as np
import pandas as pd
import networkx as nx
from skimage import measure
from skimage import morphology
from scipy import ndimage
import matplotlib.pyplot as plt
import cdms2 as cdms
import MV2 as MV
from genutil import statistics as stats
import cdutil
from utils import rdp
from utils import funcs
from utils import peak_prominence2d as pp2d
NX_VERSION=nx.__version__[0]
def plotGraph(graph,ax=None,show=True):
'''Helper func to plot the graph of an AR coordinates
'''
if ax is None:
fig=plt.figure()
ax=fig.add_subplot(111)
pos=[(ii[1],ii[0]) for ii in graph.nodes()] # x,y
pos_dict=dict(zip(graph.nodes(),pos))
nx.draw(graph,ax=ax,pos=pos_dict,node_size=15,node_color='darkgray',
edge_color='dimgray')
if show:
plt.show(block=False)
return
def areaFilt(mask,area,min_area=None,max_area=None):
'''Filter AR binary masks by region areas
Args:
mask (ndarray): 2D binary mask with detected objects shown as 1s.
area (ndarray): 2D map showing grid cell areas in km^2.
min_area (float or None): if not None, minimum area to filter objects
in <mask>.
max_area (float or None): if not None, maximum area to filter objects
in <mask>.
Returns:
result (ndarray): 2D binary mask with objects area-filtered.
'''
if min_area is None and max_area is None:
return mask
labels=measure.label(mask,connectivity=1)
n=labels.max()+1
areas=ndimage.sum(area,labels,np.arange(n))
sel=np.ones(n,bool)
if min_area is not None:
sel=np.where(areas<min_area,0,sel)
if max_area is not None:
sel=np.where(areas>max_area,0,sel)
# remove background area
sel[0]=0
result=sel[labels]
return result
def spherical2Cart(lat,lon):
clat=(90-lat)*np.pi/180.
lon=lon*np.pi/180.
x=np.cos(lon)*np.sin(clat)
y=np.sin(lon)*np.sin(clat)
z=np.cos(clat)
return np.array([x,y,z])
def cart2Spherical(x,y,z, shift_lon):
r=np.sqrt(x**2+y**2+z**2)
clat=np.arccos(z/r)/np.pi*180
lat=90.-clat
lon=np.arctan2(y,x)/np.pi*180
lon=(lon+360)%360
lon=np.where((lon>=0) & (lon<shift_lon),lon+360,lon)
return np.array([lat,lon,np.ones(lat.shape)])
def computeTheta(p1,p2):
'''Tangent line to the arc |p1-p2|
<p1>,<p2>: (lat,lon) coordinates
'''
p1=spherical2Cart(p1[0],p1[1])
p2=spherical2Cart(p2[0],p2[1])
theta=p2-np.dot(p1,p2)*p1
norm=np.linalg.norm(theta)
if norm>0:
theta=theta/norm
return theta
def wind2Cart(u,v,lats,lons):
'''Convert u,v winds to Cartesian, consistent with spherical2Cart.
'''
latsr=lats*np.pi/180
lonsr=lons*np.pi/180
vh=v*np.sin(latsr)
ux=-u*np.sin(lonsr) - vh*np.cos(lonsr)
uy=u*np.cos(lonsr) - vh*np.sin(lonsr)
uz=v*np.cos(latsr)
vs=np.array([ux,uy,uz])
return vs
def cart2Wind(vs,lats,lons):
'''Convert winds in Cartesian to u,v, inverse to wind2Cart.
'''
latsr=lats*np.pi/180
lonsr=lons*np.pi/180
#ux=vs[0]
uy=vs[1]
uz=vs[2]
u=uy/np.cos(lonsr) + uz*np.tan(latsr)*np.tan(lonsr)
v=uz/np.cos(latsr)
return u,v
def maskToGraph(mask, quslab, qvslab, costhetas, sinthetas, edge_eps,
connectivity=2):
'''Create graph from AR mask
Args:
mask (ndarray): 2D binary map showing the location of an AR with 1s.
quslab (cdms.TransientVariable): 2D map of u-flux.
qvslab (cdms.TransientVariable): 2D map of v-flux.
costhetas (cdms.TransientVariable): (n * m) 2D slab of grid cell shape:
cos=dx/sqrt(dx^2+dy^2).
sinthetas (cdms.TransientVariable): (n * m) 2D slab of grid cell shape:
sin=dy/sqrt(dx^2+dy^2).
edge_eps (float): float in (0,1), minimal proportion of flux component
in a direction to total flux to allow edge building
in that direction. Defined in Global preamble.
connectivity (int): 1 or 2. 4- or 8- connectivity in defining neighbor-
hood relationship in a 2D square grid.
Returns:
g (networkx.DiGraph): directed planar graph constructed from AR mask
and flows.
'''
quslab=np.array(quslab)
qvslab=np.array(qvslab)
wsslab=np.sqrt(quslab**2+qvslab**2)
g=nx.DiGraph()
# 1 connectivity edges
# the list approach
'''
y,x=np.where(mask)
zipcor=zip(y,x)
right=[(yi,xi) for yi,xi in zipcor if (yi,xi+1) in zipcor]
left=[(yi,xi) for yi,xi in zipcor if (yi,xi-1) in zipcor]
up=[(yi,xi) for yi,xi in zipcor if (yi+1,xi) in zipcor]
down=[(yi,xi) for yi,xi in zipcor if (yi-1,xi) in zipcor]
# nodes to the right/left/up/down
right0=[(yi,xi+1) for yi,xi in right]
left0=[(yi,xi-1) for yi,xi in left]
up0=[(yi+1,xi) for yi,xi in up]
down0=[(yi-1,xi) for yi,xi in down]
'''
# the shifting approach
right=np.roll(mask, -1, axis=1)*mask
left=np.roll(mask, 1, axis=1)*mask
up=np.roll(mask, -1, axis=0)*mask
down=np.roll(mask, 1, axis=0)*mask
def addWeightedEdges2(nodes1,speedslab,d):
'''Add directed edges to graph. For shifting approach
'''
ratio=np.where(wsslab==0., 0, speedslab/wsslab)
idx=np.where(ratio>=edge_eps, 1, 0)*nodes1
idx=zip(*np.where(idx>0))
for ii, (yii,xii) in enumerate(idx):
# nii: start, nii2: end
yii=int(yii)
xii=int(xii)
nii=(yii,xii)
if d=='r':
nii2=(yii,xii+1)
elif d=='l':
nii2=(yii,xii-1)
elif d=='u':
nii2=(yii+1,xii)
elif d=='d':
nii2=(yii-1,xii)
elif d=='tr':
nii2=(yii+1,xii+1)
elif d=='br':
nii2=(yii-1,xii+1)
elif d=='tl':
nii2=(yii+1,xii-1)
elif d=='bl':
nii2=(yii-1,xii-1)
meanivt=speedslab[yii,xii]
g.add_edge(nii,nii2,
weight=np.exp(-meanivt/1e2),
ivt=meanivt)
def addWeightedEdges(nodes1,nodes2,speedslab):
'''Add directed edges to graph. For the list approach
'''
# nii: start, nii2: end
for nii,nii2 in zip(nodes1,nodes2):
if speedslab[nii]/wsslab[nii]>=edge_eps:
meanivt=speedslab[nii]
g.add_edge(nii,nii2,
weight=np.exp(-meanivt/1e2),
ivt=meanivt)
# add 1 connectivity edges
#addWeightedEdges(right,right0,quslab)
#addWeightedEdges(left,left0,-quslab)
#addWeightedEdges(up,up0,qvslab)
#addWeightedEdges(down,down0,-qvslab)
addWeightedEdges2(right,quslab,'r')
addWeightedEdges2(left,-quslab,'l')
addWeightedEdges2(up,qvslab,'u')
addWeightedEdges2(down,-qvslab,'d')
# 2 connectivity edges
if connectivity==2:
# the list approach
'''
tr=[(yi,xi) for yi,xi in zipcor if (yi+1,xi+1) in zipcor]
br=[(yi,xi) for yi,xi in zipcor if (yi-1,xi+1) in zipcor]
tl=[(yi,xi) for yi,xi in zipcor if (yi+1,xi-1) in zipcor]
bl=[(yi,xi) for yi,xi in zipcor if (yi-1,xi-1) in zipcor]
tr0=[(yi+1,xi+1) for yi,xi in tr]
br0=[(yi-1,xi+1) for yi,xi in br]
tl0=[(yi+1,xi-1) for yi,xi in tl]
bl0=[(yi-1,xi-1) for yi,xi in bl]
'''
# the shifting approach
tr=np.roll(np.roll(mask, -1, axis=0), -1, axis=1)*mask
br=np.roll(np.roll(mask, 1, axis=0), -1, axis=1)*mask
tl=np.roll(np.roll(mask, -1, axis=0), 1, axis=1)*mask
bl=np.roll(np.roll(mask, 1, axis=0), 1, axis=1)*mask
# add 2 connectivity edges
#addWeightedEdges(tr,tr0,quslab*costhetas+qvslab*sinthetas)
#addWeightedEdges(br,br0,quslab*costhetas-qvslab*sinthetas)
#addWeightedEdges(tl,tl0,-quslab*costhetas+qvslab*sinthetas)
#addWeightedEdges(bl,bl0,-quslab*costhetas-qvslab*sinthetas)
addWeightedEdges2(tr,quslab*costhetas+qvslab*sinthetas,'tr')
addWeightedEdges2(br,quslab*costhetas-qvslab*sinthetas,'br')
addWeightedEdges2(tl,-quslab*costhetas+qvslab*sinthetas,'tl')
addWeightedEdges2(bl,-quslab*costhetas-qvslab*sinthetas,'bl')
return g
def getARAxis(g, quslab, qvslab, mask):
'''Find AR axis from AR region mask
Args:
g (networkx.DiGraph): directed planar graph constructed from AR mask
and flows. See maskToGraph().
quslab (cdms.TransientVariable): 2D map of u-flux.
qvslab (cdms.TransientVariable): 2D map of v-flux.
mask (ndarray): 2D binary map showing the location of an AR with 1s.
Returns:
path (ndarray): Nx2 array storing the AR axis coordinate indices in
(y, x) format.
axismask (ndarray): 2D binary map with same shape as <mask>, with
grid cells corresponding to coordinates in <path>
set to 1s.
'''
nodes=list(g.nodes())
#---------------Find boundary nodes---------------
edge=mask-morphology.binary_erosion(mask)
gy,gx=np.gradient(np.array(mask))
inedge=(gx*quslab+gy*qvslab)*edge
inedgecoor=np.where(inedge>0)
inedgecoor=zip(inedgecoor[0],inedgecoor[1])
inedgecoor=list(set(inedgecoor).intersection(nodes))
outedgecoor=np.where(inedge<0)
outedgecoor=zip(outedgecoor[0],outedgecoor[1])
outedgecoor=list(set(outedgecoor).intersection(nodes))
n1=len(inedgecoor)
n2=len(outedgecoor)
# when mask is at edge of the map. Rarely happens.
if n1==0:
inedgecoor=nodes
n1=len(inedgecoor)
if n2==0:
outedgecoor=nodes
n2=len(outedgecoor)
dists=np.zeros((n1,n2))
def sumDists(path,attr,g):
'''Sum edge distances along a path'''
s=0
for ii in range(len(path)-1):
if NX_VERSION=='2':
sii=g[path[ii]][path[ii+1]][attr]
else:
sii=g.edge[path[ii]][path[ii+1]][attr]
# penalize sharp turns. Doesn't make big difference but notably
# slower
'''
if ii+2<len(path):
pii1=(lats[path[ii][0]], lons[path[ii][1]])
pii2=(lats[path[ii+1][0]], lons[path[ii+1][1]])
pii3=(lats[path[ii+2][0]], lons[path[ii+2][1]])
theta1=computeTheta(pii1,pii2)
theta2=computeTheta(pii2,pii3)
dtheta=theta1.dot(theta2)
dtheta=abs(dtheta)**1
#if ii==0:
#dtheta_old=1.
#dtheta=np.mean([dtheta,dtheta_old])
#sii=sii*dtheta
#dtheta_old=dtheta
'''
s+=sii
return s
#---------------Find "longest" path---------------
for ii in range(n1):
eii=inedgecoor[ii]
pathsii=nx.single_source_dijkstra_path(g,eii,weight='weight')
pathsii=dict([(kk,vv) for kk,vv in pathsii.items() if kk in outedgecoor])
if len(pathsii)>0:
distdict=dict([(kk, sumDists(vv,'ivt',g)) for kk,vv in pathsii.items()])
nodeii=sorted(distdict,key=distdict.get)[-1]
distii=distdict[nodeii]
dists[ii,outedgecoor.index(nodeii)]=distii
if np.max(dists)==0:
# this may happen when a mask is touching the map edges, and inedgecoor
# outedgecoor can't be linked by a path. Very rarely happen, but damn
# annoying. A fallback solution is to use an undirected graph linking
# the most inward and most outward pixels.
mostin=np.unravel_index(np.argmax(inedge), mask.shape)
mostout=np.unravel_index(np.argmin(inedge), mask.shape)
g_und=g.to_undirected()
try:
path=nx.dijkstra_path(g_und,mostin,mostout,weight='weight')
except:
# if it still can't find a path, make a full connected network
g_full=maskToGraph(mask, quslab, qvslab, np.ones(mask.shape),
np.ones(mask.shape), -np.inf)
path=nx.dijkstra_path(g_full,mostin,mostout,weight='weight')
else:
maxidx=np.argmax(dists)
yidx,xidx=np.unravel_index(maxidx,(n1,n2))
path=nx.dijkstra_path(g,inedgecoor[yidx],outedgecoor[xidx],weight='weight')
# get a mask for axis
axismask=np.zeros(mask.shape)
for (y,x) in path:
axismask[y,x]=1
path=np.array(path)
return path, axismask
def cropMask(mask, edge=4):
'''Cut out a bounding box around mask==1 areas
Args:
mask (ndarray): 2D binary map showing the location of an AR with 1s.
edge (int): number of pixels as edge at 4 sides.
Returns:
mask[y1:y2, x1:x2] (ndarray): a sub region cut from <mask> surrouding
regions with value=1.
(yy,xx): y-, x- indices of the box of the cut region. Can later by
used in applyCropIdx(new_slab, (yy,xx)) to crop out the same
region from a new array <new_slab>.
'''
yidx,xidx=np.where(mask==1)
if len(yidx)==0:
raise Exception("mask empty")
y1=np.min(yidx)
y2=np.max(yidx)
x1=np.min(xidx)
x2=np.max(xidx)
y1=max(0,y1-edge)
y2=min(mask.shape[0],y2+edge)
x1=max(0,x1-edge)
x2=min(mask.shape[1],x2+edge)
xx=np.arange(x1,x2)
yy=np.arange(y1,y2)
return mask[y1:y2,x1:x2], (yy,xx)
def applyCropIdx(slab, cropidx):
'''Cut out a bounding box from given 2d slab given corner indices
Args:
slab (ndarray): 2D array to cut a box from.
cropidx (tuple): (y, x) coordinate indices, output from cropMask().
Returns:
cropslab (ndarray): 2D sub array cut from <slab> using <cropidx> as
boundary indices.
'''
cropslab=np.array(slab)[np.ix_(*cropidx)]
try:
croplat=slab.getLatitude()[:][cropidx[0]]
croplon=slab.getLongitude()[:][cropidx[1]]
croplat=cdms.createAxis(croplat)
croplat.designateLatitude()
croplat.id='y'
croplat.units='degree'
croplat.name='latitude'
croplon=cdms.createAxis(croplon)
croplon.designateLongitude()
croplon.id='x'
croplon.units='degree'
croplon.name='longitude'
cropslab=MV.array(cropslab)
cropslab.setAxis(0,croplat)
cropslab.setAxis(1,croplon)
except:
pass
return cropslab
def insertCropSlab(shape, cropslab, cropidx, axislist=None):
'''Insert the cropped sub-array back to a larger empty slab
Args:
shape (tuple): (n, m) size of the larger slab.
cropslab (ndarray): 2D array to insert.
cropidx (tuple): (y, x) coordinate indices, output from cropMask(),
defines where <cropslab> will be inserted into.
Kwargs:
axislist (list or None): if list, a list of cdms.TransientAxis objs.
Returns:
result (ndarray): 2D slab with shape (n, m), an empty array with a
box at <cropidx> replaced with data from <cropslab>.
Optionally, axes information is added if <axistlist>
is not None, making it an TransientVariable.
'''
result=np.zeros(shape)
result[np.ix_(*cropidx)]=cropslab
if axislist is not None:
result=MV.array(result)
result.setAxisList(axislist)
return result
def getMaskEdge(mask):
'''Get the ordered boundary cell indices around non-zeros values in a
binary mask
Args:
mask (ndarray): 2D binary mask.
Returns:
edge (ndarray): Nx2 array storing (x, y) coordinate indices of the
grid cells in <mask> that form the boundary of
objects defined as non-zero values.
'''
edge=mask-morphology.binary_erosion(mask)
edge=np.where(edge>0)
edge=zip(edge[1],edge[0])
edge=np.array(edge)
edge=funcs.getLineFromPoints(edge)
return edge
def partPeaks(cropmask, cropidx, orislab, max_ph_ratio):
'''Separate local maxima by topographical prominence
Args:
cropmask (ndarray): 2D binary array, defines regions of local maxima.
cropidx (tuple): (y, x) coordinate indices, output from cropMask().
orislab (ndarray): 2D array, giving magnitude/height/intensity values
defining the topography.
max_ph_ratio (float): maximum peak/height ratio. Local peaks with
a peak/height ratio larger than this value is
treated as an independent peak.
Returns:
result (ndarray): 2D binary array, similar as the input <cropmask>
but with connected peaks (if any) separated so that
each connected region (with 1s) denotes an
independent local maximum.
'''
cropslab=applyCropIdx(orislab,cropidx)
if 0 in cropidx[0] or 0 in cropidx[1] or orislab.shape[0]-1 in\
cropidx[0] or orislab.shape[1]-1 in cropidx[1]:
include_edge=True
else:
include_edge=False
# compute prominences
peaks,peakid,peakpro,peakparents=pp2d.getProminence(cropslab*cropmask,
10.,include_edge=include_edge,centroid_num_to_center=1,verbose=False)
peakheights=(peakpro>0)*cropslab*cropmask
ratios=cropmask*peakpro/peakheights
# take maxima whose prominence/height ratio> max_ph_ratio
localpeaks=np.where(ratios>max_ph_ratio)
localpeaks=zip(localpeaks[0],localpeaks[1])
mask1=np.zeros(cropmask.shape) # modified mask
# residual mask, the union of complimentary masks. A complimentary mask
# is the sea level mask that separates a peak from its parent. Note that
# peaks' sea levels are not necessarily at the same height.
resmask=np.zeros(cropmask.shape)
def breakPeaks(yidx,xidx,localpeaks,col):
'''Separate the contour of a peak from its parent by iteratively
rising the sea level
'''
labels=morphology.label(cropslab*cropmask>col)
dropthis=False
while True:
#plabels=[labels[yjj,xjj] for yjj,xjj in localpeaks]
plabels=[labels[yjj,xjj] for yjj,xjj in localpeaks if labels[yjj, xjj]==labels[yidx, xidx]]
#if len(set(plabels))==len(localpeaks):
if len(plabels)==1:
break
col+=5.
if col>cropslab[yidx,xidx]:
dropthis=True
col-=5.
break
labels=morphology.label(cropslab*cropmask>col)
tmpmask=np.zeros(cropmask.shape)
if not dropthis:
tmpmask[yidx,xidx]=1
tmpmask=morphology.reconstruction(tmpmask,cropslab>col,'dilation')
return tmpmask,col
if len(localpeaks)==1:
mask1=cropmask
else:
# sort by prominence/height ratios
ratios=[ratios[int(yjj), int(xjj)] for yjj,xjj in localpeaks]
heights=[peakheights[int(yjj), int(xjj)] for yjj, xjj in localpeaks]
sortidx=np.argsort(ratios)
ratios.sort()
localpeaks=[localpeaks[idjj] for idjj in sortidx]
'''
localpeakids=[peakid[yjj,xjj] for yjj,xjj in localpeaks]
localpeakcols=[peaks[idjj]['col_level'] for idjj in localpeakids]
c_col=np.min(localpeakcols)-10
labs=morphology.label(cropslab*cropmask>c_col)
while True:
if c_col>np.max(cropslab*cropmask):
break
plabels=[labs[yjj,xjj] for yjj,xjj in localpeaks]
if len(set(plabels))==len(localpeaks):
break
c_col+=5.
labs=morphology.label(cropslab*cropmask>c_col)
mask1=morphology.reconstruction(localpeaks_map, cropslab>c_col, 'dilation')
'''
for yjj,xjj in localpeaks:
yjj=int(yjj)
xjj=int(xjj)
idjj=peakid[yjj,xjj]
coljj=peaks[idjj]['col_level']
if peaks[idjj]['parent']==0 and peakheights[yjj,xjj]==np.max(heights):
# the heighest peak
tmpmask=np.zeros(cropslab.shape)
tmpmask[yjj,xjj]=1
tmpmask=morphology.reconstruction(tmpmask,
(cropmask-resmask)>0,'dilation')
mask1=mask1+tmpmask
else:
# separate local peaks
tmpmask,coljj2=breakPeaks(yjj,xjj,localpeaks,coljj)
# if childrens overlap, may not need this anymore
if (tmpmask+mask1).max()>1:
tmpmask2=np.zeros(cropmask.shape)
tmpmask2[yjj,xjj]=1
tmpmask=morphology.reconstruction(tmpmask2,tmpmask-tmpmask*resmask,'dilation')
mask1=mask1+tmpmask
resmask=np.where((resmask==1) | (cropslab<coljj2),1,0)
result=insertCropSlab(orislab.shape,mask1,cropidx)
return result
def getARData(slab, quslab, qvslab, anoslab, quano, qvano, areas,
mask_list, axis_list, timestr, param_dict, shift_lon, isplot,
outputdir):
'''Fetch AR related data
Args:
slab (cdms.TransientVariable): (n * m) 2D array of IVT, in kg/m/s.
quslab (cdms.TransientVariable): (n * m) 2D array of u-flux, in kg/m/s.
qvslab (cdms.TransientVariable): (n * m) 2D array of v-flux, in kg/m/s.
anoslab (cdms.TransientVariable): (n * m) 2D array of IVT anomalies,
in kg/m/s.
quano (cdms.TransientVariable): (n * m) 2D array of u-flux anomalies,
in kg/m/s.
qvano (cdms.TransientVariable): (n * m) 2D array of v-flux anomalies,
in kg/m/s.
areas (cdms.TransientVariable): (n * m) 2D grid cell area slab, in km^2.
mask_list (list): list of 2D binary masks, each with the same shape as
<anoslab> etc., and with 1s denoting the location of a
found AR.
axis_list (list): list of AR axis coordinates. Each coordinate is defined
as a Nx2 ndarray storing (y, x) indices of the axis
(indices defined in the matrix of corresponding mask
in <masks>.)
timestr (str): string of time snap.
param_dict (dict): parameter dict defined in Global preamble.
shift_lon (float): starting longitude of data domain, defined in Global
preamble.
isplot (bool): if True, create plot of AR axis, flux orientation and
cross-sectional flux for each AR.
outputdir (str): folder to save plots. If None, don't save. If <isplot>
is False, not relevant.
Returns:
labels (cdms.TransientVariable): (n * m) 2D int map showing all ARs
at current time. Each AR is labeled by
an int label, starting from 1. Background
is filled with 0s.
angles (cdms.TransientVariable): (n * m) 2D map showing orientation
differences between AR axes and fluxes,
for all ARs. In degrees.
crossfluxes (cdms.TransientVariable): (n * m) 2D map showing cross-
sectional fluxes in all ARs.
In kg/m/s.
anocrossflux (cdms.TransientVariable): similar as <crossfluxes> but for
anomalous fluxes (corresponding
to <anoslab>).
df (pandas.DataFrame): AR record table. Each row is an AR, see code
below for columns.
'''
max_isoq=param_dict['max_isoq']
min_length=param_dict['min_length']
min_length_hard=param_dict['min_length_hard']
rdp_thres=param_dict['rdp_thres']
min_area=param_dict['min_area']
lonax=slab.getLongitude() # NOTE: max > 360
latax=slab.getLatitude()
# prepare outputs
labels=MV.zeros(slab.shape)
angles=MV.zeros(slab.shape)
crossfluxes=MV.zeros(slab.shape)
results={}
#-----------------Loop through ARs-----------------
for ii in range(len(mask_list)):
maskii=mask_list[ii]
# region properties, in pixel units
rpii=measure.regionprops(maskii, intensity_image=np.array(slab))[0]
# get centroid
centroidy,centroidx=rpii.weighted_centroid
centroidy=latax[int(centroidy)]
centroidx=lonax[int(centroidx)]
# get axis coordinate array
skelii=axis_list[ii]
latsii=latax[skelii[:,0]]
lonsii=lonax[skelii[:,1]]
axisii=np.c_[latsii,lonsii]
# segment axis using rdp
axis_rdpii=np.array(rdp.rdpGC(axisii.tolist(),rdp_thres)) # lat,lon
# area
areaii=(maskii*areas).sum() # km^2
# compute length
lens=funcs.greatCircle(axis_rdpii[:-1,0], axis_rdpii[:-1,1],
axis_rdpii[1:,0], axis_rdpii[1:,1])/1e3
lenii=lens.sum() #km
# skip if too small and too short
if areaii<min_area or lenii<min_length_hard:
continue
# mean width
widthii=areaii/lenii # km
# mask contour
contii=funcs.getBinContour(maskii,lonax,latax)
# isoperimetric quotient
isoquoii=4*np.pi*rpii.area/rpii.perimeter**2
# length/width ratio
ratioii=lenii/widthii
# mean strength
slabii=MV.masked_where(maskii==0,slab)
strengthii=cdutil.averager(slabii,axis='xy',
weights=['generate','generate'])
# strength std
strengthstdii=float(stats.std(slabii,axis='xy'))
# anomaly strength
anoslabii=MV.masked_where(maskii==0,anoslab)
anostrengthii=cdutil.averager(anoslabii,axis='xy',
weights=['generate','generate'])
# max strength
max_strengthii=float(MV.max(slabii))
# compute angles and cross-section flux of total flux
cropmask,cropidx=cropMask(maskii)
cropskelii=skelii-np.array([cropidx[0].min(), cropidx[1].min()])
cropu=applyCropIdx(quslab,cropidx)
cropv=applyCropIdx(qvslab,cropidx)
anglesii,anglesmeanii,crossfluxii,seg_thetasii=crossSectionFlux(
cropmask, cropu, cropv, axis_rdpii)
# create plots
if isplot:
pass
#plotARCrosssectionFlux(cropmask, cropu, cropv, cropskelii, axis_rdpii,
#'%s AR-%d' %(timestr, ii+1), shift_lon, anglesii, anglesmeanii,
#crossfluxii, seg_thetasii, outputdir)
# insert crop back to the big map
anglesii=insertCropSlab(maskii.shape,anglesii,cropidx,
slab.getAxisList())
anglesii=MV.where(maskii==1,anglesii,0)
crossfluxii=insertCropSlab(maskii.shape,crossfluxii,cropidx,
slab.getAxisList())
crossfluxii=MV.where(maskii==1,crossfluxii,0)
# mean meridional flux
cropv=applyCropIdx(qvslab,cropidx)
cropv=MV.masked_where(cropmask==0,cropv)
qvmeanii=cdutil.averager(cropv,axis='xy',weights=['generate',\
'generate'])
# is candidate a strict AR
is_relaxedii=False
if isoquoii>max_isoq or ratioii<2:
is_relaxedii=True
if lenii<min_length:
is_relaxedii=True
if qvmeanii<=0:
is_relaxedii=True
labels=labels+maskii*(ii+1)
angles=angles+anglesii
crossfluxes=crossfluxes+crossfluxii
results[ii+1]={
'id': ii+1,
'time':timestr,
'contour_y': contii.vertices[:,1],
'contour_x': contii.vertices[:,0],
'centroid_y': centroidy,
'centroid_x': centroidx,
'axis_y':axisii[:,0],
'axis_x':axisii[:,1],
'axis_rdp_y':axis_rdpii[:,0],
'axis_rdp_x':axis_rdpii[:,1],
'area': areaii,
'length': lenii,
'width': widthii,
'iso_quotient':isoquoii,
'LW_ratio':ratioii,
'strength':strengthii,
'strength_ano':anostrengthii,
'strength_std':strengthstdii,
'max_strength':max_strengthii,
'mean_angle': float(anglesmeanii),
'is_relaxed':is_relaxedii,
'qv_mean':qvmeanii
}
labels.setAxisList(slab.getAxisList())
angles.setAxisList(slab.getAxisList())
crossfluxes.setAxisList(slab.getAxisList())
labels.id='labels'
labels.long_name='AR labels'
labels.standard_name=labels.long_name
labels.title=labels.long_name
labels.units=''
angles.id='angles'
angles.long_name='AR moisture flux orientation difference'
angles.standard_name=angles.long_name
angles.title=angles.long_name
angles.units='degree'
crossfluxes.id='ivt_cross'
crossfluxes.long_name='AR total cross sectional moisture flux'
crossfluxes.standard_name=crossfluxes.long_name
crossfluxes.title=crossfluxes.long_name
crossfluxes.units=getattr(slab, 'units', '')
keys=['id', 'time', 'contour_y', 'contour_x', 'centroid_y', 'centroid_x',
'axis_y', 'axis_x', 'axis_rdp_y', 'axis_rdp_x',
'area', 'length', 'width', 'iso_quotient', 'LW_ratio',
'strength', 'strength_ano', 'strength_std', 'max_strength',
'mean_angle', 'is_relaxed', 'qv_mean']
df=pd.DataFrame(results).T
if len(df)>0:
df=df[keys]
return labels,angles,crossfluxes,df
def uvDecomp(u0, v0, i1, i2):
'''Decompose background-transient components of u-, v- fluxes
Args:
u0 (cdms.TransientVariable): nd array of total u-flux.
v0 (cdms.TransientVariable): nd array of total v-flux.
i1 (cdms.TransientVariable): nd array of the reconstruction component
of IVT.
i2 (cdms.TransientVariable): nd array of the anomalous component
of IVT (i2 = IVT - i1).
Returns:
u1 (cdms.TransientVariable): nd array of the u-flux component
corresponding to <i1>, i.e. the background
component.
v1 (cdms.TransientVariable): nd array of the v-flux component
corresponding to <i1>, i.e. the background
component.
u2 (cdms.TransientVariable): nd array of the u-flux component
corresponding to <i2>, i.e. the transient
component.
v2 (cdms.TransientVariable): nd array of the v-flux component
corresponding to <i2>, i.e. the transient
component.
'''
i0=i1+i2
v1=v0*i1/i0
v2=v0*i2/i0
u1=u0*i1/i0
u2=u0*i2/i0
return u1,u2,v1,v2
def save2DF(result_dict):
'''Save AR records to a pandas DataFrame
Args:
result_dict (dict): key: time str in 'yyyy-mm-dd hh:00'
value: pandas dataframe. See getARData().
Returns:
result_df (pandas.DataFrame): AR record table containing records
from multiple time steps sorted by
time.
'''
for ii,kk in enumerate(result_dict.keys()):
vv=result_dict[kk]
if ii==0:
result_df=vv
else:
result_df=pd.concat([result_df,vv],axis=0,ignore_index=True)
result_df['time']=pd.to_datetime(result_df.time)
result_df=result_df.sort_values(by='time')
return result_df
def plotAR(ardf, ax, bmap):
'''Helper function to plot the regions and axes of ARs
Args:
ardf (pandas.DataFrame): table containing AR records.
ax (matplotlib axis): axis to plot onto.
bmap (Basemap obj): defining the geo map.
'''
for ii in range(len(ardf)):
vv=ardf.iloc[ii]
isrelaxkk=vv['is_relaxed']
# plot contour
px=vv['contour_x']
py=vv['contour_y']
px,py=bmap(px,py)
linewidth=1 if isrelaxkk else 1
linestyle=':' if isrelaxkk else '-'
ax.plot(px,py,color='k',linestyle=linestyle,linewidth=linewidth)
# plot axis
px=vv['axis_x']
py=vv['axis_y']
px,py=bmap(px,py)
ax.plot(px,py,'g:',linewidth=1.5)
# plot cross flux text
'''
lenkk=vv['length']
areakk=vv['area']
widthkk=vv['width']
cx=float(vv['centroid_x'])%360
cy=float(vv['centroid_y'])
cx,cy=bmap(cx,cy)
strkk=r'ID=%d, $R=%.0f$' %(ii+1,np.sqrt(areakk/3.14)) + '\n'+\
r'$L = %d km$' %lenkk +'\n'+\
r'$W = %d km$' %widthkk
ax.annotate(strkk,xy=(cx,cy),
horizontalalignment='center',
verticalalignment='center',
fontsize=8,
bbox=dict(facecolor='white',alpha=0.5))
'''