-
Notifications
You must be signed in to change notification settings - Fork 7
/
cloneshake
executable file
·685 lines (625 loc) · 30.7 KB
/
cloneshake
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
#!/usr/bin/env python
#stdlib imports
import os.path
import urllib.request, urllib.error, urllib.parse
import urllib.parse
from xml.dom.minidom import parseString
import sys
import io
import argparse
import json
import datetime
from time import strptime
import re
from mapio.gmt import GMTGrid
from mapio.geodict import GeoDict
from mapio.shake import ShakeGrid
import numpy as np
YESNO = {'yes':'true','no':'false'}
ARGBOOL = {'yes':True,'no':False}
EVENT_TEMPLATE = '''<?xml version="1.0" encoding="US-ASCII" standalone="yes"?>
<!DOCTYPE earthquake [
<!ELEMENT earthquake EMPTY>
<!ATTLIST earthquake
id ID #REQUIRED
lat CDATA #REQUIRED
lon CDATA #REQUIRED
mag CDATA #REQUIRED
year CDATA #REQUIRED
month CDATA #REQUIRED
day CDATA #REQUIRED
hour CDATA #REQUIRED
minute CDATA #REQUIRED
second CDATA #REQUIRED
timezone CDATA #REQUIRED
depth CDATA #REQUIRED
type CDATA #REQUIRED
locstring CDATA #REQUIRED
pga CDATA #REQUIRED
pgv CDATA #REQUIRED
sp03 CDATA #REQUIRED
sp10 CDATA #REQUIRED
sp30 CDATA #REQUIRED
created CDATA #REQUIRED
>
]>
<earthquake id="[ID]" lat="[LAT]" lon="[LON]" mag="[MAG]" year="[YEAR]" month="[MONTH]" day="[DAY]" hour="[HOUR]" minute="[MINUTE]" second="[SECOND]" timezone="GMT" depth="[DEPTH]" locstring="[LOCSTRING]" created="[CREATED]" network="[NET]" />'''
GRIND_TEMPLATE = '''smVs30default : [VS30]
bad_station : 8016 9.9 19990101-
bad_station : 8010 9.9 19990101-
bad_station : 8022 9.9 19990101-
bad_station : 8034 9.9 19990101-
bad_station : 8040 9.9 19990101-
gmpe: [GMPE] 0.0 9.9 0 999
ipe: [IPE] 0.0 9.9 0 999
outlier_deviation_level : [OUTLIER_DEVIATION_LEVEL]
outlier_max_mag : [OUTLIER_MAX_MAG]
qtm_file : [QTM_FILE]
latspan : [LATSPAN]
lonspan : [LONSPAN]
x_grid_interval : [X_GRID_INTERVAL]
y_grid_interval : [Y_GRID_INTERVAL]
use_gmpe_sc : [USE_GMPE_SC]
bias_norm : [BIAS_NORM]
bias_max_range : [BIAS_MAX_RANGE]
bias_min_stations : [BIAS_MIN_STATIONS]
bias_max_mag : [BIAS_MAX_MAG]
bias_max_bias : [BIAS_MAX_BIAS]
bias_min_bias : [BIAS_MIN_BIAS]
bias_log_amp : [BIAS_LOG_AMP]
gmdecay : [GMDECAY]
gmroi : [GMROI]
idecay : [IDECAY]
iroi : [IROI]
direct_patch_size : 1000
mi2pgm : [MI2PGM]
pgm2mi : [PGM2MI]
[BOUNDS]
source_network : us'''
SOURCE_TEMPLATE = '''mech=[MECH]\n'''
RUN_TEMPLATE = '''[SHAKEHOME]/bin/zoneconfig2 -event [EVENT]
[SHAKEHOME]/bin/retrieve -event [EVENT]
[SHAKEHOME]/bin/grind -event [EVENT] [QTM] -xml -lonspan 6.0 -psa [DIRECTIVITY]
[SHAKEHOME]/bin/tag -event [EVENT]
[SHAKEHOME]/bin/mapping -event [EVENT] -timestamp -itopo
[SHAKEHOME]/bin/plotregr -event [EVENT] -lab_dev 6 -psa
[SHAKEHOME]/bin/genex -event [EVENT] -zip -metadata -shape shape -shape hazus
[SHAKEHOME]/bin/transfer -event [EVENT] -www -push
[SHAKEHOME]/bin/setversion -event [EVENT] -savedata'''
RUN_TEMPLATE_EST = '''#[SHAKEHOME]/bin/zoneconfig2 -event [EVENT]
#[SHAKEHOME]/bin/retrieve -event [EVENT]
[SHAKEHOME]/bin/grind -event [EVENT] [QTM] -xml -lonspan 6.0 -psa [DIRECTIVITY]
[SHAKEHOME]/bin/edit_info -event [EVENT] -tag gmpe -value "[GMPE]"
[SHAKEHOME]/bin/edit_info -event [EVENT] -tag ipe -value "[IPE]"
[SHAKEHOME]/bin/edit_info -event [EVENT] -tag site_correction -value "[SITE]"
[SHAKEHOME]/bin/edit_info -event [EVENT] -tag mean_uncertainty -value -1
[SHAKEHOME]/bin/tag -event [EVENT]
[SHAKEHOME]/bin/mapping -event [EVENT] -timestamp -itopo
[SHAKEHOME]/bin/plotregr -event [EVENT] -lab_dev 6 -psa
[SHAKEHOME]/bin/genex -event [EVENT] -zip -metadata -shape shape -shape hazus
#[SHAKEHOME]/bin/transfer -event [EVENT] -www -push
#[SHAKEHOME]/bin/setversion -event [EVENT] -savedata'''
def parseJSONInfo(jsondata):
truth = {'yes':'true','no':'false'}
jdict = json.loads(jsondata)
faultfile = jdict['input']['event_information']['faultfiles']
sources = {'mech':jdict['input']['event_information']['src_mech']}
grind = {'strictbound':''}
args = {}
args['directivity'] = jdict['processing']['ground_motion_modules']['directivity']['module']
grind['basin_module'] = jdict['processing']['ground_motion_modules']['basin_correction']['module']
grind['mi2pgm'] = jdict['processing']['ground_motion_modules']['mi2pgm']['module']
grind['ipe'] = jdict['processing']['ground_motion_modules']['ipe']['module']
grind['gmpe'] = jdict['processing']['ground_motion_modules']['gmpe']['module']
grind['pgm2mi'] = jdict['processing']['ground_motion_modules']['pgm2mi']['module']
grind['use_gmpe_sc'] = 'false'
args['qtm'] = 'false'
if jdict['processing']['site_response']['site_correction'] == 'GMPE native':
grind['use_gmpe_sc'] = 'true'
args['qtm'] = True
grind['vs30'] = jdict['processing']['site_response']['vs30default']
grind['bias_max_range'] = jdict['processing']['miscellaneous']['bias_max_range']
grind['outlier_max_mag'] = jdict['processing']['miscellaneous']['outlier_max_mag']
grind['bias_max_bias'] = jdict['processing']['miscellaneous']['bias_max_bias']
grind['bias_min_bias'] = jdict['processing']['miscellaneous']['bias_min_bias']
grind['bias_max_mag'] = jdict['processing']['miscellaneous']['bias_max_mag']
grind['bias_norm'] = jdict['processing']['miscellaneous']['bias_norm']
grind['bias_log_amp'] = truth[jdict['processing']['miscellaneous']['bias_log_amp']]
grind['outlier_deviation_level'] = jdict['processing']['miscellaneous']['outlier_deviation_level']
grind['bias_min_stations'] = jdict['processing']['miscellaneous']['bias_min_stations']
grind['gmroi'] = '%ik' % jdict['processing']['roi']['gm']['roi']
grind['gmdecay'] = jdict['processing']['roi']['gm']['decay']
grind['iroi'] = '%ik' % jdict['processing']['roi']['intensity']['roi']
grind['idecay'] = jdict['processing']['roi']['intensity']['decay']
grind['latspan'] = float(jdict['output']['map_information']['grid_span']['latitude'])
grind['lonspan'] = float(jdict['output']['map_information']['grid_span']['longitude'])
nx = jdict['output']['map_information']['grid_points']['longitude']
ny = jdict['output']['map_information']['grid_points']['latitude']
grind['x_grid_interval'] = grind['lonspan']/nx
grind['y_grid_interval'] = grind['latspan']/ny
args['nomedian'] = 'false'
if jdict['processing']['miscellaneous']['median_dist'] == 'yes':
args['nomedian'] = 'true'
return (grind,args,sources,faultfile)
def parseOldInfo(root):
tags = root.getElementsByTagName('tag')
grind = {'vs30':686.0}
args = {'qtm':'True',
'directivity':False} #grind command line arguments
sources = {'mech':'ALL'}
faultfile = None
ipe_done = False
for tag in tags:
tname = tag.getAttribute('name')
#print(tname)
if tag.getAttribute('name') == 'faultfiles':
faultfile = tag.getAttribute('value')
if tag.getAttribute('name') == 'src_mech':
sources['mech'] = tag.getAttribute('value')
#things that will go in grind.conf
if tag.getAttribute('name') == 'pgm2mi':
value = tag.getAttribute('value')
vparts = value.split()
grind['pgm2mi'] = vparts[0].split('::')[-1]
if tag.getAttribute('name').strip() == 'mi2pgm':
value = tag.getAttribute('value')
vparts = value.split()
grind['mi2pgm'] = vparts[0].split('::')[-1]
if tag.getAttribute('name') == 'GMPE':
value = tag.getAttribute('value')
vparts = value.split()
grind['gmpe'] = vparts[0].split('::')[-1]
if tag.getAttribute('name') == 'IPE':
ipe_done = True
value = tag.getAttribute('value')
vparts = value.split()
grind['ipe'] = vparts[0].split('::')[-1]
if tag.getAttribute('name') == 'Vs30default':
grind['vs30'] = tag.getAttribute('value')
if tag.getAttribute('name') == 'latspan':
grind['latspan'] = tag.getAttribute('value')
if tag.getAttribute('name') == 'lonspan':
grind['lonspan'] = tag.getAttribute('value')
if tag.getAttribute('name') == 'x_grid_interval':
grind['x_grid_interval'] = tag.getAttribute('value')
if tag.getAttribute('name') == 'y_grid_interval':
grind['y_grid_interval'] = tag.getAttribute('value')
if tag.getAttribute('name') == 'bias_log_amp':
grind['bias_log_amp'] = tag.getAttribute('value')
if tag.getAttribute('name') == 'outlier_deviation_level':
grind['outlier_deviation_level'] = tag.getAttribute('value')
if tag.getAttribute('name') == 'outlier_max_mag':
grind['outlier_max_mag'] = tag.getAttribute('value')
if tag.getAttribute('name') == 'gmdecay':
grind['gmdecay'] = tag.getAttribute('value')
if tag.getAttribute('name') == 'gmroi':
grind['gmroi'] = tag.getAttribute('value')
if tag.getAttribute('name') == 'idecay':
grind['idecay'] = tag.getAttribute('value')
if tag.getAttribute('name') == 'iroi':
grind['iroi'] = tag.getAttribute('value')
if tag.getAttribute('name') == 'map_bound':
grind['map_bound'] = tag.getAttribute('value')
#basin correction not in this format?
#site correction
if tag.getAttribute('name') == 'site_correction':
tvalue = tag.getAttribute('value')
grind['site_correction'] = tvalue
if tvalue in ['disabled','none']:
args['qtm'] = False
grind['use_gmpe_sc'] = 'false'
if tvalue == 'GMPE native':
grind['use_gmpe_sc'] = 'true'
args['qtm'] = True
else:
grind['use_gmpe_sc'] = 'false'
if tag.getAttribute('name') == 'directivity':
args['directivity'] = ARGBOOL[tag.getAttribute('value')]
#get bias parameters
if tag.getAttribute('name') == 'bias_log_amp':
grind['bias_log_amp'] = YESNO[tag.getAttribute('value')]
if tag.getAttribute('name') == 'bias_max_bias':
grind['bias_max_bias'] = tag.getAttribute('value')
if tag.getAttribute('name') == 'bias_max_mag':
grind['bias_max_mag'] = tag.getAttribute('value')
if tag.getAttribute('name') == 'bias_max_range':
grind['bias_max_range'] = tag.getAttribute('value')
if tag.getAttribute('name') == 'bias_min_bias':
grind['bias_min_bias'] = tag.getAttribute('value')
if tag.getAttribute('name') == 'bias_norm':
grind['bias_norm'] = tag.getAttribute('value')
if tag.getAttribute('name') == 'bias_min_stations':
grind['bias_min_stations'] = tag.getAttribute('value')
if (ipe_done is False) and (pargs.missing is True):
grind['ipe'] = 'DefaultIPE'
#Defaults for things that aren't included in older info.xml files.
defaults = {'outlier_deviation_level':3,
'outlier_max_mag':7,
'bias_norm':'l1',
'bias_max_range':120,
'bias_min_stations':6,
'bias_max_mag':7,
'bias_max_bias':2,
'bias_min_bias':-2,
'gmdecay':0.5,
'gmroi':'10k',
'idecay':0.5,
'iroi':'10k'}
grind.update(defaults)
return (grind,args,sources,faultfile)
def parseInfo20(root):
grind = {'vs30':686.0,'strictbound':''}
args = {'qtm':'True',
'directivity':False} #grind command line arguments
sources = {'mech':'ALL'}
faultfile = None
lat = None
lon = None
for section in root.getElementsByTagName('section'):
if section.getAttribute('name') == 'input':
for subsection in section.getElementsByTagName('subsection'):
if subsection.getAttribute('name') == 'event_information':
faultfile = subsection.getElementsByTagName('faultfiles')[0].getAttribute('value').split(',')[0]
lat = float(subsection.getElementsByTagName('latitude')[0].getAttribute('value'))
lon = float(subsection.getElementsByTagName('longitude')[0].getAttribute('value'))
elif section.getAttribute('name') == 'processing':
for subsection in section.getElementsByTagName('subsection'):
if subsection.getAttribute('name') == 'ground_motion_modules':
grind['gmpe'] = subsection.getElementsByTagName('gmpe')[0].getAttribute('value')
grind['ipe'] = subsection.getElementsByTagName('ipe')[0].getAttribute('value')
grind['mi2pgm'] = subsection.getElementsByTagName('mi2pgm')[0].getAttribute('value')
grind['pgm2mi'] = subsection.getElementsByTagName('pgm2mi')[0].getAttribute('value')
args['directivity'] = ARGBOOL[subsection.getElementsByTagName('directivity')[0].getAttribute('value')]
if subsection.getAttribute('name') == 'site_response':
vs30 = subsection.getElementsByTagName('vs30default')[0].getAttribute('value')
scvalue = subsection.getElementsByTagName('site_correction')[0].getAttribute('value')
grind['site_correction'] = scvalue
if scvalue in ['disabled','none']:
args['qtm'] = False
grind['use_gmpe_sc'] = 'true'
if scvalue == 'GMPE native':
grind['use_gmpe_sc'] = 'true'
args['qtm'] = True
else:
grind['use_gmpe_sc'] = 'false'
if subsection.getAttribute('name') == 'miscellaneous':
grind['bias_log_amp'] = YESNO[subsection.getElementsByTagName('bias_log_amp')[0].getAttribute('value')]
grind['bias_max_bias'] = subsection.getElementsByTagName('bias_max_bias')[0].getAttribute('value')
grind['bias_max_mag'] = subsection.getElementsByTagName('bias_max_bias')[0].getAttribute('value')
grind['bias_max_range'] = subsection.getElementsByTagName('bias_max_range')[0].getAttribute('value')
grind['bias_min_bias'] = subsection.getElementsByTagName('bias_min_bias')[0].getAttribute('value')
grind['bias_min_stations'] = subsection.getElementsByTagName('bias_min_stations')[0].getAttribute('value')
grind['bias_norm'] = subsection.getElementsByTagName('bias_norm')[0].getAttribute('value')
if subsection.getElementsByTagName('median_dist')[0].getAttribute('value') == 'no':
args['nomedian'] = 'true'
grind['outlier_deviation_level'] = subsection.getElementsByTagName('outlier_deviation_level')[0].getAttribute('value')
grind['outlier_max_mag'] = subsection.getElementsByTagName('outlier_max_mag')[0].getAttribute('value')
if subsection.getAttribute('name') == 'roi':
grind['gmdecay'] = subsection.getElementsByTagName('gmdecay')[0].getAttribute('value')
grind['gmroi'] = subsection.getElementsByTagName('gmroi')[0].getAttribute('value')
grind['idecay'] = subsection.getElementsByTagName('idecay')[0].getAttribute('value')
grind['iroi'] = subsection.getElementsByTagName('iroi')[0].getAttribute('value')
elif section.getAttribute('name') == 'output':
for subsection in section.getElementsByTagName('subsection'):
if subsection.getAttribute('name') == 'map_information':
grind['latspan'] = subsection.getElementsByTagName('latspan')[0].getAttribute('value')
grind['lonspan'] = subsection.getElementsByTagName('lonspan')[0].getAttribute('value')
grind['x_grid_interval'] = subsection.getElementsByTagName('x_grid_interval')[0].getAttribute('value')
grind['y_grid_interval'] = subsection.getElementsByTagName('y_grid_interval')[0].getAttribute('value')
ymin = float(subsection.getElementsByTagName('lat_min')[0].getAttribute('value'))
ymax = float(subsection.getElementsByTagName('lat_max')[0].getAttribute('value'))
xmin = float(subsection.getElementsByTagName('lon_min')[0].getAttribute('value'))
xmax = float(subsection.getElementsByTagName('lon_max')[0].getAttribute('value'))
x1p = lon/100.0
y1p = lat/100.0
ycenter = ymin + (ymax-ymin)/2.0
xcenter = xmin + (xmax-xmin)/2.0
if xcenter > lon-x1p and xcenter < lon+x1p and ycenter > lat-y1p and ycenter < lat+y1p:
pass
else:
grind['strictbound'] = '%.4f %.4f %.4f %.4f' % (xmin,ymin,xmax,ymax)
return (grind,args,sources,faultfile)
def readInfo(infourl):
try:
fh = urllib.request.urlopen(infourl)
infoxml = fh.read().decode('utf-8')
fh.close()
except:
raise Exception('The supplemental file %s does not exist.' % infourl)
if infourl.endswith('.xml'):
root = parseString(infoxml)
info = root.getElementsByTagName('info')[0]
if info.hasAttribute('version') and info.getAttribute('version') == '2.0':
grind,args,sources,faultfile = parseInfo20(info)
else:
grind,args,sources,faultfile = parseOldInfo(info)
root.unlink()
elif infourl.endswith('.json'):
grind,args,sources,faultfile = parseJSONInfo(infoxml)
else:
raise Exception('The supplemental file %s is in an unknown format.' % infourl)
return (grind,args,sources,faultfile)
def getEventInfo(gridurl):
gridfh = urllib.request.urlopen(gridurl)
gdata = gridfh.read().decode('utf-8')
gridfh.close()
gdata = gdata[0:gdata.find('<grid_data>')] + '</shakemap_grid>'
xdom = parseString(gdata)
root = xdom.getElementsByTagName('shakemap_grid')[0]
infodict = {}
eventid = root.getAttribute('event_id')
net = root.getAttribute('shakemap_originator')
if not eventid.startswith(net):
eventid = net + eventid
if eventid.lower().endswith('_se'):
eventid = eventid.lower().replace('.', 'p')
eventid = "".join(x for x in eventid if x.isalnum())
eventid = eventid[:-2] + '_se'
infodict['id'] = eventid
event = root.getElementsByTagName('event')[0]
gridspec = root.getElementsByTagName('grid_specification')[0]
infodict['lat'] = float(event.getAttribute('lat'))
infodict['lon'] = float(event.getAttribute('lon'))
infodict['depth'] = float(event.getAttribute('depth'))
infodict['mag'] = float(event.getAttribute('magnitude'))
timestr = event.getAttribute('event_timestamp')
timestr = timestr[0:19]
time = datetime.datetime(*strptime(timestr,"%Y-%m-%dT%H:%M:%S")[0:6])
infodict['locstring'] = event.getAttribute('event_description')
infodict['year'] = time.year
infodict['month'] = time.month
infodict['day'] = time.day
infodict['hour'] = time.hour
infodict['minute'] = time.minute
infodict['second'] = time.second
infodict['lon_min'] = float(gridspec.getAttribute('lon_min'))
infodict['lon_max'] = float(gridspec.getAttribute('lon_max'))
infodict['lat_min'] = float(gridspec.getAttribute('lat_min'))
infodict['lat_max'] = float(gridspec.getAttribute('lat_max'))
infodict['lon_spacing'] = float(gridspec.getAttribute('nominal_lon_spacing'))
infodict['lat_spacing'] = float(gridspec.getAttribute('nominal_lat_spacing'))
ctimestr = root.getAttribute('process_timestamp')
ctimestr = ctimestr[0:19]
ctime = datetime.datetime(*strptime(ctimestr,"%Y-%m-%dT%H:%M:%S")[0:6])
infodict['created'] = ctime.strftime('%s')
root.unlink()
return infodict
def writeEvent(grind,args,sources,faultfile,faulturl,stationurl,eventdict,shakehome,gridurl,pargs):
#write the event.xml file
datadir = os.path.join(shakehome,'data',eventdict['id'])
inputdir = os.path.join(datadir,'input')
confdir = os.path.join(datadir,'config')
if not os.path.isdir(inputdir):
os.makedirs(inputdir)
if not os.path.isdir(confdir):
os.makedirs(confdir)
if pargs.estimates is True:
# Create *_estimates.grd from grid.xml
gridfh = urllib.request.urlopen(gridurl)
sg = ShakeGrid.load(gridfh, adjust = "res")
gridfh.close()
dat = sg.getData()
gd = sg.getGeoDict()
pgagrd = GMTGrid(dat['pga'].getData(), gd)
pgagrd.save(os.path.join(inputdir, 'pga_estimates.grd'))
pgvgrd = GMTGrid(dat['pgv'].getData(), gd)
pgvgrd.save(os.path.join(inputdir, 'pgv_estimates.grd'))
mmigrd = GMTGrid(dat['mmi'].getData(), gd)
mmigrd.save(os.path.join(inputdir, 'mi_estimates.grd'))
psa03grd = GMTGrid(dat['psa03'].getData(), gd)
psa03grd.save(os.path.join(inputdir, 'psa03_estimates.grd'))
psa10grd = GMTGrid(dat['psa10'].getData(), gd)
psa10grd.save(os.path.join(inputdir, 'psa10_estimates.grd'))
psa30grd = GMTGrid(dat['psa30'].getData(), gd)
psa30grd.save(os.path.join(inputdir, 'psa30_estimates.grd'))
# Note: should check for presence of uncertainty.xml.zip and use it
# to make *_sd.grd. Since I don't have any examples that have it
# currently, I'm just going to use -1 for sd.
sd = np.ones_like(dat['pga'].getData()) * -1.0
sdgrd = GMTGrid(sd, gd)
sdgrd.save(os.path.join(inputdir, 'pga_sd.grd'))
sdgrd.save(os.path.join(inputdir, 'pgv_sd.grd'))
sdgrd.save(os.path.join(inputdir, 'mi_sd.grd'))
sdgrd.save(os.path.join(inputdir, 'psa03_sd.grd'))
sdgrd.save(os.path.join(inputdir, 'psa10_sd.grd'))
sdgrd.save(os.path.join(inputdir, 'psa30_sd.grd'))
#write grind.conf file
if len(grind):
#get the location of the qtm file on this system
system_grindfile = os.path.join(shakehome,'config','grind.conf')
grindfile = os.path.join(confdir,'grind.conf')
lines = open(system_grindfile,'rt').readlines()
for line in lines:
if line.find('qtm_file') > -1 and not line.strip().startswith('#'):
grind['qtm_file'] = line.split(':')[1].strip()
break
gstr = GRIND_TEMPLATE
for key,value in grind.items():
if (pargs.estimates is True) and (key is 'use_gmpe_sc'):
gstr = gstr.replace('['+key.upper()+']','false')
else:
gstr = gstr.replace('['+key.upper()+']',str(value))
# Need to handle bounds separately...
if 'map_bound' in list(grind.keys()):
mbsp = grind['map_bound'].split('/')
bstr = 'strictbound : ' + mbsp[0] + ' ' + mbsp[2] + ' ' + mbsp[1] + ' ' + mbsp[3]
else:
bstr = 'strictbound : ' + grind['strictbound']
gstr = gstr.replace('[BOUNDS]', bstr)
#make sure we replaced all the macros
pat = '\[([^]]+)\]'
unfilled = re.findall(pat,gstr)
if len(unfilled):
print(('Did not fill in all macros with values, missing "%s".' % str(unfilled)))
if pargs.missing is False:
sys.exit(1)
f = open(grindfile,'wt')
f.write(gstr)
f.close()
print(('Writing grind config to %s' % grindfile))
else:
print('No grind information found.')
#write event.xml file
eventfile = os.path.join(inputdir,'event.xml')
f = open(eventfile,'wt')
estr = EVENT_TEMPLATE
for key,value in eventdict.items():
estr = estr.replace('['+key.upper()+']',str(value))
estr = estr.replace('[NET]', pargs.network)
f.write(estr)
f.close()
print(('Writing input file to %s' % eventfile))
#write stationlist.xml file (if it exists)
try:
fh = urllib.request.urlopen(stationurl)
data = fh.read()
fh.close()
datafile = os.path.join(inputdir,'stationlist.xml')
f = open(datafile,'wt')
f.write(data)
f.close()
except:
print('No stationlist file found.')
#write fault file
try:
fh = urllib.request.urlopen(faulturl)
parts = urllib.parse.urlparse(faulturl)
fpath = parts.path
fbase,fname = os.path.split(fpath)
faultfile = os.path.join(inputdir,fname)
data = fh.read()
fh.close()
f = open(faultfile,'wt')
f.write(data)
f.close()
print(('Writing fault file to %s' % faultfile))
except:
print('No fault file found.')
#Write sources.txt file
sourcefile = os.path.join(inputdir,'source.txt')
f = open(sourcefile,'wt')
for key,value in sources.items():
f.write('%s = %s\n' % (key,value))
f.close()
#write run script
runfile = os.path.join(datadir,'RUNFILE.sh')
f = open(runfile,'wt')
if pargs.estimates is True:
template = RUN_TEMPLATE_EST
else:
template = RUN_TEMPLATE
runtext = template.replace('[EVENT]',eventdict['id'])
runtext = runtext.replace('[SHAKEHOME]',shakehome)
if 'qtm' in args and args['qtm'] and (pargs.estimates is False):
runtext = runtext.replace('[QTM]','-qtm')
else:
runtext = runtext.replace('[QTM]','')
if 'directivity' in args and args['directivity']:
runtext = runtext.replace('[DIRECTIVITY]','-directivity')
else:
runtext = runtext.replace('[DIRECTIVITY]','')
if pargs.estimates is True:
runtext = runtext.replace('[GMPE]', grind['gmpe'])
if ('ipe' in list(grind.keys())) or (pargs.missing is False):
runtext = runtext.replace('[IPE]', grind['ipe'])
runtext = runtext.replace('[SITE]', grind['site_correction'])
f.write(runtext)
f.close()
def getShakeURLs(shakeurl):
urlt = 'http://earthquake.usgs.gov/fdsnws/event/1/query?eventid=[EVENTID]&format=geojson'
eventid = urllib.parse.urlparse(shakeurl).path.strip('/').split('/')[-1]
url = urlt.replace('[EVENTID]',eventid)
fh = urllib.request.urlopen(url)
data = fh.read().decode('utf-8')
jdict = json.loads(data)
fh.close()
contentlist = list(jdict['properties']['products']['shakemap'][0]['contents'].keys())
infourl = None
gridurl = None
stationurl = None
faulturl = None
for content in contentlist:
if content.find('info.xml') > -1:
infourl = jdict['properties']['products']['shakemap'][0]['contents'][content]['url']
if content.find('info.json') > -1:
infourl = jdict['properties']['products']['shakemap'][0]['contents'][content]['url']
if content.endswith('grid.xml'):
gridurl = jdict['properties']['products']['shakemap'][0]['contents'][content]['url']
if content.find('stationlist.xml') > -1:
stationurl = jdict['properties']['products']['shakemap'][0]['contents'][content]['url']
if content.find('_fault.txt') > -1:
faulturl = jdict['properties']['products']['shakemap'][0]['contents'][content]['url']
return (infourl,faulturl,gridurl,stationurl)
def main(args):
pargs = args # gets overwritten later...
shakeurl = args.url
#remove any stuff after a # sign in the url
if shakeurl.find('#') == -1:
endidx = len(shakeurl)
else:
endidx = shakeurl.find('#')
shakeurl = shakeurl[0:endidx]
if not shakeurl.endswith('/'):
shakeurl += '/'
#shakeurl: http://earthquake.usgs.gov/earthquakes/shakemap/ut/shake/shakeoutff_se/
#http://earthquake.usgs.gov/earthquakes/shakemap/ut/shake/shakeoutff_se/download/info.xml
if args.shakehome:
shakehome = args.shakehome
else:
shakehome = os.path.join(os.path.expanduser('~'),'ShakeMap')
if not os.path.isdir(shakehome):
msg = 'Could not find a ShakeMap installation at %s. Specify the location of your ShakeMap installation with -s.'
print((msg % (shakehome)))
sys.exit(1)
#Is this a scenario?
if shakeurl.find('_se') > -1:
infourl = urllib.parse.urljoin(shakeurl,'download/info.xml')
gridurl = urllib.parse.urljoin(shakeurl,'download/grid.xml')
stationurl = urllib.parse.urljoin(shakeurl,'download/stationlist.xml')
try:
grind,args,sources,faultfile = readInfo(infourl)
except Exception as error:
print(('There was a problem trying to clone the ShakeMap.\nError message:\n"%s".\nExiting.' % error.message))
sys.exit(1)
faulturl = urllib.parse.urljoin(shakeurl,'download/%s' % faultfile)
else:
infourl,faulturl,gridurl,stationurl = getShakeURLs(shakeurl)
if infourl is not None:
grind,args,sources,faultfile = readInfo(infourl)
else:
grind = {}
args = {}
sources = {}
faultfile = ''
eventdict = getEventInfo(gridurl)
if 'latspan' not in grind:
grind['latspan'] = eventdict['lat_max'] - eventdict['lat_min']
grind['lonspan'] = eventdict['lon_max'] - eventdict['lon_min']
grind['x_grid_interval'] = eventdict['lon_spacing']
grind['y_grid_interval'] = eventdict['lat_spacing']
writeEvent(grind,args,sources,faultfile,faulturl,stationurl,eventdict,shakehome,gridurl,pargs)
print(('Cloning completed.\nTo run this event, do:\nsh %s/data/%s/RUNFILE.sh' % (shakehome,eventdict['id'])))
if __name__ == '__main__':
desc = '''Clone a ShakeMap from NEIC web site.
Examples:
Cloning a scenario:
%(prog)s http://earthquake.usgs.gov/earthquakes/shakemap/global/shake/capstone2014_nmsw_m7.7_se/
Cloning a real-time event:
%(prog)s http://comcat.cr.usgs.gov/earthquakes/eventpage/usb000slwn#summary
'''
parser = argparse.ArgumentParser(description=desc,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('url', help='the URL of the desired ShakeMap.')
shakehome = os.path.join(os.path.expanduser('~'),'ShakeMap')
parser.add_argument('-s','--shakehome', help='the location of ShakeMap install; default is %s.' % shakehome)
parser.add_argument('-e','--estimates', action = 'store_true',
help='create *_estimates.grd files from grid.xml')
parser.add_argument('-n','--network', action = 'store', default = "us",
help='Overwrite network code in event file.')
parser.add_argument('-m','--missing', action = 'store_true',
help='allow missing tags from info.xml; default is False; use of this option is for cloning very old shakemaps (usually with -e) for which the info.xml is not complete.')
pargs = parser.parse_args()
if not pargs.url:
print((parser.print_help()))
sys.exit(1)
main(pargs)