-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
executable file
·2070 lines (1720 loc) · 68.4 KB
/
utils.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
#!/usr/bin/env python
"""
Utilities for CyberShake related
"""
# General libraries
import os,sys, shutil
import glob, time
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from time import sleep
import MySQLdb as mdb
import pyproj
# =============
# NGA package with Directivity
# =============
from pynga import *
from pynga.CB08 import *
from pynga.BA08 import *
from pynga.CY08 import *
from pynga.AS08 import *
from pynga.SC08 import *
from pynga.utils import *
# ================
# Geo related utilities
# ================
def projection(x,y,**kwds):
"""
Projection of lon/lat to UTM or reverse direction
input:
x,y ( lon/lat or x/y )
kwds: zone, origin, rot, inverse
output:
x,y ( x/y or lon/lat )
"""
zone = kwds['zone']
origin = kwds['origin']
rot = kwds['rot']
inverse = kwds['inverse']
if origin == None:
return
# geometrical origin
x0 = origin[0]; y0 = origin[1]
rot = rot*np.pi/180.
c,s = np.cos(rot),np.sin(rot)
x = np.array(x,'f')
y = np.array(y,'f')
proj = pyproj.Proj(proj='utm',zone=zone,ellps='WGS84')
if inverse:
x0,y0 = proj(x0,y0,inverse=False)
x,y = c*x-s*y, s*x+c*y
x,y = x+x0,y+y0
x,y = proj(x,y,inverse=True)
else:
x0,y0 = proj(x0,y0,inverse=False)
x,y = proj(x,y,inverse=False)
x,y = x-x0,y-y0
x,y = x*c+y*s, -s*x+c*y
return x,y
# point and a plane
def point_plane(point0,points):
"""
point and line relationship
distance and the coordinate on a plane
reference:
http://jtaylor1142001.net/calcjat/Solutions/VPlanes/VP3Pts.htm
http://www.9math.com/book/projection-point-plane
Input:
point0: a point outside or within the plane
points (3 row, 3 col LIST contains three know points on the plane)
Output:
D: distance between point0 and the plane
point1: projection point of point0 on the plane
"""
points = np.array(points)
vn = np.cross(points[1,:]-points[0,:], points[2,:]-points[0,:]) # plane normal
vn = vn / np.sqrt( np.dot(vn,vn) ) # get the normal vector of the plane
a = vn[0]; b = vn[1]; c = vn[2]
d = -a*points[0,0]-b*points[0,1]-c*points[0,2]
u,v,w = point0
L1 = a*u+b*v+c*w+d
L2 = a**2+b**2+c**2
x = u-a*L1/L2
y = v-b*L1/L2
z = w-c*L1/L2
point1 = x,y,z
dist = abs( L1 )/ np.sqrt( L2 )
return dist, point1
# ==========================================================
# General interpolation (1D and 2D, or even 3D) based on lease-square inversion
# the both known points and unknown points could be irregular!
def interp(xj,yj,zj,xi,yi,debug=0,eps=0.1,method={'name':'exp','smooth':10}):
"""
General 1d and 2d interpolation based on inversion theory
Input:
(xj,yj): location for known point j (j = 1,2,...,N)
yj = None: 1D case
zj: data points for point j
(xi,yi): location for esitmated point i (i = 1,2,...,M)
yi = None: 1D case
debug: for debug (=1)
method: dictionary for different covariance matrix
eps: noise ( the smaller, the better )
Note: smooth factor in method name = 'exp' should be small two, otherwise, it will be too sharp
it will be order of .1 or smaller in order to get good interpolation
Output:
zi: interpolated value for point i
"""
import scipy.linalg
# 1. C^ff_jj*(B_ij).T
N = len(xj); M = len(xi)
mtype = method['name']
if debug == 1:
print 'problem size: M,N = %d, %d'%(M,N)
if mtype == 'exp':
smooth = method['smooth']
dis1 = np.zeros( (M,N) )
dis2 = np.zeros( (N,N) )
xxj, xxi = np.meshgrid( xj,xi )
dis1 = abs(xxi-xxj) # might cause the problem of singularity when input coordinates are in lon/lat
xxj1, xxj2 = np.meshgrid( xj, xj )
dis2 = abs(xxj1-xxj2)
if yj != None:
yyj,yyi = np.meshgrid( yj,yi )
dyy = yyi-yyj
yyj1, yyj2 = np.meshgrid( yj, yj )
dyy1 = yyj1-yyj2
dis1 = np.sqrt( dis1**2 + dyy**2 )
dis2 = np.sqrt( dis2**2 + dyy1**2 )
if debug == 1:
print 'distance size should be: (%d, %d) and (%d, %d)'%(M,N,N,N)
print 'Actual size is: ', dis1.shape,dis2.shape
print 'distance computed'
A1 = np.exp( -smooth*dis1 ) # C_ff*B
A2 = np.exp( -smooth*dis2 ) # B*C_ff*B
# correction for eps == 0:
if eps == 0:
eps = 0.0001
# common for every option
for j in xrange( N ):
A2[j,j] += eps**2 # (B*C_ff*B+C_nn)
A22 = scipy.linalg.inv( A2 ) # (B*C_ff*B.T+C_nn)^-1
if debug == 1:
print 'A1 A2 size should be: (%d, %d) and (%d, %d)'%(M,N,N,N)
print 'A1 and A2 actual size are: ', A1.shape, A22.shape
print 'A1, A2 computed'
zi = scipy.matrix(A1)*scipy.matrix(A22)*scipy.matrix(zj).T
zi = scipy.array( zi )
return zi[:,0]
def GetKey4(group_i,index_j,rup_var_id, Ti):
"""
Generate key for rupture variations (related to hypocenter group)
"""
return '(%s,%s,%s,%s)'%(group_i,index_j,rup_var_id,Ti)
def GetKey2(ih, Ti):
"""
Generate key for ihypo and T_i (related to hypocenter group)
"""
return '(%s,%s)'%(ih,Ti)
# communicate with HPC to download files
# This can be used for other platforms
def hpc_scp(srcfile, dst, machine='hpc', opt='-r', inverse=False):
# transfer file between local machine and hpcc
# inverse = False: Download from hpc
# inverse = True: Upload to hpc
usrnam = 'fengw@hpc-login1.usc.edu:'
scp = 'scp'
if inverse == False:
if not os.path.exists( dst ):
os.mkdir(dst)
prefix = ' '.join( (scp,opt,usrnam) )
cmd = ' '.join( (prefix+srcfile, dst+os.sep) )
#print cmd
os.system( cmd )
else:
prefix1 = ' '.join((scp,opt))
prefix2 = usrnam
cmd = ' '.join( (prefix1, srcfile, prefix2 + dst + os.sep) )
#print cmd
os.system( cmd )
# ================================================
# waveform extraction
# ================================================
def ExtractRups(cursor,sids,rids,erf_id=35,rup_scenario_id=3):
# can be modified
rups_info = {}
if rup_scenario_id == 4:
rup_scenario_id = 3
# rupture variation model
hypoStartIndex = 2 # s0000-h0000
if rup_scenario_id > 4:
hypoStartIndex = 1 # r000001
for irup in xrange( len(sids) ):
sid = sids[irup]
rid = rids[irup]
sr_key = '%s_%s'%(sid,rid)
# Ruptures
query = "select * from %s where %s = %s and %s = %s and %s = %s"%\
('Ruptures','ERF_ID',erf_id,'Source_ID',sid,'Rupture_ID',rid)
cursor.execute( query ) # run query
row_rup = cursor.fetchone()
nvar = len(row_rup)
if nvar == 0:
print 'There is no rupture for (erf_id,rup_var_id,sid,rid) = (%s,%s,%s,%s)\n'%(erf_id,rup_scenario_id,sid,rid)
return rups_info
else:
pass
# Rupture Variances (hypocenter and slip)
query = "select * from %s where ERF_ID = %s and Rup_Var_Scenario_ID = %s and Source_ID = %s and Rupture_ID = %s"%('Rupture_Variations',erf_id,rup_scenario_id,sid,rid)
cursor.execute( query ) # run query
row_rup_var = cursor.fetchall()
nvar = len(row_rup_var)
if nvar == 0:
print 'There is no rupture variations for (erf_id,rup_var_id,sid,rid) = (%s,%s,%s,%s)\n'%(erf_id,rup_scenario_id,sid,rid)
return rups_info
else:
pass
# regroup the hypocenter and slip variation
for k in xrange( len(row_rup_var) ):
slip_hypo = row_rup_var[k][5].strip().split('-')
tmp = int(slip_hypo[hypoStartIndex][1:])
if tmp != k:
break
Nh = tmp + 1
Ns = nvar/Nh
rups_info[sr_key] = [Nh,Ns]
return rups_info
def ExtractListGen(cursor, Sites, Sources, Ruptures, fid, rup_model_ids=(35,5,3,1), ih=None, islip=None, bb=None ):
erf_id, sgt_id, rup_scenario_id, vel_id = rup_model_ids
rups_info = ExtractRups( cursor, Sources, Ruptures, erf_id=erf_id, rup_scenario_id = rup_scenario_id )
SourceRups = []
for stanam in Sites:
# Get site id for further selection
query = "select * from %s where %s = '%s'"%('CyberShake_Sites','CS_Short_Name',stanam)
cursor.execute( query ) # run query
row_sites = cursor.fetchone()
# fetch run id (select verified runs)
# and also Max_Frequency and Low_Frequency_Cutoff to get deterministic and broadband
if bb == None:
query = "select * from %s where ERF_ID = %s and \
SGT_Variation_ID = %s and Rup_Var_Scenario_ID = %s and Velocity_Model_ID= %s and \
Site_ID = %s and Status = '%s'"%('CyberShake_Runs',erf_id,sgt_id, rup_scenario_id, vel_id, row_sites[0],'Verified')
else:
query = "select * from %s where ERF_ID = %s and \
SGT_Variation_ID = %s and Rup_Var_Scenario_ID = %s and Velocity_Model_ID= %s and \
Site_ID = %s and Status = '%s' and Max_Frequency = %s"%('CyberShake_Runs',erf_id,sgt_id, rup_scenario_id, vel_id, row_sites[0],'Verified', bb)
cursor.execute( query ) # run query
try:
row_run = cursor.fetchone()
Nrun = len( row_run )
site_run_id = row_run[0]
except:
print 'There is no verified run for parameter set (erfid,sgtid,rup_var_scenario_id,vel_id,site_name)=(%s,%s,%s,%s,%s)\n'%(erf_id,sgt_id,rup_scenario_id,vel_id,stanam)
continue
RunID = '%s'%site_run_id
sids = []; rids = []
for irup in xrange( len(Sources) ):
sid = Sources[irup]
rid = Ruptures[irup]
# CyberShake_Site_Ruptures selection
query = "select * from %s where CS_Site_ID = %s and Source_ID = %s and Rupture_ID = %s"%('CyberShake_Site_Ruptures',row_sites[0],sid,rid)
cursor.execute( query ) # run query
row_site_rup = cursor.fetchall()
nvar = len(row_site_rup)
if nvar == 0:
print 'There is no ruptures for (Site_name, Site_ID, run_id, sid,rid) = (%s, %s,%s,%s,%s)\n'%(row_sites[2],row_sites[0],site_run_id,sid,rid)
continue
sr_key = '%s_%s'%(sid,rid)
sids.append(sid)
rids.append(rid)
Nh,Ns = rups_info[sr_key]
Nvar = Nh*Ns
if ih == None and islip == None:
# choose the center hypocenter location and slip = 1, 2 for this hypocenter?
ih = int(Nh/2) # centroid biased
# since for one hypocenter, there are two more slip distributions generated (Ns = 2*Nh for each hypocenter, but we only take the two generated for the hypocenter)
islip1 = 2*ih
ivar1 = HypoSlip2RupVar((ih,islip1), Nh, Ns)
islip2 = 2*ih + 1
ivar2 = HypoSlip2RupVar((ih,islip2), Nh, Ns)
#print sr_key, Nh, Ns, ih, ivar1, ivar2
fid.write( '%s %s %s %s %s\n'%(stanam,RunID,sid,rid,ivar1) )
fid.write( '%s %s %s %s %s\n'%(stanam,RunID,sid,rid,ivar2) )
else:
ivar = HypoSlip2RupVar((ih,islip), Nh, Ns)
fid.write( '%s %s %s %s %s\n'%(stanam,RunID,sid,rid,ivar) )
SourceRups.append( [sids,rids] )
return Sites, SourceRups
# ==================================
# CyberShake NGA related
# ==================================
def cybershk_sites(sitedata):
"""
All CyberShake Sites information (Vs30, Z2.5, Z1.0 etc.)
sitedata give the full path of the site file
"""
sites = {}
# required header of the sitedata file
keys = 'lat','lon', 'Vs30_Wills_2006', 'Vs30_Wald_2007', 'Z2.5', 'Z1.0' # Z2.5,Z1.0 all in km !!
lines = open( sitedata, 'r' ).readlines()
for i in range( 1, len(lines) ):
spl = lines[i].strip().split()
name = spl[0]
sites[name] = {}
for ikey in xrange( len(keys) ):
sites[name][keys[ikey]] = spl[ikey+1]
return sites
# Source related
def RupSelect(sids,cybershk_database_password, erf_id=35):
"""
Select from UCERF and CyberShake database (by Region and Magnitude)
Input:
Select Dictionary (contain all information need to select ruptures)
erf_id = 35 (CyberShake database)
Output:
sids
rids
"""
rids = []; sids0 = []
hostname = 'focal.usc.edu' # host
username = 'cybershk_ro' # usrname
password = cybershk_database_password # password
database = 'CyberShake' # Database name
db = mdb.connect( host = hostname, user = username, \
passwd = password, db = database )
cursor = db.cursor()
# constains on Ruptures Table in CyberShake to Select Ruptures
Nsid = len(sids)
for isid in xrange( Nsid ):
sid = sids[isid]
query = 'select * from Ruptures where ERF_ID=%s and Source_ID=%s'%(erf_id,sid)
cursor.execute( query )
rows = cursor.fetchall()
Nrup = len(rows)
rid0 = []; sid0 = []; Mws = []
Area = rows[-1][10] # preserve the rupture area!
for irup in xrange( Nrup ):
# deal with different cases
if rows[irup][10] == Area:
if not rows[irup][5] in Mws:
rid0.append( rows[irup][2] )
Mws.append( rows[irup][5] )
sid0.append( sid )
else:
continue
sids0.append(sid0)
rids.append( rid0 )
cursor.close()
db.close()
return sids0, rids
# =============================
# Extract Rupture Info from CyberShake Database
# =============================
def rup_gen(cursor, sid, rups_info, fid_stdout, erf_id=35, rup_scenario_id=3, hypo_info=True):
"""
Extract src detail info from UCERF
Given one source, get all source infomation:
stress drop variability (Mw)
hypocenter location (Nh)
slip distribution (Nvar)
"""
# correction (due to database error)
# for example: select * from Rupture_Variations where ERF_ID=35 and Source_ID=10 and Rupture_ID=3 and Rup_Var_Scenario_ID=4
# which gives all the same hypocenter locations (just this)
if rup_scenario_id == 4:
rup_scenario_id = 3
# Ruptures (consistent with Points, use erf_id = 35 since right now ERF_ID = 36 has no Points table in the database)
# The change from 35 to 36 is the resolution of the fault surface, the fault location and dimension stays the same!
query = "select * from Ruptures where ERF_ID = %s and Source_ID = %s"%(35,sid)
cursor.execute( query ) # run query
row_rup = cursor.fetchall()
Nrup = len(row_rup)
if Nrup == 0:
fid_stdout.write('There is no SourceID=%s for erf_id = %s\n'%(sid, erf_id))
return rups_info
else:
pass
# fault information (use the last one)
SourceName = row_rup[-1][3] # section name
Nrow = row_rup[-1][8] # vertical points on the fault plane
Ncol = row_rup[-1][9] # horizontal poinst on the fault plane
Mws = []; rids = []
Area = row_rup[-1][10] # preserve the rupture area!
for irup in xrange( Nrup ):
# deal with different cases
if row_rup[irup][10] == Area:
if not row_rup[irup][5] in Mws:
rids.append( row_rup[irup][2] )
Mws.append( row_rup[irup][5] )
else:
continue
# Fault surface and trace line
# use the last Rupture ID to get the Full length of fault segment (Type A) [for ERF=36, use ERF=35]
query = "select * from Points where ERF_ID= %s and Source_ID= %s and Rupture_ID=%s"%(35, sid, Nrup-1)
cursor.execute( query )
row_point = cursor.fetchall()
Npoints = len(row_point)
if Npoints == 0:
fid_stdout.write('There is no faults surface points for (erf_id,sid) = (%s,%s)\n'%(erf_id,sid))
return rups_info
else:
pass
row_point = np.array( row_point )
Ztor = row_point[0,6]
Zbom = row_point[-1,6]
rake = np.mean( row_point[:,7] )
dip = np.mean( row_point[:,8] )
# surface points
index_surf = (row_point[:,6] == Ztor).nonzero()[0]
lon = row_point[index_surf,5]
lat = row_point[index_surf,4]
strike = row_point[index_surf,9]
# decimate the surface points
dec = 5
lon = lon[::dec].tolist()
lat = lat[::dec].tolist()
strike = strike[::dec].tolist()
# all fault points
lonf = row_point[:,5].tolist()
latf = row_point[:,4].tolist()
depf = row_point[:,6].tolist()
if hypo_info == True:
# Rupture Variances (hypocenter and slip)
query = "select * from %s where ERF_ID = %s and Rup_Var_Scenario_ID = %s and Source_ID = %s and Rupture_ID = %s"%('Rupture_Variations',erf_id,rup_scenario_id,sid,Nrup-1)
cursor.execute( query ) # run query
row_rup_var = cursor.fetchall()
nvar = len(row_rup_var)
if nvar == 0:
fid_stdout.write('There is no rupture variations for (erf_id,rup_var_id,sid) = (%s,%s,%s)\n'%(erf_id,rup_scenario_id,sid))
return rups_info
else:
pass
# regroup the hypocenter and slip variation
tmp = row_rup_var[-1][5].strip().split('-')
if rup_scenario_id <= 4:
Nh = int(tmp[2][1:]) + 1
Nf = int(tmp[1][1:]) + 1
else:
# new rupture variation model
Nh = int(tmp[1][1:]) + 1
Nf = 1
hypo_loc = {}
# get hypocenter locations
for ih in xrange( Nh ):
# attention: for the new rupture generator, the rupture variations are the combination of
# s and h. for example, for the same h id, but different s id, the hypocenter locations are not the same due to
# the randomization process, for the old rupture generator, for the same h id, the location and
# the depth are the same regardless the s id.
rup_var_id = HypoSlip2RupVar( (ih,0), Nh, Nf )
hypo_key = 'h%4.4i'%ih
hlon = row_rup_var[rup_var_id][7]
hlat = row_rup_var[rup_var_id][6]
hdep = row_rup_var[rup_var_id][8]
hypo_loc[hypo_key] = [hlon,hlat,hdep]
rups_info['hypo_slip'] = [Nh, Nf, hypo_loc]
else:
rups_info['hypo_slip'] = []
# Save fault geometry info to dictionary for further use
rups_info['name'] = SourceName
rups_info['MR'] = [Mws,rids,Nrow,Ncol,rake,dip,Ztor,Zbom] # magnitude and points on the fault, averege rake, dip, Ztor, and Zbom
rups_info['surface'] = [lon,lat,strike] # fault plane surface projection
rups_info['fault'] = [lonf, latf, depf] # fault plane
return rups_info
def HypoSlip2RupVar(index, Nh, Nf, inverse=False):
"""
Relation between rupture variation ID and hypocenter and slip distribution ID
"""
if not inverse:
ih, islip = index
ivar = islip * Nh + ih
else:
for islip in xrange( Nf ):
for ih in xrange( Nh ):
if index == islip * Nh + ih:
ivar = (ih, islip)
break
return ivar
# ========================================
# Extract IM data from CyberShake databas
# ========================================
def im_gen(cursor, sid, rid, stanam, \
sites_info, Ek,\
fid_stdout, rup_model_ids=(35,5,3,1), bb=None, site_only=False):
"""
Give CyberShake site (stanam), UCERF2.0 Source (sid)
rup_model_ids = (erf_id, sgt_id, rup_var_scenario_id, velocity_id)
if site_only == True, then just save the site info, not other
bb = None: get the deterministic runs
bb = 0: get all verified simulations
otherwise Max_Frequency = bb
"""
debugPlot = False
#if stanam == 'STNI': debugPlot = True
#if debugPlot: print stanam
# CyberShake study
erf_id, sgt_id, rup_scenario_id, vel_id = rup_model_ids
# Get site id for further selection
query = "select * from %s where %s = '%s'"%('CyberShake_Sites','CS_Short_Name',stanam)
#if debugPlot: print query
cursor.execute( query ) # run query
row_sites = cursor.fetchone()
# fetch run id (select verified runs)
# and also Max_Frequency and Low_Frequency_Cutoff to get deterministic and broadband
if bb == None:
# just use the low frequency runs
query = "select * from %s where ERF_ID = %s and \
SGT_Variation_ID = %s and Rup_Var_Scenario_ID = %s and Velocity_Model_ID= %s and \
Site_ID = %s and Status = '%s' and Max_Frequency IS %s"%('CyberShake_Runs',erf_id,sgt_id, rup_scenario_id, vel_id, row_sites[0],'Verified', 'NULL')
else:
if bb != 0:
# specify the max frequency
query = "select * from %s where ERF_ID = %s and \
SGT_Variation_ID = %s and Rup_Var_Scenario_ID = %s and Velocity_Model_ID= %s and \
Site_ID = %s and Status = '%s' and Max_Frequency = %s"%('CyberShake_Runs',erf_id,sgt_id, rup_scenario_id, vel_id, row_sites[0],'Verified', bb)
else:
# include all (there might be repeated sites, this extraction will overwrite the existing sites)
query = "select * from %s where ERF_ID = %s and \
SGT_Variation_ID = %s and Rup_Var_Scenario_ID = %s and Velocity_Model_ID= %s and \
Site_ID = %s and Status = '%s'"%('CyberShake_Runs',erf_id,sgt_id, rup_scenario_id, vel_id, row_sites[0],'Verified')
#if debugPlot: print query
cursor.execute( query ) # run query
try:
row_run = cursor.fetchone()
Nrun = len( row_run )
site_run_id = row_run[0]
except:
fid_stdout.write('There is no verified run for parameter set (erfid,sgtid,rup_var_scenario_id,vel_id,site_name)=(%s,%s,%s,%s,%s)\n'%(erf_id,sgt_id,rup_scenario_id,vel_id,stanam))
return sites_info, Ek
#print site_run_id
# PeakAmplitude selection (rupture_ID, some sources donot use part of their rupture))
query = "select Source_ID, Rupture_ID from %s where Run_ID = %s and Source_ID = %s and Rup_Var_ID = %s"%('PeakAmplitudes',site_run_id,sid,0)
#if debugPlot: print query
cursor.execute( query ) # run query
row_Sa = cursor.fetchall()
Nrup = len(row_Sa)
if Nrup == 0:
fid_stdout.write('There is SA for (Site_name, Site_ID, run_id, sid) = (%s, %s,%s,%s)\n'%(row_sites[2],row_sites[0],site_run_id,sid))
return sites_info, Ek
else:
pass
# deal with the problem that not all ruptures for one source are used in the simulation
# if all selection rules above are satisfied, then leave the sites and do the following stuff.
# site info dict (create if run_id for the site exists)
# From now on, stanam is used as the combination of (SiteName, RunID, SourceID)
sites_info[stanam] = {}
sites_info[stanam]['id'] = row_sites[0]
sites_info[stanam]['name'] = row_sites[2] # short name of Sites
sites_info[stanam]['lat'] = row_sites[3]
sites_info[stanam]['lon'] = row_sites[4]
sites_info[stanam]['type'] = row_sites[5]
sites_info[stanam]['run_id'] = site_run_id
if site_only == False:
# get hypo slip index
query = "select * from %s where ERF_ID = %s and Rup_Var_Scenario_ID = %s and Source_ID = %s and Rupture_ID = %s"%('Rupture_Variations',erf_id,rup_scenario_id,sid,rid)
# if debugPlot: print query
cursor.execute( query ) # run query
row_rup_var = cursor.fetchall()
tmp = row_rup_var[-1][5].strip().split('-')
if rup_scenario_id <= 4:
Nh = int(tmp[2][1:]) + 1
Nf = int(tmp[1][1:]) + 1
else:
Nh = int(tmp[1][1:]) + 1
Nf = 1
# Get all periods (from IM_Types table based on IM_Type_ID)
query = "select * from %s"%('IM_Types')
# if debugPlot: print query
cursor.execute( query ) # run query
row_imtype = cursor.fetchall()
periods = {};
for ir in xrange( len(row_imtype) ):
periods[str(ir+1)] = row_imtype[ir][2] # unit: sec; Sa unit: cm/s^2
# intensity Measure dictionary
Ek[stanam] = {}
if erf_id == 36:
# PeakAmplitude selection (rupture_ID, some sources donot use part of their rupture))
query = "select * from %s where Run_ID = %s and Source_ID = %s and Rupture_ID = %s and IM_Type_ID in (86,26,21,11,1)"%('PeakAmplitudes',site_run_id,sid,rid)
# if debugPlot: print query
cursor.execute( query ) # run query
row_Sa = cursor.fetchall()
#if debugPlot: print row_Sa
nvar = len(row_Sa)
if nvar == 0:
fid_stdout.write('There is no SA for (Site_name, Site_ID, run_id, sid,rid) = (%s, %s,%s,%s,%s)\n'%(row_sites[2],row_sites[0],site_run_id,sid,rid))
return sites_info, Ek
else:
pass
Ts = [10.0, 5.0, 3.00003, 2.0, 1.0]
Nt = 5
tmpSa = np.zeros( (Nh, Nf, Nt) )
for ih in xrange( Nh ):
for islip in xrange( Nf ):
ivar = islip*Nh + ih
for it in xrange( Nt ):
ik = ivar * Nt + it
tmpSa[ih,islip,it] = row_Sa[ik][5]/980. # in gravity
# if debugPlot: print tmpSa[ih,islip,:]*980.
else:
# PeakAmplitude selection (rupture_ID, some sources donot use part of their rupture))
query = "select * from %s where Run_ID = %s and Source_ID = %s and Rupture_ID = %s"%('PeakAmplitudes',site_run_id,sid,rid)
cursor.execute( query ) # run query
row_Sa = cursor.fetchall()
nvar = len(row_Sa)
if nvar == 0:
fid_stdout.write('There is no SA for (Site_name, Site_ID, run_id, sid,rid) = (%s, %s,%s,%s,%s)\n'%(row_sites[2],row_sites[0],site_run_id,sid,rid))
return sites_info, Ek
else:
pass
# get all available periods
Nt = 0; Ts = []
for ik in xrange( len(row_Sa) ):
IMtype = row_Sa[ik][4]
if row_Sa[ik][2] == 0: # just deal with the first rupture variation
if 1<= IMtype <= 26 or 82<= IMtype <=99:
# For geometric mean and 1-26: 2 to 10 sec, 82-99: 0.1-1.666 sec (broadband)
Nt = Nt+1
Ts.append( periods[str(IMtype)] )
else:
break
tmpSa = np.zeros( (Nh, Nf, Nt) )
for ih in xrange( Nh ):
for islip in xrange( Nf ):
ivar = islip*Nh + ih
for it in xrange( Nt ):
ik = ivar * Nt + it
tmpSa[ih,islip,it] = row_Sa[ik][5]/980. # in gravity
Ek[stanam] = tmpSa.tolist()
# all periods information (corresponding to it)
Ek['periods'] = Ts
return sites_info, Ek
#Utilities to use OpenSHA produce NGA site flatfiles
#Could be extended to generate NGA site flatfiles using pynga.utils
def cpt_OpenSHA_nga(cwd, NGAmeta, sids, rids, Ti, SiteName=None, erf_id=35):
"""
run NGA of OpenSHA
"""
try:
Nt = len(Ti)
except:
Ti = [Ti,]
Nt = len(Ti)
if erf_id != 35:
erf_id = 35
nga_input = NGAmeta + 'nga_inputs'
fid = open( nga_input, 'w' )
for irup in xrange( len(sids) ):
sid = sids[irup]
rid = rids[irup]
for it in xrange( Nt ):
fid.write( '%s %s %s\n'%(sid,rid,'%.3f'%Ti[it]) )
fid.close()
os.chdir( NGAmeta )
if SiteName == None:
# add ABFanalysis/bin in the system PATH
os.system( 'nga_comparison_calc nga_inputs' )
else:
os.system( 'nga_comparison_calc --site %s nga_inputs'%SiteName )
os.chdir( cwd )
def OpenSHA_nga_files(NGAmeta, sid, rid, Ti, SiteName=None, RunID=None, erf_id=35):
"""
Return OpenSHA output file names (select using sid, rid, Ti, and SiteName)
"""
if SiteName == None:
ftmp = 'ERF%s_src%s_rup%s_SA%s.csv'%(erf_id, sid, rid, '%2.1f'%(Ti))
else:
if RunID != None:
ftmp = 'ERF%s_%s.csv'%(erf_id,SiteName)
else:
print 'When SiteName is not None, RunID cannot be None'
raise ValueError
OpenSHA_output = NGAmeta + ftmp
if not os.path.exists( OpenSHA_output ):
print 'OpenSHA computed NGA file %s are not found...'%OpenSHA_output
raise ValueError
else:
if RunID != None and SiteName != None:
ftmp0 = 'ERF%s_%s_RunID%s.csv'%(erf_id,SiteName,RunID)
shutil.copyfile( NGAmeta+ftmp, NGAmeta+ftmp0 )
OpenSHA_output = NGAmeta+ftmp0
return OpenSHA_output
# this will be used by other classes (not used)
# original output from OpenSHA (two ways to use it)
def OpenSHA_nga(NGAmeta,NGAmodel,sid,rid,Ti,SiteName=None,erf_id=35):
"""
Computed OpenSHA (information rearangement)
Using dictionary (attention to the structure)
"""
OpenSHA_output = OpenSHA_nga_files(NGAmeta, sid, rid, Ti, SiteName=SiteName )
ngaO = {}
for inga,nga in enumerate( NGAmodel ):
ngaO[nga] = {}
if SiteName == None:
lines = open(OpenSHA_output, 'r').readlines()
for il in range( 1, len(lines) ):
spl = lines[il].strip().split(',')
stanam = spl[1] # short name
for inga,nga in enumerate( NGAmodel ):
index1 = 2*inga
ngaO[nga][stanam] = [float(spl[index1-8]),float(spl[index1-7])] # return (median,std) in natural log
else:
lines = open(OpenSHA_output, 'r').readlines()
for il in range( 3, len(lines) ):
spl = lines[il].strip().split(',')
sid = spl[0]
rid = spl[1]
sr_key = '%s_%s'%(sid,rid)
for inga,nga in enumerate( NGAmodel ):
index1 = 2*inga
ngaO[nga][sr_key] = [float(spl[index1-8]),float(spl[index1-7])] # return (median,std) in natural log
return ngaO
def CSmetaRup_gen(metafile, cybershk_database_password):
"""
Extract rupture info and save as metadata
"""
rups_info = {}
hostname = 'focal.usc.edu' # host
username = 'cybershk_ro' # usrname
password = cybershk_database_password # password
database = 'CyberShake' # Database name
db = mdb.connect( host = hostname, user = username, \
passwd = password, db = database )
suffix = metafile.strip().split('/')[-1].split('_')
erf_id,rup_scenario_id = suffix[2:4]
sid = suffix[4].split('.')[0]
cursor = db.cursor()
fid_stdout = open( './stdout', 'w' )
rups_info = rup_gen( cursor, sid, rups_info, fid_stdout, rup_scenario_id=rup_scenario_id )
fid_stdout.close()
cursor.close()
db.close()
# save rupture info into file
meta1 = dict(
rups_info = rups_info,
)
header = '# Rupture meta file for rupture %s\n'%sid
save(metafile,meta1,header=header)
return 1
def CSmetafile_gen(metafile, cybershk_sitedata, cybershk_database_password ):
sites_info = {}
Ek = {}
hostname = 'focal.usc.edu' # host
username = 'cybershk_ro' # usrname
password = cybershk_database_password # password
database = 'cybershake' # database name
db = mdb.connect( host = hostname, user = username, \
passwd = password, db = database )
suffix = metafile.strip().split('/')[-1].split('_')
erf_id,sgt_id, rup_scenario_id, vel_id = suffix[1:5]
sid,rid = suffix[5], suffix[6].split('.')[0]
rup_model_ids = (erf_id, sgt_id, rup_scenario_id, vel_id)
# stdout file
fid_stdout = open( './stdout', 'w' )
rup_info = {}
sites = cybershk_sites( cybershk_sitedata )
for stanam in sites.keys():
cursor = db.cursor()
sites_info, Ek = \
im_gen( cursor,sid,stanam,\
sites_info,Ek,fid_stdout, rup_model_ids = rup_model_ids )
cursor.close()
meta1 = dict(
sites_info = sites_info,
im11 = Ek
)
header = '# Meta file for src %s\n'%sid
save( metafile, meta1, header = header )
# close what left
fid_stdout.close()
db.close()
def SC08_input_NGAinfo(fD_input,NGAmodel,Tlist):
# NGA_info file
fid = open(fD_input+'NGA_info','w')
for inga in xrange( len(NGAmodel) ):
if inga == len(NGAmodel)-1:
fid.write( '%s6\n'%NGAmodel[inga] )
else:
fid.write('%s6, '%NGAmodel[inga] )
for it in xrange( len(Tlist) ):
if it != 0:
fid.write(', %s'%('%3.2f'%Tlist[it]))
else:
fid.write('%s'%('%3.2f'%Tlist[it]))
fid.close()
return 1
def SC08_input_SiteInfo(CSmetafile, RupMetafile, cybershk_sitedata, fD_input, projection, kwds, dimS ):
if not os.path.exists( CSmetafile ):
CSmetafile_gen(CSmetafile, cybershk_sitedata)
meta = load( CSmetafile )
sites_info = meta.sites_info
sites_run = meta.sites_info.keys()
suffix = CSmetafile.strip().split('/')[-1].split('_')
erf_id,sgt_id,rup_scenario_id, vel_id = suffix[1:5]
sid = suffix[5].split('.')[0]
meta_rup = load( RupMetafile )
rups_info = meta_rup.rups_info
# just compute the last one (for geometry parameters)
Mw = rups_info['MR'][0][-1]
rid = rups_info['MR'][1][-1]
fD_input1 = fD_input + '/ERF%s_RupVar%s/'%(erf_id, rup_scenario_id)
if not os.path.exists( fD_input1 ):
os.mkdir( fD_input1 )
fD_input2 = fD_input1 + '/SourceID%s_RuptureID%s/'%(sid,rid)
if not os.path.exists( fD_input2 ):
os.mkdir( fD_input2 )
# Site_info file (fix the origion for all cases, or fix the coordinate)
fid = open(fD_input2+'sites_info','w')
Nsta = len(sites_run)
fid.write('%s %s %s %s\n'%(Nsta,dimS[0],dimS[1],dimS[2])) # header:total # of run sites
#print kwds
for ista in xrange( Nsta ):
slon = sites_info[sites_run[ista]]['lon']
slat = sites_info[sites_run[ista]]['lat']
siteID = sites_info[sites_run[ista]]['id']
# Site ID X (east) Y(north) Z(up, here=0) [loop over sites_run, get siteID from sites_info]
# X,Y are computed based on the pre-defined project
Xsta,Ysta = projection( slon, slat,**kwds )
Xsta,Ysta = Xsta/1000., Ysta/1000. # should be in km
fid.write( '%s %s %s %s\n'%(siteID,Xsta,Ysta,0) )
fid.close()
return 1
def SC08_input_FaultInfo(RupMetafile,fD_input,projection,kwds):
# Some bugs related to the strike and hypocenter loation
# Strikes cannot change very rapidly (<60) and hypocenter should be
# within the fault surface
if not os.path.exists( RupMetafile):
CSmetaRup_gen( RupMetafile )
suffix = RupMetafile.strip().split('/')[-1].split('_')