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

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

""" 

Simple ASCII time series formats 

 

* ``SLIST``, a ASCII time series format represented with a header line 

  followed by a sample lists (see also 

  :func:`SLIST format description<obspy.core.ascii.writeSLIST>`):: 

 

    TIMESERIES BW_RJOB__EHZ_D, 6001 samples, 200 sps, 2009-08-24T00:20:03.0000\ 

00, SLIST, INTEGER, 

    288 300 292 285 265 287 

    279 250 278 278 268 258 

    ... 

 

* ``TSPAIR``, a ASCII format where data is written in time-sample pairs 

  (see also :func:`TSPAIR format description<obspy.core.ascii.writeTSPAIR>`):: 

 

    TIMESERIES BW_RJOB__EHZ_D, 6001 samples, 200 sps, 2009-08-24T00:20:03.0000\ 

00, TSPAIR, INTEGER, 

    2009-08-24T00:20:03.000000  288 

    2009-08-24T00:20:03.005000  300 

    2009-08-24T00:20:03.010000  292 

    2009-08-24T00:20:03.015000  285 

    2009-08-24T00:20:03.020000  265 

    2009-08-24T00:20:03.025000  287 

    ... 

 

:copyright: 

    The ObsPy Development Team (devs@obspy.org) 

:license: 

    GNU Lesser General Public License, Version 3 

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

""" 

from StringIO import StringIO 

from obspy import Stream, Trace, UTCDateTime 

from obspy.core import Stats 

from obspy.core.util import AttribDict, loadtxt 

import numpy as np 

 

 

HEADER = "TIMESERIES %s_%s_%s_%s_%s, %d samples, %d sps, %.26s, %s, %s, %s\n" 

 

 

def isSLIST(filename): 

    """ 

    Checks whether a file is ASCII SLIST format. 

 

    :type filename: str 

    :param filename: Name of the ASCII SLIST file to be checked. 

    :rtype: bool 

    :return: ``True`` if ASCII SLIST file. 

 

    .. rubric:: Example 

 

    >>> isSLIST('/path/to/slist.ascii')  # doctest: +SKIP 

    True 

    """ 

    try: 

        temp = open(filename, 'rt').readline() 

    except: 

        return False 

    if not temp.startswith('TIMESERIES'): 

        return False 

    if not 'SLIST' in temp: 

        return False 

    return True 

 

 

def isTSPAIR(filename): 

    """ 

    Checks whether a file is ASCII TSPAIR format. 

 

    :type filename: str 

    :param filename: Name of the ASCII TSPAIR file to be checked. 

    :rtype: bool 

    :return: ``True`` if ASCII TSPAIR file. 

 

    .. rubric:: Example 

 

    >>> isTSPAIR('/path/to/tspair.ascii')  # doctest: +SKIP 

    True 

    """ 

    try: 

        temp = open(filename, 'rt').readline() 

    except: 

        return False 

    if not temp.startswith('TIMESERIES'): 

        return False 

    if not 'TSPAIR' in temp: 

        return False 

    return True 

 

 

def readSLIST(filename, headonly=False, **kwargs):  # @UnusedVariable 

    """ 

    Reads a ASCII SLIST file and returns an ObsPy Stream object. 

 

    .. warning:: 

        This function should NOT be called directly, it registers via the 

        ObsPy :func:`~obspy.core.stream.read` function, call this instead. 

 

    :type filename: str 

    :param filename: ASCII file to be read. 

    :type headonly: bool, optional 

    :param headonly: If set to True, read only the head. This is most useful 

        for scanning available data in huge (temporary) data sets. 

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

    :return: A ObsPy Stream object. 

 

    .. rubric:: Example 

 

    >>> from obspy import read 

    >>> st = read('/path/to/slist.ascii') 

    """ 

    fh = open(filename, 'rt') 

    # read file and split text into channels 

    headers = {} 

    key = None 

    for line in fh: 

        if line.isspace(): 

            # blank line 

            continue 

        elif line.startswith('TIMESERIES'): 

            # new header line 

            key = line 

            headers[key] = StringIO() 

        elif headonly: 

            # skip data for option headonly 

            continue 

        elif key: 

            # data entry - may be written in multiple columns 

            headers[key].write(line.strip() + ' ') 

    fh.close() 

    # create ObsPy stream object 

    stream = Stream() 

    for header, data in headers.iteritems(): 

        # create Stats 

        stats = Stats() 

        parts = header.replace(',', '').split() 

        temp = parts[1].split('_') 

        stats.network = temp[0] 

        stats.station = temp[1] 

        stats.location = temp[2] 

        stats.channel = temp[3] 

        stats.sampling_rate = parts[4] 

        # quality only used in MSEED 

        stats.mseed = AttribDict({'dataquality': temp[4]}) 

        stats.ascii = AttribDict({'unit': parts[-1]}) 

        stats.starttime = UTCDateTime(parts[6]) 

        stats.npts = parts[2] 

        if headonly: 

            # skip data 

            stream.append(Trace(header=stats)) 

        else: 

            data = _parse_data(data, parts[8]) 

            stream.append(Trace(data=data, header=stats)) 

    return stream 

 

 

def readTSPAIR(filename, headonly=False, **kwargs):  # @UnusedVariable 

    """ 

    Reads a ASCII TSPAIR file and returns an ObsPy Stream object. 

 

    .. warning:: 

        This function should NOT be called directly, it registers via the 

        ObsPy :func:`~obspy.core.stream.read` function, call this instead. 

 

    :type filename: str 

    :param filename: ASCII file to be read. 

    :type headonly: bool, optional 

    :param headonly: If set to True, read only the headers. This is most useful 

        for scanning available data in huge (temporary) data sets. 

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

    :return: A ObsPy Stream object. 

 

    .. rubric:: Example 

 

    >>> from obspy import read 

    >>> st = read('/path/to/tspair.ascii') 

    """ 

    fh = open(filename, 'rt') 

    # read file and split text into channels 

    headers = {} 

    key = None 

    for line in fh: 

        if line.isspace(): 

            # blank line 

            continue 

        elif line.startswith('TIMESERIES'): 

            # new header line 

            key = line 

            headers[key] = StringIO() 

        elif headonly: 

            # skip data for option headonly 

            continue 

        elif key: 

            # data entry - may be written in multiple columns 

            headers[key].write(line.strip().split()[-1] + ' ') 

    fh.close() 

    # create ObsPy stream object 

    stream = Stream() 

    for header, data in headers.iteritems(): 

        # create Stats 

        stats = Stats() 

        parts = header.replace(',', '').split() 

        temp = parts[1].split('_') 

        stats.network = temp[0] 

        stats.station = temp[1] 

        stats.location = temp[2] 

        stats.channel = temp[3] 

        stats.sampling_rate = parts[4] 

        # quality only used in MSEED 

        stats.mseed = AttribDict({'dataquality': temp[4]}) 

        stats.ascii = AttribDict({'unit': parts[-1]}) 

        stats.starttime = UTCDateTime(parts[6]) 

        stats.npts = parts[2] 

        if headonly: 

            # skip data 

            stream.append(Trace(header=stats)) 

        else: 

            data = _parse_data(data, parts[8]) 

            stream.append(Trace(data=data, header=stats)) 

    return stream 

 

 

def writeSLIST(stream, filename, **kwargs):  # @UnusedVariable 

    """ 

    Writes a ASCII SLIST file. 

 

    .. warning:: 

        This function should NOT be called directly, it registers via the 

        the :meth:`~obspy.core.stream.Stream.write` method of an 

        ObsPy :class:`~obspy.core.stream.Stream` object, call this instead. 

 

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

    :param stream: The ObsPy Stream object to write. 

    :type filename: str 

    :param filename: Name of file to write. 

 

    .. rubric:: Example 

 

    >>> from obspy import read 

    >>> st = read() 

    >>> st.write("slist.ascii", format="SLIST")  #doctest: +SKIP 

 

    .. rubric:: SLIST Format Description 

 

    SLIST is a simple ASCII time series format. Each contiguous time series 

    segment (no gaps or overlaps) is represented with a header line followed by 

    a sample lists. There are no restrictions on how the segments are organized 

    into files, a file might contain a single segment or many, concatenated 

    segments either for the same channel or many different channels. 

 

    Header lines have the general form:: 

 

        TIMESERIES SourceName, # samples, # sps, Time, Format, Type, Units 

 

    with 

 

    ``SourceName`` 

        "Net_Sta_Loc_Chan_Qual", no spaces, quality code optional 

    ``# samples`` 

        Number of samples following header 

    ``# sps`` 

        Sampling rate in samples per second 

    ``Time`` 

        Time of first sample in ISO YYYY-MM-DDTHH:MM:SS.FFFFFF format 

    ``Format`` 

        'TSPAIR' (fixed) 

    ``Type`` 

        Sample type 'INTEGER', 'FLOAT' or 'ASCII' 

    ``Units`` 

        Units of time-series, e.g. Counts, M/S, etc., may not contain 

        spaces 

 

    Samples are listed in 6 columns with the time-series incrementing from left 

    to right and wrapping to the next line. The time of the first sample is the 

    time listed in the header. 

 

    *Example SLIST file*:: 

 

        TIMESERIES NL_HGN_00_BHZ_R, 12 samples, 40 sps, 2003-05-29T02:13:22.04\ 

3400, SLIST, INTEGER, Counts 

        2787        2776        2774        2780        2783        2782 

        2776        2766        2759        2760        2765        2767 

        ... 

    """ 

    fh = open(filename, 'wt') 

    for trace in stream: 

        stats = trace.stats 

        # quality code 

        try: 

            dataquality = stats.mseed.dataquality 

        except: 

            dataquality = '' 

        # sample type 

        if trace.data.dtype.name.startswith('int'): 

            dtype = 'INTEGER' 

            fmt = '%d' 

        elif trace.data.dtype.name.startswith('float'): 

            dtype = 'FLOAT' 

            fmt = '%f' 

        else: 

            raise NotImplementedError 

        # unit 

        try: 

            unit = stats.ascii.unit 

        except: 

            unit = '' 

        # write trace header 

        header = HEADER % (stats.network, stats.station, stats.location, 

                           stats.channel, dataquality, stats.npts, 

                           stats.sampling_rate, stats.starttime, 'SLIST', 

                           dtype, unit) 

        fh.write(header) 

        # write data 

        rest = stats.npts % 6 

        if rest: 

            data = trace.data[:-rest] 

        else: 

            data = trace.data 

        data = data.reshape((-1, 6)) 

        np.savetxt(fh, data, fmt=fmt, delimiter='\t') 

        if rest: 

            fh.write('\t'.join([fmt % d for d in trace.data[-rest:]]) + '\n') 

    fh.close() 

 

 

def writeTSPAIR(stream, filename, **kwargs):  # @UnusedVariable 

    """ 

    Writes a ASCII TSPAIR file. 

 

    .. warning:: 

        This function should NOT be called directly, it registers via the 

        the :meth:`~obspy.core.stream.Stream.write` method of an 

        ObsPy :class:`~obspy.core.stream.Stream` object, call this instead. 

 

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

    :param stream: The ObsPy Stream object to write. 

    :type filename: str 

    :param filename: Name of file to write. 

 

    .. rubric:: Example 

 

    >>> from obspy import read 

    >>> st = read() 

    >>> st.write("tspair.ascii", format="TSPAIR")  #doctest: +SKIP 

 

    .. rubric:: TSPAIR Format Description 

 

    TSPAIR is a simple ASCII time series format. Each contiguous time series 

    segment (no gaps or overlaps) is represented with a header line followed by 

    data samples in time-sample pairs. There are no restrictions on how the 

    segments are organized into files, a file might contain a single segment 

    or many, concatenated segments either for the same channel or many 

    different channels. 

 

    Header lines have the general form:: 

 

        TIMESERIES SourceName, # samples, # sps, Time, Format, Type, Units 

 

    with 

 

    ``SourceName`` 

        "Net_Sta_Loc_Chan_Qual", no spaces, quality code optional 

    ``# samples`` 

        Number of samples following header 

    ``# sps`` 

        Sampling rate in samples per second 

    ``Time`` 

        Time of first sample in ISO YYYY-MM-DDTHH:MM:SS.FFFFFF format 

    ``Format`` 

        'TSPAIR' (fixed) 

    ``Type`` 

        Sample type 'INTEGER', 'FLOAT' or 'ASCII' 

    ``Units`` 

        Units of time-series, e.g. Counts, M/S, etc., may not contain 

        spaces 

 

    *Example TSPAIR file*:: 

 

        TIMESERIES NL_HGN_00_BHZ_R, 12 samples, 40 sps, 2003-05-29T02:13:22.04\ 

3400, TSPAIR, INTEGER, Counts 

        2003-05-29T02:13:22.043400  2787 

        2003-05-29T02:13:22.068400  2776 

        2003-05-29T02:13:22.093400  2774 

        2003-05-29T02:13:22.118400  2780 

        2003-05-29T02:13:22.143400  2783 

        2003-05-29T02:13:22.168400  2782 

        2003-05-29T02:13:22.193400  2776 

        2003-05-29T02:13:22.218400  2766 

        2003-05-29T02:13:22.243400  2759 

        2003-05-29T02:13:22.268400  2760 

        2003-05-29T02:13:22.293400  2765 

        2003-05-29T02:13:22.318400  2767 

        ... 

    """ 

    fh = open(filename, 'wt') 

    for trace in stream: 

        stats = trace.stats 

        # quality code 

        try: 

            dataquality = stats.mseed.dataquality 

        except: 

            dataquality = '' 

        # sample type 

        if trace.data.dtype.name.startswith('int'): 

            dtype = 'INTEGER' 

            fmt = '%d' 

        elif trace.data.dtype.name.startswith('float'): 

            dtype = 'FLOAT' 

            fmt = '%f' 

        else: 

            raise NotImplementedError 

        # unit 

        try: 

            unit = stats.ascii.unit 

        except: 

            unit = '' 

        # write trace header 

        header = HEADER % (stats.network, stats.station, stats.location, 

                           stats.channel, dataquality, stats.npts, 

                           stats.sampling_rate, stats.starttime, 'TSPAIR', 

                           dtype, unit) 

        fh.write(header) 

        # write data 

        times = np.linspace(stats.starttime.timestamp, stats.endtime.timestamp, 

                            stats.npts) 

        times = [UTCDateTime(t) for t in times] 

        data = np.vstack((times, trace.data)).T 

        # .26s cuts the Z from the time string 

        np.savetxt(fh, data, fmt="%.26s  " + fmt) 

    fh.close() 

 

 

def _parse_data(data, data_type): 

    """ 

    Simple function to read data contained in a StringIO object to a numpy 

    array. 

 

    :type data: StringIO.StringIO object. 

    :param data: The actual data. 

    :type data_type: String 

    :param data_type: The data type of the expected data. Currently supported 

        are 'INTEGER' and 'FLOAT'. 

    """ 

    if data_type == "INTEGER": 

        dtype = "int" 

    elif data_type == "FLOAT": 

        dtype = "float32" 

    else: 

        raise NotImplementedError 

    # Seek to the beginning of the StringIO. 

    data.seek(0) 

    # Data will always be a StringIO. Avoid to send empty StringIOs to 

    # numpy.readtxt() which raises a warning. 

    if not data.buf: 

        return np.array([], dtype=dtype) 

    return loadtxt(data, dtype=dtype, ndlim=1) 

 

 

if __name__ == '__main__': 

    import doctest 

    doctest.testmod(exclude_empty=True)