-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBASScast1.py
More file actions
1682 lines (1590 loc) · 62.1 KB
/
Copy pathBASScast1.py
File metadata and controls
1682 lines (1590 loc) · 62.1 KB
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 datetime as dtm
import pytz
import operator
import math
import random
import numpy
import scipy
import os
from PIL import Image as ipp
#
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mpd
import matplotlib.mpl as mpl
#
import shapely.geometry as sgp
import polytest as ptp
#
from mpl_toolkits.basemap import Basemap as Basemap
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import ANSStools as atp
#
days2secs = 60.*60.*24.
year2secs = 60.*60.*24.*365.
deg2km=111.12
deg2rad = 2.0*math.pi/360.
alpha_0 = 2.28
class BASScast(object):
# BASS/ETAS type forecast container.
sites=[]
quakes=[]
conts=[] # contour (local) objects (from sites x,y,z data).
latrange=[]
lonrange=[] # lat/lon range (rectangular) of catalog
gridsize=.1 # degrees
midlat=None # average latitude of the catalog, though i think we'll employ a more accurate calc. that uses both lat coords (dx = cos(l2)*x2 - cos(l1)*x1)
mc=2.0 # minimum magnitude (at least for BASS/ETAS calculations)
contres=2
contfact=5
fcdate=None
fcdatef=None # forecast date, float(forecast date)
deg2km=111.12 # degrees (latitute) to km conversion
zresolution=9 # decimal resolution of Z_ij array from which contours are calculated.
#
reffMag=5.0 # equivalent number of this magnitude/year earthquakes.
# so, the contours can be read as " n m>5/km^2. nominally
# we can integrate the contours as well if we like...
# but from this we should be able to talk about critical rates et al.
# n -> n0*10^(mc-rateMag.)
mapres='i' # basemap map resolution.
#
def __init__(self, incat=[], fcdate=dtm.datetime.now(pytz.timezone('UTC')), gridsize=.1, contres=2, mc=2.0):
return self.initialize(incat=incat, fcdate=fcdate, gridsize=gridsize, contres=contres, mc=mc)
#
#
def initialize(self, incat=[], fcdate=dtm.datetime.now(pytz.timezone('UTC')), gridsize=.1, contres=2, mc=2.0):
#
# incat: [ [dtm, lat, lon, mag, (depth?)], [], ... ] (consistent with ypp.eqcatalog() format).
# note: catalog dates/times must be in seconds (or convert all the scaling bits to days-- yuck).
self.mc=mc
self.contres=contres
self.gridsize=gridsize
self.fcdate=fcdate
self.fcdatef = mpd.date2num(fcdate)*days2secs
#
# read a catalog
if type(incat)==type('astring'):
# it's a filename. assume it's formatted for a catalog object...
# ... and we're not sure what to do with this just yet. for now, require a list
# [ [dtm, lat, lon, mag, (depth?)], [], ... ] (consistent with ypp.eqcatalog() format.
#
# load catalog into [quakes] and determine X, Y range from catalog.
print("we need a list-catalog. files are not supported at this time.")
#
return None
#
self.catalog=incat # dt, lat, lon, mag
#
# permit an empty catalog:
if len(self.catalog)==0:
# nothing to do, but we can still use the member functions.
return None
# initialize the lat/lon range arrays:
self.latrange = [incat[0][1], incat[0][1]]
self.lonrange = [incat[0][2], incat[0][2]]
#
# add earthquakes and other catalog related bits.
for rw in incat:
self.quakes+=[earthquake(mag=rw[3], loc=[rw[2], rw[1]], evtime=rw[0], mc=mc)]
#
# rupture length, to modify catalog dimensions (we set the grid to the lat/lon from the catalog + rupture-len)
rl=self.quakes[-1].getruptlen()
dlon=rl/(self.deg2km*math.cos(rw[1]*2.0*math.pi/360.0)) # noting the deg -> rad and the km -> deg. conversions.
dlat=rl/self.deg2km
# adjust the forecast extents according to catalog events and their rupture lens.
if self.latrange[0]>(rw[1]-dlat): self.latrange[0] = (rw[1]-dlat) # expand min-lat?
if self.latrange[1]<(rw[1]+dlat): self.latrange[1] = (rw[1]+dlat) # expand max-lat?
if self.lonrange[0]>(rw[2]-dlon): self.lonrange[0] = (rw[2]-dlon)
if self.lonrange[1]<(rw[2]+dlon): self.lonrange[1] = (rw[2]+dlon)
#
self.midlat = .5*(sum(self.latrange))
#
# for now, let's use gridsize x gridsize (in degrees) size elements (rather than project into a proper rectangular coord-system,
# though this is potentially not terribly difficult for this application since the grid is not strictly enforced (aka, we
# have a set of center-points for which we calc. z-values based on distance between [(x1,y1), (x2, y2)]. the potential difficulty arises
# from the fact that the array from which contours are calculated must be square... so maybe it is difficult.
#
# set up forecast sites:
x0 = self.lonrange[0]-self.lonrange[0]%gridsize
xmax = gridsize + self.lonrange[1]-self.lonrange[1]%gridsize
self.nLon = int(math.ceil((xmax-x0)/gridsize))
#
y0 = self.latrange[0]-self.latrange[0]%gridsize
ymax = gridsize + self.latrange[1]-self.latrange[1]%gridsize
self.nLat = int(math.ceil((ymax-y0)/gridsize))
#
#print self.lonrange, self.latrange
y=y0
#
self.sites=[]
for i in range(self.nLat*self.nLon):
self.sites+=[forecastsite(loc=[x0+gridsize*(i%self.nLon), y0+gridsize*(i/int(self.nLon))], dxdy=[gridsize, gridsize], evtime=self.fcdatef, mc=mc)]
#
#print "lengths: %d, %d, %d" % (self.nLon, self.nLat, len(self.sites))
#
# and now, this object should br ready to calculate forecasts...
#bc=self.calcBASScast()
#bc=self.plotContours()
bcast=self.calcBASScast()
#self.conts = self.getContourSet(X_i=self.X_i, Y_i=self.Y_i, Z_ij=self.Z2d.round(self.zresolution), contres=self.contfact*self.contres)
#self.conts = self.getContourSet(X_i=bcast[0], Y_i=bcast[1], Z_ij=bcast[2].round(4), contres=self.contfact*self.contres)
self.conts = self.getContourSet(X_i=bcast[0], Y_i=bcast[1], Z_ij=bcast[2], contres=self.contfact*self.contres)
return None
#
def resetzvals(self):
# set all z to 0 or None.
for i in range(len(self.sites)):
self.sites[i].z=None
#
def calcBASScast(self, grid=None, quakes=None, nx=None, ny=None, gridsize=None):
if grid==None: grid = self.sites
if quakes==None: quakes = self.quakes
if nx==None: nx = self.nLon
if ny==None: ny = self.nLat
if gridsize==None: gridsize=self.gridsize
#
X=[]
Y=[]
Z=[]
for site in grid:
site.setz(equakes=quakes)
# note, z values (eq counts) have been summed at this point
#
X+=[site.loc[0]]
Y+=[site.loc[1]]
if site.z!=0: Z+=[math.log10(site.z)]
if site.z==0: Z+=[None]
#
#
#Z=map(operator.itemgetter(2), cdata)
Z2d=scipy.array(Z)
#
#Z2d.shape=(len(Y), len(X))
Z2d.shape=(ny, nx) # aka, (ny rows, of nx elements) such that ny*nx=N
#X1, Y1=numpy.meshgrid(X, Y)
#
X_i=numpy.array(list(map(float, list(range(nx)))))
X_i*=gridsize
X_i+=grid[0].loc[0]
#
Y_i=numpy.array(list(map(float, list(range(ny)))))
Y_i*=gridsize
Y_i+=grid[0].loc[1]
#
self.X_i = X_i
self.Y_i = Y_i
self.Z2d=Z2d
#
return [X_i, Y_i, Z2d]
#self.fillHexString=fillHexString
def gridplot(self, ncontours=25):
plt.figure(0)
plt.clf()
minval=self.Z2d.min()
maxval=self.Z2d.max()
zrange=maxval-minval
#
hexColorMin='0x000000'
hexColorMax='0xFFFFFF'
colorRange=int('0xFFFFFF', 0)
#
#print "gridlens: %d, %d" % (len(self.Z2d), len(self.Z2d[0]))
#
#dz=(maxval-minval)/float(ncontours)
for y in range(len(self.Z2d)):
for x in range(len(self.Z2d[0])):
colorint=int(colorRange*(self.Z2d[y,x]-minval)/zrange)
#colorhex=self.fillHexString(hex(colorint), 6)
colorhex=fillHexString(hex(colorint), 6)
colorhexstr='#' + colorhex.split('x')[1]
plt.plot([x], [y], '.', color=colorhexstr, ms=10)
'''
def plotContours(self, grid=None, quakes=None, nx=None, ny=None, gridsize=None):
XYZ=self.calcBASScast(grid=grid, quakes=quakes, nx=nx, ny=ny, gridsize=gridsize)
return self.BASScastContours(XYZ[0], XYZ[1], XYZ[2])
def mapContours(self, grid=None, quakes=None, nx=None, ny=None, gridsize=None):
XYZ=self.calcBASScast(grid=grid, quakes=quakes, nx=nx, ny=ny, gridsize=gridsize)
return self.BASScastContourMap(XYZ[0], XYZ[1], XYZ[2])
def BASScastContours(self, X_i, Y_i, Z2d, fignum=0):
#
if fignum!=None: plt.figure(fignum)
#plt.clf()
cnts = self.getContourSet(X_i, Y_i, Z2d, self.contfact*self.contres)
#
self.conts = cnts
#
return None
'''
def BASScastContourMap(self, X_i=None, Y_i=None, Z2d=None, fignum=1, maxNquakes=250.0):
#
if X_i==None: X_i = self.X_i
if Y_i==None: Y_i = self.Y_i
if Z2d==None: Z2d = self.Z2d
#
plt.figure(fignum)
plt.clf()
plt.ion()
#
cntr = [self.lonrange[0] + .5*(self.lonrange[1]-self.lonrange[0]), self.latrange[0] + .5*(self.latrange[1]-self.latrange[0])]
cm = Basemap(llcrnrlon=self.lonrange[0], llcrnrlat=self.latrange[0], urcrnrlon=self.lonrange[1], urcrnrlat=self.latrange[1], resolution=self.mapres, projection='tmerc', lon_0=cntr[0], lat_0=cntr[1])
self.cm=cm
cm.drawcoastlines(color='gray', zorder=1)
cm.drawcountries(color='gray', zorder=1)
cm.drawstates(color='gray', zorder=1)
cm.drawrivers(color='gray', zorder=1)
cm.fillcontinents(color='beige', zorder=0)
cm.drawmeridians(list(range(int(self.lonrange[0]), int(self.lonrange[1]))), color='k', labels=[1,1,1,1])
cm.drawparallels(list(range(int(self.latrange[0]), int(self.latrange[1]))), color='k', labels=[1, 1, 1, 1])
#
# get X,Y for contours:
#
X,Y=cm(*numpy.meshgrid(X_i, Y_i))
#X,Y=cm(X_i, Y_i)
#
cnts = self.getContourSet(X, Y, Z2d, self.contfact*self.contres)
plt.colorbar()
plt.spectral()
#
#maxNquakes=250.0 # max num. equakes to plot (approximately)
Nquakes = float(len(self.quakes))
#
mthresh=math.log10(Nquakes/maxNquakes) + self.mc # we can take out the "if" bc for N<Nmax, mthresh<mc
# now, plot the earthquakes:
for q in self.quakes:
if q.mag<mthresh: continue
qx, qy, qm = q.loc[0], q.loc[1], q.mag
qxp, qyp = cm(qx, qy)
cm.plot([qxp], [qyp], 'ro', ms=qm, alpha=.7)
#
#self.conts = cnts
#
return None
def getContourSet(self, X_i=None, Y_i=None, Z_ij=None, contres=None):
#
if X_i==None: X_i=self.X_i
if Y_i==None: Y_i=self.Y_i
if Z_ij==None: Z_ij=self.Z2d
if contres==None: contres=self.contfact*self.contres
#
# X_i, Y_i are x,y coordinates (aka, like range(100), range(200) ), Z_ij is a 2D array that is actually contoured.
# contres is the resolution of the contoursl; numConts -> 5*contres
#
resolution = contres
LevelsNumber = self.contfact * resolution
warnings = ['No','Low','Guarded','Elevated','High','Severe']
#
# cnts=plt.contourf(gridsize*numpy.array(range(nelements)), gridsize*numpy.array(range(nelements)), Z2d,10)
# retrieve the collections() object from the contourf() function which returns a matplotlib.contour.ContourSet
#
#cs = plt.contourf(X_i, Y_i, Z_ij, LevelsNumber, cm=plt.spectral()).collections
cs = plt.contourf(X_i, Y_i, Z_ij, LevelsNumber, cm=plt.spectral(), alpha=.3)
return cs
def arrayFromSet(self, cs=None):
# get an array (list) from a contourset (matplotlib.contour.ContourSet object returned by contourf() call).
# format:
# [ [z0, [[x,y], [x,y],...], [z1, [paths1]],
#
if cs==None: cs=self.conts
#
levels=cs.levels # lower bound of contours
layers=cs.layers # upper bound of contours (at least for contours <0)
dz= layers[0] - levels[0]
collects=cs.collections
carray = []
for i in range(0, len(collects)):
bgra_array = 255*collects[i].get_facecolor()[0]
strclr = '7d%02x%02x%02x' % ( bgra_array[2] , bgra_array[1] , bgra_array[0] )
#
for trace in collects[i].get_paths():
#carray+=[[levels[i], layers[i], '%s' % strclr, []]]
# objContour(low=None, high=None, alpha=None, R=None, G=None, B=None, verts=None, RGB=None)
carray += [objContour(low=cs.levels[i], high=cs.layers[i], RGB=strclr, verts=[])]
for lng, lat in trace.vertices:
#carray[-1][-1]+=[[lng, lat]]
carray[-1].verts+=[[lng, lat]]
#
#
#
#
#
return carray
#
def contsToStr(self, cset=None):
if cset==None: cset=self.conts
cs=cset.collections
outstr='# contour coordinates\n'
#
for i in range(len(cs)):
outstr+='#contour\t%d\n' % i
itrace=0
for trace in cs[i].get_paths():
#tmpLL=[] # KML is not always rendering properly. maybe incomplete polygons?
outstr+='#trace\t%d\n' % itrace
for lng,lat in trace.vertices:
#kmlstr+='%s,%s,0\n' % (round(lng,7),round(lat,7))
outstr+='%f,%f,0\n' % (lng, lat)
#tmpLL+=[[lng, lat]]
#if tmpLL[0]!=tmpLL[-1]:
# print "completing a polygon, %d." % fixedpolys
# fixedpolys+=1
# kmlstr+='%f,%f,0\n' % (tmpLL[0][0], tmpLL[0][1])
#
return outstr
#self.plotcolor=plotcolor
def Z2str(self):
outstr=''
for rw in self.Z2d:
for elem in rw:
outstr+='%f\t' % elem
outstr=outstr[:-1] + '\n'
#
return outstr
#
def contsToPlotLists(self, cset=None, getlevels=False):
# this corrects a mpl/kml mismatch. mpl likes to plot inner polygons by drawing a line from the outside
# ring to the inner poly, draw the inenr poly, then back to the outer ring over the first line. mpl
# interprets the line as infinitely thin and basically ignores it. KML will not ignore that line, and so
# you get a big fat mess. This script separates the outer/inner groups into outer and inner poly rings.
#
# BUT, (2012 09 05) this needs to be revisited. inner-inner polys are not plotting correctly. aka,
# the z-profile like: /-\_/-\_/-\ (like an s0 within an s1) need to be considered. in such a case,
# we get: <outer><inner><inner></inner></inner></outer>, but there should be 1 outer/inner poly then a
# separate poly entirely. the second "inner" needs to be pulled out as a separate poly. (see similar note below)
#
# so, polys that are inside an odd number of polys are "inner" polys; polys inside an even number are "outside"
# any poly (as per knot theory), or otherwise constitute an "outer" poly. poly1 is an "inner" poly of poly2 if:
# 1: it is inside poly2
# 2: its "inner index n2 = n1 - 1
if cset==None: cset=self.conts
cs=cset.collections
outlist=[] # the length of this will be the number of levels: (or contours?)
# outlist -> [ [level0: [[cont0x], [cont0y]], [[cont1x], [cont1y]] ], [level1: ] ???
levels=[]
#contlevel=0
#
for i in range(len(cs)):
# level-level:
outlist+=[[]]
#contcount=0
# each level will have multiple polygons:
for trace in cs[i].get_paths():
# each "trace" will be a polygon (there might be multiple polygons per level), which might have "internal" polygons.
tmpLL=[] # KML is not always rendering properly. maybe incomplete polygons?
#outlist[-1]+=[[[],[]]]
newpoly=[ [[], []] ] # newpoly[poly-index][x=0 or y=1][x_i or y_i]. note, outer poly is first element.
# draw the polygons (first the outside one, then the inside ones -- presumably)
for lng,lat in trace.vertices:
#
# fix mangled contours:
#
newpoly[-1][0]+=[lng]
newpoly[-1][1]+=[lat]
#
# have we closed the polygon (in the middle?):
# what is happening is that the inner polys are being drawn screwy ways.
# the errors are not a total mess; basically, the link between then inner and outer poly is drawn
# from the last/first point rather than clostest two points.
# the first poly is probably the outer-most poly. subsequent closed sequences are inside polys.
# however, see comments above. the inner-inner->outer polys must be separated. do the following procedure
# first, then pass that list of polys for further parsing.
#
# SO, make a list of all closed objects in a single poly object, then insert them into the outer sequence
# (noting the inner poly has to close and then return to the starting point on the outer ring.
# is newpoly[-1] == newpoly[0] ?
if newpoly[-1][0][-1] == newpoly[-1][0][0] and newpoly[-1][1][-1] == newpoly[-1][1][0] and len(newpoly[-1][0])>1:
# the polygon has closed. pinch it off and start a new poly.
newpoly+=[ [[],[]] ]
tmpLL=[]
#contcount+=1
#
# now, clean up a bit:
# if it's a bogus poly -- probably a line back to a prev. poly (each poly is like: poly0, line (segment) to poly1,
# poly1, either: {line back to poly0, line to poly2, nothing?}
# i think the problem we're having is multi-inner polys aka, profile like 1 - 0 - 1. (ring=1, dip-ring=0, bump in middle=1)
# ___|-\_/-\_/-|___ . the inner-inner bit is causing a problem. to fix this, i think, we have to draw all the polys
# and explicitly determine which polys they are inside. (<outer><inner><inner></innter></inner></outer> ??)
# note: a poly-ring inside an even number of polys is an outer ring; a poly inside an odd number of rings is an inner ring.
if len(newpoly[-1][0])<2: newpoly.pop()
if newpoly[-1][0][-1] != newpoly[-1][0][0] and newpoly[-1][1][-1] != newpoly[-1][1][0]:
newpoly.pop()
#
# at this point, newpoly is like: [[likely-outermost],[maybe-inner], [maybe-inner], ... ]
# where we infer, or have in the past, that the first row represents the outer-most poly; subsequent polys are inners.
# this is not the cast. find the 2xinner (aka, outer) polys within as per comments above.
#
# break up newpoly into inner-outer groups
newpolylist=self.innerouterpolys(newpoly)
#if len(newpoly)>2:
# print "len(newpoly), len(newpolylist): %d, %d" % (len(newpoly), len(newpolylist))
#print newpoly
#print newpolylist
#newpolylist = [newpoly]
# return the full list and interpret i=0 as the outer ring; i>0 as the inner boundaries.
#
#outlist[-1]+=[newpoly] # add this trace(set) to the last level of outlist.
for ply in newpolylist:
#outlist[-1]+=[newpoly]
outlist[-1]+=[ply]
#
#contcount+=1
#contlevel+=1
if getlevels==False:
return outlist
if getlevels==True:
return [levels, outlist]
def innerouterpolys(self, polylist):
#print "do nothing yet."
# but, eventually: separate polygons that are "inside" two two polys (aka, and "outside" poly), and
# associate their inner polys with them.
# use shapely.geometry (sgp) module?? maybe not, as per compatiblity.
#
# note, pollys are coming like [ [[Xs], [Ys]], [] ],
# so the jth vertex of the ith poly is (x,y) = (polylist[i][0][j], polylist[i][1][j])
polylistplus=[] # indexed entries: [polyindex, [list of inners], [verts] ]
#outerpolys=[] # these will be lists. each entry is like: [[outer],[true-inner],[true-inner],..]
#
#for ply in polylist:
for i in range(len(polylist)):
polylistplus += [[i, [], polylist[i]]]
#
# shorthand:
# which poly each polygon it is inside, and how many polys it is inside (aka, len(that list)).
#x0,y0=poly[i][0][0], poly[i][1][0] # we only need to test one point since we're starting with contours (don't cross).
x0,y0=polylistplus[-1][2][0][0], polylistplus[-1][2][1][0] # we only need to test one point since we're starting with contours (don't cross).
#print "x0, y0: ", x0, y0
# in general, we'd need to test all points to be inside.
#
# for each polygon in this level:
# is the ith ("top") polygon inside the j'th poly?
for j in range(len(polylist)):
if j==i: continue # (and also use exclusive inclusion (yi>y_test, not >=) to exclude self-insidedness).
X,Y = polylist[j][0][:], polylist[j][1][:]
#if x0>=max(X) or x0<=min(X) or y0>max(Y) or y0<min(Y):
# print "outside max/min..."
# continue
#
if X[0]!=X[-1]:
X+=[X[0]]
Y+=[Y[0]] # complete the poly...
#
N=len(X)
ncrossings = 0
# how many poly boundaries do we cross if we draw a line out of the poly in one direction.
# equivalently (and in computer language), how many segments at y1 < y <y2 (or upside down)
# are to the right of the point (or to the left, or up/down -- pick one).
for k in range(1,N):
k1 = k-1
#k2 = (k+1)%N # note the k%N: the poly does not have to be closed
k2 = k # but it should be, or you can count a crossing twice and get a bogus answer.
x1,y1 = polylist[j][0][k1], polylist[j][1][k1]
x2,y2 = polylist[j][0][k2], polylist[j][1][k2]
#if y0>=min(y1, y2) and y0<=max(y1, y2) and x0<max(x1, x2):
#
if x0>=min(x1, x2) and x0<max(x1, x2): # note, one must be <= and the other < or, if we're on a grid -- and
fx = (y2-y1)/(x2-x1)*(x0-x1) # we're always on a grid, we'll count each crossing (left seg then right).
if fx>=(y0-y1): # that's why the test script worked (x1,y1 != x2, y2) and the production
ncrossings += 1 # failed...
#
#print i,j,j,ncrossings, ncrossings%2
if ncrossings%2==1:
# i'th poly is inside j'th poly...
polylistplus[-1][1] += [j]
#
#
# so now, we have a list of polygons and the polys they are inside.
# for outerPolys, len(innersList)%2==0. if polyA is inside polyB and nA-nB=1, polyA is an inner-poly to polyB
#
#for rw in polylistplus:
# print rw
outerpolys=[]
for ply1 in polylistplus:
#print "inner-len: ", len(ply1[1]), len(ply1[1])%2
if len(ply1[1])%2==0:
#print "***", len(ply1[1])
# it's an outer poly...
outerpolys+=[[ply1[2]]]
for ply2 in polylistplus:
# find its inners:
if ply2==ply1: continue
if len(ply2[1])%2==0: continue # skip outers...
#
#print len(ply2[1]), (len(ply1[1])+1)
if ply1[0] in ply2[1] and len(ply2[1])==(len(ply1[1])+1):
# the outer poly's index is in ply2's "inside-list", then ply2 is inside ply...
# AND, ply2 is one "deeper" (inside exactly one more poly) thatn ply
outerpolys[-1]+=[ply2[2]]
#
#return polylist
return outerpolys
#
def contsToPlotListsOuter(self, cset=None):
# simple polygons, not distinguishing inner/outer.
if cset==None: cset=self.conts
cs=cset.collections
outlist=[] # the length of this will be the number of levels: (or contours?)
# outlist -> [ [level0: [[cont0x], [cont0y]], [[cont1x], [cont1y]] ], [level1: ] ???
contlevel=0
#
for i in range(len(cs)):
# level-level:
outlist+=[[]]
contcount=0
for trace in cs[i].get_paths():
tmpLL=[] # KML is not always rendering properly. maybe incomplete polygons?
outlist[-1]+=[[[],[]]]
for lng,lat in trace.vertices:
#
# fix mangled contours:
#
outlist[-1][-1][0]+=[lng]
outlist[-1][-1][1]+=[lat]
tmpLL+=[[lng, lat]]
#
# have we closed the polygon (in the middle?):
# what is happening is that the inner polys are being drawn screwy ways.
# the errors are not a total mess; basically, the link between then inner and outer poly is drawn
# from the last/first point rather than clostest two points.
# the first poly (i think) is the outer poly. subsequent closed sequences are inner polys (excluded regions).
# SO, make a list of all closed objects in a single poly object, then insert them into the outer sequence
# (noting the inner poly has to close and then return to the starting point on the outer ring.
if outlist[-1][-1][0][-1] == outlist[-1][-1][0][0] and outlist[-1][-1][1][-1] == outlist[-1][-1][1][0] and len(outlist[-1][-1][0])>1:
# the polygon has closed. pinch it off and start a new poly.
outlist[-1]+=[[[],[]]]
tmpLL=[]
contcount+=1
if len(outlist[-1][-1][0])<2: outlist[-1].pop()
if outlist[-1][-1][0][-1] != outlist[-1][-1][0][0] and outlist[-1][-1][1][-1] != outlist[-1][-1][1][0]:
outlist[-1].pop()
# (outlist[contour level][polynum][x or y][x,y index] )
'''
#if tmpLL[0]!=tmpLL[-1]:
while tmpLL[0]!=tmpLL[-1]:
# print "completing a polygon, %d." % fixedpolys
#fixedpolys+=1
#outlist[-1][-1][0] += [tmpLL[0][0]]
#outlist[-1][-1][1] += [tmpLL[0][1]]
outlist[-1][-1][0].pop()
outlist[-1][-1][1].pop()
tmpLL.pop()
'''
#
contcount+=1
contlevel+=1
return outlist
def plotPolyList(self, polys=None, markerstr='.-', fignum=3, pllevels=None):
if polys==None: polys=self.contsToPlotLists()
if pllevels==None: pllevels = list(range(len(polys)))
if type(pllevels).__name__ in ('float', 'int'): pllevels=[pllevels]
plt.figure(fignum)
plt.clf()
plt.ion()
nlevels=len(polys)
#
ilevel=0
for level in polys:
#lvlclr=self.plotcolor(ilevel, nlevels)
if ilevel not in pllevels:
ilevel+=1
continue
lvlclr=plotcolor(ilevel, nlevels*2)
print(ilevel, lvlclr)
for xy in level:
for ring in xy:
#fixedpolys = checkPoly(inpoly=xy, fignum=None)
#for fxy in fixedpolys:
plt.plot(ring[0], ring[1], markerstr, color=lvlclr)
#plt.plot(xy[0], xy[1], markerstr, color=lvlclr)
ilevel+=1
return polys
def plotPolyListOuter(self, polys=None, markerstr='.-', fignum=3, pllevels=None):
# plot the simpler "just outers" version of the polygon list.
if polys==None: polys=self.contsToPlotListsOuter()
if pllevels==None: pllevels = list(range(len(polys)))
if type(pllevels).__name__ in ('float', 'int'): pllevels=[pllevels]
plt.figure(fignum)
plt.clf()
plt.ion()
nlevels=len(polys)
#
ilevel=0
for level in polys:
#lvlclr=self.plotcolor(ilevel, nlevels)
if ilevel not in pllevels:
ilevel+=1
continue
lvlclr=plotcolor(ilevel, nlevels*2)
print(ilevel, lvlclr)
for xy in level:
#fixedpolys = checkPoly(inpoly=xy, fignum=None)
#for fxy in fixedpolys:
# plt.plot(fxy[0], fxy[1], markerstr, color=lvlclr)
plt.plot(xy[0], xy[1], markerstr, color=lvlclr)
ilevel+=1
return polys
def getmarkerKMLstr(self, markers):
#kmlstr='<?xml version="1.0" encoding="UTF-8"?>\n<kml xmlns="http://www.opengis.net/kml/2.2">\n<Document>\n'
kmlstr=''
for ev in markers:
thisdt=str(mpd.num2date(ev[0]))
datestr=thisdt.split('.')[0]
kmlstr+='<Placemark><name>%s, %.2f</name><Point><coordinates>%f,%f,0</coordinates></Point></Placemark>' % (datestr, ev[3], ev[2], ev[1])
return kmlstr
def writeKMLfile(self, cset=None, fout='conts.kml', colorbarname='scale.png', equakes=None):
#kmlstr=self.KMLstrFromConts(cset)
kmlstr=self.KMLstrFromConts1(cset, openfile=True, closefile=False)
if equakes !=None:
# we've been given some earthquakes to plot as well.
kmlstr+='\n'
kmlstr+=self.getmarkerKMLstr(equakes)
kmlstr+='</Document>\n'
kmlstr+='</kml>'
#
f=open(fout, 'w')
f.write(kmlstr)
f.close()
return None
def KMLstrFromConts(self, cset=None, colorbarname='scale.png', openfile=True, closefile=True, warnings=None):
# get a KML string from a contourset (matplotlib.contour.ContourSet object returned by contourf() call).
# (will it be necessary to write directly to file? is there a string length limit problem?)
#
if cset==None:
cset=self.conts
#cset=plt.contourf(self.X_i, self.Y_i, self.Z2d, self.contres*self.contfact, cm=plt.spectral())
cs=cset.collections
polys = self.contsToPlotLists(cset=cset) # this function fixes multi-closed polys. use for actual kml contours.
# still has same polys[cont. level][contour index][x=0,y=1][x,y index] format
# the polys array will differ from cset.collections in the number of polys
# per level; the number of levels should be the same.
#
#resolution = 5
#LevelsNumber = 5 * resolution
if warnings==None: warnings = ['No','Low','Guarded','Elevated','High','Severe']
#contoursStart=int(.2*len(cs))
#resolution = int(len(cs)/len(warnings))
resolution = int(len(polys)/len(warnings))
#startindex=resolution
startindex=0
kmlstr=''
#
if openfile==True:
kmlstr='<?xml version="1.0" encoding="UTF-8"?>\n<kml xmlns="http://www.opengis.net/kml/2.2">\n<Document>\n'
#
# styles come from the contours collection (cs):
for i in range(0,len(cs)):
bgra_array = 255*cs[i].get_facecolor()[0]
kmlstr+='<Style id="l%d">\n' % i
kmlstr+='<LineStyle><color>00000000</color></LineStyle>\n'
kmlstr+='<PolyStyle><color>7d%02x%02x%02x</color></PolyStyle>\n' % ( bgra_array[2] , bgra_array[1] , bgra_array[0] )
kmlstr+='</Style>\n'
#
#
kmlstr+='<ScreenOverlay id="scale">\n'
kmlstr+='<name>Color Scale</name>\n'
#kmlstr+='<Icon><href>scale.png</href></Icon>\n'
kmlstr+='<Icon><href>%s</href></Icon>\n' % colorbarname
kmlstr+='<overlayXY x="0" y="1" xunits="fraction" yunits="fraction"/>\n'
kmlstr+='<screenXY x="0" y="1" xunits="fraction" yunits="fraction"/>\n'
kmlstr+='<size x="0" y="0" xunits="pixels" yunits="pixels"/>\n'
kmlstr+='</ScreenOverlay>\n'
#
#fixedpolys=0
# now, stake out the contours from the polys array.
# note: len(cs) = len(polys) (same number of levels)
# len(cs[i]) != len(polys[i]) (in fact, len(polys[i]>=len(cs[i]) ), which is to say
# polys may have more distinct polygons per contour level. of course, the individual polys
# will have differend length as well.
#for i in xrange(startindex, len(cs)):
for i in range(startindex, len(polys)):
# each i is a contour level.
kmlstr+='<Placemark>\n'
#print i, resolution, len(warnings), len(polys)
warningindex=int(float(i)/float(resolution))
if warningindex>(len(warnings)-1): warningindex=len(warnings)-1 # in the event that we have off-integer numbers.
kmlstr+='<name>%s Risk</name>\n' % warnings[warningindex]
kmlstr+='<styleUrl>#l%d</styleUrl>\n' % i
kmlstr+='<MultiGeometry>\n'
#for trace in cs[i].get_paths():
for ii in range(len(polys[i])):
# each ii is a polygon (set).
kmlstr+='<Polygon>\n'
kmlstr+='<extrude>0</extrude>\n'
kmlstr+='<altitudeMode>clampToGround</altitudeMode>\n'
kmlstr+='<outerBoundaryIs>\n'
kmlstr+='<LinearRing>\n'
kmlstr+='<coordinates>\n'
#tmpLL=[] # KML is not always rendering properly. maybe incomplete polygons?
#for lng,lat in trace.vertices:
for ill in range(len(polys[i][ii][0][0])):
# first set is the outerBoundary
# noting that each polygon is stored as [[x], [y]], so len(polys[i][ii])=2 always.
# len(polys[i][ii][0])=len(polys[i][ii][1]) is the length or size (num. verts.) of the polygon.
lng=polys[i][ii][0][0][ill]
lat=polys[i][ii][0][1][ill]
#
kmlstr+='%f,%f,0\n' % (lng, lat)
#tmpLL+=[[lng, lat]]
#if tmpLL[0]!=tmpLL[-1]:
# print "completing a polygon, %d." % fixedpolys
# fixedpolys+=1
# kmlstr+='%f,%f,0\n' % (tmpLL[0][0], tmpLL[0][1])
kmlstr+='</coordinates>\n</LinearRing>\n</outerBoundaryIs>\n'
#
# inner polys?
for iInner in range(1,len(polys[i][ii])):
thispoly=polys[i][ii][iInner]
# if any, these will be inner polys, each like [[x], [y]]
kmlstr+='<innerBoundaryIs>\n<LinearRing>\n<coordinates>\n'
# coords like 'lon,lat,alt\n'
# -77.05668055019126,38.87154239798456,100
for ill in range(len(thispoly[0])):
kmlstr+='%f,%f,0\n' % (thispoly[0][ill], thispoly[1][ill])
kmlstr+='</coordinates>\n</LinearRing>\n</innerBoundaryIs>\n'
#
kmlstr+='</Polygon>\n'
#
kmlstr+='</MultiGeometry>\n'
kmlstr+='</Placemark>\n'
#
if closefile==True:
kmlstr+='</Document>\n'
kmlstr+='</kml>'
#
return kmlstr
def KMLstrFromConts1(self, cset=None, colorbarname='scale.png', openfile=True, closefile=True, warnings=None):
# get a KML string from a contourset (matplotlib.contour.ContourSet object returned by contourf() call).
# (will it be necessary to write directly to file? is there a string length limit problem?)
#
if cset==None:
cset=self.conts
#cset=plt.contourf(self.X_i, self.Y_i, self.Z2d, self.contres*self.contfact, cm=plt.spectral())
cs=cset.collections
polys = self.contsToPlotLists(cset=cset) # this function fixes multi-closed polys. use for actual kml contours.
# still has same polys[cont. level][contour index][x=0,y=1][x,y index] format
# the polys array will differ from cset.collections in the number of polys
# per level; the number of levels should be the same.
#
#resolution = 5
#LevelsNumber = 5 * resolution
if warnings==None: warnings = ['No','Low','Guarded','Elevated','High','Severe']
#contoursStart=int(.2*len(cs))
#resolution = int(len(cs)/len(warnings))
resolution = int(len(polys)/len(warnings))
#startindex=resolution
startindex=0
kmlstr=''
#
if openfile==True:
kmlstr='<?xml version="1.0" encoding="UTF-8"?>\n<kml xmlns="http://www.opengis.net/kml/2.2">\n<Document>\n'
#
# styles come from the contours collection (cs):
for i in range(0,len(cs)):
bgra_array = 255*cs[i].get_facecolor()[0]
kmlstr+='<Style id="l%d">\n' % i
kmlstr+='<LineStyle><color>00000000</color></LineStyle>\n'
kmlstr+='<PolyStyle><color>7d%02x%02x%02x</color></PolyStyle>\n' % ( bgra_array[2] , bgra_array[1] , bgra_array[0] )
kmlstr+='</Style>\n'
#
#
kmlstr+='<ScreenOverlay id="scale">\n'
kmlstr+='<name>Color Scale</name>\n'
#kmlstr+='<Icon><href>scale.png</href></Icon>\n'
kmlstr+='<Icon><href>%s</href></Icon>\n' % colorbarname
kmlstr+='<overlayXY x="0" y="1" xunits="fraction" yunits="fraction"/>\n'
kmlstr+='<screenXY x="0" y="1" xunits="fraction" yunits="fraction"/>\n'
kmlstr+='<size x="0" y="0" xunits="pixels" yunits="pixels"/>\n'
kmlstr+='</ScreenOverlay>\n'
#
#fixedpolys=0
# now, stake out the contours from the polys array.
# note: len(cs) = len(polys) (same number of levels)
# len(cs[i]) != len(polys[i]) (in fact, len(polys[i]>=len(cs[i]) ), which is to say
# polys may have more distinct polygons per contour level. of course, the individual polys
# will have differend length as well.
#for i in xrange(startindex, len(cs)):
for i in range(startindex, len(polys)):
# each i is a contour level.
kmlstr+='<Placemark>\n'
#print i, resolution, len(warnings), len(polys)
warningindex=int(float(i)/float(resolution))
if warningindex>(len(warnings)-1): warningindex=len(warnings)-1 # in the event that we have off-integer numbers.
kmlstr+='<name>%s Risk</name>\n' % warnings[warningindex]
kmlstr+='<styleUrl>#l%d</styleUrl>\n' % i
kmlstr+='<MultiGeometry>\n'
#for trace in cs[i].get_paths():
for ii in range(len(polys[i])):
# each ii is a polygon (set).
kmlstr+='<Polygon>\n'
kmlstr+='<extrude>0</extrude>\n'
kmlstr+='<altitudeMode>clampToGround</altitudeMode>\n'
kmlstr+='<outerBoundaryIs>\n'
kmlstr+='<LinearRing>\n'
kmlstr+='<coordinates>\n'
#tmpLL=[] # KML is not always rendering properly. maybe incomplete polygons?
#for lng,lat in trace.vertices:
for ill in range(len(polys[i][ii][0][0])): #[level][trace][outer(top)-poly][Xcoords] (last one could be 1)
# first set is the outerBoundary
# noting that each polygon is stored as [[x], [y]], so len(polys[i][ii])=2 always.
# len(polys[i][ii][0])=len(polys[i][ii][1]) is the length or size (num. verts.) of the polygon.
lng=polys[i][ii][0][0][ill]
lat=polys[i][ii][0][1][ill]
#
kmlstr+='%f,%f,0\n' % (lng, lat)
#tmpLL+=[[lng, lat]]
#if tmpLL[0]!=tmpLL[-1]:
# print "completing a polygon, %d." % fixedpolys
# fixedpolys+=1
# kmlstr+='%f,%f,0\n' % (tmpLL[0][0], tmpLL[0][1])
kmlstr+='</coordinates>\n</LinearRing>\n</outerBoundaryIs>\n'
#
# inner polys?
for iInner in range(1,len(polys[i][ii])):
thispoly=polys[i][ii][iInner]
# if any, these will be inner polys, each like [[x], [y]]
kmlstr+='<innerBoundaryIs>\n<LinearRing>\n<coordinates>\n'
# coords like 'lon,lat,alt\n'
# -77.05668055019126,38.87154239798456,100
for ill in range(len(thispoly[0])):
kmlstr+='%f,%f,0\n' % (thispoly[0][ill], thispoly[1][ill])
kmlstr+='</coordinates>\n</LinearRing>\n</innerBoundaryIs>\n'
#
kmlstr+='</Polygon>\n'
#
kmlstr+='</MultiGeometry>\n'
kmlstr+='</Placemark>\n'
#
if closefile==True:
kmlstr+='</Document>\n'
kmlstr+='</kml>'
#
return kmlstr
#
def KMLstrFromConts_raw(self, cset=None, colorbarname='scale.png'):
# get a KML string from a contourset (matplotlib.contour.ContourSet object returned by contourf() call).
# (will it be necessary to write directly to file? is there a string length limit problem?)
#
if cset==None:
cset=self.conts
#cset=plt.contourf(self.X_i, self.Y_i, self.Z2d, self.contres*self.contfact, cm=plt.spectral())
cs=cset.collections
#
#resolution = 5
#LevelsNumber = 5 * resolution
warnings = ['No','Low','Guarded','Elevated','High','Severe']
#contoursStart=int(.2*len(cs))
resolution = int(len(cs)/self.contfact)
#startindex=resolution
startindex=0
#
#
kmlstr='<?xml version="1.0" encoding="UTF-8"?>\n<kml xmlns="http://www.opengis.net/kml/2.2">\n<Document>\n'
#
for i in range(0,len(cs)):
bgra_array = 255*cs[i].get_facecolor()[0]
kmlstr+='<Style id="l%d">\n' % i
kmlstr+='<LineStyle><color>00000000</color></LineStyle>\n'
kmlstr+='<PolyStyle><color>7d%02x%02x%02x</color></PolyStyle>\n' % ( bgra_array[2] , bgra_array[1] , bgra_array[0] )
kmlstr+='</Style>\n'
#
#
kmlstr+='<ScreenOverlay id="scale">\n'
kmlstr+='<name>Color Scale</name>\n'
#kmlstr+='<Icon><href>scale.png</href></Icon>\n'
kmlstr+='<Icon><href>%s</href></Icon>\n' % colorbarname
kmlstr+='<overlayXY x="0" y="1" xunits="fraction" yunits="fraction"/>\n'
kmlstr+='<screenXY x="0" y="1" xunits="fraction" yunits="fraction"/>\n'
kmlstr+='<size x="0" y="0" xunits="pixels" yunits="pixels"/>\n'
kmlstr+='</ScreenOverlay>\n'
#
fixedpolys=0
for i in range(startindex, len(cs)):
kmlstr+='<Placemark>\n'
kmlstr+='<name>%s Risk</name>\n' % warnings[i/resolution]
kmlstr+='<styleUrl>#l%d</styleUrl>\n' % i
kmlstr+='<MultiGeometry>\n'
for trace in cs[i].get_paths():
kmlstr+='<Polygon>\n'
kmlstr+='<extrude>0</extrude>\n'
kmlstr+='<altitudeMode>clampToGround</altitudeMode>\n'
kmlstr+='<outerBoundaryIs>\n'
kmlstr+='<LinearRing>\n'
kmlstr+='<coordinates>\n'
tmpLL=[] # KML is not always rendering properly. maybe incomplete polygons?
for lng,lat in trace.vertices:
#kmlstr+='%s,%s,0\n' % (round(lng,7),round(lat,7))
# fixing contours mangled by pyplot:
# an older attempted fixing routine that didn't quite work out.
# keep this version as the "raw" form; see other KML function that
# uses a repaired set of polygons.
#
thislng=round(lng, self.zresolution)
thislat=round(lat, self.zresolution)
kmlstr+='%f,%f,0\n' % (thislng, thislat)
tmpLL+=[[thislng, thislat]]
#if tmpLL[0]!=tmpLL[-1]:
# print "completing a polygon, %d." % fixedpolys
# fixedpolys+=1
# kmlstr+='%f,%f,0\n' % (tmpLL[0][0], tmpLL[0][1])
kmlstr+='</coordinates>\n'
kmlstr+='</LinearRing>\n'
kmlstr+='</outerBoundaryIs>\n'
kmlstr+='</Polygon>\n'
#
kmlstr+='</MultiGeometry>\n'
kmlstr+='</Placemark>\n'
#
kmlstr+='</Document>\n'
kmlstr+='</kml>'
#
return kmlstr
def makeColorbar(self, cset=None, colorbarname=None, reffMag=5.0):
#
# reffMag:
if reffMag==None: reffMag=self.reffMag
#
if colorbarname==None: colorbarname='scale.png'
if cset==None: cset=self.conts
cs=cset.collections
#resolution = 5
#LevelsNumber = 5 * resolution
warnings = ['No','Low','Guarded','Elevated','High','Severe']
#contoursStart=int(.2*len(cs))