Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

# -*- coding: utf-8 -*- 

""" 

SeisHub database client for ObsPy. 

 

:copyright: 

    The ObsPy Development Team (devs@obspy.org) 

:license: 

    GNU Lesser General Public License, Version 3 

    (http://www.gnu.org/copyleft/lesser.html) 

""" 

 

from datetime import datetime 

from lxml import objectify 

from lxml.etree import Element, SubElement, tostring 

from math import log 

from obspy import UTCDateTime 

from obspy.core.util import guessDelta 

from obspy.xseed import Parser 

import os 

import pickle 

import time 

import urllib 

import urllib2 

import warnings 

import functools 

 

 

HTTP_ACCEPTED_DATA_METHODS = ["PUT", "POST"] 

HTTP_ACCEPTED_NODATA_METHODS = ["HEAD", "GET", "DELETE"] 

HTTP_ACCEPTED_METHODS = HTTP_ACCEPTED_DATA_METHODS + \ 

                        HTTP_ACCEPTED_NODATA_METHODS 

 

 

KEYWORDS = {'network': 'network_id', 'station': 'station_id', 

            'location': 'location_id', 'channel': 'channel_id', 

            'starttime': 'start_datetime', 'endtime': 'end_datetime'} 

 

 

def _callChangeGetPAZ(func): 

    """ 

    This is a decorator to intercept a change in the arg list for 

    seishub.client.station.getPAZ() with revision [3778]. 

 

    * throw a DeprecationWarning 

    * make the correct call 

    """ 

    @functools.wraps(func) 

    def new_func(*args, **kwargs): 

        # function itself is first arg so len(args) == 3 means we got 2 args. 

        if len(args) > 3: 

            msg = "The arg/kwarg call syntax of getPAZ() has changed. " + \ 

                  "Please update your code! The old call syntax has been " + \ 

                  "deprecated and will stop working with the next version." 

            warnings.warn(msg, DeprecationWarning) 

            _self = args[0] 

            network = args[1] 

            station = args[2] 

            datetime = args[3] 

            args = args[4:] 

            if len(args) == 0: 

                location = kwargs.get('location', '') 

                channel = kwargs.get('channel', '') 

            elif len(args) == 1: 

                location = args[0] 

                channel = kwargs.get('channel', '') 

            elif len(args) == 2: 

                location = args[0] 

                channel = args[1] 

            if channel == "": 

                msg = "Requesting PAZ for empty channel codes is not " + \ 

                      "supported anymore." 

                warnings.warn(msg, UserWarning) 

            seed_id = ".".join((network, station, location, channel)) 

            args = [_self, seed_id, datetime] 

            kwargs = {} 

        return func(*args, **kwargs) 

    new_func.__name__ = func.__name__ 

    new_func.__doc__ = func.__doc__ 

    new_func.__dict__.update(func.__dict__) 

    return new_func 

 

 

class Client(object): 

    """ 

    SeisHub database request Client class. 

 

    The following classes are automatically linked with initialization. 

    Follow the links in "Linked Class" for more information. They register 

    via the name listed in "Entry Point". 

 

    ===================  ==================================================== 

    Entry Point          Linked Class 

    ===================  ==================================================== 

    ``Client.waveform``  :class:`~obspy.seishub.client._WaveformMapperClient` 

    ``Client.station``   :class:`~obspy.seishub.client._StationMapperClient` 

    ``Client.event``     :class:`~obspy.seishub.client._EventMapperClient` 

    ===================  ==================================================== 

 

    .. rubric:: Example 

 

    >>> from obspy.seishub import Client 

    >>> from obspy import UTCDateTime 

    >>> 

    >>> t = UTCDateTime("2009-09-03 00:00:00") 

    >>> client = Client() 

    >>> 

    >>> st = client.waveform.getWaveform("BW", "RTPI", "", "EHZ", t, t + 20) 

    >>> print(st)  # doctest: +ELLIPSIS 

    1 Trace(s) in Stream: 

    BW.RTPI..EHZ | 2009-09-03T00:00:00.000000Z - ... | 250.0 Hz, 5001 samples 

    """ 

    def __init__(self, base_url="http://teide.geophysik.uni-muenchen.de:8080", 

                 user="admin", password="admin", timeout=10, debug=False, 

                 retries=3): 

        """ 

        Initializes the SeisHub Web service client. 

 

        :type base_url: str, optional 

        :param base_url: SeisHub connection string. Defaults to 

            'http://teide.geophysik.uni-muenchen.de:8080'. 

        :type user: str, optional 

        :param user: The user name used for identification with the Web 

            service. Defaults to ``'admin'``. 

        :type password: str, optional 

        :param password: A password used for authentication with the Web 

            service. Defaults to ``'admin'``. 

        :type timeout: int, optional 

        :param timeout: Seconds before a connection timeout is raised (default 

            is 10 seconds). Available only for Python >= 2.6.x. 

        :type debug: boolean, optional 

        :param debug: Enables verbose output. 

        :type retries: int 

        :param retries: Number of retries for failing requests. 

        """ 

        self.base_url = base_url 

        self.waveform = _WaveformMapperClient(self) 

        self.station = _StationMapperClient(self) 

        self.event = _EventMapperClient(self) 

        self.timeout = timeout 

        self.debug = debug 

        self.retries = retries 

        self.xml_seeds = {} 

        self.station_list = {} 

        # Create an OpenerDirector for Basic HTTP Authentication 

        password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() 

        password_mgr.add_password(None, base_url, user, password) 

        auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr) 

        opener = urllib2.build_opener(auth_handler) 

        # install globally 

        urllib2.install_opener(opener) 

 

    def ping(self): 

        """ 

        Ping the SeisHub server. 

        """ 

        try: 

            t1 = time.time() 

            urllib2.urlopen(self.base_url).read() 

            return (time.time() - t1) * 1000.0 

        except: 

            None 

 

    def testAuth(self): 

        """ 

        Test if authentication information is valid. Raises an Exception if 

        status code of response is not 200 (OK) or 401 (Forbidden). 

 

        :rtype: bool 

        :return: ``True`` if OK, ``False`` if invalid. 

        """ 

        (code, _msg) = self._HTTP_request(self.base_url + "/xml/", 

                                         method="HEAD") 

        if code == 200: 

            return True 

        elif code == 401: 

            return False 

        else: 

            raise Exception("Unexpected request status code: %s" % code) 

 

    def _fetch(self, url, *args, **kwargs):  # @UnusedVariable 

        params = {} 

        # map keywords 

        for key, value in KEYWORDS.iteritems(): 

            if key in kwargs.keys(): 

                kwargs[value] = kwargs[key] 

                del kwargs[key] 

        # check for ranges and empty values 

        for key, value in kwargs.iteritems(): 

            if not value and value != 0: 

                continue 

            if isinstance(value, tuple) and len(value) == 2: 

                params['min_' + str(key)] = str(value[0]) 

                params['max_' + str(key)] = str(value[1]) 

            elif isinstance(value, list) and len(value) == 2: 

                params['min_' + str(key)] = str(value[0]) 

                params['max_' + str(key)] = str(value[1]) 

            else: 

                params[str(key)] = str(value) 

        # replace special characters 

        remoteaddr = self.base_url + url + '?' + urllib.urlencode(params) 

        if self.debug: 

            print('\nRequesting %s' % (remoteaddr)) 

        # certain requests randomly fail on rare occasions, retry 

        for _i in xrange(self.retries): 

            try: 

                response = urllib2.urlopen(remoteaddr, timeout=self.timeout) 

                doc = response.read() 

                return doc 

            # XXX currently there are random problems with SeisHub's internal 

            # XXX sql database access ("cannot operate on a closed database"). 

            # XXX this can be circumvented by issuing the same request again.. 

            except Exception: 

                continue 

        response = urllib2.urlopen(remoteaddr, timeout=self.timeout) 

        doc = response.read() 

        return doc 

 

    def _HTTP_request(self, url, method, xml_string="", headers={}): 

        """ 

        Send a HTTP request via urllib2. 

 

        :type url: String 

        :param url: Complete URL of resource 

        :type method: String 

        :param method: HTTP method of request, e.g. "PUT" 

        :type headers: dict 

        :param headers: Header information for request, e.g. 

                {'User-Agent': "obspyck"} 

        :type xml_string: String 

        :param xml_string: XML for a send request (PUT/POST) 

        """ 

        if method not in HTTP_ACCEPTED_METHODS: 

            raise ValueError("Method must be one of %s" % \ 

                             HTTP_ACCEPTED_METHODS) 

        if method in HTTP_ACCEPTED_DATA_METHODS and not xml_string: 

            raise TypeError("Missing data for %s request." % method) 

        elif method in HTTP_ACCEPTED_NODATA_METHODS and xml_string: 

            raise TypeError("Unexpected data for %s request." % method) 

 

        req = _RequestWithMethod(method=method, url=url, data=xml_string, 

                                 headers=headers) 

        # it seems the following always ends in a urllib2.HTTPError even with 

        # nice status codes...?!? 

        try: 

            response = urllib2.urlopen(req) 

            return response.code, response.msg 

        except urllib2.HTTPError, e: 

            return e.code, e.msg 

 

    def _objectify(self, url, *args, **kwargs): 

        doc = self._fetch(url, *args, **kwargs) 

        return objectify.fromstring(doc) 

 

 

class _BaseRESTClient(object): 

    def __init__(self, client): 

        self.client = client 

 

    def getResource(self, resource_name, format=None, **kwargs): 

        """ 

        Gets a resource. 

 

        :type resource_name: str 

        :param resource_name: Name of the resource. 

        :type format: str, optional 

        :param format: Format string, e.g. ``'xml'`` or ``'map'``. 

        :return: Resource 

        """ 

        # NOTHING goes ABOVE this line! 

        for key, value in locals().iteritems(): 

            if key not in ["self", "kwargs"]: 

                kwargs[key] = value 

        url = '/xml/' + self.package + '/' + self.resourcetype + '/' + \ 

              resource_name 

        return self.client._fetch(url, **kwargs) 

 

    def getXMLResource(self, resource_name, **kwargs): 

        """ 

        Gets a XML resource. 

 

        :type resource_name: str 

        :param resource_name: Name of the resource. 

        :return: Resource as :class:`lxml.objectify.ObjectifiedElement` 

        """ 

        url = '/xml/' + self.package + '/' + self.resourcetype + '/' + \ 

              resource_name 

        return self.client._objectify(url, **kwargs) 

 

    def putResource(self, resource_name, xml_string, headers={}): 

        """ 

        PUTs a XML resource. 

 

        :type resource_name: str 

        :param resource_name: Name of the resource. 

        :type headers: dict 

        :param headers: Header information for request, 

            e.g. ``{'User-Agent': "obspyck"}`` 

        :type xml_string: str 

        :param xml_string: XML for a send request (PUT/POST) 

        :rtype: tuple 

        :return: (HTTP status code, HTTP status message) 

        """ 

        url = '/'.join([self.client.base_url, 'xml', self.package, 

                        self.resourcetype, resource_name]) 

        return self.client._HTTP_request(url, method="PUT", 

                xml_string=xml_string, headers=headers) 

 

    def deleteResource(self, resource_name, headers={}): 

        """ 

        DELETEs a XML resource. 

 

        :type resource_name: str 

        :param resource_name: Name of the resource. 

        :type headers: dict 

        :param headers: Header information for request, 

            e.g. ``{'User-Agent': "obspyck"}`` 

        :return: (HTTP status code, HTTP status message) 

        """ 

        url = '/'.join([self.client.base_url, 'xml', self.package, 

                        self.resourcetype, resource_name]) 

        return self.client._HTTP_request(url, method="DELETE", 

                headers=headers) 

 

 

class _WaveformMapperClient(object): 

    """ 

    Interface to access the SeisHub Waveform Web service. 

 

    .. warning:: 

        This function should NOT be initialized directly, instead access the 

        object via the :attr:`obspy.seishub.Client.waveform` attribute. 

 

    .. seealso:: https://github.com/barsch/seishub.plugins.seismology/blob/\ 

master/seishub/plugins/seismology/waveform.py 

    """ 

    def __init__(self, client): 

        self.client = client 

 

    def getNetworkIds(self, **kwargs): 

        """ 

        Gets a list of network ids. 

 

        :rtype: list 

        :return: List of containing network ids. 

        """ 

        url = '/seismology/waveform/getNetworkIds' 

        root = self.client._objectify(url, **kwargs) 

        return [str(node['network']) for node in root.getchildren()] 

 

    def getStationIds(self, network=None, **kwargs): 

        """ 

        Gets a list of station ids. 

 

        :type network: str 

        :param network: Network code, e.g. ``'BW'``. 

        :rtype: list 

        :return: List of containing station ids. 

        """ 

        # NOTHING goes ABOVE this line! 

        for key, value in locals().iteritems(): 

            if key not in ["self", "kwargs"]: 

                kwargs[key] = value 

        url = '/seismology/waveform/getStationIds' 

        root = self.client._objectify(url, **kwargs) 

        return [str(node['station']) for node in root.getchildren()] 

 

    def getLocationIds(self, network=None, station=None, **kwargs): 

        """ 

        Gets a list of location ids. 

 

        :type network: str 

        :param network: Network code, e.g. ``'BW'``. 

        :type station: str 

        :param station: Station code, e.g. ``'MANZ'``. 

        :rtype: list 

        :return: List of containing location ids. 

        """ 

        # NOTHING goes ABOVE this line! 

        for key, value in locals().iteritems(): 

            if key not in ["self", "kwargs"]: 

                kwargs[key] = value 

        url = '/seismology/waveform/getLocationIds' 

        root = self.client._objectify(url, **kwargs) 

        return [str(node['location']) for node in root.getchildren()] 

 

    def getChannelIds(self, network=None, station=None, location=None, 

                      **kwargs): 

        """ 

        Gets a list of channel ids. 

 

        :type network: str 

        :param network: Network code, e.g. ``'BW'``. 

        :type station: str 

        :param station: Station code, e.g. ``'MANZ'``. 

        :type location: str 

        :param location: Location code, e.g. ``'00'``. 

        :rtype: list 

        :return: List of containing channel ids. 

        """ 

        # NOTHING goes ABOVE this line! 

        for key, value in locals().iteritems(): 

            if key not in ["self", "kwargs"]: 

                kwargs[key] = value 

        url = '/seismology/waveform/getChannelIds' 

        root = self.client._objectify(url, **kwargs) 

        return [str(node['channel']) for node in root.getchildren()] 

 

    def getLatency(self, network=None, station=None, location=None, 

                   channel=None, **kwargs): 

        """ 

        Gets a list of network latency values. 

 

        :type network: str 

        :param network: Network code, e.g. ``'BW'``. 

        :type station: str 

        :param station: Station code, e.g. ``'MANZ'``. 

        :type location: str 

        :param location: Location code, e.g. ``'00'``. 

        :type channel: str 

        :param channel: Channel code, e.g. ``'EHE'``. 

        :rtype: list 

        :return: List of dictionaries containing latency information. 

        """ 

        # NOTHING goes ABOVE this line! 

        for key, value in locals().iteritems(): 

            if key not in ["self", "kwargs"]: 

                kwargs[key] = value 

        url = '/seismology/waveform/getLatency' 

        root = self.client._objectify(url, **kwargs) 

        return [dict(((k, v.pyval) for k, v in node.__dict__.iteritems())) \ 

                for node in root.getchildren()] 

 

    def getWaveform(self, network, station, location=None, channel=None, 

                    starttime=None, endtime=None, apply_filter=False, 

                    getPAZ=False, getCoordinates=False, 

                    metadata_timecheck=True, **kwargs): 

        """ 

        Gets a ObsPy Stream object. 

 

        :type network: str 

        :param network: Network code, e.g. ``'BW'``. 

        :type station: str 

        :param station: Station code, e.g. ``'MANZ'``. 

        :type location: str 

        :param location: Location code, e.g. ``'00'``. 

        :type channel: str 

        :param channel: Channel code, supporting wildcard for component, 

            e.g. ``'EHE'`` or ``'EH*'``. 

        :type starttime: :class:`~obspy.core.utcdatetime.UTCDateTime` 

        :param starttime: Start date and time. 

        :type endtime: :class:`~obspy.core.utcdatetime.UTCDateTime` 

        :param endtime: End date and time. 

        :type apply_filter: bool, optional 

        :param apply_filter: Apply filter (default is ``False``). 

        :type getPAZ: bool, optional 

        :param getPAZ: Fetch PAZ information and append to 

            :class:`~obspy.core.trace.Stats` of all fetched traces. This 

            considerably slows down the request (default is ``False``). 

        :type getCoordinates: bool, optional 

        :param getCoordinates: Fetch coordinate information and append to 

            :class:`~obspy.core.trace.Stats` of all fetched traces. This 

            considerably slows down the request (default is ``False``). 

        :type metadata_timecheck: bool, optional 

        :param metadata_timecheck: For ``getPAZ`` and ``getCoordinates`` check 

            if metadata information is changing from start to end time. Raises 

            an Exception if this is the case. This can be deactivated to save 

            time. 

        :rtype: :class:`~obspy.core.stream.Stream` 

        :return: A ObsPy Stream object. 

        """ 

        # NOTHING goes ABOVE this line! 

        # append all args to kwargs, thus having everything in one dictionary 

        for key, value in locals().iteritems(): 

            if key not in ["self", "kwargs"]: 

                kwargs[key] = value 

 

        # allow time strings in arguments 

        for time in ["starttime", "endtime"]: 

            if isinstance(kwargs[time], str): 

                kwargs[time] = UTCDateTime(kwargs[time]) 

 

        trim_start = kwargs['starttime'] 

        trim_end = kwargs['endtime'] 

        # we expand the requested timespan on both ends by two samples in 

        # order to be able to make use of the nearest_sample option of 

        # stream.trim(). (see trim() and tickets #95 and #105) 

        # only possible if a channel is specified otherwise delta = 0 

        delta = 2 * guessDelta(kwargs['channel']) 

        kwargs['starttime'] = trim_start - delta 

        kwargs['endtime'] = trim_end + delta 

 

        url = '/seismology/waveform/getWaveform' 

        data = self.client._fetch(url, **kwargs) 

        if data == '': 

            raise Exception("No waveform data available") 

        # unpickle 

        stream = pickle.loads(data) 

        if len(stream) == 0: 

            raise Exception("No waveform data available") 

        stream._cleanup() 

 

        # trimming needs to be done only if we extend the datetime above 

        if channel: 

            stream.trim(trim_start, trim_end) 

        if getPAZ: 

            for tr in stream: 

                paz = self.client.station.getPAZ(seed_id=tr.id, 

                                                 datetime=starttime) 

                if metadata_timecheck: 

                    paz_check = self.client.station.getPAZ(seed_id=tr.id, 

                                                           datetime=endtime) 

                    if paz != paz_check: 

                        msg = "PAZ information changing from start time to" + \ 

                              " end time." 

                        raise Exception(msg) 

                tr.stats['paz'] = paz 

 

        if getCoordinates: 

            coords = self.client.station.getCoordinates(network=network, 

                    station=station, location=location, 

                    datetime=starttime) 

            if metadata_timecheck: 

                coords_check = self.client.station.getCoordinates( 

                        network=network, station=station, 

                        location=location, datetime=endtime) 

                if coords != coords_check: 

                    msg = "Coordinate information changing from start " + \ 

                          "time to end time." 

                    raise Exception(msg) 

            for tr in stream: 

                tr.stats['coordinates'] = coords.copy() 

        return stream 

 

    def getPreview(self, network, station, location=None, channel=None, 

                   starttime=None, endtime=None, trace_ids=None, **kwargs): 

        """ 

        Gets a preview of a ObsPy Stream object. 

 

        :type network: str 

        :param network: Network code, e.g. ``'BW'``. 

        :type station: str 

        :param station: Station code, e.g. ``'MANZ'``. 

        :type location: str 

        :param location: Location code, e.g. ``'00'``. 

        :type channel: str 

        :param channel: Channel code, supporting wildcard for component, 

            e.g. ``'EHE'`` or ``'EH*'``. 

        :type starttime: :class:`~obspy.core.utcdatetime.UTCDateTime` 

        :param starttime: Start date and time. 

        :type endtime: :class:`~obspy.core.utcdatetime.UTCDateTime` 

        :param endtime: End date and time. 

        :rtype: :class:`~obspy.core.stream.Stream` 

        :return: Waveform preview as ObsPy Stream object. 

        """ 

        # NOTHING goes ABOVE this line! 

        for key, value in locals().iteritems(): 

            if key not in ["self", "kwargs"]: 

                kwargs[key] = value 

 

        url = '/seismology/waveform/getPreview' 

        data = self.client._fetch(url, **kwargs) 

        if not data: 

            raise Exception("No waveform data available") 

        # unpickle 

        stream = pickle.loads(data) 

        return stream 

 

    def getPreviewByIds(self, trace_ids=None, starttime=None, endtime=None, 

                        **kwargs): 

        """ 

        Gets a preview of a ObsPy Stream object. 

 

        :type trace_ids: list 

        :type trace_ids: List of trace IDs, e.g. ``['BW.MANZ..EHE']``. 

        :type starttime: :class:`~obspy.core.utcdatetime.UTCDateTime` 

        :param starttime: Start date and time. 

        :type endtime: :class:`~obspy.core.utcdatetime.UTCDateTime` 

        :param endtime: End date and time. 

        :rtype: :class:`~obspy.core.stream.Stream` 

        :return: Waveform preview as ObsPy Stream object. 

        """ 

        # NOTHING goes ABOVE this line! 

        for key, value in locals().iteritems(): 

            if key not in ["self", "kwargs"]: 

                kwargs[key] = value 

        # concatenate list of IDs into string 

        if 'trace_ids' in kwargs: 

            if isinstance(kwargs['trace_ids'], list): 

                kwargs['trace_ids'] = ','.join(kwargs['trace_ids']) 

        url = '/seismology/waveform/getPreview' 

        data = self.client._fetch(url, **kwargs) 

        if not data: 

            raise Exception("No waveform data available") 

        # unpickle 

        stream = pickle.loads(data) 

        return stream 

 

 

class _StationMapperClient(_BaseRESTClient): 

    """ 

    Interface to access the SeisHub Station Web service. 

 

    .. warning:: 

        This function should NOT be initialized directly, instead access the 

        object via the :attr:`obspy.seishub.Client.station` attribute. 

 

    .. seealso:: https://github.com/barsch/seishub.plugins.seismology/blob/\ 

master/seishub/plugins/seismology/waveform.py 

    """ 

    package = 'seismology' 

    resourcetype = 'station' 

 

    def getList(self, network=None, station=None, **kwargs): 

        """ 

        Gets a list of station information. 

 

        :type network: str 

        :param network: Network code, e.g. ``'BW'``. 

        :type station: str 

        :param station: Station code, e.g. ``'MANZ'``. 

        :rtype: list 

        :return: List of dictionaries containing station information. 

        """ 

        # NOTHING goes ABOVE this line! 

        for key, value in locals().iteritems(): 

            if key not in ["self", "kwargs"]: 

                kwargs[key] = value 

        url = '/seismology/station/getList' 

        root = self.client._objectify(url, **kwargs) 

        return [dict(((k, v.pyval) for k, v in node.__dict__.iteritems())) \ 

                for node in root.getchildren()] 

 

    def getCoordinates(self, network, station, datetime, location=''): 

        """ 

        Get coordinate information. 

 

        Returns a dictionary with coordinate information for specified station 

        at the specified time. 

 

        :type network: str 

        :param network: Network code, e.g. ``'BW'``. 

        :type station: str 

        :param station: Station code, e.g. ``'MANZ'``. 

        :type datetime: :class:`~obspy.core.utcdatetime.UTCDateTime` 

        :param datetime: Time for which the PAZ is requested, 

            e.g. ``'2010-01-01 12:00:00'``. 

        :type location: str 

        :param location: Location code, e.g. ``'00'``. 

        :rtype: dict 

        :return: Dictionary containing station coordinate information. 

        """ 

        # NOTHING goes ABOVE this line! 

        kwargs = {}  # no **kwargs so use empty dict 

        for key, value in locals().iteritems(): 

            if key not in ["self", "kwargs"]: 

                kwargs[key] = value 

 

        # try to read coordinates from previously obtained station lists 

        netsta = ".".join([network, station]) 

        for data in self.client.station_list.get(netsta, []): 

            # check if starttime is present and fitting 

            if data['start_datetime'] == "": 

                pass 

            elif datetime < UTCDateTime(data['start_datetime']): 

                continue 

            # check if endtime is present and fitting 

            if data['end_datetime'] == "": 

                pass 

            elif datetime > UTCDateTime(data['end_datetime']): 

                continue 

            coords = {} 

            for key in ['latitude', 'longitude', 'elevation']: 

                coords[key] = data[key] 

            return coords 

 

        metadata = self.getList(**kwargs) 

        if not metadata: 

            msg = "No coordinates for station %s.%s at %s" % \ 

                    (network, station, datetime) 

            raise Exception(msg) 

        stalist = self.client.station_list.setdefault(netsta, []) 

        for data in metadata: 

            if data not in stalist: 

                stalist.append(data) 

        if len(metadata) > 1: 

            warnings.warn("Received more than one metadata set. Using first.") 

        metadata = metadata[0] 

        coords = {} 

        for key in ['latitude', 'longitude', 'elevation']: 

            coords[key] = metadata[key] 

        return coords 

 

    @_callChangeGetPAZ 

    def getPAZ(self, seed_id, datetime): 

        """ 

        Get PAZ for a station at given time span. Gain is the A0 normalization 

        constant for the poles and zeros. 

 

        :type seed_id: str 

        :param seed_id: SEED or channel id, e.g. ``"BW.RJOB..EHZ"`` or 

            ``"EHE"``. 

        :type datetime: :class:`~obspy.core.utcdatetime.UTCDateTime` 

        :param datetime: Time for which the PAZ is requested, 

            e.g. ``'2010-01-01 12:00:00'``. 

        :rtype: dict 

        :return: Dictionary containing zeros, poles, gain and sensitivity. 

 

        .. rubric:: Example 

 

        >>> c = Client() 

        >>> paz = c.station.getPAZ('BW.MANZ..EHZ', '20090707') 

        >>> paz['zeros'] 

        [0j, 0j] 

        >>> len(paz['poles']) 

        5 

        >>> print(paz['poles'][0]) 

        (-0.037004+0.037016j) 

        >>> paz['gain'] 

        60077000.0 

        >>> paz['sensitivity'] 

        2516800000.0 

        """ 

        # try to read PAZ from previously obtained XSEED data 

        for res in self.client.xml_seeds.get(seed_id, []): 

            parser = Parser(res) 

            try: 

                paz = parser.getPAZ(seed_id=seed_id, 

                                    datetime=UTCDateTime(datetime)) 

                return paz 

            except: 

                continue 

        network, station, location, channel = seed_id.split(".") 

        # request station information 

        station_list = self.getList(network=network, station=station, 

                                    datetime=datetime) 

        if not station_list: 

            return {} 

        # don't allow wild cards 

        for wildcard in ['*', '?']: 

            if wildcard in seed_id: 

                msg = "Wildcards in seed_id are not allowed." 

                raise ValueError(msg) 

 

        if len(station_list) > 1: 

            warnings.warn("Received more than one XSEED file. Using first.") 

 

        xml_doc = station_list[0] 

        res = self.client.station.getResource(xml_doc['resource_name']) 

        reslist = self.client.xml_seeds.setdefault(seed_id, []) 

        if res not in reslist: 

            reslist.append(res) 

        parser = Parser(res) 

        paz = parser.getPAZ(seed_id=seed_id, datetime=UTCDateTime(datetime)) 

        return paz 

 

 

class _EventMapperClient(_BaseRESTClient): 

    """ 

    Interface to access the SeisHub Event Web service. 

 

    .. warning:: 

        This function should NOT be initialized directly, instead access the 

        object via the :attr:`obspy.seishub.Client.event` attribute. 

 

    .. seealso:: https://github.com/barsch/seishub.plugins.seismology/blob/\ 

master/seishub/plugins/seismology/event.py 

    """ 

    package = 'seismology' 

    resourcetype = 'event' 

 

    def getList(self, limit=50, offset=None, localisation_method=None, 

                account=None, user=None, min_datetime=None, max_datetime=None, 

                first_pick=None, last_pick=None, min_latitude=None, 

                max_latitude=None, min_longitude=None, max_longitude=None, 

                min_magnitude=None, max_magnitude=None, min_depth=None, 

                max_depth=None, used_p=None, min_used_p=None, max_used_p=None, 

                used_s=None, min_used_s=None, max_used_s=None, 

                document_id=None, **kwargs): 

        """ 

        Gets a list of event information. 

 

        :rtype: list 

        :return: List of dictionaries containing event information. 

 

        The number of resulting events is by default limited to 50 entries from 

        a SeisHub server. You may raise this by setting the ``limit`` option to 

        a maximal value of 2500. Numbers above 2500 will result into an 

        exception. 

        """ 

        # check limit 

        if limit > 2500: 

            msg = "Maximal allowed limit is 2500 entries." 

            raise ValueError(msg) 

        # NOTHING goes ABOVE this line! 

        for key, value in locals().iteritems(): 

            if key not in ["self", "kwargs"]: 

                kwargs[key] = value 

        url = '/seismology/event/getList' 

        root = self.client._objectify(url, **kwargs) 

        results = [dict(((k, v.pyval) for k, v in node.__dict__.iteritems())) \ 

                   for node in root.getchildren()] 

        if limit == len(results) or \ 

           limit == None and len(results) == 50 or \ 

           len(results) == 2500: 

            msg = "List of results might be incomplete due to option 'limit'." 

            warnings.warn(msg) 

        return results 

 

    def getKML(self, nolabels=False, **kwargs): 

        """ 

        Posts an event.getList() and returns the results as a KML file. For 

        optional arguments, see documentation of 

        :meth:`~obspy.seishub.client._EventMapperClient.getList()` 

 

        :type nolabels: bool 

        :param nolabels: Hide labels of events in KML. Can be useful with large 

            data sets. 

        :rtype: str 

        :return: String containing KML information of all matching events. This 

            string can be written to a file and loaded into e.g. Google Earth. 

        """ 

        events = self.getList(**kwargs) 

        timestamp = datetime.now() 

 

        # construct the KML file 

        kml = Element("kml") 

        kml.set("xmlns", "http://www.opengis.net/kml/2.2") 

 

        document = SubElement(kml, "Document") 

        SubElement(document, "name").text = "Seishub Event Locations" 

 

        # style definitions for earthquakes 

        style = SubElement(document, "Style") 

        style.set("id", "earthquake") 

 

        iconstyle = SubElement(style, "IconStyle") 

        SubElement(iconstyle, "scale").text = "0.5" 

        icon = SubElement(iconstyle, "Icon") 

        SubElement(icon, "href").text = \ 

            "http://maps.google.com/mapfiles/kml/shapes/earthquake.png" 

        hotspot = SubElement(iconstyle, "hotSpot") 

        hotspot.set("x", "0.5") 

        hotspot.set("y", "0") 

        hotspot.set("xunits", "fraction") 

        hotspot.set("yunits", "fraction") 

 

        labelstyle = SubElement(style, "LabelStyle") 

        SubElement(labelstyle, "color").text = "ff0000ff" 

        SubElement(labelstyle, "scale").text = "0.8" 

 

        folder = SubElement(document, "Folder") 

        SubElement(folder, "name").text = "SeisHub Events (%s)" % \ 

                                          timestamp.date() 

        SubElement(folder, "open").text = "1" 

 

        # additional descriptions for the folder 

        descrip_str = "Fetched from: %s" % self.client.base_url 

        descrip_str += "\nFetched at: %s" % timestamp 

        descrip_str += "\n\nSearch options:\n" 

        descrip_str += "\n".join(["=".join((str(k), str(v))) \ 

                                  for k, v in kwargs.items()]) 

        SubElement(folder, "description").text = descrip_str 

 

        style = SubElement(folder, "Style") 

        liststyle = SubElement(style, "ListStyle") 

        SubElement(liststyle, "listItemType").text = "check" 

        SubElement(liststyle, "bgColor").text = "00ffffff" 

        SubElement(liststyle, "maxSnippetLines").text = "5" 

 

        # add one marker per event 

        interesting_keys = ['resource_name', 'localisation_method', 'account', 

                            'user', 'public', 'datetime', 'longitude', 

                            'latitude', 'depth', 'magnitude', 'used_p', 

                            'used_s'] 

        for event_dict in events: 

            placemark = SubElement(folder, "Placemark") 

            date = str(event_dict['datetime']).split(" ")[0] 

            mag = str(event_dict['magnitude']) 

 

            # scale marker size to magnitude if this information is present 

            if mag: 

                mag = float(mag) 

                label = "%s: %.1f" % (date, mag) 

                try: 

                    icon_size = 1.2 * log(1.5 + mag) 

                except ValueError: 

                    icon_size = 0.1 

            else: 

                label = date 

                icon_size = 0.5 

            if nolabels: 

                SubElement(placemark, "name").text = "" 

            else: 

                SubElement(placemark, "name").text = label 

            SubElement(placemark, "styleUrl").text = "#earthquake" 

            style = SubElement(placemark, "Style") 

            icon_style = SubElement(style, "IconStyle") 

            liststyle = SubElement(style, "ListStyle") 

            SubElement(liststyle, "maxSnippetLines").text = "5" 

            SubElement(icon_style, "scale").text = str(icon_size) 

            point = SubElement(placemark, "Point") 

            SubElement(point, "coordinates").text = "%.10f,%.10f,0" % \ 

                    (event_dict['longitude'], event_dict['latitude']) 

 

            # detailed information on the event for the description 

            descrip_str = "" 

            for key in interesting_keys: 

                if not key in event_dict: 

                    continue 

                descrip_str += "\n%s: %s" % (key, event_dict[key]) 

            SubElement(placemark, "description").text = descrip_str 

 

        # generate and return KML string 

        return tostring(kml, pretty_print=True, xml_declaration=True) 

 

    def saveKML(self, filename, overwrite=False, **kwargs): 

        """ 

        Posts an event.getList() and writes the results as a KML file. For 

        optional arguments, see help for 

        :meth:`~obspy.seishub.client._EventMapperClient.getList()` and 

        :meth:`~obspy.seishub.client._EventMapperClient.getKML()` 

 

        :type filename: str 

        :param filename: Filename (complete path) to save KML to. 

        :type overwrite: bool 

        :param overwrite: Overwrite existing file, otherwise if file exists an 

            Exception is raised. 

        :type nolabels: bool 

        :param nolabels: Hide labels of events in KML. Can be useful with large 

            data sets. 

        :rtype: str 

        :return: String containing KML information of all matching events. This 

            string can be written to a file and loaded into e.g. Google Earth. 

        """ 

        if not overwrite and os.path.lexists(filename): 

            raise OSError("File %s exists and overwrite=False." % filename) 

        kml_string = self.getKML(**kwargs) 

        open(filename, "wt").write(kml_string) 

        return 

 

 

class _RequestWithMethod(urllib2.Request): 

    """ 

    Improved urllib2.Request Class for which the HTTP Method can be set to 

    values other than only GET and POST. 

    See http://benjamin.smedbergs.us/blog/2008-10-21/\ 

    putting-and-deleteing-in-python-urllib2/ 

    """ 

    def __init__(self, method, *args, **kwargs): 

        if method not in HTTP_ACCEPTED_METHODS: 

            msg = "HTTP Method not supported. " + \ 

                  "Supported are: %s." % HTTP_ACCEPTED_METHODS 

            raise ValueError(msg) 

        urllib2.Request.__init__(self, *args, **kwargs) 

        self._method = method 

 

    def get_method(self): 

        return self._method 

 

 

if __name__ == '__main__': 

    import doctest 

    doctest.testmod(exclude_empty=True)