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

# http://pyrocko.org - GPLv3 

# 

# The Pyrocko Developers, 21st Century 

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

from __future__ import absolute_import 

 

import os 

import sys 

import subprocess 

import tempfile 

import calendar 

import time 

import re 

import logging 

import shutil 

 

from pyrocko import ExternalProgramMissing 

from pyrocko import trace, pile, model, util 

from pyrocko.io import eventdata 

 

pjoin = os.path.join 

logger = logging.getLogger('pyrocko.io.rdseed') 

 

 

def cmp(a, b): 

return (a > b) - (a < b) 

 

 

def read_station_header_file(fn): 

 

def m(i, *args): 

if len(ltoks) >= i + len(args) \ 

and (tuple(ltoks[i:i+len(args)]) == args): 

return True 

return False 

 

def f(i): 

return float(toks[i]) 

 

def s(i): 

if len(toks) > i: 

return toks[i] 

else: 

return '' 

 

with open(fn, 'r') as fi: 

 

stations = [] 

atsec, station, channel = None, None, None 

 

for line in fi: 

toks = line.split() 

ltoks = line.lower().split() 

if m(2, 'station', 'header'): 

atsec = 'station' 

station = {'channels': []} 

stations.append(station) 

continue 

 

if m(2, 'station') and m(5, 'channel'): 

atsec = 'channel' 

channel = {} 

station['channels'].append(channel) 

continue 

 

if atsec == 'station': 

if m(1, 'station', 'code:'): 

station['station'] = s(3) 

 

elif m(1, 'network', 'code:'): 

station['network'] = s(3) 

 

elif m(1, 'name:'): 

station['name'] = ' '.join(toks[2:]) 

 

if atsec == 'channel': 

if m(1, 'channel:'): 

channel['channel'] = s(2) 

 

elif m(1, 'location:'): 

channel['location'] = s(2) 

 

elif m(1, 'latitude:'): 

station['lat'] = f(2) 

 

elif m(1, 'longitude:'): 

station['lon'] = f(2) 

 

elif m(1, 'elevation:'): 

station['elevation'] = f(2) 

 

elif m(1, 'local', 'depth:'): 

channel['depth'] = f(3) 

 

elif m(1, 'azimuth:'): 

channel['azimuth'] = f(2) 

 

elif m(1, 'dip:'): 

channel['dip'] = f(2) 

 

nsl_stations = {} 

for station in stations: 

for channel in station['channels']: 

def cs(k, default=None): 

return channel.get(k, station.get(k, default)) 

 

nsl = station['network'], station['station'], channel['location'] 

if nsl not in nsl_stations: 

nsl_stations[nsl] = model.Station( 

network=station['network'], 

station=station['station'], 

location=channel['location'], 

lat=cs('lat'), 

lon=cs('lon'), 

elevation=cs('elevation'), 

depth=cs('depth', None), 

name=station['name']) 

 

nsl_stations[nsl].add_channel(model.Channel( 

channel['channel'], 

azimuth=channel['azimuth'], 

dip=channel['dip'])) 

 

return list(nsl_stations.values()) 

 

 

def cmp_version(a, b): 

ai = [int(x) for x in a.split('.')] 

bi = [int(x) for x in b.split('.')] 

return cmp(ai, bi) 

 

 

def dumb_parser(data): 

 

(in_ws, in_kw, in_str) = (1, 2, 3) 

 

state = in_ws 

 

rows = [] 

cols = [] 

accu = '' 

for c in data: 

if state == in_ws: 

if c == '"': 

new_state = in_str 

 

elif c not in (' ', '\t', '\n', '\r'): 

new_state = in_kw 

 

if state == in_kw: 

if c in (' ', '\t', '\n', '\r'): 

cols.append(accu) 

accu = '' 

if c in ('\n', '\r'): 

rows.append(cols) 

cols = [] 

new_state = in_ws 

 

if state == in_str: 

if c == '"': 

accu += c 

cols.append(accu[1:-1]) 

accu = '' 

if c in ('\n', '\r'): 

rows.append(cols) 

cols = [] 

new_state = in_ws 

 

state = new_state 

 

if state in (in_kw, in_str): 

accu += c 

 

if len(cols) != 0: 

rows.append(cols) 

 

return rows 

 

 

class Programs(object): 

rdseed = 'rdseed' 

avail = None 

 

@staticmethod 

def check(): 

if Programs.avail is not None: 

return Programs.avail 

 

else: 

try: 

rdseed_proc = subprocess.Popen( 

[Programs.rdseed], 

stdin=subprocess.PIPE, 

stdout=subprocess.PIPE, 

stderr=subprocess.PIPE) 

 

(out, err) = rdseed_proc.communicate() 

 

except OSError as e: 

if e.errno == 2: 

reason = "Could not find executable: '%s'." \ 

% Programs.rdseed 

else: 

reason = str(e) 

 

logging.debug('Failed to run rdseed program. %s' % reason) 

Programs.avail = False 

return Programs.avail 

 

ms = [re.search( 

r'Release (\d+(\.\d+(\.\d+)?)?)', s.decode()) 

for s in (err, out)] 

ms = list(filter(bool, ms)) 

if not ms: 

logger.error('Cannot determine rdseed version number.') 

else: 

version = ms[0].group(1) 

if cmp_version('4.7.5', version) == 1 \ 

or cmp_version(version, '5.1') == 1: 

 

logger.warning( 

'Module pyrocko.rdseed has not been tested with ' 

'version %s of rdseed.' % version) 

 

Programs.avail = True 

return Programs.avail 

 

 

class SeedVolumeNotFound(Exception): 

pass 

 

 

class SeedVolumeAccess(eventdata.EventDataAccess): 

 

def __init__(self, seedvolume, datapile=None): 

 

'''Create new SEED Volume access object. 

 

:param seedvolume: filename of seed volume 

:param datapile: if not ``None``, this should be a 

:py:class:`pile.Pile` object with data traces which are then used 

instead of the data provided by the SEED volume. 

(This is useful for dataless SEED volumes.) 

''' 

 

eventdata.EventDataAccess.__init__(self, datapile=datapile) 

self.tempdir = None 

Programs.check() 

 

self.tempdir = None 

self.seedvolume = seedvolume 

if not os.path.isfile(self.seedvolume): 

raise SeedVolumeNotFound() 

 

self.tempdir = tempfile.mkdtemp("", "SeedVolumeAccess-") 

self.station_headers_file = os.path.join( 

self.tempdir, 'station_header_infos') 

self._unpack() 

self.shutil = shutil 

 

def __del__(self): 

if self.tempdir: 

self.shutil.rmtree(self.tempdir) 

 

def get_pile(self): 

if self._pile is None: 

fns = util.select_files([self.tempdir], regex=r'\.SAC$') 

self._pile = pile.Pile() 

self._pile.load_files(fns, fileformat='sac') 

 

return self._pile 

 

def get_resp_file(self, tr): 

respfile = pjoin(self.tempdir, 'RESP.%s.%s.%s.%s' % tr.nslc_id) 

if not os.path.exists(respfile): 

raise eventdata.NoRestitution( 

'no response information available for trace %s.%s.%s.%s' 

% tr.nslc_id) 

 

return respfile 

 

def get_stationxml(self): 

stations = self.get_pyrocko_stations() 

respfiles = [] 

for station in stations: 

for channel in station.get_channels(): 

nslc = station.nsl() + (channel.name,) 

respfile = pjoin(self.tempdir, 'RESP.%s.%s.%s.%s' % nslc) 

respfiles.append(respfile) 

 

from pyrocko.fdsn import resp 

sxml = resp.make_stationxml(stations, resp.iload(respfiles)) 

return sxml 

 

def get_restitution(self, tr, allowed_methods): 

if 'evalresp' in allowed_methods: 

respfile = pjoin(self.tempdir, 'RESP.%s.%s.%s.%s' % tr.nslc_id) 

if not os.path.exists(respfile): 

raise eventdata.NoRestitution( 

'no response information available for trace %s.%s.%s.%s' 

% tr.nslc_id) 

 

trans = trace.InverseEvalresp(respfile, tr) 

return trans 

else: 

raise eventdata.NoRestitution( 

'no response information available for trace %s.%s.%s.%s' 

% tr.nslc_id) 

 

def get_pyrocko_response(self, tr, target): 

'''Extract the frequency response as :py:class:`trace.EvalResp` 

instance for *tr*. 

 

:param tr: :py:class:`trace.Trace` instance 

''' 

respfile = self.get_resp_file(tr) 

return trace.Evalresp(respfile, tr, target) 

 

def _unpack(self): 

input_fn = self.seedvolume 

output_dir = self.tempdir 

 

def strerr(s): 

return '\n'.join(['rdseed: '+line.decode() 

for line in s.splitlines()]) 

try: 

 

# seismograms: 

if self._pile is None: 

rdseed_proc = subprocess.Popen( 

[Programs.rdseed, '-f', input_fn, '-d', '-z', '3', '-o', 

'1', '-p', '-R', '-q', output_dir], 

stdin=subprocess.PIPE, 

stdout=subprocess.PIPE, 

stderr=subprocess.PIPE) 

 

(out, err) = rdseed_proc.communicate() 

logging.info(strerr(err)) 

else: 

rdseed_proc = subprocess.Popen( 

[Programs.rdseed, '-f', input_fn, '-z', '3', '-p', '-R', 

'-q', output_dir], 

stdin=subprocess.PIPE, 

stdout=subprocess.PIPE, 

stderr=subprocess.PIPE) 

 

(out, err) = rdseed_proc.communicate() 

logging.info(strerr(err)) 

 

# event data: 

rdseed_proc = subprocess.Popen( 

[Programs.rdseed, '-f', input_fn, '-e', '-q', output_dir], 

stdin=subprocess.PIPE, 

stdout=subprocess.PIPE, 

stderr=subprocess.PIPE) 

 

(out, err) = rdseed_proc.communicate() 

logging.info(strerr(err)) 

 

# station summary information: 

rdseed_proc = subprocess.Popen( 

[Programs.rdseed, '-f', input_fn, '-S', '-q', output_dir], 

stdin=subprocess.PIPE, 

stdout=subprocess.PIPE, 

stderr=subprocess.PIPE) 

 

(out, err) = rdseed_proc.communicate() 

logging.info(strerr(err)) 

 

# station headers: 

rdseed_proc = subprocess.Popen( 

[Programs.rdseed, '-f', input_fn, '-s', '-q', output_dir], 

stdin=subprocess.PIPE, 

stdout=subprocess.PIPE, 

stderr=subprocess.PIPE) 

 

(out, err) = rdseed_proc.communicate() 

with open(self.station_headers_file, 'w') as fout: 

fout.write(out.decode()) 

logging.info(strerr(err)) 

 

except OSError as e: 

if e.errno == 2: 

reason = "Could not find executable: '%s'." % Programs.rdseed 

else: 

reason = str(e) 

 

logging.fatal('Failed to unpack SEED volume. %s' % reason) 

sys.exit(1) 

 

def _get_events_from_file(self): 

rdseed_event_file = os.path.join(self.tempdir, 'rdseed.events') 

if not os.path.isfile(rdseed_event_file): 

return [] 

 

with open(rdseed_event_file, 'r') as f: 

events = [] 

for line in f: 

toks = line.split(', ') 

if len(toks) == 9: 

datetime = toks[1].split('.')[0] 

format = '%Y/%m/%d %H:%M:%S' 

secs = util.to_time_float(calendar.timegm( 

time.strptime(datetime, format))) 

e = model.Event( 

lat=float(toks[2]), 

lon=float(toks[3]), 

depth=float(toks[4])*1000., 

magnitude=float(toks[8]), 

time=secs) 

 

events.append(e) 

else: 

raise Exception('Event description in unrecognized format') 

 

return events 

 

def _get_stations_from_file(self): 

stations = read_station_header_file(self.station_headers_file) 

return stations 

 

def _insert_channel_descriptions(self, stations): 

# this is done beforehand in this class 

pass 

 

 

def check_have_rdseed(): 

if not Programs.check(): 

raise ExternalProgramMissing( 

'rdseed is not installed or cannot be found')