1# http://pyrocko.org - GPLv3 

2# 

3# The Pyrocko Developers, 21st Century 

4# ---|P------/S----------~Lg---------- 

5 

6from __future__ import absolute_import, print_function 

7 

8import re 

9import logging 

10import os.path as op 

11 

12import numpy as num 

13 

14from pyrocko import io, trace, util 

15from pyrocko.progress import progress 

16from pyrocko.has_paths import Path, HasPaths 

17from pyrocko.guts import Dict, String, Choice, Float, List, Timestamp, \ 

18 StringChoice, IntChoice, Defer, load_all, clone 

19from pyrocko.squirrel.dataset import Dataset 

20from pyrocko.squirrel.client.local import LocalData 

21from pyrocko.squirrel.error import ToolError 

22from pyrocko.squirrel.model import CodesNSLCE 

23from pyrocko.squirrel.operators.base import NetworkGrouping, StationGrouping, \ 

24 ChannelGrouping, SensorGrouping 

25 

26tts = util.time_to_str 

27 

28guts_prefix = 'jackseis' 

29logger = logging.getLogger('psq.cli.jackseis') 

30 

31 

32def make_task(*args): 

33 return progress.task(*args, logger=logger) 

34 

35 

36class JackseisError(ToolError): 

37 pass 

38 

39 

40class Chain(object): 

41 def __init__(self, node, parent=None): 

42 self.node = node 

43 self.parent = parent 

44 

45 def mcall(self, name, *args, **kwargs): 

46 ret = [] 

47 if self.parent is not None: 

48 ret.append(self.parent.mcall(name, *args, **kwargs)) 

49 

50 ret.append(getattr(self.node, name)(*args, **kwargs)) 

51 return ret 

52 

53 def fcall(self, name, *args, **kwargs): 

54 v = getattr(self.node, name)(*args, **kwargs) 

55 if v is None and self.parent is not None: 

56 return self.parent.fcall(name, *args, **kwargs) 

57 else: 

58 return v 

59 

60 def get(self, name): 

61 v = getattr(self.node, name) 

62 if v is None and self.parent is not None: 

63 return self.parent.get(name) 

64 else: 

65 return v 

66 

67 def dget(self, name, k): 

68 v = getattr(self.node, name).get(k, None) 

69 if v is None and self.parent is not None: 

70 return self.parent.dget(name, k) 

71 else: 

72 return v 

73 

74 

75class OutputFormatChoice(StringChoice): 

76 choices = io.allowed_formats('save') 

77 

78 

79class OutputDataTypeChoice(StringChoice): 

80 choices = ['int32', 'int64', 'float32', 'float64'] 

81 name_to_dtype = { 

82 'int32': num.int32, 

83 'int64': num.int64, 

84 'float32': num.float32, 

85 'float64': num.float64} 

86 

87 

88class TraversalChoice(StringChoice): 

89 choices = ['network', 'station', 'channel', 'sensor'] 

90 name_to_grouping = { 

91 'network': NetworkGrouping(), 

92 'station': StationGrouping(), 

93 'sensor': SensorGrouping(), 

94 'channel': ChannelGrouping()} 

95 

96 

97class Converter(HasPaths): 

98 

99 in_dataset = Dataset.T(optional=True) 

100 in_path = String.T(optional=True) 

101 in_paths = List.T(String.T(optional=True)) 

102 

103 codes = List.T(CodesNSLCE.T(), optional=True) 

104 

105 rename = Dict.T( 

106 String.T(), 

107 Choice.T([ 

108 String.T(), 

109 Dict.T(String.T(), String.T())])) 

110 tmin = Timestamp.T(optional=True) 

111 tmax = Timestamp.T(optional=True) 

112 tinc = Float.T(optional=True) 

113 

114 downsample = Float.T(optional=True) 

115 

116 out_path = Path.T(optional=True) 

117 out_sds_path = Path.T(optional=True) 

118 out_format = OutputFormatChoice.T(optional=True) 

119 out_data_type = OutputDataTypeChoice.T(optional=True) 

120 out_mseed_record_length = IntChoice.T( 

121 optional=True, 

122 choices=list(io.mseed.VALID_RECORD_LENGTHS)) 

123 out_mseed_steim = IntChoice.T( 

124 optional=True, 

125 choices=[1, 2]) 

126 out_meta_path = Path.T(optional=True) 

127 

128 traversal = TraversalChoice.T(optional=True) 

129 

130 parts = List.T(Defer('Converter.T')) 

131 

132 @classmethod 

133 def add_arguments(cls, p): 

134 p.add_squirrel_query_arguments(without=['time']) 

135 

136 p.add_argument( 

137 '--downsample', 

138 dest='downsample', 

139 type=float, 

140 metavar='RATE', 

141 help='Downsample to RATE [Hz].') 

142 

143 p.add_argument( 

144 '--out-path', 

145 dest='out_path', 

146 metavar='TEMPLATE', 

147 help='Set output path to TEMPLATE. Available placeholders ' 

148 'are %%n: network, %%s: station, %%l: location, %%c: ' 

149 'channel, %%b: begin time, %%e: end time, %%j: julian day of ' 

150 'year. The following additional placeholders use the window ' 

151 'begin and end times rather than trace begin and end times ' 

152 '(to suppress producing many small files for gappy traces), ' 

153 '%%(wmin_year)s, %%(wmin_month)s, %%(wmin_day)s, %%(wmin)s, ' 

154 '%%(wmin_jday)s, %%(wmax_year)s, %%(wmax_month)s, ' 

155 '%%(wmax_day)s, %%(wmax)s, %%(wmax_jday)s. ' 

156 'Example: --output=\'data/%%s/trace-%%s-%%c.mseed\'') 

157 

158 p.add_argument( 

159 '--out-sds-path', 

160 dest='out_sds_path', 

161 metavar='PATH', 

162 help='Set output path to create SDS (https://www.seiscomp.de' 

163 '/seiscomp3/doc/applications/slarchive/SDS.html), rooted at ' 

164 'the given path. Implies --tinc=86400. ' 

165 'Example: --output-sds-path=data/sds') 

166 

167 p.add_argument( 

168 '--out-format', 

169 dest='out_format', 

170 choices=io.allowed_formats('save'), 

171 metavar='FORMAT', 

172 help='Set output file format. Choices: %s' % io.allowed_formats( 

173 'save', 'cli_help', 'mseed')) 

174 

175 p.add_argument( 

176 '--out-data-type', 

177 dest='out_data_type', 

178 choices=OutputDataTypeChoice.choices, 

179 metavar='DTYPE', 

180 help='Set numerical data type. Choices: %s. The output file ' 

181 'format must support the given type. By default, the data ' 

182 'type is kept unchanged.' % ', '.join( 

183 OutputDataTypeChoice.choices)) 

184 

185 p.add_argument( 

186 '--out-mseed-record-length', 

187 dest='out_mseed_record_length', 

188 type=int, 

189 choices=io.mseed.VALID_RECORD_LENGTHS, 

190 metavar='INT', 

191 help='Set the mseed record length in bytes. Choices: %s. ' 

192 'Default is 4096 bytes, which is commonly used for archiving.' 

193 % ', '.join(str(b) for b in io.mseed.VALID_RECORD_LENGTHS)) 

194 

195 p.add_argument( 

196 '--out-mseed-steim', 

197 dest='out_mseed_steim', 

198 type=int, 

199 choices=(1, 2), 

200 metavar='INT', 

201 help='Set the mseed STEIM compression. Choices: 1 or 2. ' 

202 'Default is STEIM-2, which can compress full range int32. ' 

203 'Note: STEIM-2 is limited to 30 bit dynamic range.') 

204 

205 p.add_argument( 

206 '--out-meta-path', 

207 dest='out_meta_path', 

208 metavar='PATH', 

209 help='Set output path for station metadata (StationXML) export.') 

210 

211 p.add_argument( 

212 '--traversal', 

213 dest='traversal', 

214 metavar='GROUPING', 

215 choices=TraversalChoice.choices, 

216 help='By default the outermost processing loop is over time. ' 

217 'Add outer loop with given GROUPING. Choices: %s' 

218 % ', '.join(TraversalChoice.choices)) 

219 

220 @classmethod 

221 def from_arguments(cls, args): 

222 kwargs = args.squirrel_query 

223 

224 obj = cls( 

225 downsample=args.downsample, 

226 out_format=args.out_format, 

227 out_path=args.out_path, 

228 out_sds_path=args.out_sds_path, 

229 out_data_type=args.out_data_type, 

230 out_mseed_record_length=args.out_mseed_record_length, 

231 out_mseed_steim=args.out_mseed_steim, 

232 out_meta_path=args.out_meta_path, 

233 traversal=args.traversal, 

234 **kwargs) 

235 

236 obj.validate() 

237 return obj 

238 

239 def add_dataset(self, sq): 

240 if self.in_dataset is not None: 

241 sq.add_dataset(self.in_dataset) 

242 

243 if self.in_path is not None: 

244 ds = Dataset(sources=[LocalData(paths=[self.in_path])]) 

245 ds.set_basepath_from(self) 

246 sq.add_dataset(ds) 

247 

248 if self.in_paths: 

249 ds = Dataset(sources=[LocalData(paths=self.in_paths)]) 

250 ds.set_basepath_from(self) 

251 sq.add_dataset(ds) 

252 

253 def get_effective_rename_rules(self, chain): 

254 d = {} 

255 for k in ['network', 'station', 'location', 'channel']: 

256 v = chain.dget('rename', k) 

257 if isinstance(v, str): 

258 m = re.match(r'/([^/]+)/([^/]*)/', v) 

259 if m: 

260 try: 

261 v = (re.compile(m.group(1)), m.group(2)) 

262 except Exception: 

263 raise JackseisError( 

264 'Invalid replacement pattern: /%s/' % m.group(1)) 

265 

266 d[k] = v 

267 

268 return d 

269 

270 def get_effective_out_path(self): 

271 nset = sum(x is not None for x in ( 

272 self.out_path, 

273 self.out_sds_path)) 

274 

275 if nset > 1: 

276 raise JackseisError( 

277 'More than one out of [out_path, out_sds_path] set.') 

278 

279 is_sds = False 

280 if self.out_path: 

281 out_path = self.out_path 

282 

283 elif self.out_sds_path: 

284 out_path = op.join( 

285 self.out_sds_path, 

286 '%(wmin_year)s/%(network)s/%(station)s/%(channel)s.D' 

287 '/%(network)s.%(station)s.%(location)s.%(channel)s.D' 

288 '.%(wmin_year)s.%(wmin_jday)s') 

289 is_sds = True 

290 else: 

291 out_path = None 

292 

293 if out_path is not None: 

294 return self.expand_path(out_path), is_sds 

295 else: 

296 return None 

297 

298 def get_effective_out_meta_path(self): 

299 if self.out_meta_path is not None: 

300 return self.expand_path(self.out_meta_path) 

301 else: 

302 return None 

303 

304 def do_rename(self, rules, tr): 

305 rename = {} 

306 for k in ['network', 'station', 'location', 'channel']: 

307 v = rules.get(k, None) 

308 if isinstance(v, str): 

309 rename[k] = v 

310 elif isinstance(v, dict): 

311 try: 

312 oldval = getattr(tr, k) 

313 rename[k] = v[oldval] 

314 except KeyError: 

315 raise ToolError( 

316 'No mapping defined for %s code "%s".' % (k, oldval)) 

317 

318 elif isinstance(v, tuple): 

319 pat, repl = v 

320 oldval = getattr(tr, k) 

321 newval, n = pat.subn(repl, oldval) 

322 if n: 

323 rename[k] = newval 

324 

325 tr.set_codes(**rename) 

326 

327 def convert(self, args, chain=None): 

328 if chain is None: 

329 defaults = clone(g_defaults) 

330 defaults.set_basepath_from(self) 

331 chain = Chain(defaults) 

332 

333 chain = Chain(self, chain) 

334 

335 if self.parts: 

336 task = make_task('Jackseis parts') 

337 for part in task(self.parts): 

338 part.convert(args, chain) 

339 

340 del task 

341 

342 else: 

343 sq = args.make_squirrel() 

344 

345 cli_overrides = Converter.from_arguments(args) 

346 cli_overrides.set_basepath('.') 

347 

348 chain = Chain(cli_overrides, chain) 

349 

350 chain.mcall('add_dataset', sq) 

351 

352 tmin = chain.get('tmin') 

353 tmax = chain.get('tmax') 

354 tinc = chain.get('tinc') 

355 codes = chain.get('codes') 

356 downsample = chain.get('downsample') 

357 out_path, is_sds = chain.fcall('get_effective_out_path') \ 

358 or (None, False) 

359 

360 if is_sds and tinc != 86400.: 

361 logger.warning('Setting time window to 1 day to generate SDS.') 

362 tinc = 86400.0 

363 

364 out_format = chain.get('out_format') 

365 out_data_type = chain.get('out_data_type') 

366 

367 out_meta_path = chain.fcall('get_effective_out_meta_path') 

368 

369 if out_meta_path is not None: 

370 sx = sq.get_stationxml(codes=codes, tmin=tmin, tmax=tmax) 

371 util.ensuredirs(out_meta_path) 

372 sx.dump_xml(filename=out_meta_path) 

373 if out_path is None: 

374 return 

375 

376 target_deltat = None 

377 if downsample is not None: 

378 target_deltat = 1.0 / float(downsample) 

379 

380 save_kwargs = {} 

381 if out_format == 'mseed': 

382 save_kwargs['record_length'] = chain.get( 

383 'out_mseed_record_length') 

384 save_kwargs['steim'] = chain.get( 

385 'out_mseed_steim') 

386 

387 traversal = chain.get('traversal') 

388 if traversal is not None: 

389 grouping = TraversalChoice.name_to_grouping[traversal] 

390 else: 

391 grouping = None 

392 

393 tpad = 0.0 

394 if target_deltat is not None: 

395 tpad += target_deltat * 50. 

396 

397 task = None 

398 rename_rules = self.get_effective_rename_rules(chain) 

399 for batch in sq.chopper_waveforms( 

400 tmin=tmin, tmax=tmax, tpad=tpad, tinc=tinc, 

401 codes=codes, 

402 snap_window=True, 

403 grouping=grouping): 

404 

405 if task is None: 

406 task = make_task( 

407 'Jackseis blocks', batch.n * batch.ngroups) 

408 

409 tlabel = '%s%s - %s' % ( 

410 'groups %i / %i: ' % (batch.igroup, batch.ngroups) 

411 if batch.ngroups > 1 else '', 

412 util.time_to_str(batch.tmin), 

413 util.time_to_str(batch.tmax)) 

414 

415 task.update(batch.i + batch.igroup * batch.n, tlabel) 

416 

417 twmin = batch.tmin 

418 twmax = batch.tmax 

419 

420 traces = batch.traces 

421 

422 if target_deltat is not None: 

423 out_traces = [] 

424 for tr in traces: 

425 try: 

426 tr.downsample_to( 

427 target_deltat, snap=True, demean=False) 

428 

429 out_traces.append(tr) 

430 

431 except (trace.TraceTooShort, trace.NoData): 

432 pass 

433 

434 traces = out_traces 

435 

436 for tr in traces: 

437 self.do_rename(rename_rules, tr) 

438 

439 if out_data_type: 

440 for tr in traces: 

441 tr.ydata = tr.ydata.astype( 

442 OutputDataTypeChoice.name_to_dtype[out_data_type]) 

443 

444 chopped_traces = [] 

445 for tr in traces: 

446 try: 

447 otr = tr.chop(twmin, twmax, inplace=False) 

448 chopped_traces.append(otr) 

449 except trace.NoData: 

450 pass 

451 

452 traces = chopped_traces 

453 

454 if out_path is not None: 

455 try: 

456 io.save( 

457 traces, out_path, 

458 format=out_format, 

459 overwrite=args.force, 

460 additional=dict( 

461 wmin_year=tts(twmin, format='%Y'), 

462 wmin_month=tts(twmin, format='%m'), 

463 wmin_day=tts(twmin, format='%d'), 

464 wmin_jday=tts(twmin, format='%j'), 

465 wmin=tts(twmin, format='%Y-%m-%d_%H-%M-%S'), 

466 wmax_year=tts(twmax, format='%Y'), 

467 wmax_month=tts(twmax, format='%m'), 

468 wmax_day=tts(twmax, format='%d'), 

469 wmax_jday=tts(twmax, format='%j'), 

470 wmax=tts(twmax, format='%Y-%m-%d_%H-%M-%S')), 

471 **save_kwargs) 

472 

473 except io.FileSaveError as e: 

474 raise JackseisError(str(e)) 

475 

476 else: 

477 for tr in traces: 

478 print(tr.summary) 

479 

480 if task: 

481 task.done() 

482 

483 

484g_defaults = Converter( 

485 out_mseed_record_length=4096, 

486 out_format='mseed', 

487 out_mseed_steim=2) 

488 

489 

490headline = 'Convert waveform archive data.' 

491 

492 

493def make_subparser(subparsers): 

494 return subparsers.add_parser( 

495 'jackseis', 

496 help=headline, 

497 description=headline) 

498 

499 

500def setup(parser): 

501 parser.add_squirrel_selection_arguments() 

502 

503 parser.add_argument( 

504 '--config', 

505 dest='config_path', 

506 metavar='NAME', 

507 help='File containing `jackseis.Converter` settings.') 

508 

509 parser.add_argument( 

510 '--force', 

511 dest='force', 

512 action='store_true', 

513 default=False, 

514 help='Force overwriting of existing files.') 

515 

516 Converter.add_arguments(parser) 

517 

518 

519def run(parser, args): 

520 if args.config_path: 

521 try: 

522 converters = load_all(filename=args.config_path) 

523 except Exception as e: 

524 raise ToolError(str(e)) 

525 

526 for converter in converters: 

527 if not isinstance(converter, Converter): 

528 raise ToolError( 

529 'Config file should only contain ' 

530 '`jackseis.Converter` objects.') 

531 

532 converter.set_basepath(op.dirname(args.config_path)) 

533 

534 else: 

535 converter = Converter() 

536 converter.set_basepath('.') 

537 converters = [converter] 

538 

539 with progress.view(): 

540 task = make_task('Jackseis jobs') 

541 for converter in task(converters): 

542 converter.convert(args)