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

# http://pyrocko.org - GPLv3 

# 

# The Pyrocko Developers, 21st Century 

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

from __future__ import absolute_import 

 

 

import logging 

import re 

from xml.parsers.expat import ParserCreate 

try: 

from urllib2 import Request, HTTPError, urlopen 

except ImportError: 

from urllib.request import Request, urlopen 

from urllib.error import HTTPError 

from urllib import parse 

 

from pyrocko import util, pz, model 

 

 

logger = logging.getLogger('pyrocko.client.iris') 

 

base_url = 'http://service.iris.edu/irisws' 

 

 

def tdate(s): 

return util.str_to_time(s, '%Y-%m-%d') 

 

 

def sdate(t): 

return util.time_to_str(t, '%Y-%m-%d') 

 

 

def tdatetime(s): 

return util.str_to_time(s, format='%Y-%m-%dT%H:%M:%S') 

 

 

def sdatetime(t): 

return util.time_to_str(t, format='%Y-%m-%dT%H:%M:%S') 

 

 

class Element(object): 

 

def __init__(self, name, depth, attrs): 

self.name = name 

self.depth = depth 

self.attrs = attrs 

 

def __getattr__(self, k): 

return self.attrs[k] 

 

def __str__(self): 

return '%s:\n ' % self.name + '\n '.join( 

'%s : %s' % (k, v) for (k, v) in self.attrs.items()) 

 

 

class XMLZipHandler(object): 

 

def __init__(self, watch): 

self.watch = watch 

self.stack = [] 

self.wstack = [] 

self.outstack = [] 

 

def startElement(self, name, attrs): 

self.stack.append((name, [])) 

if len(self.wstack) < len(self.watch) and \ 

name == self.watch[len(self.wstack)]: 

 

el = Element(name, len(self.stack), dict(attrs.items())) 

self.wstack.append(el) 

 

def characters(self, content): 

if self.wstack and len(self.stack) == self.wstack[-1].depth + 1: 

if content.strip(): 

self.stack[-1][1].append(content) 

 

def endElement(self, name): 

if self.wstack: 

if len(self.stack) == self.wstack[-1].depth + 1 and \ 

self.stack[-1][1]: 

 

self.wstack[-1].attrs[name] = ''.join(self.stack[-1][1]) 

 

if name == self.watch[len(self.wstack)-1]: 

if len(self.wstack) == len(self.watch): 

self.outstack.append(list(self.wstack)) 

 

self.wstack.pop() 

 

self.stack.pop() 

 

def getQueuedElements(self): 

outstack = self.outstack 

self.outstack = [] 

return outstack 

 

 

def xmlzip(source, watch, bufsize=10000): 

parser = ParserCreate() 

handler = XMLZipHandler(watch) 

 

parser.StartElementHandler = handler.startElement 

parser.EndElementHandler = handler.endElement 

parser.CharacterDataHandler = handler.characters 

 

while True: 

data = source.read(bufsize) 

if not data: 

break 

 

parser.Parse(data, False) 

for elements in handler.getQueuedElements(): 

yield elements 

 

parser.Parse('', True) 

for elements in handler.getQueuedElements(): 

yield elements 

 

 

class NotFound(Exception): 

def __init__(self, url): 

Exception.__init__(self) 

self._url = url 

 

def __str__(self): 

return 'No results for request %s' % self._url 

 

 

def ws_request(url, post=False, **kwargs): 

url_values = parse.urlencode(kwargs) 

url = url + '?' + url_values 

logger.debug('Accessing URL %s' % url) 

 

req = Request(url) 

if post: 

req.add_data(post) 

 

req.add_header('Accept', '*/*') 

 

try: 

return urlopen(req) 

 

except HTTPError as e: 

if e.code == 404: 

raise NotFound(url) 

else: 

raise e 

 

 

def ws_station(**kwargs): 

 

for k in 'startbefore', 'startafter', 'endbefore', 'endafter': 

if k in kwargs: 

kwargs[k] = sdate(kwargs[k]) 

 

if 'timewindow' in kwargs: 

tmin, tmax = kwargs.pop('timewindow') 

kwargs['startbefore'] = sdate(tmin) 

kwargs['endafter'] = sdate(tmax) 

 

return ws_request(base_url + '/station/1/query', **kwargs) 

 

 

def ws_virtualnetwork(**kwargs): 

 

for k in 'starttime', 'endtime': 

if k in kwargs: 

kwargs[k] = sdate(kwargs[k]) 

 

if 'timewindow' in kwargs: 

tmin, tmax = kwargs.pop('timewindow') 

kwargs['starttime'] = sdate(tmin) 

kwargs['endtime'] = sdate(tmax) 

 

return ws_request(base_url + '/virtualnetwork/1/query', **kwargs) 

 

 

def ws_bulkdataselect( 

selection, 

quality=None, 

minimumlength=None, 

longestonly=False): 

 

sel = [] 

if quality is not None: 

sel.append('quality %s' % quality) 

if minimumlength is not None: 

sel.append('minimumlength %s' % minimumlength) 

if longestonly: 

sel.append('longestonly') 

 

for (network, station, location, channel, tmin, tmax) in selection: 

if location == '': 

location = '--' 

 

sel.append(' '.join(( 

network, station, location, channel, 

sdatetime(tmin), sdatetime(tmax)))) 

 

return ws_request(base_url + '/bulkdataselect/1/query', 

post='\n'.join(sel)) 

 

 

def ws_sacpz( 

network=None, 

station=None, 

location=None, 

channel=None, 

time=None, 

tmin=None, 

tmax=None): 

 

d = {} 

if network: 

d['network'] = network 

if station: 

d['station'] = station 

if location: 

d['location'] = location 

else: 

d['location'] = '--' 

if channel: 

d['channel'] = channel 

 

if tmin is not None and tmax is not None: 

d['starttime'] = sdatetime(tmin) 

d['endtime'] = sdatetime(tmax) 

elif time is not None: 

d['time'] = sdatetime(time) 

 

return ws_request(base_url + '/sacpz/1/query', **d) 

 

 

def ws_resp( 

network=None, 

station=None, 

location=None, 

channel=None, 

time=None, 

tmin=None, 

tmax=None): 

 

d = {} 

if network: 

d['network'] = network 

if station: 

d['station'] = station 

if location: 

d['location'] = location 

else: 

d['location'] = '--' 

if channel: 

d['channel'] = channel 

 

if tmin is not None and tmax is not None: 

d['starttime'] = sdatetime(tmin) 

d['endtime'] = sdatetime(tmax) 

elif time is not None: 

d['time'] = sdatetime(time) 

 

return ws_request(base_url + '/resp/1/query', **d) 

 

 

class ChannelInfo(object): 

def __init__( 

self, network, station, location, channel, start, end, azimuth, 

dip, elevation, depth, latitude, longitude, sample, input, output, 

zpk): 

 

self.network = network 

self.station = station 

self.location = location 

self.channel = channel 

self.start = start 

self.end = end 

self.azimuth = azimuth 

self.dip = dip 

self.elevation = elevation 

self.depth = depth 

self.latitude = latitude 

self.longitude = longitude 

self.sample = sample 

self.input = input 

self.output = output 

self.zpk = zpk 

 

def __str__(self): 

return '%s.%s.%s.%s' % ( 

self.network, self.station, self.location, self.channel) 

 

 

def nslc(x): 

return x.network, x.station, x.location, x.channel 

 

 

def grok_sacpz(data): 

pzlines = [] 

d = {} 

responses = [] 

float_keys = ('latitude', 'longitude', 'elevation', 'depth', 'dip', 

'azimuth', 'sample') 

string_keys = ('input', 'output', 'network', 'station', 'location', 

'channel') 

time_keys = ('start', 'end') 

for line in data.splitlines(): 

line = line.strip() 

if line.startswith('*'): 

if pzlines: 

if any(pzlines): 

d['zpk'] = pz.read_sac_zpk(string='\n'.join(pzlines)) 

responses.append(d) 

d = {} 

pzlines = [] 

 

m = re.match(r'^\* ([A-Z]+)[^:]*:(.*)$', line) 

if m: 

k, v = m.group(1).lower(), m.group(2).strip() 

if k in d: 

assert False, 'duplicate entry? %s' % k 

 

if k in float_keys: 

d[k] = float(v) 

elif k in string_keys: 

d[k] = v 

elif k in time_keys: 

d[k] = tdatetime(v) 

 

else: 

pzlines.append(line) 

 

if pzlines and any(pzlines): 

d['zpk'] = pz.read_sac_zpk(string='\n'.join(pzlines)) 

responses.append(d) 

 

cis = {} 

for kwargs in responses: 

try: 

for k in float_keys + string_keys + time_keys: 

if k not in kwargs: 

logger.error('Missing entry: %s' % k) 

raise Exception() 

 

ci = ChannelInfo(**kwargs) 

 

cis[nslc(ci)] = ci 

 

except Exception: 

logger.error('Error while parsing SACPZ data') 

 

return cis 

 

 

def grok_station_xml(data, tmin, tmax): 

 

stations = {} 

 

for (sta, sta_epo, cha, cha_epo) in xmlzip(data, ( 

'Station', 'StationEpoch', 'Channel', 'Epoch')): 

 

sta_beg, sta_end, cha_beg, cha_end = [tdatetime(x) for x in ( 

sta_epo.StartDate, sta_epo.EndDate, cha_epo.StartDate, 

cha_epo.EndDate)] 

 

if not (sta_beg <= tmin and tmax <= sta_end and 

cha_beg <= tmin and tmax <= cha_end): 

 

continue 

 

nslc = tuple([str(x.strip()) for x in ( 

sta.net_code, sta.sta_code, cha.loc_code, cha.chan_code)]) 

 

lat, lon, ele, dep, azi, dip = [ 

float(cha_epo.attrs[x]) 

for x in 'Lat Lon Elevation Depth Azimuth Dip'.split()] 

 

nsl = nslc[:3] 

if nsl not in stations: 

stations[nsl] = model.Station( 

nsl[0], nsl[1], nsl[2], lat, lon, ele, dep) 

 

stations[nsl].add_channel(model.station.Channel(nslc[-1], azi, dip)) 

 

return list(stations.values()) 

 

 

def grok_virtualnet_xml(data): 

net_sta = set() 

 

for network, station in xmlzip(data, ('network', 'station')): 

net_sta.add((network.code, station.code)) 

 

return net_sta 

 

 

def data_selection(stations, tmin, tmax, channel_prio=[ 

['BHZ', 'HHZ'], 

['BH1', 'BHN', 'HH1', 'HHN'], 

['BH2', 'BHE', 'HH2', 'HHE']]): 

 

selection = [] 

for station in stations: 

wanted = [] 

for group in channel_prio: 

gchannels = [] 

for channel in station.get_channels(): 

if channel.name in group: 

gchannels.append(channel) 

if gchannels: 

gchannels.sort(key=lambda a: group.index(a.name)) 

wanted.append(gchannels[0]) 

 

if wanted: 

for channel in wanted: 

selection.append(( 

station.network, station.station, station.location, 

channel.name, tmin, tmax)) 

 

return selection