-
Notifications
You must be signed in to change notification settings - Fork 0
/
hazmap.py
1608 lines (1521 loc) · 58.7 KB
/
hazmap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math
import scipy
#
import pylab as plt
import matplotlib
import matplotlib.mpl as mpl
import numpy
from PIL import Image as ipp
#import numpy.fft as nft
import scipy.optimize as spo
#from matplotlib import pyplot as plt
#from matplotlib import rc
from matplotlib.patches import Ellipse
#
import string
import sys
#from matplotlib import *
#from pylab import *
import os
import random
import time
#
# gamma function lives here:
#import scipy.special
from scipy.special import gamma
#from scipy.optimize import leastsq
from matplotlib import axis as aa
#
from threading import Thread
#
import datetime as dtm
import pytz
import calendar
import operator
import urllib
import eqcatalog as yp
import rbIntervals as rbi
#
# python3 vs python2 issues:
# a bit of version 3-2 compatibility:
if sys.version_info.major>=3:
xrange=range
class hazCrack(object):
# record-breaking hazard map on crack.
hazmaps=[]
plotstyle=0 #{0: little squares, 1: little squares mean-val, 2: mean-val contours, 3: overlapping big squares, 4: mean-val big squares}
gridsize=1.0 # sometimes called L; it's the length of the grid size.
ndithers=3 # so the total number of elements will be ndithers^2 (aka, 3-> dither into thirds on each side).
dL=None # will be L/ndithers
hmdate=None
#
#
def __init__(self, catalog=None, catnum=0, mc=2.5, gridsize=.5, ndithers=3, winlen=128, avlen=1, bigmag=5.0, fignum=0, logZ=1.0, mapres='i'):
self.dL=gridsize/float(ndithers)
self.hazmaps=[]
self.mc=mc
self.gridsize=gridsize
self.ndithers=ndithers
self.winlen=winlen
self.avlen=avlen
self.bigmag=bigmag
self.fignum=fignum
self.mapres=mapres
if logZ==None: logZ=math.log10(winlen)
self.logZ=logZ # for log-normalizing rb-ratios
#self.logZ=1.0
#self.forecastDate=dtm.datetime.now(pytz.timezone('UTC')) # or we might change this.
self.forecastDate=dtm.datetime(2011, 3,5, 0, 0, 0, 0, pytz.timezone('UTC'))
self.hmdate=dtm.datetime.now(pytz.timezone('UTC'))
self.rb=rbi.intervalRecordBreaker(None)
#
for i in xrange(ndithers*ndithers):
xphase=(i%ndithers)*self.dL # lon phase
yphase=(int(i/ndithers))*self.dL # lat pahse
# in the end, it is going to be easier to rewrite the hazmap object. make a lean class excluding the graphical parts - just
# an array of subcats. we'll load a single own rb object to this class or rewrite the RB counting script.
# catalog=None, catnum=0, mc=2.5, gridsize=.5, phi=[0,0], winlen=128, avlen=1, bigmag=5.0
thishm=rbHazMapLean(catalog=catalog, catnum=catnum, mc=mc, gridsize=gridsize, phi=[yphase, xphase], winlen=winlen, avlen=avlen, bigmag=bigmag, logZ=logZ) # but we'll need to suppress fig-plotting and i don't know if the phases are switched.
a=thishm.hazMapTo(self.forecastDate)
self.hazmaps+=[thishm]
def getcat(self, catindex=0):
if len(self.hazmaps)<1:
return None
if catindex>(len(self.hazmaps)-1):
catindex=len(self.hazmaps)-1
#
return self.hazmaps[catindex].catalog
def getNlon(self):
#nlon=0
#for hm in self.hazmaps:
# nlon+=hm.Nlon
return self.hazmaps[0].Nlon*self.ndithers
#return nlon
def getNlat(self):
#nlat=0
#for hm in self.hazmaps:
# nlat+=hm.Nlat
return self.hazmaps[0].Nlat*self.ndithers
#return nlat
def boxesTo(self, hmdate=dtm.datetime.now(pytz.timezone('UTC')), fignum=0):
self.hazMapTo(hmdate)
return self.simpleBoxes(fignum)
def hazMapTo(self, hmdate=dtm.datetime.now(pytz.timezone('UTC'))):
self.hmdate=hmdate
for i in xrange(len(self.hazmaps)):
self.hazmaps[i].hazMapTo(hmdate)
def contourData(self, dobinary=0):
# for our first trick, just combine all the hazard maps into one big map and contour it.
# later, we'll do some averaging schemes.
#
# first, get one big array of X,Y,Z:
#cX=[]
#cY=[]
#cZ=[]
cdata=[]
#for i in xrange(len(self.hazmaps[0].rbRatios)):
# for hm in self.hazmaps:
for hm in self.hazmaps:
for i in xrange(len(hm.rbRatios)):
#cX+=[hm.getLon(i) + (self.gridsize-self.dL)/2.0]
#cY+=[hm.getLat(i) + (self.gridsize-self.dL)/2.0]
#cZ+=[hm.rbRatios[i]]
#
thisval=hm.rbRatios[i]
#if thisval==None: thisval=0
if thisval!=None:
thisval=-thisval # because we've defined r<1 to be high risk. the easiest way to color these "hot" colors is to reverse them.
if dobinary:
# return binary (or arguably tri-mary, {-1, None, 1} (noting at this point that the parity has been reversed)
if thisval>=0: thisval=1
if thisval<0: thisval=-1
# so these should be bin-centered:
cdata+=[[hm.getLon(i) + (self.gridsize-self.dL)/2.0, hm.getLat(i) + (self.gridsize-self.dL)/2.0, thisval]]
#
# so now we have a [[x, y, rb]] array from all the hazard maps.
# sort them by x,y (row vectors if you will). [x0, y0], [x1, y0], [x2, y0]..., [x0, y1], [x1, y1], [x2, y1], ...]
# sort first by the secondary key (x), then on primary (y):
cdata.sort(key=operator.itemgetter(0))
cdata.sort(key=operator.itemgetter(1))
#
# give all the clusters a 0-value border (for prettiness).
#width=self.hazmaps[0].Nlon*self.ndithers
width=self.getNlon()
maxi=len(cdata) # actually, max i + 1, so tread carefully.
#
# pad the clusters to make better contours:
# spin through cdata. if for every element, if an adjacent cell is None and not over an edge, make it zero. note this is made easy because
# the lat/lon are provided...
for i in xrange(maxi):
if cdata[i][2]==0. or cdata[i][2]==None: continue #(0, None) because, if we start placing 0 values, we fill the whole space with 0's.
#thislat=cdata[1]
#thislon=cdata[0]
# on the left border?
if i%width>0:
if cdata[i-1][2]==None: cdata[i-1][2]=0.
# right:
if i%width<(width-1):
if cdata[i+1][2]==None: cdata[i+1][2]=0.
# top:
#if i/width!=0:
if (i-width)>=0:
if cdata[i-width][2]==None: cdata[i-width][2]=0.
if (i+width)<maxi:
if cdata[i+width][2]==None: cdata[i+width][2]=0.
#
#
# though we might eventually return a later form of this data (as per see contourPlot()...
return cdata
def contourArrays(self):
#
cdata=self.contourData()
# now, borrowing from ffgridplot.py contouring methods, we "shape" the array:
# can we just contour() from here? no.
#
Xs=map(operator.itemgetter(0), cdata)
Ys=map(operator.itemgetter(1), cdata)
Xvals=list(set(Xs))
Yvals=list(set(Ys))
Xvals.sort()
Yvals.sort()
#
#Xax=list(set(map(operator.itemgetter(0), cdata))).sort()
#Yax=list(set(map(operator.itemgetter(1), cdata))).sort()
#
X,Y=numpy.meshgrid(Xvals, Yvals)
#z=map(operator.itemgetter(2), cdata)
Z=map(operator.itemgetter(2), cdata)
Z2d=scipy.array(Z)
Z2d.shape=(len(Yvals), len(Xvals))
#
# for now, this is a fully class-contained function, so we can set some class-scope
# variables.
self.X_i = X
self.Y_i = Y
self.Z2d = Z2d
#
return [X,Y,Z2d]
def contourPlot(self, fignum=1):
cary=self.contourArrays()
X = cary[0]
Y = cary[1]
Z2d = cary[2]
plt.ion()
plt.figure(fignum+1)
plt.clf()
plt.figure(fignum)
plt.clf()
#plt.contourf(map(operator.itemgetter(0), cdata), map(operator.itemgetter(1), cdata), map(operator.itemgetter(2), cdata))
#return X, Y, Z2d
self.conts = plt.contourf(X,Y,Z2d, alpha=.3)
plt.colorbar()
plt.spectral()
#return [cX, cY, cZ]
#return cdata
return None
def plotEvent(self, coords=None, symbolstr='r*', msize=18, fignum=0, zorder=5):
cm=self.hazmaps[0]
if coords==None: coords=cm.getMainEvent()
x,y=cm.catalog.catmap(coords[0], coords[1])
plt.figure(fignum)
plt.plot([x], [y], symbolstr, ms=msize, zorder=zorder)
return None
def plotEvents(self, events=None, symbolstr=',', msize=1, fignum=0, alpha=1.0, zorder=5):
cm=self.hazmaps[0]
print("doing events. %d, %d" % (len(events), fignum))
#
#fignum=1
# assume events come in 'catalog' form [dtm, lat, lon, mag, ...]
lats=map(operator.itemgetter(1), events)
lons=map(operator.itemgetter(2), events)
X,Y=cm.catalog.catmap(lons, lats)
plt.figure(fignum)
plt.plot(X,Y, symbolstr, ms=msize, alpha=alpha, zorder=zorder)
return None
def contourMap(self, fignum=1, nconts=12, mapres=None, maptransform=True, alpha=.85):
# maptransform: transform to matplotlib.basemap coords. for KML export, set this to false (coords in LL).
# (though we might not use this feature; we might do it another way...)
if mapres==None: mapres=self.mapres
cdata=self.contourData()
if nconts==None: nconts=12 # but we can also pass a list of contour values (to standardize output)[c1, c2, c3...]
#
# set up the map. we'll need it to process the contour data.
#
catdate=self.hazmaps[0].catalog.cat[-1][0] # most recent date in catalog.
hmdatestr='%d-%d-%d, %d:%d:%d (UTC)' % (self.hmdate.year, self.hmdate.month, self.hmdate.day, self.hmdate.hour, self.hmdate.minute, self.hmdate.second)
#
plt.ion()
fig1=plt.figure(fignum+1)
plt.clf()
#plt.title("Record-breaking contour hazard map\ndtm=%s, $d\\lambda=%.4f$, nDith=%d, mc=%.2f, rblen=%d, avlen=%d\n\n" % (str(self.hmdate), self.gridsize, self.ndithers, self.mc, self.winlen, self.avlen))
plt.title("Record-breaking contour hazard map\ndtm=%s, $d\\lambda=%.4f$, nDith=%d, mc=%.2f, rblen=%d, avlen=%d\n\n" % (hmdatestr, self.gridsize, self.ndithers, self.mc, self.winlen, self.avlen))
ax1 = fig1.add_subplot(111)
#
fig=plt.figure(fignum)
fig.clf()
ax = fig.add_subplot(111)
#plt.title('(diagnostic) Record-breaking intervals Hazard Map')
plt.title("Record-breaking contour haz-map\ndtm=%s, $d\\lambda=%.4f$, nDith=%d, mc=%.2f, rblen=%d\n\n" % (hmdatestr, self.gridsize, self.ndithers, self.mc, self.winlen))
#
llrange=self.hazmaps[0].catalog.getLatLonRange(self.hazmaps[0].thiscat)
self.llrange = llrange
self.deltaLat=abs(float(self.llrange[1][0])-self.llrange[0][0])
self.deltaLon=abs(float(self.llrange[1][1])-self.llrange[0][1])
Nlat=1+int(self.deltaLat/self.gridsize)
Nlon=1+int(self.deltaLon/self.gridsize) #number of cells in row/col
#
lat0=self.llrange[0][0]
lon0=self.llrange[0][1]
#
#thismev=self.hazmaps[0].catalog.getMainEvent(self.hazmaps[0].catalog.getcat(0))
#epicen=[thismev[2], thismev[1]]
try:
epicen=self.epicen
except:
c=self.hazmaps[0].catalog.getcat(0)
i=0
m0=c[i][3]
i0=0
while i<len(c):
if c[i][3]>m0 and c[i][0]>self.hmdate:
m0=c[i][3]
i0=i
i+=1
self.epicen=[c[i0][2], c[i0][1]]
plt.figure(fignum)
plottingCat=yp.eqcatalog(self.hazmaps[0].catalog.getcat(0))
# now, make two sub-cats, one before, one after the haz-date:
# addTimeRangeCat(self, subcatname='dtSubcat', fullcat=None, dtFrom=None, dtTo=None)
plottingCat.addTimeRangeCat(subcatname='before', fullcat=None, dtFrom=self.hmdate-dtm.timedelta(days=1000), dtTo=self.hmdate)
plottingCat.addTimeRangeCat(subcatname='after', fullcat=None, dtFrom=self.hmdate, dtTo=self.hmdate+dtm.timedelta(days=1000))
plotcat=[[plottingCat.subcats[0][0], plottingCat.subcats[0][1]], [plottingCat.subcats[1][0], plottingCat.subcats[1][1][-1000:]]]
#cm=self.hazmaps[0].catalog.plotCatMap(self.hazmaps[0].catalog.getcat(0), True, False, None, epicen, 'best', True, 'g,', ax, fignum)
self.hazmaps[0].catalog.mapres=mapres
cm=self.hazmaps[0].catalog.plotCatMap(self.hazmaps[0].catalog.getcat(0), True, False, None, None, 'best', True, 'g,', ax, fignum, plotevents=1)
#cm1=plottingCat.plotCatsMap(catalogses=[plottingCat.subcats[0]], legendLoc='best', doCLF=True, fignum=fignum+1, bigmag=6.0)
#cm1=self.hazmaps[0].catalog.plotCatsMap(catalogses=plottingCat.subcats, legendLoc='best', doCLF=False, fignum=fignum+1, bigmag=self.bigmag)
#cm1=self.hazmaps[0].catalog.plotCatsMap(catalogses=[plottingCat.subcats[0], plottingCat.subcats[1]], legendLoc='best', doCLF=False, fignum=fignum+1, bigmag=self.bigmag)
#cm1=self.hazmaps[0].catalog.plotCatsMap(catalogses=plotcat, legendLoc='best', doCLF=False, fignum=fignum+1, bigmag=self.bigmag)
#### (this (above) produces a skewed catalog-map. instead, plot a map with no events and add the events separately.
cm1=self.hazmaps[0].catalog.plotCatMap(self.hazmaps[0].catalog.getcat(0), True, False, None, None, 'best', True, 'g,', ax1, fignum+1, plotevents=0)
#cm=self.hazmaps[0].catalog.plotCatMap(self.hazmaps[0].catalog.getcat(0), True, False, None, epicen, 'best', True, 'g,', ax, fignum)
####
plt.figure(fignum)
#
Xs=map(operator.itemgetter(0), cdata)
Ys=map(operator.itemgetter(1), cdata)
Xvals=list(set(Xs))
Yvals=list(set(Ys))
Xvals.sort()
Yvals.sort()
#
X,Y=numpy.meshgrid(Xvals, Yvals)
X1, Y1=numpy.meshgrid(Xvals, Yvals)
# and now, we have to mash these into map coordinates:
for i in xrange(len(Y)):
for j in xrange(len(Y[0])):
myx, myy = X[i][j], Y[i][j]
myxm, myym = cm(myx, myy) # map coords...
#
if maptransform==True:
myxm1, myym1 = cm1(myx, myy)
else:
myxm1, myym1 = myx, myy
#
X[i][j]=myxm
Y[i][j]=myym
#
X1[i][j]=myxm1
Y1[i][j]=myym1
#
#X[i][j],Y[i][j] =cm(myx, myy)
#
Z=map(operator.itemgetter(2), cdata)
Z2d=scipy.array(Z)
Z2d.shape=(len(Yvals), len(Xvals))
#
# and pyplot has a weird, or stupid, feathre such that if we truncate the upper/lower contour range, it just leaves
# a hole (instead of inferring all z>zmax -> zmax). so, we "clip".
myZ = numpy.array(Z2d, copy=True)
#if nconts.insert:
try:
nconts.insert
# nconts has an "insert" function or property anyway (more properly see if
# type(a.insert).__name__== 'builtin_function_or_method'
#zmin=nconts[0]
#zmax=nconts[-1]
#myZ = Z2d.clip(nconts[0], nconts[-1])
# the problem with .clip() is that it replaces all the None values with zmin, so jus do it
# old-school:
for iy in xrange(len(myZ[0])):
if myZ[ix][iy]==None: continue
if myZ[ix][iy]>nconts[-1]: myZ[ix][iy] = nconts[-1]
if myZ[ix][iy]<nconts[0]: myZ[ix][iy] = nconts[0]
except:
# jut move on...
dummyvar=None
#
plt.figure(fignum)
#plt.clf()
#self.conts = plt.contourf(X,Y,Z2d, nconts, alpha=alpha, zorder=10)
self.conts = plt.contourf(X,Y,myZ, nconts, alpha=alpha, zorder=10)
plt.colorbar()
plt.spectral()
plt.figure(fignum+1)
self.conts2 = plt.contourf(X1,Y1,myZ, nconts, alpha=alpha, zorder=10)
plt.colorbar()
plt.spectral()
return self.conts2
def makeColorbar(self, cset=None, colorbarname=None, reffMag=5.0, contfact=5.0):
#
# reffMag:
if reffMag==None:
#reffMag=self.reffMag
reffMag=5.0
#
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']
#
#resolution = int(len(cs)/self.contfact)
resolution = int(len(cs)/contfact)
#
startindex=0
#
fig = plt.figure(figsize=(1.5,3))
axe = fig.add_axes([0.05, 0.05, 0.2, 0.9])
#
fig.figurePatch.set_alpha(0)
#
matplotlib.rc('font', family='monospace', weight='black')
#
cmap = mpl.cm.spectral
#norm = mpl.colors.Normalize(vmin=Z_i.min(), vmax=Z_i.max())
#ratefactor=10**(self.mc-self.reffMag)
ratefactorExp=self.mc-reffMag # so the raw rate probably should be with mc_catalog = mc_etas.
# but, we'll want to report some rate of m>reffMag
#
#tics = [0,10,20,40,80]
#tics = [round(self.Z2d.min(),3), round(self.Z2d.max(),3)]
#timefactExp = math.log10(year2secs)
# min, max functions puking on None types, so do it manually:
zmin=None
zmax=None
for i in xrange(len(self.Z2d)):
for ii in xrange(len(self.Z2d[0])):
z0=self.Z2d[i][ii]
if z0==None: continue
if zmin==None: zmin=z0
if zmax==None: zmax=z0
#
if z0>zmax: zmax=z0
if z0<zmin: zmin=z0
#
norm = mpl.colors.Normalize(vmin=zmin, vmax=zmax)
#
t1='%.2f' % (zmin)
t2='%.2f' % (zmax)
#
# poisson noise thresholds:
poissonSigma = (.5*math.log10(self.winlen))/self.logZ
tsn = '-%.2f' % poissonSigma
tsp = '%.2f' % poissonSigma
#print("max set: ", self.Z2d.max(), timefactExp, ratefactorExp)
tics = [zmin, -poissonSigma, 0.0, poissonSigma, zmax]
tlbls = [t1, tsn, 0.0, tsp, t2]
# clean up labels/tics in case max/min values are near poisson threshold.
if abs(poissonSigma - zmax)<.1:
tics.pop(-1)
tlbls.pop(-1)
if abs(-poissonSigma - zmin)<.1:
tics.pop(0)
tlbls.pop(0)
#
#cb1 = mpl.colorbar.ColorbarBase(axe, norm=norm, ticks=tics, format="%g%%", orientation='vertical')
cb1 = mpl.colorbar.ColorbarBase(axe, norm=norm, ticks=tics, format="%.2f", orientation='vertical')
cb1.set_ticklabels(tlbls, update_ticks=True)
cb1.set_label('Local normalized RB ratio\n$r=\\frac{\\log (n_{rb-short}/n_{rb-long})}{\\log(N)}$')
#cb1.set_label('ETAS rate')
plt.savefig(colorbarname) # vertical
#
#suffix=''
i=len(colorbarname)-1
#while colorbarname[i]!='.':
# #suffix.insert(0, colorbarcopy[-i])
# # this will get us the last '.'
# i-=1
i=colorbarname.rfind('.')
hname=colorbarname[:i] + '-h' + colorbarname[i:]
#
im = ipp.open(colorbarname, 'r')
im.load() # just to be sure. open() only creates a pointer; data are not loaded until analyzed.
im=im.rotate(-90)
#im.show()
im.save(hname)
#
# depricated method:
#os.system('convert -rotate 90 %s %s' % (colorbarname, hname))
#os.system('cp %s %s' % (colorbarname, hname))
#
return [colorbarname, hname]
def simplePlot(self, fignum=0, thresh=0.):
# do a simple matplotlib plot of hazmap. this is probably diagnostic, so it may just be points of some sort.
# note: this plots the ll-corner of each box. for a science-interesting plot, we should center these points (aka, [x+L/2, y+L/2]
#
if thresh==None or type(thresh).__name__ not in ('float', 'int'): thresh=0.0
plt.figure(fignum)
plt.clf()
plt.ion()
#
plt.title("diagnostic plot of dithered rb-hazmaps")
hmindex=0
for hm in self.hazmaps:
llrange=hm.llrange
lonsRed=[]
latsRed=[]
#rbvals=[]
lonsBlue=[]
latsBlue=[]
#
lonsCyan=[]
latsCyan=[] # for None , at least temporarily
#
for i in xrange(len(hm.rbRatios)):
#
#x=llrange[0][1]+self.gridsize*(i%hm.Nlon) #lon
#y=llrange[0][0]+self.gridsize*int(i/hm.Nlon) # lat
x=hm.getLon(i)
y=hm.getLat(i)
#if x<0: x+=180. # this seems to be more trouble than it's worth...
if hm.rbRatios[i]==None:
continue
#lonsCyan+=[x]
#latsCyan+=[y]
#
if hm.rbRatios[i]<=thresh:
lonsRed+=[x]
latsRed+=[y]
elif hm.rbRatios[i]>thresh:
lonsBlue+=[x]
latsBlue+=[y]
#plt.plot(lonsRed, latsRed, 'r%s' % yp.pyicon(hmindex))
#plt.plot(lonsBlue, latsBlue, 'b%s' % yp.pyicon(hmindex))
plt.plot(lonsRed, latsRed, 'r.')
plt.plot(lonsBlue, latsBlue, 'b.')
#plt.plot(lonsCyan, latsCyan, '%s' % yp.pyicon(hmindex), color='y')
hmindex+=1
def simpleBoxes(self, fignum=0, thresh=0.0, plotevents=1, mapres=None):
# do a simple matplotlib plot of hazmap. this is probably diagnostic, so it may just be points of some sort.
# note: this plots the ll-corner of each box. for a science-interesting plot, we should center these points (aka, [x+L/2, y+L/2]
# eventually, turn this into a map plot.
#
if mapres==None: mapres=self.mapres
#if thresh==None or type(thresh).__name__ not in ('float', 'int'): thresh=0.0
noisethresh=thresh
if thresh==None:
thresh=((self.winlen/2.)-.577 - math.log(self.winlen))/((self.winlen/2.)+.577 + math.log(self.winlen))
thresh=abs(math.log10(thresh))
# print("noisethresh: %f" % (noisethresh))
#
catdate=self.hazmaps[0].catalog.cat[-1][0]
hmdatestr='%d-%d-%d, %d:%d:%d (UTC)' % (self.hmdate.year, self.hmdate.month, self.hmdate.day, self.hmdate.hour, self.hmdate.minute, self.hmdate.second)
#
plt.ion()
self.fig=plt.figure(fignum)
self.fig.clf()
self.ax = self.fig.add_subplot(111)
#plt.title('(diagnostic) Record-breaking intervals Hazard Map')
#plt.title("Record-breaking hazardmap\ndtm=%s, $d\\lambda=%.4f$, nDith=%d, mc=%.2f, rblen=%d, avlen=%d\n\n" % (str(self.hmdate), self.gridsize, self.ndithers, self.mc, self.winlen, self.avlen))
plt.title("Record-breaking hazardmap\ndtm=%s, $d\\lambda=%.4f$, nDith=%d, mc=%.2f, rblen=%d, avlen=%d\n\n" % (hmdatestr, self.gridsize, self.ndithers, self.mc, self.winlen, self.avlen))
#
self.llrange=self.hazmaps[0].catalog.getLatLonRange(self.hazmaps[0].thiscat)
self.deltaLat=abs(float(self.llrange[1][0])-self.llrange[0][0])
self.deltaLon=abs(float(self.llrange[1][1])-self.llrange[0][1])
self.Nlat=1+int(self.deltaLat/self.gridsize)
self.Nlon=1+int(self.deltaLon/self.gridsize) #number of cells in row/col
#
self.lat0=self.llrange[0][0]
self.lon0=self.llrange[0][1]
#
#ilat=0
#ilon=0 # index counters
#self.cm=self.catalog.plotCatMap(self.thiscat, True, False, None, None, 'best', True, 'g,', None, self.fignum)
#self.cm=self.catalog.plotCatMap(self.thiscat, True, False, None, None, 'best', True, 'g,', self.ax)
#minicat=self.catalog.getcat(0)[0:10]
#
#thismev=self.hazmaps[0].catalog.getMainEvent(self.hazmaps[0].catalog.getcat(0))
#epicen=[thismev[2], thismev[1]]
#
#self.cm=self.hazmaps[0].catalog.plotCatMap(self.hazmaps[0].catalog.getcat(0), True, False, None, self.epicen, 'best', True, 'g,', self.ax, fignum, plotevents)
self.hazmaps[0].catalog.mapres=mapres
self.cm=self.hazmaps[0].catalog.plotCatMap(self.hazmaps[0].catalog.getcat(0), True, False, None, self.epicen, 'best', True, 'g,', self.ax, fignum, plotevents)
#
plt.figure(fignum)
hmindex=0
for hm in self.hazmaps:
llrange=hm.llrange
lonsRed=[]
latsRed=[]
#rbvals=[]
lonsBlue=[]
latsBlue=[]
#
lonsCyan=[]
latsCyan=[] # for None , at least temporarily
#
for i in xrange(len(hm.rbRatios)):
#
#x=llrange[0][1]+self.gridsize*(i%hm.Nlon) #lon
#y=llrange[0][0]+self.gridsize*int(i/hm.Nlon) # lat
x=hm.getLon(i) + self.gridsize/2.0 - self.dL/2.0
y=hm.getLat(i) + self.gridsize/2.0 - self.dL/2.0 # to center the little boxes on their area of influence. note, this visually
# excludes the left side of the cluster.
# let's try always casting all lon values as positive:
# if x<0: x+=180. # basemap appears to not understand the int. dt. line.
if hm.rbRatios[i]==None:
continue
#lonsCyan+=[x]
#latsCyan+=[y]
#
#mapX, mapY=self.cm(map(operator.itemgetter(0), thissquare), map(operator.itemgetter(1), thissquare))
#self.gridSquares+=self.ax.fill(mapX, mapY, alpha=.1, color='b', lw=2, zorder=2)
thissq=hm.getSquare([x,y], float(self.gridsize)/self.ndithers)
#thissq=hm.getSquare([x,y], float(self.gridsize))
X=map(operator.itemgetter(0), thissq)
Y=map(operator.itemgetter(1), thissq)
X,Y=self.cm(X,Y)
#thisalpha=abs(hm.rbRatios[i])
if hm.rbRatios[i]<(-thresh):
# (note: ratios are "loggoe": r[i]=log(nrb1/nrb2)
# getSquare(self, xy=[], dx=.1):
#plt.fill(X,Y, alpha=thisalpha, color='r', lw=2, zorder=9)
plt.fill(X,Y, alpha=.55, color='r', lw=2, zorder=9)
#lonsRed+=[x]
#latsRed+=[y]
elif hm.rbRatios[i]>=thresh:
#elif hm.rbRatios[i]>thresh:
#lonsBlue+=[x]
#latsBlue+=[y]
#plt.fill(X,Y, alpha=thisalpha/2., color='b', lw=2, zorder=8)
plt.fill(X,Y, alpha=.2, color='b', lw=2, zorder=8)
elif hm.rbRatios[i]>=-thresh and hm.rbRatios[i]<0.:
plt.fill(X,Y, alpha=.4, color='y', lw=2, zorder=8)
elif hm.rbRatios[i]>=0. and hm.rbRatios[i]<=thresh:
#lonsBlue+=[x]
#latsBlue+=[y]
plt.fill(X,Y, alpha=.2, color='c', lw=2, zorder=8)
#plt.plot(lonsRed, latsRed, 'r%s' % yp.pyicon(hmindex))
#plt.plot(lonsBlue, latsBlue, 'b%s' % yp.pyicon(hmindex))
#plt.plot(lonsRed, latsRed, 'r.')
#plt.plot(lonsBlue, latsBlue, 'b.')
#plt.plot(lonsCyan, latsCyan, '%s' % yp.pyicon(hmindex), color='y')
hmindex+=1
def getClusters(self, beta=2):
#cdata=self.contourData()
clusts=self.findClusters(map(operator.itemgetter(2), self.contourData()), self.getNlon())
'''
clusts=[]
for rw in clusts0:
if len(rw[1])==0: continue
clusts+=rw[1]
'''
return clusts
#
def getClustStats(self, clusts=None, beta=2):
if clusts==None: clusts=self.getClusters()
clustStats=[]
for i in xrange(len(clusts)):
#for rw in clusts:
rw=clusts[i]
#clustStats+=[[len(rw), self.guessMag(len(rw), beta=beta)]]
clustStats+=[[i, len(rw), self.guessMag(len(rw), beta=beta)]]
#clustStats.sort() # i think this will, by default, sort by first element. if not, use a key, itemgetter(), etc.
clustStats.sort(key=lambda rw: rw[1])
return clustStats
def plotClustRBratios(self, clustlist=None, rblen=None, minmag=1.5, fignum=1, avlen=1, justTop=False):
# notes: the idea here is to see if a cluster is coherent, in other words, if two adjacen sites show r<1, is r<1 for both sites together?
# a problem arises for small clusters in dithered maps. for example, if ndithers=3, each square represents only 1/9 of a full sequence.
# we estimate the area and sequence length basically from n(rblen/9). in the simple example of 1 square, we end up trying to compute rb-statistics
# as n=rblen/9, when in fact the statistics for that cell were computed over rblen intervals, so the result it toally meaningless. not until
# N_clusts is large does this approximation work. we could try to re/de-construct the clusters to figure out the actual area covered and
# actual number of events in the calculation, but as per shape-statistics, this will be nasty.
#
# given this problem of estimating cluster areas, maybe the thing to do is to look at the source haz-maps themselves. basically filter non-coherent
# clusters in hazmaps[i], then plot only the coherent clusters. of course, the next problem is that our coherent cluster might be connected to other
# clusters by noisy pixels. maybe this problem will be mitigated in the dithering, but we might end up filtering out our target. finding an efficient
# way to look for coherent clusters within larger clusters will be a big job, but it might be tractable. of course, we'll be back to the question of,
# how do we define "coherent". all red? mostly red?
#
if clustlist==None: clustlist=self.findClusters() # so do all of them?
if type(clustlist[0]).__name__ == 'int':
# we've got a list of indeces.
tmpclist=self.findClusters()
newlist=[]
for i in clustlist:
newlist+=[tmpclist[i]]
clustlist=newlist
tmpclist=None
newlist=None
#
c1=yp.eqcatalog(self.catFromClusters(clustlist, justTop))
if rblen==None:
# optimal (??) rblen:
nsquares=0
for clst in clustlist:
nsquares+=len(clst)
rblen=2*int(self.winlen*nsquares/(self.ndithers**2))
print("rblen = %d" % rblen)
self.rb.fullCat=c1.getcat(0)
self.rb.shockCat=c1.getcat(0)
#
self.rb.plotIntervalRatios(windowLen=rblen, minmag=minmag, fignum=fignum, avlen=avlen)
def catFromClusters(self, clustlist=[0], justTop=False):
# form a sub-catalog from one or more clusters.
# justTop -> take only top self.winlen events from each cluster. this weights each cell equally, rather than focusing on the most active sites.
#
# clustlist is a collection (list) of clusters from findClusters(). each entry is a sub-cat in a hazmap.catalog object.
#
# since we've dithered, we have to choose a way to choose which events. aka, do we choose all events inside the dithered boundary as we've drawn it,
# or all elements in the catalogs used to draw the cluster... or, a set of sub-cats for each dithered set.
# for now, combine all the catalogs (they will overlap a lot) and then remove duplicates.
#
# de-index the cluster-map (nLon, nLat are for for dithered set; ndithers is dither-length (ndithers=3 -> 3x3), / implies integer division).
# see getMapIndex() for index to mapID mapping. as per dithering, we're arranging our maps like (where the mapID's below represent the indeces
# of the maps as they were created. it would probably be a good idea to actually name the maps to make this process easier).
# 0 1 2| 9 10 11 | 18 19 20
# 3 4 5|12 13 14 | 21 22 23
# 6 7 8|15 16 17 | 23 25 26
# 27 o o * o o * o o
# o o o o o o o o o
# o o o o o o o o o
# * o o * o o * o o
#
# ndithers=3
# nLon=9
# then, the mapID is mapIndex%(ndithers**2),
# the gridIndex (for that map) is mapID/(ndithers**2)
#
# so combine all the indeces from the entries in clustlist, make one big catalog from all the events; strip duplicates.
newcat=[]
i0=0
if justTop==True: i0=-self.winlen
for clust in clustlist:
for elem in clust:
#print("clustLen: %d" % len(clust[i0:]))
(hazmapIndex, subcatIndex) = self.getMapIndex(elem)
#newcat+=self.hazmaps[hazmapIndex].catalog.subcats[subcatIndex][1] # because eacy point on the haz-map represents a stastic from a set of events in a subcat.
newcat+=self.hazmaps[hazmapIndex].catalog.subcats[subcatIndex][1][i0:] # because eacy point on the haz-map represents a stastic from a set of events in a subcat.
#print(hazmapIndex, subcatIndex)
#
# now, strip duplicates:
#rcat=list(set(newcat))
#rcat=newcat[[0]]
rcat=[]
i=0
while i<len(newcat):
#if newcat[i]==rcat[-1]: continue
if newcat[i] not in rcat: rcat+=[newcat[i]] # this is the slow way, but it's straight forward. otherwise, sort and look at rcat[-1]
i+=1
#
rcat.sort()
return rcat
def getMapIndexMod(self, clustIndex=0, ndithers=None, nLon=None):
# given an index from a dithered map, returns [mapID (aka, dithered hazmap object index), gridIndex (grid index from that hazmap)]
# (a funky way of doing it) (and both of these methods seem to work... at lest they are identically flawed).
if ndithers==None: ndithers=self.ndithers
if nLon==None: nLon=self.getNlon()
#
i=clustIndex
nd=ndithers
mapIndex = (i%nd) + nd*int(int(i/nLon)%nd) + nd*nd*int((i%nLon)/nd)
# but i think this is giving me only the x-position, not the proper y-pos.
fullypos=i/self.getNlon() # y position for dithered map.
# add this separately to return value or lump into mapIndex? dunno just yet...
ydithered=fullypos/self.ndithers # y position for each map.
mapGrid=mapIndex/(ndithers*ndithers) + (self.getNlon()/self.ndithers)*ydithered
return [mapIndex%(ndithers*ndithers), mapGrid]
def getMapIndex(self, clustIndex=0, ndithers=None, nLon=None):
# given an index from a dithered map, returns [mapID (aka, dithered hazmap object index), gridIndex (grid index from that hazmap)]
# (less elegant but more straight-forward) (and both of these methods seem to work... at lest they are identically flawed).
if ndithers==None: ndithers=self.ndithers
if nLon==None: nLon=self.getNlon()
#
x=clustIndex%nLon
y=clustIndex/nLon #x,y on dithered haz-map.
#
mapindex=x%ndithers + ndithers*(y%ndithers) # hazardmap index (haxmaps[mapindex])
#
# and the index on the haz-map...
mapx=x/ndithers
mapy=y/ndithers
gridindex=mapx + nLon*mapy/ndithers
#
return [mapindex, gridindex] # so this is [the hazard map being used, grid index on that hazard map]
def findClusters(self, gridlist=[], L=None):
if gridlist==[] or gridlist==None:gridlist=map(operator.itemgetter(2), self.contourData())
if L==None: L=self.getNlon()
# find clusters and their size.
# two passes total (i think) through the data:
# - walk gridk "left" to "right" (aka, i -> i+1). L/R adjacent elements are elements of a cluster; record clusters in clustList=[[j0, [indeces]], [j1, [ind.]] ]
# - if there is an element "below" (aka z[i-L]):
# - z[i] -> that cluster
# - members of z[i]'s cluster are tagged for renaming (add an entry to clustMap -> [j, j']. use new clust number going forward.
# - after walking the grid, update clustList indeces from top to bottom according to clustMap, also top to bottom.
#
mygridlist=scipy.array(gridlist)
clusterIDs=[] # will be same dim. as gridlist, but will be populated with clusterID indices.
clustList=[[0, []]] #[[j0, [indices for j0]], [j1, [indeces for j1]...] # and we might not need the index name j0, j1, ... we can probably just use order as index.
clustMap=[] # when we join two clusters: [[j0, j0'], [j1, j1'], ...]
#
# 1D or 2D array?
#if type(gridlist[0]).__name__ in ('float', 'int')
# more robustly?
'''
if type(gridlist[0])==type(5.0) or type(gridlist[0])==(5):
# in case type names change in later pythons? aka, float64, intlong, or whatever. of course, this dos not guarantee that the flavor
# of float/int we provide is the same.
#
# anyway, this is a 1D array. infer 2D from L.
# let's just cast this into a 2D array (it's got to be one or the other).
mygridlist.shape=(len(gridlist)/L, L) # assuming config. [x0,y0; x1, y0; x2,y0... we should also trap for not integer division, etc.
#
# otherwise, it's a 2D array (or something that will make a big mess and break or produce nonsense).
'''
# but i seem to be happier with 1D array management, so let's do it this way:
if type(gridlist[0]).__name__ in ('tuple', 'list', 'ndarray'):
# elemtens are list-like, aka a 2+D array. assume 2D.
L=len(gridlist[0])
mygridlist.shape=(len(mygridlsit))
#
gridlen=len(gridlist)
'''
if L==None:
# before giving up, guess a square:
squareL=((float(gridlen))**.5)
if squareL%1==0:
# it could be a square...
L=squareL
else:
# we don't know how to parse it.
print("array width not defined.")
return None
'''
#
clustIndex=0
#
i=0
while i<gridlen:
if mygridlist[i]==None or mygridlist[i]<=0:
clusterIDs+=[None]
i+=1
continue # though we might just use NONE and to allow for 0-value perimeter padding.
#
# at this point, we've found an occupied site.
#
# is it a (potentially) new cluster on the left edge?
#if i%L==0:
# for starters, assume it is:
myclustID=clustList[-1][0]+1
if i%L>0:
# not on left edge
if clusterIDs[i-1]!=None:
# join cluster to left
myclustID=clusterIDs[i-1]
if i>=L: # a more efficient (aka, not always checking i>=L) approach might be to process the first row separately.
# we've passed the first row. is it part of a prev-row cluster?
if clusterIDs[i-L]!=None:
myclustID=clusterIDs[i-L] # join the cluster below.
# was it part of a cluster to the left?
if clusterIDs[i-1]!=None and clusterIDs[i-1]!=myclustID:
# i suppose we could change this guy while we're here, but it is not necessary. write the label change:
#clustMap+=[[myclustID, clusterIDs[i-1]]] #[[i_from, i_to]] as executed from the top of the list.
clustMap+=[[clusterIDs[i-1], myclustID]] #[[i_from, i_to]] as executed from the top of the list.
#
#
#
# write to cluterIDS:
clusterIDs+=[myclustID]
#
# add this element to its cluter list.
if len(clustList)<(myclustID+1):
# we've added a new cluster.
clustList+=[[myclustID, []]]
clustList[myclustID][1]+=[i]
#
i+=1
# now, stitch together the clusters:
newclusts={}
for i in xrange(len(clustList)):
newclusts[i]=i
clustMap.reverse()
for rw in clustMap:
srcindex=newclusts[rw[0]]
targetindex=newclusts[rw[1]]
#
#clustList[rw[1]][1]+=clustList[rw[0]][1]
#clustList[rw[0]][1]=[]
if targetindex==srcindex:
#print("target/source problem")
continue
clustList[targetindex][1]+=clustList[srcindex][1]
clustList[srcindex][1]=[]
newclusts[srcindex] = targetindex
#
rlist=[]
for rw in clustList:
if len(rw[1])==0: continue
rlist+=[rw[1]]
return rlist
def guessMagL(self, nx=None, ny=None, dithers=1.0, lat=None, gridsize=None, llkm=111.0, gamma=1.0, degs=1):
# gridsize can be calculated from haz-map info.. eventually.
rlat=lat
if degs==1: rlat=2*math.pi*lat/360.
#
xsq=(nx*math.cos(rlat)*gridsize*llkm/dithers)**2. + (ny*gridsize*llkm/dithers)**2
L=xsq**.5
print("length: %f" % L)
#
m=2.*math.log10(L*gamma)+3.25
return m
def guessMag(self, nsquares=None, mc=None, deltas=2.0, beta=1.0, rblen=None, dithers=None):
# we must have mc, rblen, dithers, nsquares. other prams we can guess.
#if mc==None or nsquares==None or rblen==None or dithers==None: return None
if mc==None: mc=self.mc
if rblen==None: rblen=self.winlen
if dithers==None: dithers=self.ndithers*self.ndithers
if nsquares==None: nsquares=1 # minimun estimate, though maybe we should break it.
#
return mc + deltas + math.log10(beta*rblen*nsquares/float(dithers))
class rbHazMapLean(object):
#
# a very lean hazard map - aka, just the data. primarily, this class is to be used in a dithered haz-map. all the graphical/mapping
# bits will be in the parent class.
#plt.ion()
def __init__(self, catalog=None, catnum=0, mc=2.5, gridsize=.5, phi=[0,0], winlen=128, avlen=1, bigmag=5.0, logZ=1.0):
# catalog: yp.eqcatalog object, phi: spatial phase shift(s) [lat,lon]
self.catnum=catnum
self.mc=mc
self.gridsize=gridsize
self.phi=phi
self.winlen=winlen
self.avlen=avlen
self.bigmag=bigmag
self.logZ=logZ
#self.fignum=fignum
#self.catalog=catalog
#self.catalog=yp.eqcatalog(catalog.getcat(catnum)) # move to after "if self.catalog==None"
#self.avlen=10
self.precatindex=None
#
self.rbRatios=[] #rb ratios for grid. this will either be a single array [r_0, r1, r2...] or an array of lists; we'll take the last val or average over the
# last rblen vals [[r00, r01, r02...], [r10, r11, r12...], ... ]
#
if catalog==None:
#catalog=getMexicaliCat(mc)
self.catalog=getSocalCat(mc)
# clean up subcats:
else:
self.catalog=yp.eqcatalog(catalog.getcat(catnum))
#
while len(self.catalog.subcats)>0: self.catalog.subcats.pop()
#
try:
self.catalog.rb
#except NameError:
except:
self.catalog.rb=rbi.intervalRecordBreaker(None)
#
#self.thiscat0=self.catalog.getcat(catnum)
self.thiscat0=self.catalog.getcat(catnum)
self.thiscat=self.thiscat0 # simplify this? do we need these two subcats?
#self.thiscat=self.thiscat0
#print("mainEvent: %s" % mev)
#
self.llrange=self.catalog.getLatLonRange(self.thiscat)
# maps will stack better if we add phi to both sides of llrange:
self.llrange[0]=[self.llrange[0][0]+phi[0], self.llrange[0][1]+phi[1]]
self.llrange[1]=[self.llrange[1][0]+phi[0], self.llrange[1][1]+phi[1]]
#
self.deltaLat=abs(float(self.llrange[1][0])-self.llrange[0][0])
self.deltaLon=abs(float(self.llrange[1][1])-self.llrange[0][1])
self.Nlat=1+int(self.deltaLat/self.gridsize)
self.Nlon=1+int(self.deltaLon/self.gridsize) #number of cells in row/col
#
self.lat0=self.llrange[0][0]
self.lon0=self.llrange[0][1]
#
ilat=0