/
tsindex.py
1751 lines (1561 loc) · 75.3 KB
/
tsindex.py
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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
obspy.clients.filesystem.tsindex - IRIS TSIndex Client and Indexer
==========================================================================
The obspy.clients.filesystem.tsindex module includes a timeseries extraction
:class:`~obspy.clients.filesystem.tsindex.Client` class for a database created
by the IRIS
`mseedindex <https://github.com/iris-edu/mseedindex>`_ program, as well as, a
:class:`~obspy.clients.filesystem.tsindex.Indexer` class for creating a SQLite3
database that follows the IRIS `tsindex database
schema <https://github.com/iris-edu/mseedindex/wiki/Database-Schema/>`_\.
:copyright:
Nick Falco, Chad Trabant, IRISDMC, 2018
The ObsPy Development Team (devs@obspy.org)
:license:
GNU Lesser General Public License, Version 3
(https://www.gnu.org/copyleft/lesser.html)
.. contents:: Contents
:local:
:depth: 2
------------
Client Usage
------------
The first step is always to initialize a client object.
.. highlight:: python
>>> from obspy.clients.filesystem.tsindex import Client
>>> from obspy.clients.filesystem.tests.test_tsindex \
import get_test_data_filepath
>>> # for this example get the file path to test data
>>> filepath = get_test_data_filepath()
>>> db_path = os.path.join(filepath, 'timeseries.sqlite')
>>> # create a new Client instance
>>> client = Client(db_path, datapath_replace=("^", filepath))
The example below uses the test SQLite3 tsindex database included with ObsPy to
illustrate how to do the following:
* Determine what data is available in the tsindex database using
:meth:`~obspy.clients.filesystem.tsindex.Client.get_availability_extent()`
and :meth:`~obspy.clients.filesystem.tsindex.Client.get_availability()`, as
well as, the percentage of data available using
:meth:`~obspy.clients.filesystem.tsindex.Client.get_availability_percentage()`.
* Request available timeseries data using
:meth:`~obspy.clients.filesystem.tsindex.Client.get_waveforms()` and
:meth:`~obspy.clients.filesystem.tsindex.Client.get_waveforms_bulk()`.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Determining Data Availability
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* :meth:`~obspy.clients.filesystem.tsindex.Client.get_availability_extent()`:
Returns a list of (network, station, location, channel, earliest, latest)
tuples that represent the full extent of available data. This example
retrieves from the very small obspy test tsindex database a list of all
available (``"BHZ"``) channel extents from the Global Seismograph Network
(``"IU"``) for all times.
>>> extents = client.get_availability_extent(network="IU", channel="BHZ")
>>> for extent in extents:
... print("{0:<3} {1:<6} {2:<3} {3:<4} {4} {5}".format(*extent))
IU ANMO 10 BHZ 2018-01-01T00:00:00.019500Z 2018-01-01T00:00:59.994536Z
IU COLA 10 BHZ 2018-01-01T00:00:00.019500Z 2018-01-01T00:00:59.994538Z
* :meth:`~obspy.clients.filesystem.tsindex.Client.get_availability()`:
Works in the same way as
:meth:`~obspy.clients.filesystem.tsindex.Client.get_availability_extent()`
but returns a list of (network, station, location, channel, starttime,
endtime) tuples representing contiguous time spans for selected channels
and time ranges.
* :meth:`~obspy.clients.filesystem.tsindex.Client.get_percentage_availability()`_\: # NOQA
Returns the 2-tuple of percentage of available data (`0.0` to `1.0`) and
number of gaps/overlaps. Percentage availability is calculated relative to
the provided starttime and endtime.
>>> from obspy import UTCDateTime
>>> avail_percentage = client.get_availability_percentage( \
"IU", \
"ANMO", \
"10", \
"BHZ", \
UTCDateTime(2018, 1, 1, 0, 0, 0, 19500), \
UTCDateTime(2018, 1, 1, 0, 1, 57, 994536))
>>> print(avail_percentage)
(0.5083705674817509, 0)
^^^^^^^^^^^^^^^^^^^^^^^^^^
Requesting Timeseries Data
^^^^^^^^^^^^^^^^^^^^^^^^^^
* :meth:`~obspy.clients.filesystem.tsindex.Client.get_waveforms()`:
This example illustrates how to request 1 second of available (``"IU"``)
timeseries data in the test tsindex database. Results are returned as a
:class:`~obspy.core.stream.Stream` object. See the
:meth:`~obspy.clients.filesystem.tsindex.Client.get_waveforms_bulk()`
method for information on how to make multiple requests at once.
>>> t = UTCDateTime("2018-01-01T00:00:00.019500")
>>> st = client.get_waveforms("IU", "*", "*", "BHZ", t, t + 1)
>>> st.plot() # doctest: +SKIP
.. plot::
from obspy import UTCDateTime
from obspy.clients.filesystem.tsindex import Client
from obspy.clients.filesystem.tests.test_tsindex \
import get_test_data_filepath
# for this example get the file path to test data
filepath = get_test_data_filepath()
db_path = os.path.join(filepath, 'timeseries.sqlite')
# create a new Client instance
client = Client(db_path, datapath_replace=("^", filepath))
t = UTCDateTime("2018-01-01T00:00:00.019500")
st = client.get_waveforms("IU", "*", "*", "BHZ", t, t + 1)
st.plot()
-------------
Indexer Usage
-------------
The :class:`~obspy.clients.filesystem.tsindex.Indexer` provides a high level
API for indexing a directory tree of miniSEED files using the IRIS
`mseedindex <https://github.com/iris-edu/mseedindex/>`_ software.
Initialize a indexer object by supplying the root path to data to be indexed.
>>> from obspy.clients.filesystem.tsindex import Indexer
>>> from obspy.clients.filesystem.tests.test_tsindex \
import get_test_data_filepath
>>> # for this example get the file path to test data
>>> filepath = get_test_data_filepath()
>>> # create a new Indexer instance
>>> indexer = Indexer(filepath, filename_pattern='*.mseed')
Index a directory tree of miniSEED files by calling
:meth:`~obspy.clients.filesystem.tsindex.Indexer.run`. By default this will
create a database called 'timeseries.sqlite' in the current working directory.
The name of the index database can be changed by supplying the 'database'
parameter when instantiating the Indexer object.
.. code-block:: python
indexer.run()
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import * # NOQA
from future.utils import native_str
import os
from os.path import relpath
from glob import glob
import datetime
import uuid
import subprocess
import copyreg
from multiprocessing import Pool
import types
import logging
import requests
from collections import namedtuple
from sqlalchemy import create_engine
from sqlalchemy.pool import QueuePool
from obspy import UTCDateTime
from obspy.core.stream import Stream
from obspy.clients.filesystem.miniseed import MiniseedDataExtractor, \
NoDataError
# Setup the logger.
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# Prevent propagating to higher loggers.
logger.propagate = 0
# Console log handler. By default any logs of level info and above are
# written to the console
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# Add formatter
FORMAT = "[%(asctime)s] - %(name)s - %(levelname)s: %(message)s"
formatter = logging.Formatter(FORMAT)
ch.setFormatter(formatter)
logger.addHandler(ch)
def _pickle_method(m):
"""
Allows serializing of class and instance methods.
"""
if m.im_self is None:
return getattr, (m.im_class, m.im_func.func_name)
else:
return getattr, (m.im_self, m.im_func.func_name)
copyreg.pickle(types.MethodType, _pickle_method)
class Client(object):
"""
Time series extraction client for IRIS tsindex database schema.
"""
def __init__(self, database, datapath_replace=None, debug=False):
"""
Initializes the client.
:type database: str or
:class:`~obspy.clients.filesystem.tsindex.TSIndexDatabaseHandler`
:param database: Path to sqlite tsindex database or a
TSIndexDatabaseHandler object
:type datapath_replace: tuple
:param datapath_replace: A 2-value tuple, where any occurrence
of the first value will be replaced with the second value in
filename paths from the index.
:type debug: bool
:param debug: Debug flag.
:type logger: logging.Logger
:param logger: The logger instance to use for logging.
"""
self.debug = debug
if self.debug is True:
# write debug level logs to the console
ch.setLevel(logging.DEBUG)
# setup handler for database
if isinstance(database, (str, native_str)):
self.request_handler = TSIndexDatabaseHandler(database,
debug=self.debug)
elif isinstance(database, TSIndexDatabaseHandler):
self.request_handler = database
else:
raise ValueError("database must be a string or "
"TSIndexDatabaseHandler object.")
# Create and configure the data extraction
self.data_extractor = MiniseedDataExtractor(
dp_replace=datapath_replace,
debug=self.debug)
def get_waveforms(self, network, station, location,
channel, starttime, endtime, merge=-1):
"""
Query tsindex database and read miniSEED data from local
indexed directory tree.
:type network: str
:param network: Network code of requested data (e.g. "IU").
Wildcards '*' and '?' are supported.
:type station: str
:param station: Station code of requested data (e.g. "ANMO").
Wildcards '*' and '?' are supported.
:type location: str
:param location: Location code of requested data (e.g. "").
Wildcards '*' and '?' are supported.
:type channel: str
:param channel: Channel code of requested data (e.g. "HHZ").
Wildcards '*' and '?' are supported.
:type starttime: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param starttime: Start of requested time window.
:type endtime: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param endtime: End of requested time window.
:type merge: int or None
:param merge: Specifies, which merge operation should be performed
on the stream before returning the data. Default (``-1``) means
only a conservative cleanup merge is performed to merge seamless
traces (e.g. when reading across day boundaries). See
:meth:`Stream.merge(...) <obspy.core.stream.Stream.merge>` for
details. If set to ``None`` (or ``False``) no merge operation at
all will be performed.
:rtype: `~obspy.core.stream.Stream`
:returns: A ObsPy `~obspy.core.stream.Stream` object containing
requested timeseries data.
"""
query_rows = [(network, station, location,
channel, starttime, endtime)]
return self._get_waveforms(query_rows, merge)
def get_waveforms_bulk(self, query_rows, merge=-1):
"""
Query tsindex database and read miniSEED data from local
indexed directory tree using a bulk request.
:type query_rows: str
:param network: A list of tuples [(net, sta, loc, cha, starttime,
endtime),...] containing information on what timeseries should be
returned from the indexed archive.
Wildcards '*' and '?' are supported.
:param merge: Specifies, which merge operation should be performed
on the stream before returning the data. Default (``-1``) means
only a conservative cleanup merge is performed to merge seamless
traces (e.g. when reading across day boundaries). See
:meth:`Stream.merge(...) <obspy.core.stream.Stream.merge>` for
details. If set to ``None`` (or ``False``) no merge operation at
all will be performed.
:rtype: `~obspy.core.stream.Stream`
:returns: A ObsPy `~obspy.core.stream.Stream` object containing
requested timeseries data.
"""
return self._get_waveforms(query_rows, merge)
def get_nslc(self, network=None, station=None, location=None,
channel=None, starttime=None, endtime=None):
"""
Get a list of tuples [(net, sta, loc, cha),...] containing information
on what streams are included in the tsindex database.
:type network: str
:param network: Network code of requested data (e.g. "IU").
Wildcards '*' and '?' are supported.
:type station: str
:param station: Station code of requested data (e.g. "ANMO").
Wildcards '*' and '?' are supported.
:type location: str
:param location: Location code of requested data (e.g. "").
Wildcards '*' and '?' are supported.
:type channel: str
:param channel: Channel code of requested data (e.g. "HHZ").
Wildcards '*' and '?' are supported.
:type starttime: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param starttime: Start of requested time window.
:type endtime: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param endtime: End of requested time window.
:rtype: list
:returns: A list of tuples [(network, station, location, channel)...]
containing information on what streams are included in the tsindex
database.
"""
summary_rows = self._get_summary_rows(network, station, location,
channel, starttime, endtime)
nslc_list = []
for row in summary_rows:
nslc = (row.network, row.station, row.location, row.channel)
nslc_list.append(nslc)
return nslc_list
def get_availability_extent(self, network=None, station=None,
location=None, channel=None, starttime=None,
endtime=None):
"""
Get a list of tuples [(network, station, location, channel,
earliest, latest)] containing data extent info for time series
included in the tsindex database.
:type network: str
:param network: Network code of requested data (e.g. "IU").
Wildcards '*' and '?' are supported.
:type station: str
:param station: Station code of requested data (e.g. "ANMO").
Wildcards '*' and '?' are supported.
:type location: str
:param location: Location code of requested data (e.g. "").
Wildcards '*' and '?' are supported.
:type channel: str
:param channel: Channel code of requested data (e.g. "HHZ").
Wildcards '*' and '?' are supported.
:type starttime: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param starttime: Start of requested time window.
:type endtime: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param endtime: End of requested time window.
:rtype: list
:returns: A list of tuples [(network, station, location, channel,
earliest, latest)...] containing data extent info for time series
included in the tsindex database.
"""
summary_rows = self._get_summary_rows(network, station,
location, channel,
starttime, endtime)
availability_extents = []
for row in summary_rows:
extent = (row.network, row.station, row.location, row.channel,
UTCDateTime(row.earliest), UTCDateTime(row.latest))
availability_extents.append(extent)
return availability_extents
def get_availability(self, network=None, station=None, location=None,
channel=None, starttime=None, endtime=None,
include_sample_rate=False,
merge_overlap=False):
"""
Get a list of tuples [(network, station, location, channel,
starttime, endtime),...] containing data availability info for
time series included in the tsindex database.
If include_sample_rate=True, then a tuple containing the sample
rate [(net, sta, loc, cha, start, end, sample_rate),...] is returned.
If merge_overlap=True, then all time spans that overlap are merged.
:type network: str
:param network: Network code of requested data (e.g. "IU").
Wildcards '*' and '?' are supported.
:type station: str
:param station: Station code of requested data (e.g. "ANMO").
Wildcards '*' and '?' are supported.
:type location: str
:param location: Location code of requested data (e.g. "").
Wildcards '*' and '?' are supported.
:type channel: str
:param channel: Channel code of requested data (e.g. "HHZ").
Wildcards '*' and '?' are supported.
:type starttime: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param starttime: Start of requested time window.
:type endtime: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param endtime: End of requested time window.
:type include_sample_rate: bool
:param include_sample_rate: If include_sample_rate=True, then
a tuple containing the sample rate [(net, sta, loc, cha,
start, end, sample_rate),...] is returned.
:type mege_overlap: bool
:param merge_overlap: If merge_overlap=True, then all time
spans that overlap are merged.
:rtype: list
:returns: A list of tuples [(network, station, location, channel,
earliest, latest)...] representing contiguous time spans for
selected channels and time ranges.
"""
tsindex_rows = self._get_tsindex_rows(network, station,
location, channel,
starttime, endtime)
grouped_channels = {}
for row in tsindex_rows:
if include_sample_rate is True:
# split on different sample rates when merging
hash = "{}_{}_{}_{}_{}".format(row.network,
row.station,
row.location,
row.channel,
row.samplerate)
else:
# ignore sample rate when merging
hash = "{}_{}_{}_{}".format(row.network,
row.station,
row.location,
row.channel)
timespans = self._create_timespans_list(row.timespans)
if grouped_channels.get(hash) is not None:
if row.samplerate not in \
grouped_channels[hash]["samplerates"]:
grouped_channels[hash]["samplerates"].append(
row.samplerate)
grouped_channels[hash]["timespans"].extend(timespans)
else:
grouped_channels[hash] = {}
grouped_channels[hash]["samplerates"] = [row.samplerate]
grouped_channels[hash]["timespans"] = timespans
# sort timespans
for _, channel_group in grouped_channels.items():
channel_group["timespans"].sort()
# join timespans
joined_avail_tuples = []
for sncl, channel_group in grouped_channels.items():
net, sta, loc, cha = sncl.split("_")[:4]
samplerates = channel_group["samplerates"]
timespans = channel_group["timespans"]
avail_data = self._get_availability_from_timespans(
net,
sta,
loc,
cha,
samplerates,
include_sample_rate,
merge_overlap,
timespans
)
# extend complete list of available data
joined_avail_tuples.extend(avail_data)
return joined_avail_tuples
def get_availability_percentage(self, network, station,
location, channel,
starttime, endtime):
"""
Get percentage of available data.
:type network: str
:param network: Network code of requested data (e.g. "IU").
:type station: str
:param station: Station code of requested data (e.g. "ANMO").
:type location: str
:param location: Location code of requested data (e.g. "").
:type channel: str
:param channel: Channel code of requested data (e.g. "HHZ").
:type starttime: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param starttime: Start of requested time window.
:type endtime: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param endtime: End of requested time window.
:rtype: 2-tuple (float, int)
:returns: 2-tuple of percentage of available data (``0.0`` to ``1.0``)
and number of gaps/overlaps.
"""
avail = self.get_availability(network, station,
location, channel,
starttime, endtime,
merge_overlap=True)
if not avail:
return (0, 1)
total_duration = endtime - starttime
# sum up gaps in the middle
gap_sum = 0
gap_count = 0
for idx, cur_ts in enumerate(avail[1:]):
prev_ts = avail[idx]
gap_count = gap_count + 1
gap_sum += cur_ts[4] - prev_ts[5]
# check if we have a gap at start or end
earliest = min([ts[4] for ts in avail])
latest = max([ts[5] for ts in avail])
if earliest > starttime:
gap_sum += earliest - starttime
gap_count += 1
if latest < endtime:
gap_sum += endtime - latest
gap_count += 1
return (1 - (gap_sum / total_duration), gap_count)
def has_data(self, network=None, station=None, location=None,
channel=None, starttime=None, endtime=None):
"""
Return whether there is data for a specified network, station,
location, channel, starttime, and endtime combination.
:type network: str
:param network: Network code of requested data (e.g. "IU").
Wildcards '*' and '?' are supported.
:type station: str
:param station: Station code of requested data (e.g. "ANMO").
Wildcards '*' and '?' are supported.
:type location: str
:param location: Location code of requested data (e.g. "").
Wildcards '*' and '?' are supported.
:type channel: str
:param channel: Channel code of requested data (e.g. "HHZ").
Wildcards '*' and '?' are supported.
:type starttime: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param starttime: Start of requested time window. Defaults to
minimum possible start date.
:type endtime: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param endtime: End of requested time window. Defaults to
maximum possible end date.
:rtype: bool
:returns: Returns True if there is data in the index for a given
network, station, location, channel, starttime, endtime.
"""
if starttime is None:
starttime = UTCDateTime(year=datetime.MINYEAR,
month=1,
day=1)
if endtime is None:
endtime = UTCDateTime(year=datetime.MAXYEAR,
month=12,
day=31)
avail_percentage = self.get_availability_percentage(network,
station,
location,
channel,
starttime,
endtime)[0]
if avail_percentage > 0:
return True
else:
return False
def _get_summary_rows(self, network, station, location, channel,
starttime, endtime):
"""
Return a list of tuples [(net, sta, loc, cha, earliest, latest),...]
containing information found in the tsindex_summary table.
Information about the tsindex_summary schema may be found at:
https://github.com/iris-edu/mseedindex/wiki/Database-Schema#suggested-time-series-summary-table # NOQA
:type network: str
:param network: Network code of requested data (e.g. "IU").
Wildcards '*' and '?' are supported.
:type station: str
:param station: Station code of requested data (e.g. "ANMO").
Wildcards '*' and '?' are supported.
:type location: str
:param location: Location code of requested data (e.g. "").
Wildcards '*' and '?' are supported.
:type channel: str
:param channel: Channel code of requested data (e.g. "HHZ").
Wildcards '*' and '?' are supported.
:type starttime: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param starttime: Start of requested time window.
:type endtime: :class:`~obspy.core.utcdatetime.UTCDateTime`
"""
query_rows = [(network, station, location,
channel, starttime, endtime)]
return self.request_handler._fetch_summary_rows(query_rows)
def _get_waveforms(self, query_rows, merge=-1):
"""
Query tsindex database and read miniSEED data from local
indexed directory tree using a bulk request and return a
~obspy.core.stream.Stream object containing the requested
timeseries data.
:type query_rows: str
:param network: A list of tuples [(net, sta, loc, cha, starttime,
endtime),...] containing information on what timeseries should be
returned from the indexed archive.
Wildcards '*' and '?' are supported.
:param merge: Specifies, which merge operation should be performed
on the stream before returning the data. Default (``-1``) means
only a conservative cleanup merge is performed to merge seamless
traces (e.g. when reading across day boundaries). See
:meth:`Stream.merge(...) <obspy.core.stream.Stream.merge>` for
details. If set to ``None`` (or ``False``) no merge operation at
all will be performed.
"""
# Get the corresponding index DB entries
index_rows = self.request_handler._fetch_index_rows(query_rows)
total_bytes = 0
src_bytes = {}
logger.debug("Starting data return")
st = Stream(traces=[])
try:
# Extract the data, writing each returned segment to the response
for data_segment in self.data_extractor.extract_data(index_rows):
bytes_written = data_segment.get_num_bytes()
src_name = data_segment.get_src_name()
if bytes_written > 0:
st_segment = data_segment.read_stream()
st += st_segment
total_bytes += bytes_written
src_bytes.setdefault(src_name, 0)
src_bytes[src_name] += bytes_written
except NoDataError:
logger.debug("No data matched selection")
logger.debug("Wrote {} bytes".format(total_bytes))
if merge is None or merge is False:
pass
else:
st.merge(merge)
return st
def _get_tsindex_rows(self, network, station, location, channel, starttime,
endtime):
"""
Return a list of tuples [(net, sta, loc, cha, quality... etc.),...]
containing information found in the tsindex table.
Information about the tsindex schema may be found at:
https://github.com/iris-edu/mseedindex/wiki/Database-Schema#sqlite-schema-version-11 # NOQA
:type network: str
:param network: Network code of requested data (e.g. "IU").
Wildcards '*' and '?' are supported.
:type station: str
:param station: Station code of requested data (e.g. "ANMO").
Wildcards '*' and '?' are supported.
:type location: str
:param location: Location code of requested data (e.g. "").
Wildcards '*' and '?' are supported.
:type channel: str
:param channel: Channel code of requested data (e.g. "HHZ").
Wildcards '*' and '?' are supported.
:type starttime: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param starttime: Start of requested time window.
:type endtime: :class:`~obspy.core.utcdatetime.UTCDateTime`
"""
query_rows = [(network, station, location,
channel, starttime, endtime)]
return self.request_handler._fetch_index_rows(query_rows)
def _get_availability_from_timespans(self, network, station,
location, channel,
samplerates,
include_sample_rate,
merge_overlap,
timespans,
_sncl_joined_avail_tuples=None):
"""
Recurse over a list of timespans, joining adjacent timespans,
and merging if merge_overlaps is True.
Returns a list of tuples (network, station, location, channel,
earliest, latest) representing available data.
:type network: str
:param network: Network code of requested data (e.g. "IU").
Wildcards '*' and '?' are supported.
:type station: str
:param station: Station code of requested data (e.g. "ANMO").
Wildcards '*' and '?' are supported.
:type location: str
:param location: Location code of requested data (e.g. "").
Wildcards '*' and '?' are supported.
:type channel: str
:param channel: Channel code of requested data (e.g. "HHZ").
Wildcards '*' and '?' are supported.
:type starttime: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param starttime: Start of requested time window.
:type endtime: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param endtime: End of requested time window.
:type timespans: list
:param timespans: List of timespan tuples
"""
if _sncl_joined_avail_tuples is None:
_sncl_joined_avail_tuples = []
sr = min(samplerates)
if len(timespans) > 1:
prev_ts = timespans.pop(0)
cur_ts = timespans.pop(0)
if merge_overlap is True and \
self._do_timespans_overlap(prev_ts, cur_ts) is True:
# merge if overlapping timespans and merge_overlap
# option is set to true
merged_ts = self._create_timespan(prev_ts.earliest,
cur_ts.latest)
timespans.insert(0, merged_ts)
return self._get_availability_from_timespans(
network, station,
location, channel,
samplerates,
include_sample_rate,
merge_overlap,
timespans,
_sncl_joined_avail_tuples)
elif self._are_timespans_adjacent(prev_ts, cur_ts, sr, 0.5):
# merge if timespans are next to each other within
# a 0.5 sample tolerance
merged_ts = self._create_timespan(prev_ts.earliest,
cur_ts.latest)
timespans.insert(0, merged_ts)
return self._get_availability_from_timespans(
network, station,
location, channel,
samplerates,
include_sample_rate,
merge_overlap,
timespans,
_sncl_joined_avail_tuples)
else:
# timespan shouldn't be merged so add to list
avail_tuple = self._create_avail_tuple(
network, station,
location, channel,
prev_ts.earliest,
prev_ts.latest,
sr=sr if include_sample_rate
else None)
_sncl_joined_avail_tuples.append(avail_tuple)
timespans.insert(0, cur_ts)
return self._get_availability_from_timespans(
network, station,
location, channel,
samplerates,
include_sample_rate,
merge_overlap,
timespans,
_sncl_joined_avail_tuples)
else:
# no other timespans to merge with
cur_ts = timespans.pop(0)
avail_tuple = self._create_avail_tuple(
network, station,
location, channel,
cur_ts.earliest,
cur_ts.latest,
sr=sr if include_sample_rate
else None)
_sncl_joined_avail_tuples.append(avail_tuple)
return _sncl_joined_avail_tuples
def _are_timespans_adjacent(self, ts1, ts2, sample_rate, tolerance=0.5):
"""
Checks whether or not two time span named tuples
(e.g. NameTuple(earliest, latest)) are adjacent within
a given tolerance
:type ts1: namedtuple
:param ts1: Earliest timespan.
:type ts2: namedtuple
:param ts2: Latest timespan.
:type sample_rate: int
:param sample_rate: Sensor sample rate
:type tolerance: float
:param tolerance: Tolerance to determine whether a adjacent
timespan should be merged.
"""
# @40Hz sample period = 0.025
sample_period = 1. / float(sample_rate)
expected_next = ts1.latest + sample_period
# @40Hz tolerance = 0.0125
tolerance_amount = (tolerance*sample_period)
actual_next = ts2.earliest
if expected_next + tolerance_amount > actual_next and \
expected_next - tolerance_amount < actual_next:
return True
else:
return False
def _do_timespans_overlap(self, ts1, ts2):
"""
Checks whether or not two time span named tuples
(e.g. NameTuple(earliest, latest)) intersect with
one another.
:type ts1: namedtuple
:param ts1: Earliest timespan.
:type ts2: namedtuple
:param ts2: Latest timespan.
"""
if ts1.earliest <= ts2.latest and \
ts1.latest >= ts2.earliest:
return True
else:
return False
def _create_avail_tuple(self, network, station, location, channel,
earliest, latest, sr=None):
"""
Returns a tuple representing available waveform data.
:type network: str
:param network: Network code of requested data (e.g. "IU").
Wildcards '*' and '?' are supported.
:type station: str
:param station: Station code of requested data (e.g. "ANMO").
Wildcards '*' and '?' are supported.
:type location: str
:param location: Location code of requested data (e.g. "").
Wildcards '*' and '?' are supported.
:type channel: str
:param channel: Channel code of requested data (e.g. "HHZ").
Wildcards '*' and '?' are supported.
:type earliest: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param earliest: Earliest date of timespan.
:type latest: :class:`~obspy.core.utcdatetime.UTCDateTime`
:param latest: Latest date of timespan.
"""
if sr is not None:
avail_record = (network, station, location, channel,
UTCDateTime(float(earliest)),
UTCDateTime(float(latest)), sr)
else:
avail_record = (network, station, location, channel,
UTCDateTime(float(earliest)),
UTCDateTime(float(latest)))
return avail_record
def _create_timespan(self, earliest, latest):
"""
Create a TimeSpan named tuple object given a earliest and latest date.
:param earliest: Earliest date of timespan.
:param latest: Latest date of timespan.
"""
TimeSpan = namedtuple('TimeSpan',
['earliest', 'latest'])
return TimeSpan(earliest, latest)
def _create_timespans_list(self, raw_timespans):
"""
Given a timespans string from the database, return
a list of named tuples.
:type raw_timespans: str
:param raw_timespans: timespans field from tsindex database table.
"""
timespans = []
unparsed_timespans = \
raw_timespans.replace("[", "").replace("]", "").split(",")
for t in unparsed_timespans:
earliest, latest = t.split(":")
ts = self._create_timespan(float(earliest), float(latest))
timespans.append(ts)
return timespans
class Indexer(object):
"""
Build an index for miniSEED data using IRIS's mseedindex program.
Recursively search for files matching `filename_pattern` starting
from `root_path` and run `index_cmd` for each target file found that
is not already in the index. After all new files are indexed a summary
table is generated with the extents of each time series.
"""
def __init__(self, root_path, database="timeseries.sqlite",
leap_seconds_file="SEARCH", index_cmd='mseedindex',
bulk_params=None, filename_pattern='*', parallel=5,
debug=False):
"""
Initializes the Indexer.
:type root_path: str
:param root_path: Root path to the directory structure to index.
:type database: str or
:class:`~obspy.clients.filesystem.tsindex.TSIndexDatabaseHandler`
:param database: Path to sqlite tsindex database or a
TSIndexDatabaseHandler object. A database will be created
if one does not already exists at the specified path.
:type leap_seconds_file: str
:param leap_seconds_file: Path to leap seconds file. If set to
"SEARCH" (default), then the program looks for a leap seconds file
in the same directory as the sqlite3 database. If set to `None`
then no leap seconds file will be used.
In :meth:`~obspy.clients.filesystem.tsindex.Indexer.run` the leap
seconds listed in this file will be used to adjust the time
coverage for records that contain a leap second. Also, leap second
indicators in the miniSEED headers will be ignored. See the
`mseedindex wiki <https://github.com/iris-edu/mseedindex/blob/"
"master/doc/mseedindex.md#leap-second-list-file>`_ for more"
"for more information regarding this file.
:type index_cmd: str
:param index_cmd: Command to be run for each target file found that
is not already in the index
:type bulk_params: dict
:param bulk_params: Dictionary of options to pass to index_cmd.
:type filename_pattern: str
:param filename_pattern:
:type parallel: int
:param parallel: Max number of index_cmd instances to run in parallel.
By default a max of 5 parallel process are run.
:type debug: bool
:param debug: Debug flag. Sets logging level to debug.
"""
self.debug = debug
if self.debug is True:
# write debug level logs to the console
ch.setLevel(logging.DEBUG)
self.index_cmd = index_cmd
if bulk_params is None:
bulk_params = {}
self.bulk_params = bulk_params
self.filename_pattern = filename_pattern
self.parallel = parallel
# setup handler for database
if isinstance(database, (str, native_str)):
self.request_handler = TSIndexDatabaseHandler(database,
debug=self.debug)
elif isinstance(database, TSIndexDatabaseHandler):
self.request_handler = database
else:
raise ValueError("database must be a string or "
"TSIndexDatabaseHandler object.")
self.leap_seconds_file = self._get_leap_seconds_file(leap_seconds_file)
self.root_path = os.path.abspath(root_path)
if not os.path.isdir(self.root_path):
raise OSError("Root path `{}` does not exists."
.format(self.root_path))
def run(self, build_summary=True, relative_paths=False, reindex=False):
"""
Execute the file discovery and indexing.
:type build_summary: bool
:param build_summary: By default, a summary table is (re)generated
containing the extents for each time series in the index. This can
be turned off by setting `build_summary` to False.
:type relative_paths: bool
:param relative_paths: By default, the absolute path to each file is
stored in the index. If `relative_paths` is True, the file paths
will be relative to the `root_path`.
type reindex: bool
:param reindex: By default, files are not indexed that are already in
the index and have not been modified. The `reindex` option can be
set to True to force a re-indexing of all files regardless.
"""
if self._is_index_cmd_installed() is False:
raise OSError(
"Required program `{}` is not installed. Hint: Install "
"mseedindex at https://github.com/iris-edu/mseedindex/."
.format(self.index_cmd))
self.request_handler._init_database_for_indexing()
file_paths = self.build_file_list(relative_paths, reindex)