-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathforward.py
More file actions
4303 lines (3562 loc) · 157 KB
/
Copy pathforward.py
File metadata and controls
4303 lines (3562 loc) · 157 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
'''
D. Melgar 02/2014
Forward modeling routines
'''
def waveforms(home,project_name,rupture_name,station_file,model_name,run_name,integrate,tsunami,hot_start,resample,beta):
'''
This routine will take synthetics and apply a slip dsitribution. It will delay each
subfault by the appropriate rupture time and linearly superimpose all of them. Output
will be one sac waveform file per direction of motion (NEU) for each station defined in the
station_file. Depending on the specified rake angle at each subfault the code will compute
the contribution to dip and strike slip directions. It will also compute the moment at that
subfault and scale it according to the unit amount of momeent (1e15 N-m)
IN:
home: Home directory
project_name: Name of the problem
rupture_name: Name of rupture description file
station_file: File with coordinates of stations
model_Name: Name of Earth structure model file
integrate: =0 if you want output to be velocity, =1 if you want output to de displacement
OUT:
Nothing
'''
from numpy import loadtxt,genfromtxt,allclose,vstack,deg2rad,array,sin,cos
from obspy import read,Stream
import datetime
import gc
print('Solving for kinematic problem')
#Output where?
outpath=home+project_name+'/output/forward_models/'
logpath=home+project_name+'/logs/'
log=''
#Time for log file
now=datetime.datetime.now()
now=now.strftime('%b-%d-%H%M')
#load source
source=loadtxt(home+project_name+'/forward_models/'+rupture_name,ndmin=2)
#Load stations
stagps_file=home+project_name+'/data/station_info/'+station_file
staname=genfromtxt(station_file,dtype="U",usecols=0)
#What am I processing v or d ?
if integrate==1:
vord='disp'
else:
vord='vel'
#Loop over stations
for ksta in range(hot_start,len(staname)):
print('Working on station '+staname[ksta]+' ('+str(ksta+1)+'/'+str(len(staname))+')')
#Initalize output
n=Stream()
e=Stream()
z=Stream()
sta=staname[ksta]
#Loop over sources (Add delays)
try:
for k in range(source.shape[0]):
if k%100==0:
print('... working on parameter '+str(k)+' of '+str(len(source)))
#Get subfault parameters
nfault='subfault'+str(int(source[k,0])).rjust(4,'0')
nsub='sub'+str(int(source[k,0])).rjust(4,'0')
zs=source[k,3]
ss_slip=source[k,8]
ds_slip=source[k,9]
#Rotate
if beta != None:
beta_rot=deg2rad(beta)
R=array([[cos(beta_rot),sin(beta_rot)],[-sin(beta_rot),cos(beta_rot)]])
rot=R.dot(vstack((ss_slip,ds_slip)))
ss_slip=rot[0]
ds_slip=rot[1]
rtime=source[k,12]
#Where's the data
strdepth='%.4f' % zs
if tsunami==False:
syn_path=home+project_name+'/GFs/dynamic/'+model_name+'_'+strdepth+'.'+nsub+'/'
else:
syn_path=home+project_name+'/GFs/tsunami/'+model_name+'_'+strdepth+'.'+nsub+'/'
#Get synthetics
ess=read(syn_path+sta+'.'+nfault+'.SS.'+vord+'.e')
nss=read(syn_path+sta+'.'+nfault+'.SS.'+vord+'.n')
zss=read(syn_path+sta+'.'+nfault+'.SS.'+vord+'.z')
eds=read(syn_path+sta+'.'+nfault+'.DS.'+vord+'.e')
nds=read(syn_path+sta+'.'+nfault+'.DS.'+vord+'.n')
zds=read(syn_path+sta+'.'+nfault+'.DS.'+vord+'.z')
#Decide if resampling is required
if resample!=None:
if resample < (1/ess[0].stats.delta): #Downsample
ess[0].resample(resample)
nss[0].resample(resample)
zss[0].resample(resample)
eds[0].resample(resample)
nds[0].resample(resample)
zds[0].resample(resample)
elif resample > (1/ess[0].stats.delta): #Upsample
upsample(ess,1./resample)
upsample(nss,1./resample)
upsample(zss,1./resample)
upsample(eds,1./resample)
upsample(nds,1./resample)
upsample(zds,1./resample)
dt=ess[0].stats.delta
#Time shift them according to subfault rupture time
ess=tshift(ess,rtime)
ess[0].stats.starttime=round_time(ess[0].stats.starttime,dt)
nss=tshift(nss,rtime)
nss[0].stats.starttime=round_time(nss[0].stats.starttime,dt)
zss=tshift(zss,rtime)
zss[0].stats.starttime=round_time(zss[0].stats.starttime,dt)
eds=tshift(eds,rtime)
eds[0].stats.starttime=round_time(eds[0].stats.starttime,dt)
nds=tshift(nds,rtime)
nds[0].stats.starttime=round_time(nds[0].stats.starttime,dt)
zds=tshift(zds,rtime)
zds[0].stats.starttime=round_time(zds[0].stats.starttime,dt)
if allclose((ss_slip**2+ds_slip**2)**0.5,0)==False: #Only add things that matter
log=log+nfault+', SS='+str(ss_slip)+', DS='+str(ds_slip)+'\n'
#A'ight, add 'em up
etotal=add_traces(ess,eds,ss_slip,ds_slip)
ntotal=add_traces(nss,nds,ss_slip,ds_slip)
ztotal=add_traces(zss,zds,ss_slip,ds_slip)
#Add to previous subfault's results
e=add_traces(e,etotal,1,1)
n=add_traces(n,ntotal,1,1)
z=add_traces(z,ztotal,1,1)
else:
log=log+"No slip on subfault "+nfault+', ignoring it...\n'
gc.collect()
#Save results
e.write(outpath+run_name+'.'+sta+'.'+vord+'.e',format='SAC')
n.write(outpath+run_name+'.'+sta+'.'+vord+'.n',format='SAC')
z.write(outpath+run_name+'.'+sta+'.'+vord+'.u',format='SAC')
except:
print('An error coccured, skipping station')
f=open(logpath+'waveforms.'+now+'.log','a')
f.write(log)
f.close()
def waveforms_matrix(home,project_name,fault_name,rupture_name,station_file,GF_list,
model_name,run_name,epicenter,time_epi,integrate,tsunami,hot_start,
resample,beta,rupture_speed,num_windows,dt,NFFT):
'''
To supplant waveforms() it needs to include resmapling and all that jazz...
This routine will take synthetics and apply a slip dsitribution. It will delay each
subfault by the appropriate rupture time and linearly superimpose all of them. Output
will be one sac waveform file per direction of motion (NEU) for each station defined in the
station_file. Depending on the specified rake angle at each subfault the code will compute
the contribution to dip and strike slip directions. It will also compute the moment at that
subfault and scale it according to the unit amount of momeent (1e15 N-m)
IN:
home: Home directory
project_name: Name of the problem
rupture_name: Name of rupture description file
station_file: File with coordinates of stations
model_Name: Name of Earth structure model file
integrate: =0 if you want output to be velocity, =1 if you want output to de displacement
OUT:
Nothing
'''
from numpy import loadtxt,genfromtxt,allclose,vstack,deg2rad,array,sin,cos,where,zeros,arange
from obspy import read,Stream,Trace
import datetime
import gc
from mudpy.inverse import getG
from linecache import getline
from os import remove
print('Solving for kinematic problem')
#Output where?
outpath=home+project_name+'/output/forward_models/'
logpath=home+project_name+'/logs/'
log=''
#Time for log file
now=datetime.datetime.now()
now=now.strftime('%b-%d-%H%M')
#load source
#source=loadtxt(home+project_name+'/forward_models/'+rupture_name,ndmin=2)
#Load stations
station_file=home+project_name+'/data/station_info/'+station_file
staname=genfromtxt(station_file,dtype="U",usecols=0)
#Now load rupture model
mss=genfromtxt(home+project_name+'/forward_models/'+rupture_name,usecols=8)
mds=genfromtxt(home+project_name+'/forward_models/'+rupture_name,usecols=9)
m=zeros(2*len(mss))
i=arange(0,2*len(mss),2)
m[i]=mss
i=arange(1,2*len(mds),2)
m[i]=mds
#What am I processing v or d ?
if integrate==1:
vord='disp'
else:
vord='vel'
#Load gflist
gfsta=genfromtxt(home+project_name+'/data/station_info/'+GF_list,usecols=0,skip_header=1,dtype='U')
#Loop over stations
for ksta in range(hot_start,len(staname)):
print('Working on station '+staname[ksta]+' ('+str(ksta+1)+'/'+str(len(staname))+')')
#Initalize output
n=Stream()
e=Stream()
z=Stream()
sta=staname[ksta]
#Make dummy data
ndummy=Stream(Trace())
ndummy[0].data=zeros(int(NFFT))
ndummy[0].stats.delta=dt
ndummy[0].stats.starttime=time_epi
edummy=ndummy.copy()
udummy=ndummy.copy()
ndummy.write(home+project_name+'/data/waveforms/'+sta+'.'+vord+'.n',format='SAC')
edummy.write(home+project_name+'/data/waveforms/'+sta+'.'+vord+'.e',format='SAC')
udummy.write(home+project_name+'/data/waveforms/'+sta+'.'+vord+'.u',format='SAC')
#Extract only one station from GF_list file
ista=int(where(gfsta==staname[ksta])[0])+2
#Make mini GF_file
tmpgf='tmpfwd.gflist'
try:
remove(home+project_name+'/data/station_info/'+tmpgf)
except:
pass
gflist=getline(home+project_name+'/data/station_info/'+GF_list,ista)
f=open(home+project_name+'/data/station_info/'+tmpgf,'w')
f.write('# Headers\n')
f.write(gflist)
f.close()
#Get matrix for one station to all sources
G_from_file=False
G_name='tmpfwd'
G=getG(home,project_name,fault_name,model_name,tmpgf,G_from_file,G_name,epicenter,
rupture_speed,num_windows,decimate=None,bandpass=None,tsunami=False)
# Matrix multiply and separate data streams
d=G.dot(m)
n=ndummy.copy()
e=edummy.copy()
u=udummy.copy()
ncut=len(d)/3
n[0].data=d[0:ncut]
e[0].data=d[ncut:2*ncut]
u[0].data=d[2*ncut:3*ncut]
# Write to file
n.write(home+project_name+'/output/forward_models/'+run_name+'.'+gfsta[ksta]+'.'+vord+'.n',format='SAC')
e.write(home+project_name+'/output/forward_models/'+run_name+'.'+gfsta[ksta]+'.'+vord+'.e',format='SAC')
u.write(home+project_name+'/output/forward_models/'+run_name+'.'+gfsta[ksta]+'.'+vord+'.u',format='SAC')
def waveforms_fakequakes(home,project_name,fault_name,rupture_list,GF_list,
model_name,run_name,dt,NFFT,G_from_file,G_name,source_time_function='dreger',zeta=0.2,
stf_falloff_rate=4.0,rupture_name=None,epicenter=None,time_epi=None,hot_start=0,
ncpus=1):
'''
To supplant waveforms_matrix() it needs to include resmapling and all that jazz...
Instead of doing matrix multiplication one stations at a time, do it for all stations
This routine will take synthetics and apply a slip dsitribution. It will delay each
subfault by the appropriate rupture time and linearly superimpose all of them. Output
will be one sac waveform file per direction of motion (NEU) for each station defined in the
station_file. Depending on the specified rake angle at each subfault the code will compute
the contribution to dip and strike slip directions. It will also compute the moment at that
subfault and scale it according to the unit amount of momeent (1e15 N-m)
IN:
home: Home directory
project_name: Name of the problem
rupture_name: Name of rupture description file
station_file: File with coordinates of stations
model_Name: Name of Earth structure model file
integrate: =0 if you want output to be velocity, =1 if you want output to de displacement
OUT:
Nothing
'''
from numpy import genfromtxt,array
from obspy import UTCDateTime
import datetime
import time
from dask.distributed import Client
print('Solving for kinematic problem(s)')
#Time for log file
now=datetime.datetime.now()
now=now.strftime('%b-%d-%H%M')
#load source names
if rupture_list==None:
#all_sources=array([home+project_name+'/forward_models/'+rupture_name])
all_sources=array([rupture_name])
else:
all_sources=genfromtxt(home+project_name+'/data/'+rupture_list,dtype='U')
all_sources = array(all_sources, ndmin=1) # in case only 1 entry
#Load all synthetics
print('... loading all synthetics into memory')
Nss,Ess,Zss,Nds,Eds,Zds=load_fakequakes_synthetics(home,project_name,fault_name,model_name,GF_list,
G_from_file,G_name)
print('... ... ... done')
# Need to know how many sites and delta t
station_file=home+project_name+'/data/station_info/'+GF_list
staname=genfromtxt(station_file,dtype="U",usecols=0)
Nsta=len(staname)
dt = Nss[0].stats.delta
# Need epicetrnal time from log file to trim synthetics
print('... reading epicentral time from log file. REMEMBER: All ruptures in ruptures.list should have a common epicentral time')
log_file = home + project_name + '/output/ruptures/' + all_sources[0].replace('.rupt','.log')
flog = open(log_file,'r')
while True:
line = flog.readline()
if 'Hypocenter time' in line:
hypocenter_time = line.replace('Hypocenter time: ','')
hypocenter_time = UTCDateTime(hypocenter_time)
break
elif line == '':
break
flog.close()
#Now get the impulse response G for all sites and all subfaults
print('... broadcast to G matrix')
Gimpulse_all = stream2matrix(Nss,Ess,Zss,Nds,Eds,Zds,hypocenter_time,Nsta)
print('... ... done')
#clean up
print('... clean up: removing obspy streams from memory')
del Nss,Ess,Zss,Nds,Eds,Zds
print('... ... done')
# print('... opening DASK client')
# client = Client(n_workers=ncpus)
#Now loop over rupture models
for ksource in range(hot_start,len(all_sources)):
rupture_name = all_sources[ksource]
print('... solving for source '+str(ksource)+' of '+str(len(all_sources))+': '+rupture_name)
if rupture_list != None:
#Get epicentral time
epicenter,time_epi = read_fakequakes_hypo_time(home,project_name,rupture_name)
forward = False
else:
forward = True #This controls where we look for the rupture file
# Put in matrix
t1=time.time()
# m,G=get_fakequakes_G_and_m(Nss,Ess,Zss,Nds,Eds,Zds,home,project_name,rupture_name,time_epi,GF_list,epicenter,NFFT,source_time_function,stf_falloff_rate,zeta,forward=forward)
m,G = get_fakequakes_G_and_m(Gimpulse_all,home,project_name,rupture_name,time_epi,GF_list,
epicenter,NFFT,source_time_function,stf_falloff_rate,zeta=zeta,
forward=forward,dt=dt,ncpus=ncpus,reconvolution=False)
t2=time.time()
print('... ... slip rate convolutions completed: wall time {:.1f}s'.format(t2-t1))
# Solve
print('... ... solve for waveforms (ncpus = %d)' % ncpus)
waveforms = G.dot(m)
#Write output
write_fakequakes_waveforms(home,project_name,rupture_name,waveforms,GF_list,NFFT,time_epi,dt)
print('... ... finished with this rupture')
# print('... clean up: closing distributed client')
# client.close()
def stream2matrix(Nss,Ess,Zss,Nds,Eds,Zds,hypocenter_time,Nsta):
'''
Converts stream objects to a properly formatted G matrix
Parameters
----------
Nss,Ess ... : Stream objects with synthetics for each component of motion and
for the ss and ds rake angles
hypocenter_time : UTCDateTime object with hypocentral timne, it's used to troim
the syntehtics to a single, common time
Nsta : int, number of stations being processed
Returns
-------
G = [ Nss_sta1_sf1 Nds sta1_ sf1 Nss_sta1_sf2 Nds sta1_ sf2 ...
Ess_sta1_sf1 Eds sta1_ sf1 Nss_sta1_sf3 Nds sta1_ sf3 ...
Zss_sta1_sf1 Zds sta1_ sf1 Nss_sta1_sf3 Nds sta1_ sf3 ...
Nss_sta2_sf1 Nds sta2_ sf1
Ess_sta2_sf1 Eds sta2_ sf1
Zss_sta2_sf1 Zds sta2_ sf1
...
'''
from numpy import ones
#How many time points in snthethics
Npts = Nss[0].stats.npts
#How many sources?
Nsources = int(len(Nss) / Nsta)
#Initalize G matrix
G = ones((Npts*Nsta*3,2*Nsources))
k=0
row_start = 0
row_end = Npts
for ksta in range(Nsta):
for ksub in range(Nsources):
#Assign individual GFs
nss = Nss[k]
ess = Ess[k]
zss = Zss[k]
nds = Nds[k]
eds = Eds[k]
zds = Zds[k]
# Trim to hypocentral time and pad
nss = trim_to_hypo_time_and_pad(nss,hypocenter_time,Npts)
ess = trim_to_hypo_time_and_pad(ess,hypocenter_time,Npts)
zss = trim_to_hypo_time_and_pad(zss,hypocenter_time,Npts)
nds = trim_to_hypo_time_and_pad(nds,hypocenter_time,Npts)
eds = trim_to_hypo_time_and_pad(eds,hypocenter_time,Npts)
zds = trim_to_hypo_time_and_pad(zds,hypocenter_time,Npts)
# Done, now place in correct position in matrix
G[row_start:row_end,2*ksub] = nss
G[row_start:row_end,2*ksub+1] = nds
G[row_start+Npts:row_end+Npts,2*ksub] = ess
G[row_start+Npts:row_end+Npts,2*ksub+1] = eds
G[row_start+2*Npts:row_end+2*Npts,2*ksub] = zss
G[row_start+2*Npts:row_end+2*Npts,2*ksub+1] = zds
k += 1
row_start += 3*Npts
row_end += 3*Npts
return G
def tele_waveforms(home,project_name,fault_name,rupture_list,GF_list_teleseismic,
model_name,run_name,G_from_file,G_name,source_time_function='dreger',zeta=0.2,
stf_falloff_rate=4.0,rupture_name=None,epicenter=None,time_epi=None,
hot_start=0,decimation_factor=1,reconvolution=True,ncpus=1):
'''
'''
from numpy import genfromtxt,array
import datetime
import gc
from obspy import UTCDateTime
print('Solving for kinematic problem(s)')
#Time for log file
now=datetime.datetime.now()
now=now.strftime('%b-%d-%H%M')
#load source names
if rupture_list==None:
all_sources=array([rupture_name])
else:
all_sources=genfromtxt(home+project_name+'/data/'+rupture_list,dtype='U')
#Load all synthetics
print('... loading all synthetics into memory')
Nss,Ess,Zss,Nds,Eds,Zds=load_fakequakes_tele_synthetics(home,project_name,fault_name,model_name,GF_list_teleseismic,G_from_file,G_name,decimation_factor)
print('... ... done')
# Need to know how many sites and delta t
station_file=home+project_name+'/data/station_info/'+GF_list_teleseismic
staname=genfromtxt(station_file,dtype="U",usecols=0)
Nsta=len(staname)
Npoints=Nss[0].stats.npts
dt=Nss[0].stats.delta
# Need epicetrnal time from log file to trim synthetics
print('... reading epicentral time from log file. REMEMBER: All ruptures in ruptures.list should have a common epicentral time')
log_file = home + project_name + '/output/ruptures/' + all_sources[0].replace('.rupt','.log')
flog = open(log_file,'r')
while True:
line = flog.readline()
if 'Hypocenter time' in line:
hypocenter_time = line.replace('Hypocenter time: ','')
hypocenter_time = UTCDateTime(hypocenter_time)
break
elif line == '':
break
flog.close()
#Now get the impulse response G for all sites and all subfaults
print('... broadcast to G matrix')
Gimpulse_all = stream2matrix(Nss,Ess,Zss,Nds,Eds,Zds,hypocenter_time,Nsta)
print('... ... done')
#clean up
print('... clean up: removing obspy streams from memory')
del Nss,Ess,Zss,Nds,Eds,Zds
print('... ... done')
#Now loop over rupture models
for ksource in range(hot_start,len(all_sources)):
print('... solving for source '+str(ksource)+' of '+str(len(all_sources)))
rupture_name=all_sources[ksource]
print('... ... '+rupture_name)
if rupture_list!=None:
#Get epicentral time
epicenter,time_epi=read_fakequakes_hypo_time(home,project_name,rupture_name)
forward=False
else:
forward=True #This controls where we look for the rupture file
# Put in matrix
if source_time_function == 'gauss_prem_i2s':
reconvolution = True
else:
reconvolution = False
m,G = get_fakequakes_G_and_m(Gimpulse_all,home,project_name,rupture_name,time_epi,GF_list_teleseismic,
epicenter,Npoints,source_time_function,stf_falloff_rate,zeta=zeta,
forward=forward,dt=dt,ncpus=ncpus,reconvolution=reconvolution)
# Solve
waveforms=G.dot(m)
print('... ... DONE! saving waveforms')
#Write output
write_fakequakes_waveforms(home,project_name,rupture_name,waveforms,GF_list_teleseismic,Npoints,time_epi,dt)
#Delete variables and garbage collect
del G
gc.collect()
def waveforms_fakequakes_dynGF(home,project_name,fault_name,rupture_list,GF_list,dynamic_GFlist,dist_threshold,
model_name,run_name,dt,NFFT,G_from_file,G_name,source_time_function='dreger',
stf_falloff_rate=4.0,rupture_name=None,epicenter=None,time_epi=None,
hot_start=0,ncpus=1):
'''
To supplant waveforms_matrix() it needs to include resmapling and all that jazz...
Instead of doing matrix multiplication one stations at a time, do it for all stations
This routine will take synthetics and apply a slip dsitribution. It will delay each
subfault by the appropriate rupture time and linearly superimpose all of them. Output
will be one sac waveform file per direction of motion (NEU) for each station defined in the
station_file. Depending on the specified rake angle at each subfault the code will compute
the contribution to dip and strike slip directions. It will also compute the moment at that
subfault and scale it according to the unit amount of momeent (1e15 N-m)
IN:
home: Home directory
project_name: Name of the problem
rupture_name: Name of rupture description file
station_file: File with coordinates of stations
model_Name: Name of Earth structure model file
integrate: =0 if you want output to be velocity, =1 if you want output to de displacement
dynamic_GFlist: A boolean (Useless for current version)
dist_threshold: A float, station to the closest subfault must be closer to this distance, otherwise skip it.
OUT:
Nothing
'''
from numpy import genfromtxt,array
import datetime
import numpy as np
try:
import multiprocessing as mp
import time
use_parallel=True
except:
print('Parallel waveform generation is unavailable...')
print('Please pip install multiprocessing')
print('Otherwise, this is now continue go with single cpu')
use_parallel=False
print('Solving for kinematic problem(s)')
#Time for log file
now=datetime.datetime.now()
now=now.strftime('%b-%d-%H%M')
#load source names
if rupture_list==None:
#all_sources=array([home+project_name+'/forward_models/'+rupture_name])
all_sources=array([rupture_name])
else:
all_sources=genfromtxt(home+project_name+'/data/'+rupture_list,dtype='U')
#Load all synthetics
print('... loading all synthetics into memory')
Nss,Ess,Zss,Nds,Eds,Zds=load_fakequakes_synthetics(home,project_name,fault_name,model_name,GF_list,G_from_file,G_name)
print('... ... done loading synthetics')
#Load GF_list
STAname=np.genfromtxt(home+project_name+'/data/station_info/'+GF_list,usecols=[0],skip_header=1,dtype='S6')
STA={sta.decode():nsta for nsta,sta in enumerate(STAname)}
def loop_sources(ksource):
print('...Solving for source '+str(ksource)+' of '+str(len(all_sources)))
rupture_name=all_sources[ksource]
###make new GF_list(dynamic GF_list)###
new_GF_list='subGF_list.rupt%06d.gflist'%(ksource) #make new GF_list for only close stations
sta_close_to_rupt(home,project_name,rupture_name,GF_list,dist_threshold,new_GF_list)
if rupture_list!=None:
#Get epicentral time
epicenter,time_epi=read_fakequakes_hypo_time(home,project_name,rupture_name)
forward=False
else:
forward=True #This controls where we look for the rupture file
# Put in matrix
#use only close stations (dynamic GF_list)
m,G=get_fakequakes_G_and_m_dynGF(Nss,Ess,Zss,Nds,Eds,Zds,home,project_name,rupture_name,time_epi,STA,new_GF_list,epicenter,NFFT,source_time_function,stf_falloff_rate,forward=forward)
# Solve
waveforms=G.dot(m)
##Write output
write_fakequakes_waveforms(home,project_name,rupture_name,waveforms,new_GF_list,NFFT,time_epi,dt)
if use_parallel:
print('Using cpu=',ncpus)
#Parallel(n_jobs=ncpus,backend='loky')(delayed(loop_sources)(ksource) for ksource in range(hot_start,len(all_sources))) #Oh no, this is REALLY slow why?
ps=[]
for ksource in range(hot_start,len(all_sources)):
p = mp.Process(target=loop_sources, args=([ksource]) )
ps.append(p)
#start running
queue=np.zeros(len(ps))
for i_ps in range(len(ps)):
if (i_ps%10==0):
print('now at',i_ps,'out of',len(ps))
ps[i_ps].start()
queue[i_ps]=1
while True:
#check running status
running_idx=np.where(queue==1)[0]
for ri in running_idx:
if not(ps[ri].is_alive()):
#finnish running, close
ps[ri].join()
#ps[ri]=0 #.join() still has issue...
queue[ri]=0
else:
continue
if len(np.where(queue==1)[0])<=ncpus:
#add a process
#print('number of processer=',len(np.where(queue==1)[0]),'add a process,now at',i)
break
else:
#print('number of queue reaches max:',nprocess,'try again later,now at',i)
time.sleep(0.5) #wait and try again later
#Final check if all the processes are done
while True:
if np.sum([nps.is_alive() for nps in ps ])==0:
break
else:
time.sleep(1)
else:
#Now loop over rupture models
for ksource in range(hot_start,len(all_sources)):
loop_sources(ksource)
'''
print('... solving for source '+str(ksource)+' of '+str(len(all_sources)))
rupture_name=all_sources[ksource]
print(rupture_name)
###make new GF_list(dynamic GF_list)###
new_GF_list='subGF_list.rupt%06d.gflist'%(ksource) #make new GF_list for only close stations
sta_close_to_rupt(home,project_name,rupture_name,GF_list,dist_threshold,new_GF_list)
if rupture_list!=None:
#Get epicentral time
epicenter,time_epi=read_fakequakes_hypo_time(home,project_name,rupture_name)
forward=False
else:
forward=True #This controls where we look for the rupture file
# Put in matrix
#use only close stations (dynamic GF_list)
m,G=get_fakequakes_G_and_m_dynGF(Nss,Ess,Zss,Nds,Eds,Zds,home,project_name,rupture_name,time_epi,STA,new_GF_list,epicenter,NFFT,source_time_function,stf_falloff_rate,forward=forward)
# Solve
waveforms=G.dot(m)
##Write output
#write_fakequakes_waveforms(home,project_name,rupture_name,waveforms,GF_list,NFFT,time_epi,dt)
#Write output
write_fakequakes_waveforms(home,project_name,rupture_name,waveforms,new_GF_list,NFFT,time_epi,dt)
'''
def hf_waveforms(home,project_name,fault_name,rupture_list,GF_list,model_name,run_name,dt,NFFT,G_from_file,
G_name,rise_time_depths,moho_depth_in_km,ncpus,source_time_function='dreger',duration=100.0,
stf_falloff_rate=4.0,hf_dt=0.02,Pwave=False,Swave=True,hot_start=0,stress_parameter=50,
high_stress_depth=1e4,kappa=None,Qexp=0.6,Qmethod='shallowest',scattering='off',Qc_exp=0,
baseline_Qc=100):
'''
Make semistochastic high frequency accelerograms
'''
from numpy import genfromtxt,ones
from mudpy import hfsims
all_sources=genfromtxt(home+project_name+'/data/'+rupture_list,dtype='U')
#Now loop over rupture models
Nsources=all_sources.size
for ksource in range(hot_start,Nsources):
print('... solving HF waveforms for source '+str(ksource)+' of '+str(Nsources))
if Nsources>1:
rupture_name=all_sources[ksource]
else:
rupture_name=str(all_sources)
#Get station info from GF_list
sta=genfromtxt(home+project_name+'/data/station_info/'+GF_list,usecols=[0],dtype='U')
lonlat=genfromtxt(home+project_name+'/data/station_info/'+GF_list,usecols=[1,2])
sta_lon=lonlat[:,0]
sta_lat=lonlat[:,1]
#Multi kappa?
if kappa == 'gflist': #from station files
station_kappa = genfromtxt(home+project_name+'/data/station_info/'+GF_list,usecols=[-1])
elif kappa == None: #default values
station_kappa = 0.04*ones(len(sta))
else: #one single value for all sites that is NOT the default
station_kappa = kappa*ones(len(sta))
comp=['N','E','Z'] #components to loop through
#Now loop over stations
# TODO: don't loop but run these in parallel
# if there are more stations than faults, go for station ncpu and
# if there are more fault than stations go for fault ncpu
# or if there are more components, then go for that.
for ksta in range(len(sta)):
#Now loop over components N,E,Z
kappa = station_kappa[ksta] # assign station specific kappa values
for kcomp in range(len(comp)):
#HF_sims stochastic simulation for single station, component
make_parallel_hfsims(home,project_name,rupture_name,ncpus,sta[ksta],sta_lon[ksta],sta_lat[ksta],
comp[kcomp],model_name,rise_time_depths[0],rise_time_depths[1],moho_depth_in_km,total_duration=duration,hf_dt=hf_dt,
Pwave=Pwave,Swave=Swave,stress_parameter=stress_parameter,high_stress_depth=high_stress_depth,Qexp=Qexp,
Qmethod=Qmethod,scattering=scattering,Qc_exp=Qc_exp,baseline_Qc=baseline_Qc)
#Combine the separate MPI outputs into one full waveform
write_parallel_hfsims(home,project_name,rupture_name,sta[ksta],comp[kcomp],remove=True)
def make_parallel_hfsims(home,project_name,rupture_name,ncpus,sta,sta_lon,sta_lat,component,model_name,rise_time_depths0,
rise_time_depths1,moho_depth_in_km,total_duration,hf_dt,Pwave,Swave,stress_parameter,
kappa=0.04,Qexp=0.6,high_stress_depth=30,Qmethod='shallowest',scattering='off',Qc_exp=0,
baseline_Qc=100):
'''
Set up for MPI calculation of HF stochastics
'''
from numpy import savetxt,arange,genfromtxt,where,atleast_2d
from os import environ
import subprocess
from shlex import split
#Calculate the necessary full-fault parameters before splitting up the faults over your ncpus
rupture=home+project_name+'/output/ruptures/'+rupture_name
fault=genfromtxt(rupture)
fault = atleast_2d(fault)
slip=(fault[:,8]**2+fault[:,9]**2)**0.5
subfault_M0=slip*fault[:,10]*fault[:,11]*fault[:,13]
subfault_M0=subfault_M0*1e7 #to dyne-cm
M0=subfault_M0.sum()
i=where(slip>0)[0]
N=len(i)
#Split rupture file into ncpu rupture files
for k in range(ncpus):
i=arange(k,len(fault),ncpus)
mpi_source=fault[i,:]
#fmt='%d\t%10.6f\t%10.6f\t%10.6f\t%10.6f\t%10.6f\t%10.6f\t%10.6f\t%10.6f\t%10.6f\t%10.6f\t%10.6f\t%10.6f\t%10.6E' #old
fmt='%d\t%10.6f\t%10.6f\t%10.4f\t%10.2f\t%10.2f\t%10.6f\t%10.6E\t%10.6E\t%10.6E\t%10.6f\t%10.6f\t%10.6E\t%10.6E\t%10.6E' #new
savetxt(home+project_name+'/output/ruptures/mpi_rupt.'+str(k)+'.'+rupture_name,mpi_source,fmt=fmt)
#Make mpi system call
print("MPI: Starting Stochastic High Frequency Simulation on ", ncpus, "CPUs")
mud_source=environ['MUD']+'/src/python/mudpy/'
mpi='mpiexec -n '+str(ncpus)+' python '+mud_source+'hfsims_parallel.py run_parallel_hfsims '+home+' '+project_name+' '+rupture_name+' '+str(N)+' '+str(M0)+' '+sta+' '+str(sta_lon)+' '+str(sta_lat)+' '+model_name+' '+str(rise_time_depths0)+' '+str(rise_time_depths1)+' '+str(moho_depth_in_km)+' '+component+' '+str(total_duration)+' '+str(hf_dt)+' '+str(stress_parameter)+' '+str(kappa)+' '+str(Qexp)+' '+str(Pwave)+' '+str(Swave)+' '+str(high_stress_depth)+' '+str(Qmethod)+' '+str(scattering)+' '+str(Qc_exp)+' '+str(baseline_Qc)
mpi=split(mpi)
p=subprocess.Popen(mpi)
p.communicate()
def run_hf_waveforms(home,project_name,fault_name,rupture_list,GF_list,model_name,run_name,dt,NFFT,G_from_file,
G_name,rise_time_depths,moho_depth_in_km,source_time_function='dreger',duration=100.0,
stf_falloff_rate=4.0,hf_dt=0.02,Pwave=False,hot_start=0,stress_parameter=50,
high_stress_depth=1e4,Qexp=0.6):
'''
Make semistochastic high frequency accelerograms
'''
from numpy import genfromtxt
#import datetime
from mudpy import hfsims
#load list of source names
all_sources=genfromtxt(home+project_name+'/data/'+rupture_list,dtype='U')
#Now loop over rupture models
Nsources=all_sources.size
for ksource in range(hot_start,Nsources):
print('... solving HF waveforms for source '+str(ksource)+' of '+str(Nsources))
if Nsources>1:
rupture_name=all_sources[ksource]
else:
rupture_name=str(all_sources)
print(rupture_name)
#Get epicentral time
epicenter,time_epi=read_fakequakes_hypo_time(home,project_name,rupture_name)
#Get station info from GF_list
sta=genfromtxt(home+project_name+'/data/station_info/'+GF_list,usecols=[0],dtype='U')
lonlat=genfromtxt(home+project_name+'/data/station_info/'+GF_list,usecols=[1,2])
comp=['N','E','Z'] #components to loop through
#Now loop over stations
for ksta in range(len(sta)):
#Now loop over components N,E,Z
for kcomp in range(len(comp)):
#HF_sims stochastic simulation for single station, component
hf_waveform=hfsims.stochastic_simulation(home,project_name,rupture_name,sta[ksta],lonlat[ksta,:],time_epi,
model_name,rise_time_depths,moho_depth_in_km,hf_dt=hf_dt,total_duration=duration,component=comp[kcomp],
Pwave=Pwave,stress_parameter=stress_parameter,high_stress_depth=high_stress_depth)
#Write to file
write_fakequakes_hf_waveforms_one_by_one(home,project_name,rupture_name,hf_waveform,comp[kcomp])
def write_parallel_hfsims(home,project_name,rupture_name,station,component,remove=False):
'''
Combine outputs from parallel hfsims into one complete waveform.
Delete the parallel hfsims outputs when complete.
'''
from glob import glob
from obspy import read
import os
#rupture=rupture_name.split('.')[0]+'.'+rupture_name.split('.')[1]
#new
rupture = rupture_name.rsplit('.', 1)[0]
parallel_waveforms=glob(home+project_name+'/output/waveforms/'+rupture+'/'+station+'.HN'+component+'.[0-9][0-9][0-9].sac')
#print "Number of MPI outputs: " + str(len(parallel_waveforms))
if len(parallel_waveforms)==0:
print("No waveforms at this location to add in")
else:
for r in range(len(parallel_waveforms)):
#print parallel_waveforms[r]
st=read(parallel_waveforms[r])
if r==0:
#stdout.write(' [.'); stdout.flush()
complete_waveform=st.copy()
else:
#stdout.write('.'); stdout.flush()
complete_waveform[0].data=complete_waveform[0].data+st[0].data
complete_waveform.write(home+project_name+'/output/waveforms/'+rupture+'/'+station+'.HN'+component+'.mpi.sac',format='SAC')
if remove==True:
for r in range(len(parallel_waveforms)):
os.remove(parallel_waveforms[r])
else:
print("Keeping all parallel output files because you didn't tell me to delete them")
def write_fakequakes_hf_waveforms_one_by_one(home,project_name,rupture_name,hf_trace,component):
'''
write HF waveforms to file as they are created, station by station, component by component
'''
from os import path,makedirs
#Where am I writing to?
#rupture=rupture_name.split('.')[0]+'.'+rupture_name.split('.')[1]
#new
rupture = rupture_name.rsplit('.', 1)[0]
directory=home+project_name+'/output/waveforms/'+rupture+'/'
#Check if dir exists if not then create it
if not path.exists(directory):
makedirs(directory)
sta=hf_trace.stats.station
hf_trace.write(directory+sta+'.HN'+component+'.sac',format='SAC')
def write_fakequakes_hf_waveforms(home,project_name,rupture_name,n,e,z):
'''
write HF waveforms to file
'''
from os import path,makedirs
from numpy import genfromtxt,squeeze,sqrt
from obspy import Stream,Trace
#Where am I writing to?
#rupture=rupture_name.split('.')[0]+'.'+rupture_name.split('.')[1]
#new
rupture = rupture_name.rsplit('.', 1)[0]
directory=home+project_name+'/output/waveforms/'+rupture+'/'
#Check if dir exists if not then create it
if not path.exists(directory):
makedirs(directory)
for ksta in range(len(n)):
sta=n[ksta].stats.station
n[ksta].write(directory+sta+'.HNN.sac',format='SAC')
e[ksta].write(directory+sta+'.HNE.sac',format='SAC')
z[ksta].write(directory+sta+'.HNZ.sac',format='SAC')
def match_filter(home,project_name,fault_name,rupture_list,GF_list,
zero_phase=False,order=2,fcorner_low=1.0, fcorner_high=1.0):
'''
match filter waveforms
'''
from numpy import genfromtxt,where,r_,diff,interp
from obspy import read
#read stations list
sta=genfromtxt(home+project_name+'/data/station_info/'+GF_list,usecols=0,dtype='U')
ista=genfromtxt(home+project_name+'/data/station_info/'+GF_list,usecols=4)
ista=where(ista==1)[0]
sta=sta[ista]
#read ruptures
ruptures=genfromtxt(home+project_name+'/data/'+rupture_list,dtype='U')
Nruptures=ruptures.size
for krup in range(Nruptures):
if Nruptures>1:
rupture_name=ruptures[krup]
else:
rupture_name=str(ruptures)
rupture=rupture_name.replace('.rupt','')
directory=home+project_name+'/output/waveforms/'+rupture+'/'
print('Running matched filter for all stations for rupture '+ rupture_name)
#Get epicentral time
epicenter,time_epi=read_fakequakes_hypo_time(home,project_name,rupture_name)
for ksta in range(len(sta)):
#Read HF accelerograms
try:
hf_n=read(directory+sta[ksta]+'.HNN.sac')
hf_e=read(directory+sta[ksta]+'.HNE.sac')
hf_z=read(directory+sta[ksta]+'.HNZ.sac')
except:
hf_n=read(directory+sta[ksta]+'.HNN.mpi.sac')
hf_e=read(directory+sta[ksta]+'.HNE.mpi.sac')
hf_z=read(directory+sta[ksta]+'.HNZ.mpi.sac')