-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmakeEventData.py
More file actions
executable file
·187 lines (169 loc) · 8.32 KB
/
makeEventData.py
File metadata and controls
executable file
·187 lines (169 loc) · 8.32 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
#!/usr/bin/env python
import os
import sys
import time as time
import argparse
import numpy as np
from math import log10
import wrapOQ as woq
from openquake.hazardlib.geo.surface import ComplexFaultSurface
def formatHeader(oname):
'''
Format the FinDer template header by replacing default output with FinDer specific format.
Operation done on file.
Args:
oname: template file name
'''
fin = open(oname, 'r')
text = fin.read()
text = text.replace('# ','')
text = text.replace('\n\n','\n')
fin.close()
fout = open(oname, 'w')
fout.write(text)
fout.close()
return
if __name__ == "__main__":
import logging.config
from DEFLOG import DEFLOG
DEFLOG['handlers']['fileHandler']['filename'] = \
'makeEventData_%s.log' % time.strftime('%y%m%dT%H%M%S', time.gmtime(time.time()))
logging.config.dictConfig(DEFLOG)
# --------------------------------------------------------------------------
# Minimal config dictionary
# --------------------------------------------------------------------------
parser = argparse.ArgumentParser(description='Make FinDer templates using ShakeMap/openquake')
parser.add_argument('--gmpe', '-g', action='store', required=True,
dest='gmpeconf', help='GMPE configuration file')
parser.add_argument('--event', '-e', action='store', required=True,
dest='evconf', help='Event configuration file')
parser.add_argument('--calc', '-c', action='store', required=True,
dest='calcconf', help='Calculation configuration file')
args = parser.parse_args()
gmpeconf = woq.importConfig(args.gmpeconf)
evconf = woq.importConfig(args.evconf)
calcconf = woq.importConfig(args.calcconf)
rdir = evconf['evmech']['geometry']
if os.path.isdir(rdir):
rlist = [os.path.join(rdir, r) for r in sorted(os.listdir(rdir))]
elif os.path.isfile(rdir):
rlist = [rdir]
else:
logging.error(f'Rupture geometry {rdir} is incorrectly specified')
exit()
if 'grid' in calcconf and calcconf['grid']['compute']:
if 'rupinfo' in calcconf and calcconf['rupinfo']:
fout = open('rupinfo.tbl', 'w')
fout.write('Depth: {:.1f} Dip: {:.1f}\n'.format(evconf['evloc']['hypo_depth'],
evconf['evmech']['dip']))
fout2 = open('template_info.txt', 'w')
for f in sorted(rlist):
if f.find('.json') == -1:
continue
evconf['evmech']['geometry'] = f
rdir = os.sep.join(f.split(os.sep)[:-1])
fname = f.split(os.sep)[-1]
nind = fname.replace('rupture_','').replace('.json','')
gm, evconf, dummy = woq.computeGM(gmpeconf, evconf, calcconf)
for mag in gm:
for (centroid_lat, centroid_lon) in gm[mag]:
# lmean_mgmpe, faultplane = gm[mag][(centroid_lat, centroid_lon)]
lmean_mgmpe, faultplane, rjb = gm[mag][(centroid_lat, centroid_lon)]
maxpga = np.amax(lmean_mgmpe)
logging.info('Max PGA: %.4f' % maxpga)
if maxpga < log10(2.):
logging.info('All PGA below 2 cm/s/s threshold, no output files written')
exit()
# --------------------------------------------------------------------------
# Write out data
# --------------------------------------------------------------------------
if 'points' in calcconf and calcconf['points']['compute']:
fin = open(calcconf['points']['points_file'], 'r')
lats = []
lons = []
stnnames = []
for l in fin:
fs = l.split()
lons.append(float(fs[1]))
lats.append(float(fs[0]))
stnnames.append(fs[-1])
fin.close()
oname = 'data_0_{}_{:.4f}_{:.4f}_{:.2f}_{:03d}'.format(nind,
evconf['evloc']['centroid_lat'],
evconf['evloc']['centroid_lon'],
mag,
round(evconf['evmech']['strike']))
fout3 = open(os.path.join(rdir, oname), 'w')
fout3.write('# {:.4f} {:.4f} {:.2f} {:03d}\n'.format(evconf['evloc']['centroid_lat'],
evconf['evloc']['centroid_lon'],
mag,
round(evconf['evmech']['strike'])))
for pga, lat, lon, stnn, dist in zip(lmean_mgmpe.tolist()[0], lats, lons, stnnames, rjb):
#fout.write('{:.5f} {:.5f} {:.5f}\n'.format(lat, lon, pga))
fout3.write('{:.5f} {:.5f} {:.5f} {:.2f}\n'.format(lat, lon, pga, dist))
fout3.close()
if calcconf['plots']:
import matplotlib.pyplot as plt
flat = []
flon = []
if isinstance(faultplane, ComplexFaultSurface):
top = faultplane.surface_nodes[0].nodes[0].nodes[0].nodes[0]
bottom = faultplane.surface_nodes[0].nodes[-1].nodes[0].nodes[0]
flon.extend([float(x) for x in top.to_str().split('[')[1].split(']')[0].split(',')[::3]])
flat.extend([float(x) for x in top.to_str().split('[')[1].split(']')[0].split(',')[1::3]])
flon.extend([float(x) for x in bottom.to_str().split('[')[1].split(']')[0].split(',')[::3]])
flat.extend([float(x) for x in bottom.to_str().split('[')[1].split(']')[0].split(',')[1::3]])
else:
for x in [faultplane.top_left, faultplane.top_right, faultplane.bottom_right, faultplane.bottom_left, faultplane.top_left]:
flat.append(x.latitude)
flon.append(x.longitude)
plt.scatter(lons, lats, c=lmean_mgmpe)
plt.plot(flon, flat)
plt.scatter(evconf['evloc']['centroid_lon'], evconf['evloc']['centroid_lat'], marker='*', s=80)
plt.colorbar()
plt.savefig('%s.png' % oname)
plt.close()
if 'grid' in calcconf and calcconf['grid']['compute']:
dkm = calcconf['grid']['griddkm']
flen = faultplane.get_area()/faultplane.get_width()
oname = os.path.join(rdir, f'template_L{flen:.6f}_Azi0.txt')
if 'rupinfo' in calcconf and calcconf['rupinfo']:
if isinstance(faultplane, ComplexFaultSurface):
top = faultplane.get_top_edge_depth()
bottom = float(faultplane.surface_nodes[0].nodes[-1].nodes[0].nodes[0].to_str().split('[')[1].split(']')[0].split(',')[-1])
else:
top = min(faultplane.top_left.depth, faultplane.top_right.depth)
bottom = max(faultplane.bottom_left.depth, faultplane.bottom_right.depth)
fout.write('{:.1f} {:.4f} {:.4f} {:.2f} {:.2f}\n'.format(
mag,
flen,
faultplane.get_width(),
top,
bottom))
fout2.write('{:.6f} {} {:.1f}\n'.format(flen, oname, mag))
hstr = '%d %d\n%f %d %.1f\n' % (lmean_mgmpe.shape[1], lmean_mgmpe.shape[0], flen, 0, dkm)
woq.np.savetxt(oname, lmean_mgmpe, fmt='%.6e', header=hstr)
formatHeader(oname)
if calcconf['plots']:
import matplotlib.pyplot as plt
plt.imshow(lmean_mgmpe, origin='lower')
plt.colorbar()
plt.savefig('templ_M%.1f.png' % mag)
plt.close()
if calcconf['grid']['asym']:
oname = os.path.join(rdir, f'template_L{flen:.6f}_Azi0_asym.txt')
hstr = '%d %d\n%f %d %.1f\n' % (lmean_mgmpe.shape[1], lmean_mgmpe.shape[0], flen, 0, dkm)
masklonind = woq.floor(lmean_mgmpe.shape[1]/2) - round(xcorr/dkm)
lmean_mgmpe[:,:masklonind] = -2.0
woq.np.savetxt(oname, lmean_mgmpe, fmt='%.6e', header=hstr)
formatHeader(oname)
if calcconf['plots']:
import matplotlib.pyplot as plt
plt.imshow(lmean_mgmpe, origin='lower')
plt.colorbar()
plt.savefig('templ_M%.1f_asym.png' % mag)
plt.close()
if 'grid' in calcconf and calcconf['grid']['compute']:
if 'rupinfo' in calcconf and calcconf['rupinfo']:
fout.close()
fout2.close()