-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_plot.py
1431 lines (1093 loc) · 49.6 KB
/
test_plot.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 sys
sys.path.append("/home/kasey/PyVC/")
import math
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import quakelib
import math
import os
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.font_manager as mfont
if os.path.isfile('/home/kasey/.matplotlib/fontList.cache'):
os.remove('/home/kasey/.matplotlib/fontList.cache')
#=============================================================================
def mag_from_moment(moment):
return (2.0/3.0)*np.log10(moment) - 6.0
#=============================================================================
def weibull(x_array,beta,tau):
if len(x_array) < 2:
sys.exit("Input must be an array")
else:
return np.array([1-math.exp(x/float(tau)) for x in x_array])
def weibull_one(x,beta,tau):
return 1-np.exp( -(x/float(tau))**beta)
#=============================================================================
def fit_to_weibull(sim_file,beta_0,tau_0,event_range=None,magnitude_filter=None,section_filter=None):
from scipy import optimize
from pyvc import VCEvents,VCSimData
fitfunc = lambda p,x: weibull_one(x,p[0],p[1])
errfunc = lambda p,x,y: fitfunc(p,x) - y
p0 = [beta_0,tau_0]
with VCSimData() as sim_data:
# open the simulation data file
sim_data.open_file(sim_file)
# instantiate the vc classes passing in an instance of the VCSimData
# class
events = VCEvents(sim_data)
event_data = events.get_event_data(['event_number', 'event_year', 'event_magnitude', 'event_range_duration'], event_range=event_range, magnitude_filter=magnitude_filter, section_filter=section_filter)
intervals = np.array([ x - event_data['event_year'][n-1]
for n,x in enumerate(event_data['event_year'])
if n != 0
])
cumulative = {}
cumulative['x'] = np.sort(intervals)
cumulative['y'] = np.arange(float(intervals.size))/float(intervals.size)
p1,success = optimize.leastsq(errfunc,p0[:],args=(cumulative['x'],cumulative['y']))
print "\nBETA: {}".format(p1[0])
print "TAU : {}\n".format(p1[1])
#=============================================================================
def bin_2d(x,y,bmin=None,bmax=None,all_vals=False) :
if np.shape(x) != np.shape(y):
raise NameError('Array shape mismatch, insert coin(s) to continue.')
num_bins = math.floor(len(x)/100.0)
if num_bins <= 20:
num_bins = 20
elif num_bins >= 100:
num_bins = 100
x = np.array(x)
y = np.array(y)
if bmin==None and bmax==None:
bmin = math.floor(np.min(x))
bmax = math.ceil(np.max(x))
bins = np.linspace(bmin,bmax,num=num_bins)
inds = np.digitize(x, bins)
x_ave = []
y_ave = []
binned_data = {}
for n, iBin in enumerate(inds):
try:
binned_data[iBin].append(y[n])
except KeyError:
binned_data[iBin] = [y[n]]
KEYS = binned_data.keys()
if all_vals:
if 0 in KEYS:
x_ave.append(bmin)
y_ave.append(sum(binned_data[0])/float(len(binned_data[0])))
"""for k in sorted(KEYS):
if k != 0:
if k==len(bins):
#Catch the bins that are excluded to the right of the last bin
k=len(bins)-1
x_ave.append(0.5*(bins[k-1]+bins[k]))
y_ave.append(sum(binned_data[k])/float(len(binned_data[k])))
else:
x_ave.append(0.5*(bins[k-1]+bins[k]))
y_ave.append(sum(binned_data[k])/float(len(binned_data[k])))
"""
for k in sorted(KEYS):
if k>0 and k < len(bins):
x_ave.append(0.5*(bins[k-1]+bins[k]))
y_ave.append(sum(binned_data[k])/float(len(binned_data[k])))
if all_vals:
if len(bins) in KEYS:
x_ave.append(bmax)
y_ave.append(sum(binned_data[len(bins)])/float(len(binned_data[len(bins)])))
return np.array(x_ave), np.array(y_ave)
#-----------------------------------------------------------------------------
def hist_1d(x,bmin=None,bmax=None,norm=False,num_bins=100):
x = np.array(x)
if bmin==None and bmax==None:
bmin = math.floor(np.min(x))
bmax = math.ceil(np.max(x))
bins = np.linspace(bmin,bmax,num=num_bins)
inds = np.digitize(x, bins)
x_ave = []
count = []
binned_data = {}
for n, iBin in enumerate(inds):
try:
binned_data[iBin].append(x[n])
except KeyError:
binned_data[iBin] = [x[n]]
KEYS = binned_data.keys()
# Put values below minimum bin into first bin
if 0 in KEYS:
x_ave.append(bmin)
count.append(len(binned_data[0]))
for k in sorted(KEYS):
if k!=0:
if k<len(bins):
x_ave.append(0.5*(bins[k-1]+bins[k]))
count.append(len(binned_data[k]))
# Put values above maximum bin into last bin
if len(bins) in KEYS:
x_ave.append(bmax)
count.append(float(len(binned_data[len(bins)])))
x_ave = np.array(x_ave)
count = np.array(count)
if norm:
count /= float(len(x))
return x_ave,count
#-----------------------------------------------------------------------------
def get_slope_intercept(x,y):
from scipy import stats
slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
return slope,intercept
#-----------------------------------------------------------------------------
def get_linspaces(Xmin,Xmax,Nx,Ymin,Ymax,Ny):
x = np.linspace(Xmin,Xmax,num=Nx)
y = np.linspace(Ymin,Ymax,num=Ny)
return x,y
#-----------------------------------------------------------------------------
def get_matrix(Xmin,Xmax,Nx,Ymin,Ymax,Ny,c,dip,L,W,US,UD,UT,LAMBDA,MU,field_type='gravity'):
okada = quakelib.Okada()
X,Y = get_linspaces(Xmin,Xmax,Nx,Ymin,Ymax,Ny)
XX,YY = np.meshgrid(X,Y)
MAT = np.zeros(XX.shape)
if field_type == 'gravity':
for i in range(len(XX[0])):
for j in range(len(XX[1])):
loc = quakelib.Vec2(XX[i][j],YY[i][j])
MAT[i][j] = okada.calc_dg(loc,c,dip,L,W,US,UD,UT,LAMBDA,MU)
elif field_type == 'dilat_gravity':
for i in range(len(XX[0])):
for j in range(len(XX[1])):
loc = quakelib.Vec2(XX[i][j],YY[i][j])
MAT[i][j] = okada.calc_dg_dilat(loc,c,dip,L,W,US,UD,UT,LAMBDA,MU)
elif field_type == 'displacement':
for i in range(len(XX[0])):
for j in range(len(XX[1])):
loc = quakelib.Vec3(XX[i][j],YY[i][j],0.0)
MAT[i][j] = okada.calc_displacement_vector(loc,c,dip,L,W,US,UD,UT,LAMBDA,MU)[2]
else:
raise IOError('You must choose one of: gravity, dilat_gravity, displacement')
"""
elif field_type == 'potential':
for i in range(len(XX[0])):
for j in range(len(XX[1])):
loc = quakelib.Vec3(XX[i][j],YY[i][j],0.0)
MAT[i][j] = okada.calc_dV(loc,c,dip,L,W,US,UD,UT,LAMBDA,MU)
elif field_type == 'insar':
#!!!!!!!!!!!!?????????????
#!!!!!!!!!!!!?????????????
#!!!!!!!!!!!!?????????????
"""
return (XX,YY,MAT)
#-----------------------------------------------------------------------------
def get_filename(c,dip,L,W,US,UD,UT,folder,pre='none',suff='none'):
dip_deg = round(180.0*dip/np.pi)
fault_type = ""
if US!=0.0:
slip = US
fault_type = "strikeslip"
if UD!=0.0:
slip = UD
if UD>0:
fault_type = "thrust"
else:
fault_type = "normal"
if UT!=0.0:
slip = UT
fault_type = "tensile"
if pre=='none':
f0 = folder.split('_')[0]
else:
f0 = pre
f1 = '_'+fault_type+str(int(abs(slip)))+'_dip'+str(int(round(dip_deg)))
f2 = '_L'+str(int(round(L/1000.0)))+'k_'+'W'+str(int(round(W/1000.0)))+'k'
f3 = '_c'+str(int(round(c/1000.0)))+'k'
if suff != 'none':
f3 = f3+'_'+suff+'.png'
else:
f3 = f3+'.png'
filename = folder+'/'+f0+f1+f2+f3
return filename,fault_type
#-----------------------------------------------------------------------------
def cbar_plot(Xmin,Xmax,Nx,Ymin,Ymax,Ny,c,dip,L,W,US,UD,UT,LAMBDA,MU,
save=False,field_type='gravity',CLIMITS=False,SUFFIX='none',
HIST=False,SHOW=False,DV=False,NOLABELS=False,tick_font=12,
frame_font=12,num_ticks=7,CBAR='top',x_ticks=True):
import time
start = time.time()
# field_type options
# gravity, dilat_gravity, displacement, insar(soon), potential(soon)
# Need to remove a cached file for Arial fonts to be used
if os.path.isfile('/home/kasey/.matplotlib/fontList.cache'):
os.remove('/home/kasey/.matplotlib/fontList.cache')
ticklabelfont = mfont.FontProperties(family='Arial', style='normal', variant='normal', size=tick_font)
framelabelfont = mfont.FontProperties(family='Arial', style='normal', variant='normal', size=frame_font)
"""
Immutable constants: (hard coded in quakelib/src/QuakeLibOkada.cpp) all MKS
Free-air gravity gradient (Okubo '92): Beta = 0.00000309 1/s^2
= 309 microgal/m
Constant crustal density: Rho = 2670.0 kg/m^3
Gravitational constant: G = 0.000000000066738
Vertical displacement calculations:::
displacement: Method previously implemented, from Okada
insar (soon): InSAR interferogram (need to learn how this is calculated)
Gravity change calculations:::
gravity: Complete implementation of Okubo '92 method, for surface observations
dilat_gravity: Gravity changes only due to compression, for satellite observations
"""
#-------- Choose the data to plot vvvvvv -----------
if field_type == 'gravity':
pre = 'dg'
filename,fault_type = get_filename(c,dip,L,W,US,UD,UT,'dg_plots',pre=pre,suff=SUFFIX)
FMT = '%i'
UNIT = pow(10,-8) #micro gals
if fault_type == 'strikeslip':
CMIN,CMAX = -20,20
#plot_lab = "Strike-slip"
elif fault_type == 'thrust':
CMIN,CMAX = -200,200
#plot_lab = "Thrust"
elif fault_type == 'normal':
CMIN,CMAX = -200,200
#plot_lab = "Normal"
else:
CMIN,CMAX = -200,200
#plot_lab = "Tensile"
CLABEL = r'total gravity changes $[\mu gal]$'
elif field_type == 'dilat_gravity':
pre = 'dg_dilat'
filename,fault_type = get_filename(c,dip,L,W,US,UD,UT,'dg_dilat_plots',pre=pre,suff=SUFFIX)
FMT = '%i'
UNIT = pow(10,-8) #micro gals
if fault_type == 'strikeslip':
CMIN,CMAX = -20,20
#plot_lab = "Strike-slip"
elif fault_type == 'thrust':
CMIN,CMAX = -20,20
#plot_lab = "Thrust"
elif fault_type == 'normal':
CMIN,CMAX = -20,20
#plot_lab = "Normal"
else:
CMIN,CMAX = -20,20
#plot_lab = "Tensile"
CLABEL = r'dilatational gravity changes $[\mu gal]$'
elif field_type == 'displacement':
pre = 'dz'
filename,fault_type = get_filename(c,dip,L,W,US,UD,UT,'dz_plots',pre=pre,suff=SUFFIX)
if fault_type == 'strikeslip':
CMIN,CMAX = -.2,.2
#plot_lab = "Strike-slip"
elif fault_type == 'thrust':
CMIN,CMAX = -2.0,2.0
#plot_lab = "Thrust"
elif fault_type == 'normal':
CMIN,CMAX = -2.0,2.0
#plot_lab = "Normal"
else:
CMIN,CMAX = -2.0,2.0
#plot_lab = "Tensile"
FMT = '%.1f'
#UNIT = pow(10,-2) # centimeters
UNIT = 1.0
CLABEL = r'$\Delta z \ [m]$'
"""
elif field_type == 'insar':
pre = 'dz'
filename,fault_type = get_filename(c,dip,L,W,US,UD,UT,'InSAR_plots',pre=pre,suff=SUFFIX)
if fault_type == 'strikeslip':
CMIN,CMAX = -.2,.2
#plot_lab = "Strike-slip"
elif fault_type == 'thrust':
CMIN,CMAX = -2.0,2.0
#plot_lab = "Thrust"
elif fault_type == 'normal':
CMIN,CMAX = -2.0,2.0
#plot_lab = "Normal"
else:
CMIN,CMAX = -2.0,2.0
#plot_lab = "Tensile"
FMT = '%.1f'
#UNIT = pow(10,-2) # centimeters
UNIT = 1.0
CLABEL = r'$ | \Delta z | \ [m]$'
elif field_type == 'potential':
XX,YY,dv = get_matrix(Xmin,Xmax,Nx,Ymin,Ymax,Ny,
c,dip,L,W,US,UD,UT,LAMBDA,MU,DV=True)
UNIT = 1.0 #pow(10,-4) #GUESS?!?!?!
CLABEL = r'Gravitational potential change $[units??]$'
FMT = '%.4f'
Data = dv
filename = 'test_dV.png'
"""
XX,YY,Data = get_matrix(Xmin,Xmax,Nx,Ymin,Ymax,Ny,c,dip,L,W,US,UD,UT,LAMBDA,MU,field_type=field_type)
#---------------------------------------------------------
if HIST:
savename = filename.split('.')[0]+'_hist.png'
DG_flat = Data.flatten()/UNIT
plot_dg_hist(DG_flat,savename)
# Make the figure
this_fig = plt.figure()
fig_axes = plt.subplot(111)
this_img = plt.imshow(Data/UNIT, origin = 'lower',interpolation='nearest',
extent=[Xmin/1000.0,Xmax/1000.0,Ymin/1000.0,
Ymax/1000.0],cmap=plt.get_cmap('seismic'))
# Tighten up the axis labels
img_ax = this_fig.gca()
if not NOLABELS:
img_ax.set_xlabel(r'along fault [$km$]',labelpad=-1, fontproperties=framelabelfont)
img_ax.set_ylabel(r'[$km$]',labelpad=-5, fontproperties=framelabelfont)
if CLIMITS:
plt.clim(CMIN,CMAX)
if field_type == 'gravity' or field_type == 'dilat_gravity':
forced_ticks = [int(num) for num in np.linspace(CMIN,CMAX,num_ticks)]
else:
forced_ticks = [num for num in np.linspace(CMIN,CMAX,num_ticks)]
else:
Data = np.array(Data)
forced_ticks = [num for num in np.linspace(Data.min(),Data.max(),num_ticks)]
# Make color bar and put its label below its x-axis
divider = make_axes_locatable(fig_axes)
if CBAR=='top':
cbar_ax = divider.append_axes("top", size="5%",pad=0.02)
else:
cbar_ax = divider.append_axes("bottom", size="5%",pad=0.02)
cbar = plt.colorbar(this_img,format=FMT,
orientation='horizontal',cax=cbar_ax,
ticks=forced_ticks)
# Make and position colorbar label
if not NOLABELS:
cbar_ax.set_xlabel(CLABEL,labelpad=-40, fontproperties=framelabelfont)
if CBAR=='bottom':
PAD = 2.5
TOP = False
BOTTOM = True
else:
PAD = -.5
TOP = True
BOTTOM = False
cbar_ax.tick_params(axis='x',labelbottom=BOTTOM,labeltop=TOP,
bottom='off',top='off',right='off',left='off',pad=PAD)
# Want to change outermost tick labels on colorbar
# from 'VALUE','-VALUE' to '>VALUE' and '<-VALUE'
if field_type != 'potential':
cb_tick_labs = [str(num) for num in forced_ticks]
cb_tick_labs[0] = '<'+cb_tick_labs[0]
cb_tick_labs[-1] = '>'+cb_tick_labs[-1]
cbar.ax.set_xticklabels(cb_tick_labs)
for label in img_ax.xaxis.get_ticklabels()+img_ax.yaxis.get_ticklabels():
label.set_fontproperties(framelabelfont)
for label in cbar_ax.xaxis.get_ticklabels()+cbar_ax.yaxis.get_ticklabels():
label.set_fontproperties(ticklabelfont)
if not x_ticks:
plt.setp(img_ax.xaxis.get_ticklabels(),visible=False)
# Draw a projection of the fault
W_proj = W*np.cos(dip) #projected width of fault due to dip angle
fault_proj = mpl.patches.Rectangle((0.0,0.0),L/1000.0,W_proj/1000.0,
ec='k',fc='none',fill=False,
ls='solid',lw=4.0)
fig_axes.add_patch(fault_proj)
# Save the plot
if save:
plt.savefig(filename,dpi=200)
print '>>> plot saved: '+filename
if SHOW:
plt.show()
plt.clf()
print "{} seconds elapsed\n".format(time.time()-start)
#-----------------------------------------------------------------------------
def plot_for_cutoff(Xmin,Xmax,Nx,Ymin,Ymax,Ny,c,dip,L,W,US,UD,UT,LAMBDA,MU,
save=False,SHOW=False,_CLIMS=False):
TRIG_TOLERANCE = 0.0001
NUM_BINS = 50
NUM_TICKS = 5
ticklabelfont = mfont.FontProperties(family='Serif', style='normal', variant='normal', size=8)
framelabelfont = mfont.FontProperties(family='Serif', style='normal', variant='normal', size=8)
XX,YY,dv = get_matrix(Xmin,Xmax,Nx,Ymin,Ymax,Ny,
c,dip,L,W,US,UD,UT,LAMBDA,MU,DV=True)
UNIT = 1.0 #pow(10,-4) #GUESS?!?!?!
CLABEL = r'Gravitational potential change $[units??]$'
FMT = '%.4f'
Data = dv
filename,fault_type = get_filename(c,dip,L,W,US,UD,UT,'finding_cutoff_plots',
pre='potential')
R = []
def sin_o(dip):
if abs(np.sin(dip)) < TRIG_TOLERANCE :
return 0.0
else:
return np.sin(dip)
def cos_o(dip):
if abs(np.cos(dip)) < TRIG_TOLERANCE :
return 0.0
else:
return np.cos(dip)
cos_o_dip = cos_o(dip)
sin_o_dip = sin_o(dip)
#Centroid of fault segment
x_c = -0.5*W*cos_o_dip
y_c = 0.5*L
z_c = 0.5*W*sin_o_dip - c
for i in range(len(XX[0])):
for j in range(len(XX[1])):
x = XX[i][j]
y = YY[i][j]
dist_numerator = (x - x_c)**2 + (y-y_c)**2 + z_c**2
dist_denominator = float(L*W)
dist = np.sqrt(dist_numerator/dist_denominator)
R.append(dist)
R_bin_vals,counts = hist_1d(R,bmin=min(R),bmax=max(R),norm=True,num_bins=NUM_BINS)
this_fig = plt.figure()
fig_axes = plt.subplot(121)
plt.plot(R_bin_vals,counts,c='k')
# Make the figure
fig_axes = plt.subplot(122)
this_img = plt.imshow(Data/UNIT, origin = 'lower',interpolation='nearest',
extent=[Xmin/1000.0,Xmax/1000.0,Ymin/1000.0,
Ymax/1000.0],cmap=plt.get_cmap('seismic'))
# Tighten up the axis labels
img_ax = this_fig.gca()
img_ax.set_xlabel(r'along fault [$km$]',labelpad=-1, fontproperties=framelabelfont)
img_ax.set_ylabel(r'[$km$]',labelpad=-5, fontproperties=framelabelfont)
if _CLIMS:
LIM = 0.001
else:
max_val = abs(Data.max())
min_val = abs(Data.min())
LIM = max([max_val,min_val])
forced_ticks = [num for num in np.linspace(-LIM,LIM,NUM_TICKS)]
# Make color bar and put its label below its x-axis
divider = make_axes_locatable(fig_axes)
cbar_ax = divider.append_axes("top", size="5%",pad=0.02)
cbar = plt.colorbar(this_img,format=FMT,
orientation='horizontal',cax=cbar_ax,
ticks=forced_ticks)
plt.clim(-LIM,LIM)
# Make and position colorbar label
cbar_ax.set_xlabel(CLABEL,labelpad=-40, fontproperties=framelabelfont)
cbar_ax.tick_params(axis='x',labelbottom='off',labeltop='on',
bottom='off',top='off',right='off',left='off',pad=-0.5)
# Draw a projection of the fault
W_proj = W*np.cos(dip) #projected width of fault due to dip angle
fault_proj = mpl.patches.Rectangle((0.0,0.0),L/1000.0,W_proj/1000.0,
ec='c',fc='none',fill=False,
ls='solid')
fig_axes.add_patch(fault_proj)
for label in img_ax.xaxis.get_ticklabels()+img_ax.yaxis.get_ticklabels():
label.set_fontproperties(framelabelfont)
for label in cbar_ax.xaxis.get_ticklabels()+cbar_ax.yaxis.get_ticklabels():
label.set_fontproperties(ticklabelfont)
plt.clim(-LIM,LIM)
# Save the plot
if save:
plt.savefig(filename,dpi=300)
print '>>> plot saved: '+filename
if SHOW:
plt.show()
plt.clf()
#-----------------------------------------------------------------------------
def plot_dg_vs_uz_simple(Xmin,Xmax,Nx,Ymin,Ymax,Ny,c,dip,L,W,US,UD,UT,LAMBDA,MU,
LABELS=False,SUFFIX='none'):
from pyvc import vcutils
import os
ticklabelfont = mfont.FontProperties(family='Arial', style='normal', variant='normal', size=9)
framelabelfont = mfont.FontProperties(family='Arial', style='normal', variant='normal', size=10)
legendfont = mfont.FontProperties(family='Arial', style='normal', variant='normal', size=10)
titlefont = mfont.FontProperties(family='Arial', style='normal', variant='normal', size=12)
# Need to remove a cached file for Arial fonts to be used
if os.path.isfile('/home/kasey/.matplotlib/fontList.cache'):
os.remove('/home/kasey/.matplotlib/fontList.cache')
UNIT = float(pow(10,-8)) # 1 microgal in mks units is 10^(-8) m/s^2
dum,dum,DG = get_matrix(Xmin,Xmax,Nx,Ymin,Ymax,Ny,c,dip,L,W,US,UD,UT,LAMBDA,MU,DG=True)
dum,dum,DZ = get_matrix(Xmin,Xmax,Nx,Ymin,Ymax,Ny,c,dip,L,W,US,UD,UT,LAMBDA,MU,DZ=True)
del(dum)
## In units of microgals
DG_flat = DG.flatten()/UNIT
DZ_flat = DZ.flatten()
del(DG)
del(DZ)
if US>0.0:
fault_type = "strikeslip"
plot_lab = "Strike-slip"
if UD>0.0:
if UD>0:
fault_type = "thrust"
plot_lab = "Thrust"
if UD<0:
fault_type = "normal"
plot_lab = "Normal"
if UT>0.0:
fault_type = "tensile"
plot_lab = "Tensile"
dip_deg = int(round(dip*180.0/np.pi))
CC = int(round(c/1000.0))
LL = int(round(L/1000.0))
WW = int(round(W/1000.0))
if SUFFIX is not 'none':
output_file = "/home/kasey/Okubo-test/dg_vs_uz/dg_dz_{}_c{}km_L{}km_W{}km_dip{}_{}.png".format(fault_type,CC,LL,WW,dip_deg,SUFFIX)
else:
output_file = "/home/kasey/Okubo-test/dg_vs_uz/dg_dz_{}_c{}km_L{}km_W{}km_dip{}.png".format(fault_type,CC,LL,WW,dip_deg)
#Before plotting, clear the current axis and figure
plt.clf()
x_ave,y_ave = bin_2d(DZ_flat,DG_flat)
slope,intercept = get_slope_intercept(x_ave,y_ave)
y_fit = slope*x_ave + intercept
fit_label = 'slope = {:.3f}'.format(slope)
plt.plot(DZ_flat,DG_flat,'.',c='k')
plt.plot(x_ave,y_fit,c='grey',label=fit_label,lw=2)
this_ax = plt.gca()
this_ax.set_title(plot_lab, fontproperties=titlefont)
for label in this_ax.xaxis.get_ticklabels()+this_ax.yaxis.get_ticklabels():
label.set_fontproperties(ticklabelfont)
if LABELS:
XLABEL = r'vertical displacement $[m]$'
YLABEL = r'gravity change $[\mu gal]$'
this_ax.set_xlabel(XLABEL, fontproperties=framelabelfont)
this_ax.set_ylabel(YLABEL, fontproperties=framelabelfont)
this_ax.legend(loc=1,frameon=False,prop=legendfont)
plt.savefig(output_file,dpi=200)
"""vcutils.standard_plot(output_file,DZ_flat,DG_flat,
axis_format='plot',
add_lines=[{'label':'binned average', 'x':x_ave, 'y':y_ave}],
axis_labels = {'x':'vertical displacement [m]', 'y':r'gravity change [$\mu$gal]'},
plot_label=Plot_Label
)
"""
#-----------------------------------------------------------------------------
def plot_dg_vs_uz_event(evnum,sim_file):
from pyvc import vcutils
import os
ticklabelfont = mfont.FontProperties(family='Arial', style='normal', variant='normal', size=9)
framelabelfont = mfont.FontProperties(family='Arial', style='normal', variant='normal', size=10)
legendfont = mfont.FontProperties(family='Arial', style='normal', variant='normal', size=10)
titlefont = mfont.FontProperties(family='Arial', style='normal', variant='normal', size=12)
# Need to remove a cached file for Arial fonts to be used
if os.path.isfile('/home/kasey/.matplotlib/fontList.cache'):
os.remove('/home/kasey/.matplotlib/fontList.cache')
# get the gravity field of the event
UNIT = pow(10,-8) #microgals
dg_field,mag,slip,num_elem = get_field(evnum,sim_file,
field_type='gravity',
mag=True,avg_slip=True,
num_elem=True)
dg = dg_field.dG.flatten()/UNIT
# get the vertical displacement field of the event
dz_field = get_field(evnum,sim_file,field_type='displacement')
dz = dz_field.dZ.flatten()
#Before plotting, clear the current axis and figure
plt.clf()
# binning and fitting
x_ave,y_ave = bin_2d(dz,dg)
slope,intercept = get_slope_intercept(x_ave,y_ave)
y_fit = slope*x_ave + intercept
fit_label = 'slope = {:.3f}'.format(slope)
# plot the raw and binned & fitted data
plt.plot(dz,dg,'.',c='k')
plt.plot(x_ave,y_fit,c='grey',label=fit_label,lw=2)
this_ax = plt.gca()
# font and labels
PLOT_LABEL = 'Magnitude {:.2f} event, {} fault elements, avg. slip = {:.2f}m'.format(mag,slip,num_elem)
XLABEL = r'height change $[m]$'
YLABEL = r'gravity change $[\mu gal]$'
this_ax.set_title(PLOT_LABEL, fontproperties=titlefont)
for label in this_ax.xaxis.get_ticklabels()+this_ax.yaxis.get_ticklabels():
label.set_fontproperties(ticklabelfont)
this_ax.set_xlabel(XLABEL, fontproperties=framelabelfont)
this_ax.set_ylabel(YLABEL, fontproperties=framelabelfont)
this_ax.legend(loc=1,frameon=False,prop=legendfont)
# Saving
output_file = "/home/kasey/Okubo-test/dg_vs_uz/dg_dz_{}.png".format(evnum)
plt.savefig(output_file,dpi=200)
#-----------------------------------------------------------------------------
def get_field(evnum,sim_file,field_type='gravity',mag=False,avg_slip=False,
num_secs=False,num_elem=False):
from pyvc import *
from operator import itemgetter
from pyvc import vcplots
import sys
output_directory = 'animation_test_g/'
field_values_directory = '{}field_values/'.format(output_directory)
padding = 0.01
cutoff = None
with VCSimData() as sim_data:
sim_data.open_file(sim_file)
events = VCEvents(sim_data)
geometry = VCGeometry(sim_data)
min_lat = geometry.min_lat
max_lat = geometry.max_lat
min_lon = geometry.min_lon
max_lon = geometry.max_lon
base_lat = geometry.base_lat
base_lon = geometry.base_lon
event_data = events[evnum]
event_element_slips = events.get_event_element_slips(evnum)
event_sections = geometry.sections_with_elements(event_element_slips.keys())
if field_type=='gravity':
EF = vcplots.VCGravityField(min_lat, max_lat, min_lon, max_lon, base_lat, base_lon, padding=padding)
else:
EF = vcplots.VCDisplacementField(min_lat, max_lat, min_lon, max_lon, base_lat, base_lon, padding=padding)
field_values_loaded = EF.load_field_values('{}{}_'.format(field_values_directory, evnum))
if field_values_loaded:
sys.stdout.write('loaded'.format(evnum))
# If they havent been saved then we need to calculate them
elif not field_values_loaded:
sys.stdout.write('processing '.format(evnum))
sys.stdout.flush()
ele_getter = itemgetter(*event_element_slips.keys())
event_element_data = ele_getter(geometry)
if len(event_element_slips) == 1:
event_element_data = [event_element_data]
sys.stdout.write('{} elements :: '.format(len(event_element_slips)))
sys.stdout.flush()
EF.calculate_field_values(
event_element_data,
event_element_slips,
cutoff=cutoff,
save_file_prefix='{}{}_'.format(field_values_directory, evnum)
)
'{} elements in {} sections : '.format(len(event_element_slips), len(event_sections))
if mag or avg_slip or num_secs or num_elem:
returning = []
returning.append(EF)
if mag:
returning.append(event_data[3])
if avg_slip:
returning.append(event_data[13])
if num_secs:
returning.append(len(event_element_slips))
if num_elem:
returning.append(len(event_sections))
return returning
else:
return EF
#-----------------------------------------------------------------------------
def plot_dg_hist(evnum,sim_file,bin_min=-30.0,bin_max=-30.0,NUM_BINS=100,NORM=False):
from matplotlib import pyplot as plt
UNIT = pow(10,-8) #microgals
event_field = get_field(evnum,sim_file,field_type='gravity')
dg = event_field.dG.flatten()/UNIT
dg_bin_vals,counts = hist_1d(dg,bmin=bin_min,bmax=bin_max,norm=NORM,num_bins=NUM_BINS)
LABEL = 'M = '+str(round(mag,2))
plt.plot(dg_bin_vals,counts,label=LABEL,color='k')
plt.tick_params(axis='y',bottom='off',top='off',left='off',right='off',
labelbottom='off',labeltop='off',labelleft='off',labelright='off')
plt.tick_params(axis='x',top='off',bottom='off')
plt.legend(loc=2)
img_ax = plt.gca()
img_ax.set_xlabel(r'Gravity change $[\mu gal]$',labelpad=-1)
#plt.savefig('local/dg_hist_ev'+str(evnum)+'.png',dpi=200)
#plt.clf()
plt.show()
#-----------------------------------------------------------------------------
def plot_dg_hist_inset(evnum,sim_file,DG_MIN=-30.0,DG_MAX=30.0,NUM_BINS=100):
from pyvc import vcplots
from matplotlib import pyplot as plt
#******************************************
#evnum = 109382
#sim_file = 'ALLCAL2_1-7-11_no-creep_dyn-05_st-20.h5'
#*******************************************
out_file = 'local/dg_field_{}_hist_inset.png'.format(evnum)
# For this vvv to work you must go to vcplots and make this method return the figure
this_fig = vcplots.plot_event_field(sim_file,evnum,output_file=out_file,
save_file_prefix='animation_test_g/field_values/'+str(evnum)+'_',
field_type='gravity')
UNIT = pow(10,-8) #microgals
# Width and height are fixed
ph = 768.0
pw = 1024.0
width_frac = 200.0/pw
height_frac = 150.0/ph
left_frac = 130.0/pw
bottom_frac = 100.0/ph
event_field,mag = get_dg_field(evnum,sim_file)
dg = event_field.dG.flatten()/UNIT
dg_binned,counts = hist_1d(dg,bmin=DG_MIN,bmax=DG_MAX,num_bins=NUM_BINS,norm=True)
LABEL = r'$M={}$'.format(str(round(mag,1)))
hist_inset = this_fig.add_axes((left_frac,bottom_frac,width_frac,height_frac))
hist_inset.plot(dg_binned,counts,color='k')
hist_inset.tick_params(axis='y',bottom='off',top='off',left='off',right='off',
labelbottom='off',labeltop='off',labelleft='off',labelright='off')
hist_inset.tick_params(axis='x', labelsize='small')
#hist_inset.tick_params(axis='x',top='off',bottom='off')
# Make first and last ticks be <MIN and >MAX
#tick_labels = [item.get_text() for item in hist_inset.get_xticklabels()]
#tick_labels[0] = '<'+tick_labels[0]
#tick_labels[-1] = '>'+tick_labels[-1]
#hist_inset.set_xticklabels(tick_labels)
#hist_inset.legend(loc=2,frameon=False,numpoints=1,handlelength=0,handletextpad=0)
hist_inset.patch.set_alpha(0.0)
this_fig.savefig(out_file,dpi=200)
plt.clf()
def plot_number_area_data(sim_file, output_file=None, event_range=None):
from pyvc import *
from pyvc import vcplotutils
#Can't handle plot label if no event_range given
with VCSimData() as sim_data:
# open the simulation data file
sim_data.open_file(sim_file)
# instantiate the vc events class passing in an instance of the
# VCSimData class
events = VCEvents(sim_data)
# get the data
event_data = events.get_event_data(['event_number','event_area'], event_range=event_range)
start,end = event_range['filter']
duration = round(end-start)
#---------------------------------------------------------------------------
# Prepare the plot and do it.
#---------------------------------------------------------------------------
# initilize a dict to store the event counts and get the total number
# of events.
cum_num = {}
total_events = len(event_data['event_number'])
for num in range(total_events):
area = float(sorted(event_data['event_area'])[num])*float(pow(10,-6))
cum_num[area] = total_events - (num + 1)
sys.stdout.write("\nnumber of events : {}\n".format(total_events))
# dump the counts into x and y arrays for plotting. also, divide the count
# by the number of years so we get count per year.
x = []
y = []
for area in sorted(iter(cum_num)):
x.append(float(area))
y.append(float(cum_num[area]))
# create the line for b = 1
x_b1 = np.linspace(min(x),max(x),num=1000)
y_b1 = y[0]*x_b1[0]*(np.array(x_b1)**-1)
#sys.stdout.write(str(y_b1))
plt.title('Duration: {} years Total events: {}'.format(duration,total_events))
plt.plot(x_b1,y_b1,label='b=1',ls='-',lw=2,c='r')
plt.plot(x,y,'.',c='k')
plt.legend(loc='upper right')
plt.ylabel(r'$N (\geq A_r)$')
plt.xlabel(r'$A_r [km^2]$')
plt.xlim(-500,5500)
plt.ylim(-20,750)
plt.savefig(output_file,dpi=200)
# do the standard plot
"""vcplotutils.standard_plot(output_file, x, y,
axis_format='plot',
add_lines=[{'label':'b=1', 'x':x_b1, 'y':y_b1}],
axis_labels = {'y':'N', 'x':'rupture area [km^2]'},