-
Notifications
You must be signed in to change notification settings - Fork 529
/
test_stream.py
2844 lines (2672 loc) · 108 KB
/
test_stream.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 -*-
import inspect
import io
import os
import pickle
import platform
import warnings
from copy import deepcopy
from os.path import dirname, join, abspath
from pathlib import Path
from unittest import mock
import numpy as np
import pytest
from obspy import Stream, Trace, UTCDateTime, read, read_inventory
from obspy.core.inventory import Channel, Inventory, Network, Station
from obspy.core.stream import _is_pickle, _read_pickle, _write_pickle
from obspy.core.util.attribdict import AttribDict
from obspy.core.util.base import NamedTemporaryFile, _get_entry_points
from obspy.core.util.obspy_types import ObsPyException
from obspy.core.util.testing import streams_almost_equal
from obspy.io.xseed import Parser
class TestStream:
"""
Test suite for obspy.core.stream.Stream.
"""
_current_file = inspect.getfile(inspect.currentframe())
data_path = join(dirname(abspath(_current_file)), "data")
@pytest.fixture()
def mseed_stream(self):
"""Create a stream for testing."""
rand = np.random.RandomState(815)
header = {'network': 'BW', 'station': 'BGLD',
'starttime': UTCDateTime(2007, 12, 31, 23, 59, 59, 915000),
'npts': 412, 'sampling_rate': 200.0,
'channel': 'EHE'}
trace1 = Trace(data=rand.randint(0, 1000, 412).astype(np.float64),
header=deepcopy(header))
header['starttime'] = UTCDateTime(2008, 1, 1, 0, 0, 4, 35000)
header['npts'] = 824
trace2 = Trace(data=rand.randint(0, 1000, 824).astype(np.float64),
header=deepcopy(header))
header['starttime'] = UTCDateTime(2008, 1, 1, 0, 0, 10, 215000)
trace3 = Trace(data=rand.randint(0, 1000, 824).astype(np.float64),
header=deepcopy(header))
header['starttime'] = UTCDateTime(2008, 1, 1, 0, 0, 18, 455000)
header['npts'] = 50668
trace4 = Trace(
data=rand.randint(0, 1000, 50668).astype(np.float64),
header=deepcopy(header))
return Stream(traces=[trace1, trace2, trace3, trace4])
@pytest.fixture()
def gse2_stream(self):
"""Another example stream."""
rand = np.random.RandomState(815)
header = {'network': '', 'station': 'RNON ', 'location': '',
'starttime': UTCDateTime(2004, 6, 9, 20, 5, 59, 849998),
'sampling_rate': 200.0, 'npts': 12000,
'channel': ' Z'}
trace = Trace(
data=rand.randint(0, 1000, 12000).astype(np.float64),
header=header)
return Stream(traces=[trace])
@staticmethod
def __remove_processing(st):
"""
Helper method removing the processing information from all traces
within a Stream object.
Useful for testing.
"""
for tr in st:
if "processing" not in tr.stats:
continue
del tr.stats.processing
def test_init(self):
"""
Tests the __init__ method of the Stream object.
"""
# empty
st = Stream()
assert len(st) == 0
# single trace
st = Stream(Trace())
assert len(st) == 1
# array of traces
st = Stream([Trace(), Trace()])
assert len(st) == 2
def test_setitem(self, mseed_stream):
"""
Tests the __setitem__ method of the Stream object.
"""
stream = mseed_stream
stream[0] = stream[3]
assert stream[0] == stream[3]
st = deepcopy(stream)
stream[0].data[0:10] = 999
assert st[0].data[0] != 999
st[0] = stream[0]
np.testing.assert_array_equal(stream[0].data[:10],
np.ones(10, dtype=np.int_) * 999)
def test_getitem(self):
"""
Tests the __getitem__ method of the Stream object.
"""
stream = read()
assert stream[0] == stream.traces[0]
assert stream[-1] == stream.traces[-1]
assert stream[2] == stream.traces[2]
# out of index should fail
with pytest.raises(IndexError):
stream.__getitem__(3)
with pytest.raises(IndexError):
stream.__getitem__(-99)
def test_add(self, mseed_stream, gse2_stream):
"""
Tests the adding of two stream objects.
"""
stream = mseed_stream
assert 4 == len(stream)
# Add the same stream object to itself.
stream = stream + stream
assert 8 == len(stream)
# This will not create copies of Traces and thus the objects should
# be identical (and the Traces attributes should be identical).
for _i in range(4):
assert (stream[_i] == stream[_i + 4])
assert (stream[_i] is stream[_i + 4])
# Now add another stream to it.
other_stream = gse2_stream
assert 1 == len(other_stream)
new_stream = stream + other_stream
assert 9 == len(new_stream)
# The traces of all streams are copied.
for _i in range(8):
assert new_stream[_i] == stream[_i]
assert new_stream[_i] is stream[_i]
# Also test for the newly added stream.
assert new_stream[8] == other_stream[0]
assert new_stream[8].stats == other_stream[0].stats
np.testing.assert_array_equal(new_stream[8].data, other_stream[0].data)
# adding something else than stream or trace results into TypeError
with pytest.raises(TypeError):
stream.__add__(1)
with pytest.raises(TypeError):
stream.__add__('test')
def test_iadd(self, mseed_stream, gse2_stream):
"""
Tests the __iadd__ method of the Stream objects.
"""
stream = mseed_stream
assert 4 == len(stream)
other_stream = gse2_stream
assert 1 == len(other_stream)
# Add the other stream to the stream.
stream += other_stream
# This will leave the Traces of the new stream and create a deepcopy of
# the other Stream's Traces
assert 5 == len(stream)
assert other_stream[0] == stream[-1]
assert other_stream[0].stats == stream[-1].stats
np.testing.assert_array_equal(other_stream[0].data, stream[-1].data)
# adding something else than stream or trace results into TypeError
with pytest.raises(TypeError):
stream.__iadd__(1)
with pytest.raises(TypeError):
stream.__iadd__('test')
def test_mul(self):
"""
Tests the __mul__ method of the Stream objects.
"""
st = Stream(Trace())
assert len(st) == 1
st = st * 4
assert len(st) == 4
# multiplying by something else than an integer results into TypeError
with pytest.raises(TypeError):
st.__mul__(1.2345)
with pytest.raises(TypeError):
st.__mul__('test')
def test_add_trace_to_stream(self):
"""
Tests using a Trace on __add__ and __iadd__ methods of the Stream.
"""
st0 = read()
st1 = st0[0:2]
tr = st0[2]
# __add__
assert st1.__add__(tr) == st0
assert st1 + tr == st0
# __iadd__
st1 += tr
assert st1 == st0
def test_append(self, mseed_stream):
"""
Tests the append method of the Stream object.
"""
stream = mseed_stream
# Check current count of traces
assert len(stream) == 4
# Append first traces to the Stream object.
stream.append(stream[0])
assert len(stream) == 5
# This is supposed to make a deepcopy of the Trace and thus the two
# Traces are not identical.
assert stream[0] == stream[-1]
# But the attributes and data values should be identical.
assert stream[0].stats == stream[-1].stats
np.testing.assert_array_equal(stream[0].data, stream[-1].data)
# Append the same again
stream.append(stream[0])
assert len(stream) == 6
# Now the two objects should be identical.
assert stream[0] == stream[-1]
# Using append with a list of Traces, or int, or ... should fail.
with pytest.raises(TypeError):
stream.append(stream[:])
with pytest.raises(TypeError):
stream.append(1)
with pytest.raises(TypeError):
stream.append(stream[0].data)
def test_count_and_len(self):
"""
Tests the count and __len__ methods of the Stream object.
"""
# empty stream without traces
stream = Stream()
assert len(stream) == 0
assert stream.count() == 0
# stream with traces
stream = read()
assert len(stream) == 3
assert stream.count() == 3
def test_extend(self, mseed_stream):
"""
Tests the extend method of the Stream object.
"""
stream = mseed_stream
# Check current count of traces
assert len(stream) == 4
# Extend the Stream object with the first two traces.
stream.extend(stream[0:2])
assert len(stream) == 6
# This is NOT supposed to make a deepcopy of the Trace and thus the two
# Traces compare equal and are identical.
assert stream[0] == stream[-2]
assert stream[1] == stream[-1]
assert stream[0] is stream[-2]
assert stream[1] is stream[-1]
# Using extend with a single Traces, or a wrong list, or ...
# should fail.
with pytest.raises(TypeError):
stream.extend(stream[0])
with pytest.raises(TypeError):
stream.extend(1)
with pytest.raises(TypeError):
stream.extend([stream[0], 1])
def test_insert(self, mseed_stream):
"""
Tests the insert Method of the Stream object.
"""
stream = mseed_stream
assert 4 == len(stream)
# Insert the last Trace before the second trace.
stream.insert(1, stream[-1])
assert len(stream) == 5
# This is supposed to make a deepcopy of the Trace and thus the two
# Traces are not identical.
# self.assertNotEqual(stream[1], stream[-1])
assert stream[1] == stream[-1]
# But the attributes and data values should be identical.
assert stream[1].stats == stream[-1].stats
np.testing.assert_array_equal(stream[1].data, stream[-1].data)
# Do the same again
stream.insert(1, stream[-1])
assert len(stream) == 6
# Now the two Traces should be identical
assert stream[1] == stream[-1]
# Do the same with a list of traces this time.
# Insert the last two Trace before the second trace.
stream.insert(1, stream[-2:])
assert len(stream) == 8
# This is supposed to make a deepcopy of the Trace and thus the two
# Traces are not identical.
assert stream[1] == stream[-2]
assert stream[2] == stream[-1]
# But the attributes and data values should be identical.
assert stream[1].stats == stream[-2].stats
np.testing.assert_array_equal(stream[1].data, stream[-2].data)
assert stream[2].stats == stream[-1].stats
np.testing.assert_array_equal(stream[2].data, stream[-1].data)
# Do the same again
stream.insert(1, stream[-2:])
assert len(stream) == 10
# Now the two Traces should be identical
assert stream[1] == stream[-2]
assert stream[2] == stream[-1]
# Using insert without a single Traces or a list of Traces should fail.
with pytest.raises(TypeError):
stream.insert(1, 1)
with pytest.raises(TypeError):
stream.insert(stream[0], stream[0])
with pytest.raises(TypeError):
stream.insert(1, [stream[0], 1])
def test_get_gaps(self, mseed_stream):
"""
Tests the get_gaps method of the Stream objects.
It is compared directly to the obspy.io.mseed method getGapsList which
is assumed to be correct.
"""
stream = mseed_stream
gap_list = stream.get_gaps()
# Gaps list created with obspy.io.mseed
mseed_gap_list = [
('BW', 'BGLD', '', 'EHE',
UTCDateTime(2008, 1, 1, 0, 0, 1, 970000),
UTCDateTime(2008, 1, 1, 0, 0, 4, 35000),
2.0599999999999999, 412.0),
('BW', 'BGLD', '', 'EHE',
UTCDateTime(2008, 1, 1, 0, 0, 8, 150000),
UTCDateTime(2008, 1, 1, 0, 0, 10, 215000),
2.0599999999999999, 412.0),
('BW', 'BGLD', '', 'EHE',
UTCDateTime(2008, 1, 1, 0, 0, 14, 330000),
UTCDateTime(2008, 1, 1, 0, 0, 18, 455000),
4.120, 824.0)]
# Assert the number of gaps.
assert len(mseed_gap_list) == len(gap_list)
for _i in range(len(mseed_gap_list)):
# Compare the string values directly.
for _j in range(6):
assert gap_list[_i][_j] == mseed_gap_list[_i][_j]
# The small differences are probably due to rounding errors.
gap_6 = mseed_gap_list[_i][6]
gap_7 = mseed_gap_list[_i][7]
assert round(abs(float(gap_6)-float(gap_6)), 3) == 0
assert round(abs(float(gap_7)-float(gap_7)), 3) == 0
def test_get_gaps_multiplexed_streams(self):
"""
Tests the get_gaps method of the Stream objects.
"""
data = np.random.randint(0, 1000, 412)
# different channels
st = Stream()
for channel in ['EHZ', 'EHN', 'EHE']:
st.append(Trace(data=data, header={'channel': channel}))
assert len(st.get_gaps()) == 0
# different locations
st = Stream()
for location in ['', '00', '01']:
st.append(Trace(data=data, header={'location': location}))
assert len(st.get_gaps()) == 0
# different stations
st = Stream()
for station in ['MANZ', 'ROTZ', 'BLAS']:
st.append(Trace(data=data, header={'station': station}))
assert len(st.get_gaps()) == 0
# different networks
st = Stream()
for network in ['BW', 'GE', 'GR']:
st.append(Trace(data=data, header={'network': network}))
assert len(st.get_gaps()) == 0
def test_get_gaps_masked(self):
"""
Test get_gaps method of the Stream objects (Issue #2299)
"""
# Create a Stream with a masked array (analogous to a merged Stream)
st = Stream()
data = np.ma.array(np.arange(0, 100, step=1))
data.mask = np.zeros(data.shape)
data.mask[50:60] = 1
st.append(Trace(data=data))
# Expected gap
gap = ["", "", "", "",
UTCDateTime(1970, 1, 1, 0, 0, 49),
UTCDateTime(1970, 1, 1, 0, 1, 0),
10., 10]
# Get the gaps
gaps = st.get_gaps()
# Assert the number of gaps
assert len(gaps) == 1
# Verify the resulting gap list matches what is expected
for _i in range(6):
assert gaps[0][_i] == gap[_i]
assert round(abs(float(gaps[0][6])-float(gap[6])), 3) == 0
assert round(abs(float(gaps[0][7])-float(gap[7])), 7) == 0
# Double-check that the initial Stream is unmodified
assert len(st) == 1
def test_pop(self, mseed_stream):
"""
Test the pop method of the Stream object.
"""
stream = mseed_stream
# Make a copy of the Traces.
traces = deepcopy(stream[:])
# Remove and return the last Trace.
temp_trace = stream.pop()
assert 3 == len(stream)
# Assert attributes. The objects itself are not identical.
assert temp_trace.stats == traces[-1].stats
np.testing.assert_array_equal(temp_trace.data, traces[-1].data)
# Remove the last copied Trace.
traces.pop()
# Remove and return the second Trace.
temp_trace = stream.pop(1)
# Assert attributes. The objects itself are not identical.
assert temp_trace.stats == traces[1].stats
np.testing.assert_array_equal(temp_trace.data, traces[1].data)
# Remove the second copied Trace.
traces.pop(1)
# Compare all remaining Traces.
assert 2 == len(stream)
assert 2 == len(traces)
for _i in range(len(traces)):
assert traces[_i].stats == stream[_i].stats
np.testing.assert_array_equal(traces[_i].data, stream[_i].data)
def test_slicing(self):
"""
Tests the __getslice__ method of the Stream object.
"""
stream = read()
assert stream[0:] == stream[0:]
assert stream[:2] == stream[:2]
assert stream[:] == stream[:]
assert len(stream) == 3
new_stream = stream[1:3]
assert isinstance(new_stream, Stream)
assert len(new_stream) == 2
assert new_stream[0].stats == stream[1].stats
assert new_stream[1].stats == stream[2].stats
def test_slicing_with_steps(self):
"""
Tests the __getslice__ method of the Stream object with step.
"""
tr1 = Trace()
tr2 = Trace()
tr3 = Trace()
tr4 = Trace()
tr5 = Trace()
st = Stream([tr1, tr2, tr3, tr4, tr5])
assert st[0:6].traces == [tr1, tr2, tr3, tr4, tr5]
assert st[0:6:1].traces == [tr1, tr2, tr3, tr4, tr5]
assert st[0:6:2].traces == [tr1, tr3, tr5]
assert st[1:6:2].traces == [tr2, tr4]
assert st[1:6:6].traces == [tr2]
def test_slice(self):
"""
Slice method should not loose attributes set on stream object itself.
"""
st = read()
st.test = 1
st.muh = "Muh"
st2 = st.slice(st[0].stats.starttime, st[0].stats.endtime)
assert st2.test == 1
assert st2.muh == "Muh"
def test_slice_nearest_sample(self):
"""
Tests that the nearest_sample argument is correctly passed to the
trace function calls.
"""
# It defaults to True.
st = read()
utc1 = st[0].stats.starttime + 0.1
utc2 = st[0].stats.endtime - 0.1
with mock.patch("obspy.core.trace.Trace.slice") as patch:
patch.return_value = st[0]
st.slice(utc1, utc2)
assert patch.call_count == 3
for arg in patch.call_args_list:
assert arg[1]["nearest_sample"]
# Force True.
with mock.patch("obspy.core.trace.Trace.slice") as patch:
patch.return_value = st[0]
st.slice(utc1, utc2, nearest_sample=True)
assert patch.call_count == 3
for arg in patch.call_args_list:
assert arg[1]["nearest_sample"]
# Set to False.
with mock.patch("obspy.core.trace.Trace.slice") as patch:
patch.return_value = st[0]
st.slice(1, 2, nearest_sample=False)
assert patch.call_count == 3
for arg in patch.call_args_list:
assert not arg[1]["nearest_sample"]
def test_cutout(self):
"""
Test cutout method of the Stream object. Compare against equivalent
trimming operations.
"""
t1 = UTCDateTime("2009-06-24")
t2 = UTCDateTime("2009-08-24T00:20:06.007Z")
t3 = UTCDateTime("2009-08-24T00:20:16.008Z")
t4 = UTCDateTime("2011-09-11")
st = read()
st_cut = read()
# 1
st_cut.cutout(t4, t4 + 10)
self.__remove_processing(st_cut)
assert st == st_cut
# 2
st_cut.cutout(t1 - 10, t1)
self.__remove_processing(st_cut)
assert st == st_cut
# 3
st_cut.cutout(t1, t2)
st.trim(starttime=t2, nearest_sample=True)
self.__remove_processing(st_cut)
self.__remove_processing(st)
assert st == st_cut
# 4
st = read()
st_cut = read()
st_cut.cutout(t3, t4)
st.trim(endtime=t3, nearest_sample=True)
self.__remove_processing(st_cut)
self.__remove_processing(st)
assert st == st_cut
# 5
st = read()
st.trim(endtime=t2, nearest_sample=True)
tmp = read()
tmp.trim(starttime=t3, nearest_sample=True)
st += tmp
st_cut = read()
st_cut.cutout(t2, t3)
self.__remove_processing(st_cut)
self.__remove_processing(st)
assert st == st_cut
def test_pop2(self):
"""
Test the pop method of the Stream object.
"""
trace = Trace(data=np.arange(0, 1000))
st = Stream([trace])
st = st + st + st + st
assert len(st) == 4
st.pop()
assert len(st) == 3
st[1].stats.station = 'MUH'
st.pop(0)
assert len(st) == 2
assert st[0].stats.station == 'MUH'
def test_remove(self, mseed_stream):
"""
Tests the remove method of the Stream object.
"""
stream = mseed_stream
# Make a copy of the Traces.
stream2 = deepcopy(stream)
# Use the remove method of the Stream object and of the list of Traces.
stream.remove(stream[1])
del stream2[1]
stream.remove(stream[-1])
del stream2[-1]
# Compare remaining Streams.
assert stream == stream2
def test_reverse(self, mseed_stream):
"""
Tests the reverse method of the Stream object.
"""
stream = mseed_stream
# Make a copy of the Traces.
traces = deepcopy(stream[:])
# Use reversing of the Stream object and of the list.
stream.reverse()
traces.reverse()
# Compare all Traces.
assert 4 == len(stream)
assert 4 == len(traces)
for _i in range(len(traces)):
assert traces[_i].stats == stream[_i].stats
np.testing.assert_array_equal(traces[_i].data, stream[_i].data)
def test_select(self):
"""
Tests the select method of the Stream object.
"""
# Create a list of header dictionaries.
headers = [
{'starttime': UTCDateTime(1990, 1, 1), 'network': 'AA',
'station': 'ZZZZ', 'channel': 'EHZ', 'sampling_rate': 200.0,
'npts': 100},
{'starttime': UTCDateTime(1990, 1, 1), 'network': 'BB',
'station': 'YYYY', 'channel': 'EHN', 'sampling_rate': 200.0,
'npts': 100},
{'starttime': UTCDateTime(2000, 1, 1), 'network': 'AA',
'station': 'ZZZZ', 'channel': 'BHZ', 'sampling_rate': 20.0,
'npts': 100},
{'starttime': UTCDateTime(1989, 1, 1), 'network': 'BB',
'station': 'XXXX', 'channel': 'BHN', 'sampling_rate': 20.0,
'npts': 100},
{'starttime': UTCDateTime(2010, 1, 1), 'network': 'AA',
'station': 'XXXX', 'channel': 'EHZ', 'sampling_rate': 200.0,
'npts': 100, 'location': '00'}]
# Make stream object for test case
traces = []
for header in headers:
traces.append(Trace(data=np.random.randint(0, 1000, 100),
header=header))
stream = Stream(traces=traces)
# Test cases:
stream2 = stream.select()
assert stream == stream2
with pytest.raises(Exception):
stream.select(channel="EHZ",
component="N")
stream2 = stream.select(channel='EHE')
assert len(stream2) == 0
stream2 = stream.select(channel='EHZ')
assert len(stream2) == 2
assert stream[0] in stream2
assert stream[4] in stream2
stream2 = stream.select(component='Z')
assert len(stream2) == 3
assert stream[0] in stream2
assert stream[2] in stream2
assert stream[4] in stream2
stream2 = stream.select(component='n')
assert len(stream2) == 2
assert stream[1] in stream2
assert stream[3] in stream2
stream2 = stream.select(channel='BHZ', npts=100, sampling_rate='20.0',
network='AA', component='Z', station='ZZZZ')
assert len(stream2) == 1
assert stream[2] in stream2
stream2 = stream.select(channel='EHZ', station="XXXX")
assert len(stream2) == 1
assert stream[4] in stream2
stream2 = stream.select(network='AA')
assert len(stream2) == 3
assert stream[0] in stream2
assert stream[2] in stream2
assert stream[4] in stream2
stream2 = stream.select(id='AA.ZZZZ..EHZ')
assert len(stream2) == 1
assert stream[0] in stream2
stream2 = stream.select(sampling_rate=20.0)
assert len(stream2) == 2
assert stream[2] in stream2
assert stream[3] in stream2
# tests for wildcarded channel:
stream2 = stream.select(channel='B*')
assert len(stream2) == 2
assert stream[2] in stream2
assert stream[3] in stream2
stream2 = stream.select(channel='EH*')
assert len(stream2) == 3
assert stream[0] in stream2
assert stream[1] in stream2
assert stream[4] in stream2
stream2 = stream.select(channel='*Z')
assert len(stream2) == 3
assert stream[0] in stream2
assert stream[2] in stream2
assert stream[4] in stream2
# tests for other wildcard operations:
stream2 = stream.select(station='[XY]*')
assert len(stream2) == 3
assert stream[1] in stream2
assert stream[3] in stream2
assert stream[4] in stream2
stream2 = stream.select(station='[A-Y]*')
assert len(stream2) == 3
assert stream[1] in stream2
assert stream[3] in stream2
assert stream[4] in stream2
stream2 = stream.select(station='[A-Y]??*', network='A?')
assert len(stream2) == 1
assert stream[4] in stream2
# test case insensitivity
stream2 = stream.select(channel='BhZ', npts=100, sampling_rate='20.0',
network='aA', station='ZzZz',)
assert len(stream2) == 1
assert stream[2] in stream2
stream2 = stream.select(channel='e?z', network='aa', station='x?X*',
location='00', component='z')
assert len(stream2) == 1
assert stream[4] in stream2
def test_select_on_single_letter_channels(self):
st = read()
st[0].stats.channel = "Z"
st[1].stats.channel = "N"
st[2].stats.channel = "E"
assert [tr.stats.channel for tr in st] == ["Z", "N", "E"]
assert st.select(component="Z")[0] == st[0]
assert st.select(component="N")[0] == st[1]
assert st.select(component="E")[0] == st[2]
assert len(st.select(component="Z")) == 1
assert len(st.select(component="N")) == 1
assert len(st.select(component="E")) == 1
def test_select_from_inventory(self):
# Create a test stream
headers = [
{'network': 'AA', 'station': 'ST01', 'channel': 'EHZ',
'location': '00', 'sampling_rate': 200.0, 'npts': 100,
'starttime': UTCDateTime(1990, 1, 1)},
{'network': 'AA', 'station': 'ST01', 'channel': 'EHZ',
'location': '00', 'sampling_rate': 200.0, 'npts': 100,
'starttime': UTCDateTime(1998, 1, 1)},
{'network': 'AA', 'station': 'ST01', 'channel': 'EHZ',
'location': '00', 'sampling_rate': 200.0, 'npts': 100,
'starttime': UTCDateTime(2000, 1, 1)},
{'network': 'AA', 'station': 'ST01', 'channel': 'EHN',
'location': '00', 'sampling_rate': 200.0, 'npts': 100,
'starttime': UTCDateTime(2000, 1, 1)},
{'network': 'AA', 'station': 'ST01', 'channel': 'EHE',
'location': '00', 'sampling_rate': 200.0, 'npts': 100,
'starttime': UTCDateTime(2000, 1, 1)},
{'network': 'AA', 'station': 'ST02', 'channel': 'EHZ',
'location': '00', 'sampling_rate': 200.0, 'npts': 100,
'starttime': UTCDateTime(2000, 1, 1)},
{'network': 'AB', 'station': 'ST01', 'channel': 'EHZ',
'location': '00', 'sampling_rate': 200.0, 'npts': 100,
'starttime': UTCDateTime(2000, 1, 1)}
]
traces = []
for header in headers:
traces.append(Trace(data=np.random.randint(0, 1000, 100),
header=header))
st = Stream(traces=traces)
# Create a test inventory
channels = [
Channel(code='EHZ', location_code='00',
latitude=0.0, longitude=0.0, elevation=0.0, depth=0.0,
start_date=UTCDateTime(1990, 1, 1),
end_date=UTCDateTime(1998, 1, 1)),
Channel(code='EHZ', location_code='00',
latitude=0.0, longitude=0.0, elevation=0.0, depth=0.0,
start_date=UTCDateTime(1999, 1, 1))
]
stations = [Station(code='ST01',
latitude=0.0,
longitude=0.0,
elevation=0.0,
channels=channels)]
networks = [Network('AA', stations=stations)]
inv = Inventory(networks=networks, source='TEST')
# tests
assert len(st.select(inventory=inv)) == 2
st_sel = st.select(network='AB')
assert len(st_sel.select(inventory=inv)) == 0
inv_sel = inv.select(starttime=UTCDateTime(2000, 1, 1))
assert len(st.select(inventory=inv_sel)) == 1
def test_sort(self):
"""
Tests the sort method of the Stream object.
"""
# Create new Stream
stream = Stream()
# Create a list of header dictionaries. The sampling rate serves as a
# unique identifier for each Trace.
headers = [
{'starttime': UTCDateTime(1990, 1, 1), 'network': 'AAA',
'station': 'ZZZ', 'channel': 'XXX', 'sampling_rate': 100.0},
{'starttime': UTCDateTime(1990, 1, 1), 'network': 'AAA',
'station': 'YYY', 'channel': 'CCC', 'sampling_rate': 200.0},
{'starttime': UTCDateTime(2000, 1, 1), 'network': 'AAA',
'station': 'EEE', 'channel': 'GGG', 'sampling_rate': 300.0},
{'starttime': UTCDateTime(1989, 1, 1), 'network': 'AAA',
'station': 'XXX', 'channel': 'GGG', 'sampling_rate': 400.0},
{'starttime': UTCDateTime(2010, 1, 1), 'network': 'AAA',
'station': 'XXX', 'channel': 'FFF', 'sampling_rate': 500.0}]
# Create a Trace object of it and append it to the Stream object.
for _i in headers:
new_trace = Trace(header=_i)
stream.append(new_trace)
# Use normal sorting.
stream.sort()
assert [i.stats.sampling_rate for i in stream.traces] == \
[300.0, 500.0, 400.0, 200.0, 100.0]
# Sort after sampling_rate.
stream.sort(keys=['sampling_rate'])
assert [i.stats.sampling_rate for i in stream.traces] == \
[100.0, 200.0, 300.0, 400.0, 500.0]
# Sort after channel and sampling rate.
stream.sort(keys=['channel', 'sampling_rate'])
assert [i.stats.sampling_rate for i in stream.traces] == \
[200.0, 500.0, 300.0, 400.0, 100.0]
# Sort after npts and sampling_rate and endtime.
stream.sort(keys=['npts', 'sampling_rate', 'endtime'])
assert [i.stats.sampling_rate for i in stream.traces] == \
[100.0, 200.0, 300.0, 400.0, 500.0]
# The same with reverted sorting
# Use normal sorting.
stream.sort(reverse=True)
assert [i.stats.sampling_rate for i in stream.traces] == \
[100.0, 200.0, 400.0, 500.0, 300.0]
# Sort after sampling_rate.
stream.sort(keys=['sampling_rate'], reverse=True)
assert [i.stats.sampling_rate for i in stream.traces] == \
[500.0, 400.0, 300.0, 200.0, 100.0]
# Sort after channel and sampling rate.
stream.sort(keys=['channel', 'sampling_rate'], reverse=True)
assert [i.stats.sampling_rate for i in stream.traces] == \
[100.0, 400.0, 300.0, 500.0, 200.0]
# Sort after npts and sampling_rate and endtime.
stream.sort(keys=['npts', 'sampling_rate', 'endtime'], reverse=True)
assert [i.stats.sampling_rate for i in stream.traces] == \
[500.0, 400.0, 300.0, 200.0, 100.0]
# Sorting without a list or a wrong item string should fail.
with pytest.raises(TypeError):
stream.sort(keys=1)
with pytest.raises(TypeError):
stream.sort(keys='sampling_rate')
with pytest.raises(KeyError):
stream.sort(keys=['npts', 'wrong_value'])
def test_sorting_twice(self):
"""
Sorting twice should not change order.
"""
stream = Stream()
headers = [
{'starttime': UTCDateTime(1990, 1, 1),
'endtime': UTCDateTime(1990, 1, 2), 'network': 'AAA',
'station': 'ZZZ', 'channel': 'XXX', 'npts': 10000,
'sampling_rate': 100.0},
{'starttime': UTCDateTime(1990, 1, 1),
'endtime': UTCDateTime(1990, 1, 3), 'network': 'AAA',
'station': 'YYY', 'channel': 'CCC', 'npts': 10000,
'sampling_rate': 200.0},
{'starttime': UTCDateTime(2000, 1, 1),
'endtime': UTCDateTime(2001, 1, 2), 'network': 'AAA',
'station': 'EEE', 'channel': 'GGG', 'npts': 1000,
'sampling_rate': 300.0},
{'starttime': UTCDateTime(1989, 1, 1),
'endtime': UTCDateTime(2010, 1, 2), 'network': 'AAA',
'station': 'XXX', 'channel': 'GGG', 'npts': 10000,
'sampling_rate': 400.0},
{'starttime': UTCDateTime(2010, 1, 1),
'endtime': UTCDateTime(2011, 1, 2), 'network': 'AAA',
'station': 'XXX', 'channel': 'FFF', 'npts': 1000,
'sampling_rate': 500.0}]
# Create a Trace object of it and append it to the Stream object.
for _i in headers:
new_trace = Trace(header=_i)
stream.append(new_trace)
stream.sort()
a = [i.stats.sampling_rate for i in stream.traces]
stream.sort()
b = [i.stats.sampling_rate for i in stream.traces]
# should be equal
assert a == b
def test_merge_with_different_calibration_factors(self):
"""
Test the merge method of the Stream object.
"""
# 1 - different calibration factors for the same channel should fail
tr1 = Trace(data=np.zeros(5))
tr1.stats.calib = 1.0
tr2 = Trace(data=np.zeros(5))
tr2.stats.calib = 2.0
st = Stream([tr1, tr2])
# this also emits an UserWarning
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
with pytest.raises(Exception):
st.merge()
# 2 - different calibration factors for the different channels is ok
tr1 = Trace(data=np.zeros(5))
tr1.stats.calib = 2.00
tr1.stats.channel = 'EHE'
tr2 = Trace(data=np.zeros(5))
tr2.stats.calib = 5.0
tr2.stats.channel = 'EHZ'
tr3 = Trace(data=np.zeros(5))
tr3.stats.calib = 2.00
tr3.stats.channel = 'EHE'
tr4 = Trace(data=np.zeros(5))
tr4.stats.calib = 5.0
tr4.stats.channel = 'EHZ'
st = Stream([tr1, tr2, tr3, tr4])
st.merge()
def test_merge_with_different_sampling_rates(self):
"""
Test the merge method of the Stream object.
"""
# 1 - different sampling rates for the same channel should fail
tr1 = Trace(data=np.zeros(5))
tr1.stats.sampling_rate = 200
tr2 = Trace(data=np.zeros(5))
tr2.stats.sampling_rate = 50
st = Stream([tr1, tr2])
# this also emits an UserWarning
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
with pytest.raises(Exception):
st.merge()
# 2 - different sampling rates for the different channels is ok
tr1 = Trace(data=np.zeros(5))
tr1.stats.sampling_rate = 200
tr1.stats.channel = 'EHE'
tr2 = Trace(data=np.zeros(5))
tr2.stats.sampling_rate = 50
tr2.stats.channel = 'EHZ'
tr3 = Trace(data=np.zeros(5))
tr3.stats.sampling_rate = 200
tr3.stats.channel = 'EHE'
tr4 = Trace(data=np.zeros(5))
tr4.stats.sampling_rate = 50
tr4.stats.channel = 'EHZ'
st = Stream([tr1, tr2, tr3, tr4])
st.merge()
def test_merge_with_different_data_types(self):
"""
Test the merge method of the Stream object.
"""
# 1 - different dtype for the same channel should fail
tr1 = Trace(data=np.zeros(5, dtype=np.int32))
tr2 = Trace(data=np.zeros(5, dtype=np.float32))
st = Stream([tr1, tr2])
# this also emits an UserWarning
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
with pytest.raises(Exception):
st.merge()
# 2 - different sampling rates for the different channels is ok
tr1 = Trace(data=np.zeros(5, dtype=np.int32))
tr1.stats.channel = 'EHE'
tr2 = Trace(data=np.zeros(5, dtype=np.float32))
tr2.stats.channel = 'EHZ'
tr3 = Trace(data=np.zeros(5, dtype=np.int32))
tr3.stats.channel = 'EHE'
tr4 = Trace(data=np.zeros(5, dtype=np.float32))
tr4.stats.channel = 'EHZ'
st = Stream([tr1, tr2, tr3, tr4])
st.merge()
def test_merge_gaps(self, mseed_stream):
"""
Test the merge method of the Stream object.
"""
stream = mseed_stream
start = UTCDateTime("2007-12-31T23:59:59.915000")
end = UTCDateTime("2008-01-01T00:04:31.790000")
assert len(stream) == 4
assert len(stream[0]) == 412
assert len(stream[1]) == 824
assert len(stream[2]) == 824
assert len(stream[3]) == 50668
assert stream[0].stats.starttime == start
assert stream[3].stats.endtime == end
for i in range(4):
assert stream[i].stats.sampling_rate == 200
assert stream[i].get_id() == 'BW.BGLD..EHE'
stream.verify()
# merge it
stream.merge()
stream.verify()
assert len(stream) == 1
assert len(stream[0]) == stream[0].data.size
assert stream[0].stats.starttime == start
assert stream[0].stats.endtime == end
assert stream[0].stats.sampling_rate == 200
assert stream[0].get_id() == 'BW.BGLD..EHE'
def test_merge_gaps_2(self):
"""
Test the merge method of the Stream object on two traces with a gap in