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

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

""" 

Client for a database created by obspy.db. 

 

:copyright: 

    The ObsPy Development Team (devs@obspy.org) 

:license: 

    GNU Lesser General Public License, Version 3 

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

""" 

 

from obspy.core.preview import mergePreviews 

from obspy.core.stream import Stream 

from obspy.core.utcdatetime import UTCDateTime 

from obspy.db.db import WaveformPath, WaveformChannel, WaveformFile, Base 

from sqlalchemy import create_engine, func, or_, and_ 

from sqlalchemy.orm import sessionmaker 

import os 

 

 

class Client(object): 

    """ 

    Client for a database created by obspy.db. 

    """ 

    def __init__(self, url=None, session=None, debug=False): 

        """ 

        Initializes the client. 

 

        :type url: string, optional 

        :param url: A string that indicates database dialect and connection 

            arguments. See 

            http://docs.sqlalchemy.org/en/latest/core/engines.html for more 

            information about database dialects and urls. 

        :type session: class:`sqlalchemy.orm.session.Session`, optional 

        :param session: An existing database session object. 

        :type debug: boolean, optional 

        :param debug: Enables verbose output. 

        """ 

        if url: 

            self.engine = create_engine(url, encoding='utf-8', 

                                        convert_unicode=True) 

            Base.metadata.create_all(self.engine,  # @UndefinedVariable 

                                     checkfirst=True) 

            # enable verbosity after table creations 

            self.engine.echo = debug 

            self.session = sessionmaker(bind=self.engine) 

        else: 

            self.session = session 

 

    def getNetworkIDs(self): 

        """ 

        Fetches all possible network id's. 

        """ 

        session = self.session() 

        query = session.query(WaveformChannel.network) 

        query = query.group_by(WaveformChannel.network) 

        results = query.all() 

        session.close() 

        return [r[0] for r in results if len(r) == 1] 

 

    def getStationIds(self, network=None): 

        """ 

        Fetches all possible station id's. 

 

        :type network: string, optional 

        :param network: Filter result by given network id if given. Defaults 

            to ``None``. 

        """ 

        session = self.session() 

        query = session.query(WaveformChannel.station) 

        if network: 

            query = query.filter(WaveformChannel.network == network) 

        query = query.group_by(WaveformChannel.station) 

        results = query.all() 

        session.close() 

        return [r[0] for r in results if len(r) == 1] 

 

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

        """ 

        Fetches all possible location id's. 

 

        :type network: string, optional 

        :param network: Filter result by given network id if given. Defaults 

            to ``None``. 

        :type station: string, optional 

        :param station: Filter result by given station id if given. Defaults 

            to ``None``. 

        """ 

        session = self.session() 

        query = session.query(WaveformChannel.location) 

        if network: 

            query = query.filter(WaveformChannel.network == network) 

        if station: 

            query = query.filter(WaveformChannel.station == station) 

        query = query.group_by(WaveformChannel.location) 

        results = query.all() 

        session.close() 

        return [r[0] for r in results if len(r) == 1] 

 

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

        """ 

        Fetches all possible channel id's. 

 

        :type network: string, optional 

        :param network: Filter result by given network id if given. Defaults 

            to ``None``. 

        :type station: string, optional 

        :param station: Filter result by given station id if given. Defaults 

            to ``None``. 

        :type location: string, optional 

        :param location: Filter result by given location id if given. Defaults 

            to ``None``. 

        """ 

        session = self.session() 

        query = session.query(WaveformChannel.channel) 

        if network: 

            query = query.filter(WaveformChannel.network == network) 

        if station: 

            query = query.filter(WaveformChannel.station == station) 

        if location: 

            query = query.filter(WaveformChannel.location == location) 

        query = query.group_by(WaveformChannel.channel) 

        results = query.all() 

        session.close() 

        return [r[0] for r in results if len(r) == 1] 

 

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

                    channel=None): 

        """ 

        Generates a list of last endtimes for each channel. 

        """ 

        # build up query 

        session = self.session() 

        query = session.query( 

            WaveformChannel.network, WaveformChannel.station, 

            WaveformChannel.location, WaveformChannel.channel, 

            func.max(WaveformChannel.endtime).label('latency') 

        ) 

        query = query.group_by( 

            WaveformChannel.network, WaveformChannel.station, 

            WaveformChannel.location, WaveformChannel.channel 

        ) 

        # process arguments 

        kwargs = {'network': network, 'station': station, 

                  'location': location, 'channel': channel} 

        for key, value in kwargs.iteritems(): 

            if value == None: 

                continue 

            col = getattr(WaveformChannel, key) 

            if '*' in value or '?' in value: 

                value = value.replace('?', '_') 

                value = value.replace('*', '%') 

                query = query.filter(col.like(value)) 

            else: 

                query = query.filter(col == value) 

        results = query.all() 

        session.close() 

        adict = {} 

        for result in results: 

            key = '%s.%s.%s.%s' % (result[0], result[1], result[2], result[3]) 

            adict[key] = UTCDateTime(result[4]) 

        return adict 

 

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

                        channel=None, starttime=None, endtime=None): 

        """ 

        Generates a list of available waveform files. 

        """ 

        # build up query 

        session = self.session() 

        query = session.query(WaveformPath.path, 

                              WaveformFile.file, 

                              WaveformChannel.network, 

                              WaveformChannel.station, 

                              WaveformChannel.location, 

                              WaveformChannel.channel) 

        query = query.filter(WaveformPath.id == WaveformFile.path_id) 

        query = query.filter(WaveformFile.id == WaveformChannel.file_id) 

        # process arguments 

        kwargs = {'network': network, 'station': station, 

                  'location': location, 'channel': channel} 

        for key, value in kwargs.iteritems(): 

            if value is None: 

                continue 

            col = getattr(WaveformChannel, key) 

            if '*' in value or '?' in value: 

                value = value.replace('?', '_') 

                value = value.replace('*', '%') 

                query = query.filter(col.like(value)) 

            else: 

                query = query.filter(col == value) 

        # start and end time 

        try: 

            starttime = UTCDateTime(starttime) 

        except: 

            starttime = UTCDateTime() - 60 * 20 

        finally: 

            query = query.filter(WaveformChannel.endtime > starttime.datetime) 

        try: 

            endtime = UTCDateTime(endtime) 

        except: 

            # 10 minutes 

            endtime = UTCDateTime() 

        finally: 

            query = query.filter(WaveformChannel.starttime < endtime.datetime) 

        results = query.all() 

        session.close() 

        # execute query 

        file_dict = {} 

        for result in results: 

            fname = os.path.join(result[0], result[1]) 

            key = '%s.%s.%s.%s' % (result[2], result[3], result[4], result[5]) 

            file_dict.setdefault(key, []).append(fname) 

        return file_dict 

 

    def getPreview(self, trace_ids=[], starttime=None, endtime=None, 

                    network=None, station=None, location=None, channel=None, 

                    pad=False): 

        """ 

        Returns the preview trace. 

        """ 

        # build up query 

        session = self.session() 

        query = session.query(WaveformChannel) 

        # start and end time 

        try: 

            starttime = UTCDateTime(starttime) 

        except: 

            starttime = UTCDateTime() - 60 * 20 

        finally: 

            query = query.filter(WaveformChannel.endtime > starttime.datetime) 

        try: 

            endtime = UTCDateTime(endtime) 

        except: 

            # 10 minutes 

            endtime = UTCDateTime() 

        finally: 

            query = query.filter(WaveformChannel.starttime < endtime.datetime) 

        # process arguments 

        if trace_ids: 

            # filter over trace id list 

            trace_filter = or_() 

            for trace_id in trace_ids: 

                temp = trace_id.split('.') 

                if len(temp) != 4: 

                    continue 

                trace_filter.append(and_( 

                    WaveformChannel.network == temp[0], 

                    WaveformChannel.station == temp[1], 

                    WaveformChannel.location == temp[2], 

                    WaveformChannel.channel == temp[3])) 

            if trace_filter.clauses: 

                query = query.filter(trace_filter) 

        else: 

            # filter over network/station/location/channel id 

            kwargs = {'network': network, 'station': station, 

                      'location': location, 'channel': channel} 

            for key, value in kwargs.iteritems(): 

                if value == None: 

                    continue 

                col = getattr(WaveformChannel, key) 

                if '*' in value or '?' in value: 

                    value = value.replace('?', '_') 

                    value = value.replace('*', '%') 

                    query = query.filter(col.like(value)) 

                else: 

                    query = query.filter(col == value) 

        # execute query 

        results = query.all() 

        session.close() 

        # create Stream 

        st = Stream() 

        for result in results: 

            preview = result.getPreview() 

            st.append(preview) 

        # merge and trim 

        st = mergePreviews(st) 

        st.trim(starttime, endtime, pad=pad) 

        return st