/
test_mseed_reading_and_writing.py
1619 lines (1488 loc) · 70 KB
/
test_mseed_reading_and_writing.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 copy
import glob
import io
import re
import os
import unittest
import warnings
from datetime import datetime
from struct import unpack
import numpy as np
import pytest
from obspy import Stream, Trace, UTCDateTime, read
from obspy.core import AttribDict
from obspy.core.compatibility import from_buffer
from obspy.core.util import CatchOutput, NamedTemporaryFile
from obspy.io.mseed import (util, InternalMSEEDWarning,
InternalMSEEDError, ObsPyMSEEDError)
from obspy.io.mseed.core import _is_mseed, _read_mseed, _write_mseed
from obspy.io.mseed.headers import ENCODINGS, clibmseed
from obspy.io.mseed.msstruct import _MSStruct
class MSEEDReadingAndWritingTestCase(unittest.TestCase):
"""
Test everything related to the general reading and writing of MiniSEED
files.
"""
def setUp(self):
# Directory where the test files are located
self.path = os.path.dirname(__file__)
def test_read_head_file_via_obspy(self):
"""
Read file test via L{obspy.core.Stream}.
"""
testfile = os.path.join(self.path, 'data', 'test.mseed')
stream = read(testfile, headonly=True, format='MSEED')
self.assertEqual(stream[0].stats.network, 'NL')
self.assertEqual(stream[0].stats['station'], 'HGN')
self.assertEqual(str(stream[0].data), '[]')
# This is controlled by the stream[0].data attribute.
self.assertEqual(stream[0].stats.npts, 11947)
gapfile = os.path.join(self.path, 'data', 'gaps.mseed')
# without given format -> autodetect using extension
stream = read(gapfile, headonly=True)
starttime = ['2007-12-31T23:59:59.915000Z',
'2008-01-01T00:00:04.035000Z',
'2008-01-01T00:00:10.215000Z',
'2008-01-01T00:00:18.455000Z']
self.assertEqual(4, len(stream.traces))
for _k, _i in enumerate(stream.traces):
self.assertEqual(True, isinstance(_i, Trace))
self.assertEqual(str(_i.data), '[]')
self.assertEqual(str(_i.stats.starttime), starttime[_k])
def test_read_gappy_file(self):
"""
Compares waveform data read by obspy.io.mseed with an ASCII dump.
Checks the first 9 datasamples of each entry in trace_list of
gaps.mseed. The values are assumed to be correct. The first values
were created using Pitsa.
XXX: This tests is a straight port from an old libmseed test. Redundant
to some other tests.
"""
mseed_file = os.path.join(self.path, 'data', str('gaps.mseed'))
# list of known data samples
starttime = [1199145599915000, 1199145604035000, 1199145610215000,
1199145618455000]
datalist = [[-363, -382, -388, -420, -417, -397, -418, -390, -388],
[-427, -416, -393, -430, -426, -407, -401, -422, -439],
[-396, -399, -387, -384, -393, -380, -365, -394, -426],
[-389, -428, -409, -389, -388, -405, -390, -368, -368]]
i = 0
stream = _read_mseed(mseed_file)
for trace in stream:
self.assertEqual('BGLD', trace.stats.station)
self.assertEqual('EHE', trace.stats.channel)
self.assertEqual(200, trace.stats.sampling_rate)
self.assertEqual(
starttime[i],
util._convert_datetime_to_mstime(trace.stats.starttime))
self.assertEqual(datalist[i], trace.data[0:9].tolist())
i += 1
del stream
# Also test unicode file names.
mseed_filenames = [str('BW.BGLD.__.EHE.D.2008.001.first_record'),
str('qualityflags.mseed'),
str('test.mseed'),
str('timingquality.mseed')]
samprate = [200.0, 200.0, 40.0, 200.0]
station = ['BGLD', 'BGLD', 'HGN', 'BGLD']
npts = [412, 412, 11947, 41604, 1]
for i, _f in enumerate(mseed_filenames):
filename = os.path.join(self.path, 'data', _f)
stream = _read_mseed(filename)
self.assertEqual(samprate[i], stream[0].stats.sampling_rate)
self.assertEqual(station[i], stream[0].stats.station)
self.assertEqual(npts[i], stream[0].stats.npts)
self.assertEqual(npts[i], len(stream[0].data))
del stream
def test_read_and_write_traces(self):
"""
Writes, reads and compares files created via obspy.io.mseed.
This uses all possible encodings, record lengths and the byte order
options. A re-encoded SEED file should still have the same values
regardless of write options.
Note: Test currently only tests the first trace
"""
mseed_file = os.path.join(self.path, 'data', 'test.mseed')
stream = _read_mseed(mseed_file)
# Define test ranges
record_length_values = [2 ** i for i in range(8, 21)]
encoding_values = {"ASCII": "|S1", "INT16": "int16", "INT32": "int32",
"FLOAT32": "float32", "FLOAT64": "float64",
"STEIM1": "int32", "STEIM2": "int32"}
byteorder_values = ['>', '<']
# Loop over every combination.
for reclen in record_length_values:
for byteorder in byteorder_values:
for encoding in encoding_values.keys():
this_stream = copy.deepcopy(stream)
this_stream[0].data = \
np.require(this_stream[0].data,
dtype=encoding_values[encoding])
with NamedTemporaryFile() as tf:
temp_file = tf.name
_write_mseed(this_stream, temp_file, encoding=encoding,
byteorder=byteorder, reclen=reclen)
# some files raise "UserWarning: Record contains a
# fractional seconds" - ignore
with warnings.catch_warnings(record=True):
warnings.simplefilter('ignore', UserWarning)
new_stream = _read_mseed(temp_file)
# Assert the new stream still has the chosen attributes.
# This should mean that writing as well as reading them
# works.
self.assertEqual(new_stream[0].stats.mseed.byteorder,
byteorder)
self.assertEqual(new_stream[0].stats.mseed.record_length,
reclen)
self.assertEqual(new_stream[0].stats.mseed.encoding,
encoding)
np.testing.assert_array_equal(this_stream[0].data,
new_stream[0].data)
def test_downcast_int64_to_int32(self):
"""
Checks that sample stream of dtype int64 can be downcast to int 32 and
written to mseed by downcasting the data to int32 type data.
"""
# create a dummy stream with int64 data
x = np.array([1, 2, -3, 4], dtype=np.int64)
tr = Trace(x)
st = Stream()
st.append(tr)
# make sure the data can be written to mseed
with io.BytesIO() as buf:
st.write(buf, format="mseed")
st2 = read(buf)
self.assertEqual(len(st), len(st2))
for tr, tr2 in zip(st, st2):
self.assertTrue(np.array_equal(tr.data, tr2.data))
self.assertEqual(st[0].data.dtype.type, np.int64)
# Test that error message is indeed raised when data cannot be downcast
# Create dummy stream that cannot be properly downcast to int64
for x in [2 ** 55, -2 ** 55]:
data = np.array([1, 2, -3, x, -1], dtype=np.int64)
st = Stream([Trace(data)])
with io.BytesIO() as buf:
with self.assertRaises(ObsPyMSEEDError):
st.write(buf, format="mseed")
def test_get_record_information(self):
"""
Tests the reading of Mini-SEED record information.
"""
# Build encoding strings.
encoding_strings = {}
for key, value in ENCODINGS.items():
encoding_strings[value[0]] = key
# Test the encodings and byte orders.
path = os.path.join(self.path, "data", "encoding")
files = ['float32_Float32_bigEndian.mseed',
'float32_Float32_littleEndian.mseed',
'float64_Float64_bigEndian.mseed',
'float64_Float64_littleEndian.mseed',
'fullASCII_bigEndian.mseed', 'fullASCII_littleEndian.mseed',
'int16_INT16_bigEndian.mseed',
'int16_INT16_littleEndian.mseed',
'int32_INT32_bigEndian.mseed',
'int32_INT32_littleEndian.mseed',
'int32_Steim1_bigEndian.mseed',
'int32_Steim1_littleEndian.mseed',
'int32_Steim2_bigEndian.mseed',
'int32_Steim2_littleEndian.mseed']
for file in files:
info = util.get_record_information(os.path.join(path, file))
if 'ASCII' not in file:
encoding = file.split('_')[1].upper()
byteorder = file.split('_')[2].split('.')[0]
else:
encoding = 'ASCII'
byteorder = file.split('_')[1].split('.')[0]
if 'big' in byteorder:
byteorder = '>'
else:
byteorder = '<'
self.assertEqual(encoding_strings[encoding], info['encoding'])
self.assertEqual(byteorder, info['byteorder'])
# Also test the record length although it is equal for all files.
self.assertEqual(256, info['record_length'])
# No really good test files for the record length so just two files
# with known record lengths are tested.
info = util.get_record_information(
os.path.join(self.path, 'data', 'timingquality.mseed'))
self.assertEqual(info['record_length'], 512)
info = util.get_record_information(os.path.join(self.path, 'data',
'steim2.mseed'))
self.assertEqual(info['record_length'], 4096)
def test_read_and_write_file_with_gaps(self):
"""
Tests reading and writing files with more than one trace.
"""
filename = os.path.join(self.path, 'data', 'gaps.mseed')
# Read file and test if all traces are being read.
stream = _read_mseed(filename)
self.assertEqual(len(stream), 4)
# Write File to temporary file.
with NamedTemporaryFile() as tf:
outfile = tf.name
_write_mseed(copy.deepcopy(stream), outfile)
# Read the same file again and compare it to the original file.
new_stream = _read_mseed(outfile)
self.assertEqual(len(stream), len(new_stream))
# Compare new_trace_list with trace_list
for tr1, tr2 in zip(stream, new_stream):
self.assertEqual(tr1.stats, tr2.stats)
np.testing.assert_array_equal(tr1.data, tr2.data)
def test_is_mseed(self):
"""
This tests the _is_mseed method by just validating that each file in
the data directory is a Mini-SEED file and each file in the working
directory is not a Mini-SEED file.
The filenames are hard coded so the test will not fail with future
changes in the structure of the package.
"""
# Mini-SEED file names.
mseed_filenames = ['BW.BGLD.__.EHE.D.2008.001.first_10_records',
'gaps.mseed', 'qualityflags.mseed', 'test.mseed',
'timingquality.mseed', 'blockette008.mseed',
'fullseed.mseed', 'various_noise_records.mseed',
'rt130_sr0_cropped.mseed']
# Non Mini-SEED file names.
non_mseed_filenames = ['test_mseed_reading_and_writing.py',
'__init__.py',
os.path.join('data', 'not.mseed'),
os.path.join('data', 'not2.mseed'),
os.path.join('data', 'not3.mseed'),
os.path.join('data', 'not4.mseed')]
# Loop over Mini-SEED files
for _i in mseed_filenames:
filename = os.path.join(self.path, 'data', _i)
is_mseed = _is_mseed(filename)
self.assertTrue(is_mseed)
# Loop over non Mini-SEED files
for _i in non_mseed_filenames:
filename = os.path.join(self.path, _i)
is_mseed = _is_mseed(filename)
self.assertFalse(is_mseed)
# Also test it from an open file.
for _i in mseed_filenames:
filename = os.path.join(self.path, 'data', _i)
with io.open(filename, "rb") as fh:
is_mseed = _is_mseed(fh)
self.assertTrue(is_mseed)
for _i in non_mseed_filenames:
filename = os.path.join(self.path, _i)
with io.open(filename, "rb") as fh:
is_mseed = _is_mseed(fh)
self.assertFalse(is_mseed)
# And from a BytesIO.
for _i in mseed_filenames:
filename = os.path.join(self.path, 'data', _i)
with io.open(filename, "rb") as fh:
with io.BytesIO(fh.read()) as buf:
buf.seek(0, 0)
is_mseed = _is_mseed(buf)
self.assertTrue(is_mseed)
for _i in non_mseed_filenames:
filename = os.path.join(self.path, _i)
with io.open(filename, "rb") as fh:
with io.BytesIO(fh.read()) as buf:
buf.seek(0, 0)
is_mseed = _is_mseed(buf)
self.assertFalse(is_mseed)
def test_read_single_record_to_msr(self):
"""
Tests readSingleRecordtoMSR against start and end times.
Reference start and end times are obtained from the tracegroup.
Both cases, with and without ms_p argument are tested.
"""
filename = os.path.join(self.path, 'data',
'BW.BGLD.__.EHE.D.2008.001.first_10_records')
start, end = [1199145599915000, 1199145620510000]
# start and end time
ms = _MSStruct(filename, init_msrmsf=False)
ms.read(-1, 0, 1, 0)
self.assertEqual(start, clibmseed.msr_starttime(ms.msr))
ms.offset = ms.file_pos_from_rec_num(-1)
ms.read(-1, 0, 1, 0)
self.assertEqual(end, clibmseed.msr_endtime(ms.msr))
del ms # for valgrind
def test_read_file_via_mseed(self):
"""
Read file test via L{obspy.io.mseed.mseed._read_mseed}.
"""
testfile = os.path.join(self.path, 'data', 'test.mseed')
data = [2787, 2776, 2774, 2780, 2783]
# Read the file directly to a Stream object.
stream = _read_mseed(testfile)
stream.verify()
self.assertEqual(stream[0].stats.network, 'NL')
self.assertEqual(stream[0].stats['station'], 'HGN')
self.assertEqual(stream[0].stats.get('location'), '00')
self.assertEqual(stream[0].stats.npts, 11947)
self.assertEqual(stream[0].stats['sampling_rate'], 40.0)
self.assertEqual(stream[0].stats.get('channel'), 'BHZ')
for _i in range(5):
self.assertEqual(stream[0].data[_i], data[_i])
# Make sure it can also read from open files.
with io.open(testfile, "rb") as fh:
stream = _read_mseed(fh)
stream.verify()
self.assertEqual(stream[0].stats.network, 'NL')
self.assertEqual(stream[0].stats['station'], 'HGN')
self.assertEqual(stream[0].stats.get('location'), '00')
self.assertEqual(stream[0].stats.npts, 11947)
self.assertEqual(stream[0].stats['sampling_rate'], 40.0)
self.assertEqual(stream[0].stats.get('channel'), 'BHZ')
for _i in range(5):
self.assertEqual(stream[0].data[_i], data[_i])
# And from BytesIO.
with io.open(testfile, "rb") as fh:
with io.BytesIO(fh.read()) as buf:
buf.seek(0, 0)
stream = _read_mseed(buf)
stream.verify()
self.assertEqual(stream[0].stats.network, 'NL')
self.assertEqual(stream[0].stats['station'], 'HGN')
self.assertEqual(stream[0].stats.get('location'), '00')
self.assertEqual(stream[0].stats.npts, 11947)
self.assertEqual(stream[0].stats['sampling_rate'], 40.0)
self.assertEqual(stream[0].stats.get('channel'), 'BHZ')
for _i in range(5):
self.assertEqual(stream[0].data[_i], data[_i])
def test_read_partial_time_window_from_file(self):
"""
Uses obspy.io.mseed.mseed._read_mseed to read only read a certain time
window of a file.
"""
starttime = UTCDateTime('2007-12-31T23:59:59.915000Z')
endtime = UTCDateTime('2008-01-01T00:00:20.510000Z')
testfile = os.path.join(self.path, 'data',
'BW.BGLD.__.EHE.D.2008.001.first_10_records')
stream = _read_mseed(testfile, starttime=starttime + 6,
endtime=endtime - 6)
self.assertTrue(starttime < stream[0].stats.starttime)
self.assertGreater(endtime, stream[0].stats.endtime)
def test_read_partial_with_only_starttime_set(self):
"""
Uses obspy.io.mseed.mseed._read_mseed to read only the data starting
with a certain time.
"""
starttime = UTCDateTime('2007-12-31T23:59:59.915000Z')
endtime = UTCDateTime('2008-01-01T00:00:20.510000Z')
testfile = os.path.join(self.path, 'data',
'BW.BGLD.__.EHE.D.2008.001.first_10_records')
stream = _read_mseed(testfile, starttime=starttime + 6)
self.assertTrue(starttime < stream[0].stats.starttime)
self.assertEqual(endtime, stream[0].stats.endtime)
def test__partial_with_only_endtime_set(self):
"""
Uses obspy.io.mseed.mseed._read_mseed to read only the data ending
before a certain time.
"""
starttime = UTCDateTime('2007-12-31T23:59:59.915000Z')
endtime = UTCDateTime('2008-01-01T00:00:20.510000Z')
testfile = os.path.join(self.path, 'data',
'BW.BGLD.__.EHE.D.2008.001.first_10_records')
stream = _read_mseed(testfile, endtime=endtime - 6)
self.assertEqual(starttime, stream[0].stats.starttime)
self.assertGreater(endtime, stream[0].stats.endtime)
def test_read_partial_frame_with_empty_time_range(self):
"""
Uses obspy.io.mseed.mseed._read_mseed to read a partial file with a
timewindow outside of the actual data. Should return an empty Stream
object.
"""
starttime = UTCDateTime('2003-05-29T02:13:22.043400Z')
testfile = os.path.join(self.path, 'data', 'test.mseed')
stream = _read_mseed(testfile, starttime=starttime - 1E6,
endtime=starttime - 1E6 + 1)
self.assertEqual(len(stream), 0)
def test_read_partial_with_source_name(self):
"""
Uses obspy.io.mseed.mseed._read_mseed to read only part of a file that
matches certain sourcename patterns.
"""
testfile = os.path.join(self.path, 'data', 'two_channels.mseed')
st1 = _read_mseed(testfile)
self.assertEqual(st1[0].stats.channel, 'EHE')
self.assertEqual(st1[1].stats.channel, 'EHZ')
st2 = _read_mseed(testfile, sourcename='*')
self.assertEqual(st2[0].stats.channel, 'EHE')
self.assertEqual(st2[1].stats.channel, 'EHZ')
st3 = _read_mseed(testfile, sourcename='*.EH*')
self.assertEqual(st3[0].stats.channel, 'EHE')
self.assertEqual(st3[1].stats.channel, 'EHZ')
st4 = _read_mseed(testfile, sourcename='*E')
self.assertEqual(st4[0].stats.channel, 'EHE')
self.assertEqual(len(st4), 1)
st5 = _read_mseed(testfile, sourcename='*.EHZ')
self.assertEqual(st5[0].stats.channel, 'EHZ')
self.assertEqual(len(st5), 1)
st6 = _read_mseed(testfile, sourcename='*.BLA')
self.assertEqual(len(st6), 0)
def test_write_integers(self):
"""
Write integer array via L{obspy.io.mseed.mseed._write_mseed}.
"""
npts = 1000
# data array of integers - float won't work!
np.random.seed(815) # make test reproducible
data = np.random.randint(-1000, 1000, npts).astype(np.int32)
st = Stream([Trace(data=data)])
with NamedTemporaryFile() as tf:
tempfile = tf.name
# write
_write_mseed(st, tempfile, format="MSEED")
# read again
stream = _read_mseed(tempfile)
stream.verify()
np.testing.assert_array_equal(stream[0].data, data)
def test_read_ms_traces_via_records_multiple_ids(self):
"""
Tests a critical issue when the LibMSEED.readMSTracesViaRecords method
is used (e.g. on Windows systems) and a start/end time is set and the
file has multiple ids.
This is due to the fact that the readMSTraceViaRecords method uses the
first and the last records of a file to take an educated guess about
which records to actually read. This of course only works if all
records have the same id and are chronologically ordered.
I don't think there is an easy solution for it.
"""
# The used file has ten records in successive order and then the first
# record again with a different record id:
# 2 Trace(s) in Stream:
# BW.BGLD..EHE | 2007-12-31T23:59:59.915000Z -
# 2008-01-01T00:00:20.510000Z | 200.0 Hz, 4120 samples
# OB.BGLD..EHE | 2007-12-31T23:59:59.915000Z -
# 2008-01-01T00:00:01.970000Z | 200.0 Hz, 412 samples
#
# Thus reading a small time window in between should contain at least
# some samples.
starttime = UTCDateTime(2008, 1, 1, 0, 0, 10)
endtime = starttime + 5
file = os.path.join(self.path, 'data',
'constructedFileToTestReadViaRecords.mseed')
# Some samples should be in the time window.
st = read(file, starttime=starttime, endtime=endtime)
self.assertEqual(len(st), 1)
samplecount = st[0].stats.npts
# 5 seconds are 5s * 200Hz + 1 samples.
self.assertEqual(samplecount, 1001)
# Choose time outside of frame.
st = read(
file, starttime=UTCDateTime() - 10, endtime=UTCDateTime())
# Should just result in an empty stream.
self.assertEqual(len(st), 0)
def test_write_sequence_number(self):
"""
Tests Mini-SEED writing with an sequence number starting at something
different than 1.
"""
npts = 2200 # At least 3 records of 512 bytes
np.random.seed(815) # make test reproducible
numpy_data = np.random.randint(-1000, 1000, npts).astype(np.int32)
starttime = UTCDateTime(2008, 1, 1, 0, 0, 10)
header = {'network': "NE", 'station': "STATI", 'location': "LO",
'channel': "CHA", 'npts': npts, 'sampling_rate': 1,
'starttime': starttime,
'mseed': {'dataquality': "D", "sequence_number": "str"}}
# Invalid seq num
data_trace = Trace(data=numpy_data, header=header)
data_stream = Stream([data_trace])
with NamedTemporaryFile() as tf:
tempfile = tf.name
self.assertRaises(ValueError, data_stream.write, tempfile,
format="MSEED", encoding=11, reclen=512)
# Seq num out of range #1
header = {'network': "NE", 'station': "STATI", 'location': "LO",
'channel': "CHA", 'npts': npts, 'sampling_rate': 1,
'starttime': starttime,
'mseed': {'dataquality': "D", "sequence_number": -1}}
data_trace = Trace(data=numpy_data, header=header)
data_stream = Stream([data_trace])
with NamedTemporaryFile() as tf:
tempfile = tf.name
self.assertRaises(ValueError, data_stream.write, tempfile,
format="MSEED", encoding=11, reclen=512)
# Seq num out of range #2
header = {'network': "NE", 'station': "STATI", 'location': "LO",
'channel': "CHA", 'npts': npts, 'sampling_rate': 1,
'starttime': starttime,
'mseed': {'dataquality': "D", "sequence_number": 1000001}}
data_trace = Trace(data=numpy_data, header=header)
data_stream = Stream([data_trace])
with NamedTemporaryFile() as tf:
tempfile = tf.name
self.assertRaises(ValueError, data_stream.write, tempfile,
format="MSEED", encoding=11, reclen=512)
# Seq num missing, defaults to 1
header = {'network': "NE", 'station': "STATI", 'location': "LO",
'channel': "CHA", 'npts': npts, 'sampling_rate': 1,
'starttime': starttime,
'mseed': {'dataquality': "D"}}
data_trace = Trace(data=numpy_data, header=header)
data_stream = Stream([data_trace])
with NamedTemporaryFile() as tf:
tempfile = tf.name
data_stream.write(tempfile, format="MSEED", encoding=11,
reclen=512)
tf.seek(0, os.SEEK_SET)
self.assertEqual(tf.read(6), b"000001")
# Seq num changed to 999998, expecting rollover
header = {'network': "NE", 'station': "STATI", 'location': "LO",
'channel': "CHA", 'npts': npts, 'sampling_rate': 1,
'starttime': starttime,
'mseed': {'dataquality': "D", "sequence_number": 999998}}
data_trace = Trace(data=numpy_data, header=header)
data_stream = Stream([data_trace])
with NamedTemporaryFile() as tf:
tempfile = tf.name
data_stream.write(tempfile, format="MSEED", encoding=11,
reclen=512)
tf.seek(0, os.SEEK_SET)
seq_counts = [b"999998", b"999999", b"000001"]
for count in seq_counts:
self.assertEqual(tf.read(6), count)
tf.seek(506, os.SEEK_CUR)
# Setting sequence number as kwarg argument of write
header = {'network': "NE", 'station': "STATI", 'location': "LO",
'channel': "CHA", 'npts': npts, 'sampling_rate': 1,
'starttime': starttime,
'mseed': {'dataquality': "D"}}
data_trace = Trace(data=numpy_data, header=header)
data_stream = Stream([data_trace])
with NamedTemporaryFile() as tf:
tempfile = tf.name
data_stream.write(tempfile, format="MSEED", encoding=11,
reclen=512, sequence_number=42)
tf.seek(0, os.SEEK_SET)
self.assertEqual(tf.read(6), b"000042")
def test_write_and_read_different_record_lengths(self):
"""
Tests Mini-SEED writing and record lengths.
"""
# libmseed instance.
npts = 6000
np.random.seed(815) # make test reproducible
data = np.random.randint(-1000, 1000, npts).astype(np.int32)
st = Stream([Trace(data=data)])
record_lengths = [256, 512, 1024, 2048, 4096, 8192]
# Loop over some record lengths.
for rec_len in record_lengths:
# Write it.
with NamedTemporaryFile() as tf:
tempfile = tf.name
st.write(tempfile, format="MSEED", reclen=rec_len)
# Get additional header info
info = util.get_record_information(tempfile)
# Test reading the two files.
temp_st = read(tempfile)
np.testing.assert_array_equal(data, temp_st[0].data)
del temp_st
# Check record length.
self.assertEqual(info['record_length'], rec_len)
# Check if filesize is a multiple of the record length.
self.assertEqual(info['filesize'] % rec_len, 0)
def test_read_full_seed(self):
"""
Reads a full SEED volume.
"""
files = os.path.join(self.path, 'data', 'fullseed.mseed')
st = _read_mseed(files)
self.assertEqual(len(st), 3)
self.assertEqual(len(st[0]), 602)
self.assertEqual(len(st[1]), 623)
self.assertEqual(len(st[2]), 610)
def test_read_with_wild_card(self):
"""
Reads wildcard filenames.
"""
files = os.path.join(self.path, 'data',
'BW.BGLD.__.EHE.D.2008.001.*_record')
st = read(files)
self.assertEqual(len(st), 3)
st.merge()
self.assertEqual(len(st), 1)
def test_header(self):
"""
Tests whether the header is correctly written and read.
"""
np.random.seed(815) # make test reproducible
data = np.random.randint(-1000, 1000, 50).astype(np.int32)
stats = {'network': 'BW', 'station': 'TEST', 'location': 'A',
'channel': 'EHE', 'npts': len(data), 'sampling_rate': 200.0,
'mseed': {'record_length': 512, 'encoding': 'STEIM2',
'filesize': 512, 'dataquality': 'D',
'number_of_records': 1, 'byteorder': '>'}}
stats['starttime'] = UTCDateTime(2000, 1, 1)
st = Stream([Trace(data=data, header=stats)])
with NamedTemporaryFile() as tf:
tempfile = tf.name
# Write it.
st.write(tempfile, format="MSEED")
# Read it again and delete the temporary file.
stream = read(tempfile)
stream.verify()
# Loop over the attributes to be able to assert them because a
# dictionary is not a stats dictionary.
# This also assures that there are no additional keys.
for key in stats.keys():
self.assertEqual(stats[key], stream[0].stats[key])
def test_reading_and_writing_via_the_stats_attribute(self):
"""
Tests the writing with MSEED file attributes set via the attributes in
trace.stats.mseed.
"""
npts = 6000
np.random.seed(815) # make test reproducible
data = np.random.randint(-1000, 1000, npts).astype(np.int32)
# Test all possible combinations of record length, encoding and
# byte order.
record_lengths = [256, 512, 1024, 2048, 4096, 8192]
byteorders = ['>', '<']
# Only select encoding that have write support.
encodings = [value[0] for value in ENCODINGS.values() if value[3]]
np_encodings = {}
# Special handling for ASCII encoded files.
for value in ENCODINGS.values():
if value[0] == 'ASCII':
np_encodings[value[0]] = np.dtype("|S1")
else:
np_encodings[value[0]] = value[2]
st = Stream([Trace(data=data)])
st[0].stats.mseed = AttribDict()
st[0].stats.mseed.dataquality = 'D'
# Loop over all combinations.
for reclen in record_lengths:
for order in byteorders:
for encoding in encodings:
# Create new stream and change stats.
stream = copy.deepcopy(st)
stream[0].stats.mseed.record_length = reclen
stream[0].stats.mseed.byteorder = order
stream[0].stats.mseed.encoding = encoding
# Convert the data so that it is compatible with the
# encoding.
stream[0].data = np.require(
stream[0].data, np_encodings[encoding])
# Write it.
with NamedTemporaryFile() as tf:
tempfile = tf.name
stream.write(tempfile, format="MSEED")
# Open the file.
stream2 = read(tempfile)
# remove file specific stats
stream2[0].stats.mseed.pop('filesize')
stream2[0].stats.mseed.pop('number_of_records')
# compare stats
self.assertEqual(stream[0].stats.mseed,
stream2[0].stats.mseed)
del stream
del stream2
def test_read_parts_of_file(self):
"""
Test reading only parts of an Mini-SEED file without unpacking or
touching the rest.
"""
temp = os.path.join(self.path, 'data', 'BW.BGLD.__.EHE.D.2008.001')
file = temp + '.first_10_records'
t = [UTCDateTime(2008, 1, 1, 0, 0, 1, 975000),
UTCDateTime(2008, 1, 1, 0, 0, 4, 30000)]
tr1 = read(file, starttime=t[0], endtime=t[1])[0]
self.assertEqual(t[0], tr1.stats.starttime)
self.assertEqual(t[1], tr1.stats.endtime)
# initialize second record
file2 = temp + '.second_record'
tr2 = read(file2)[0]
np.testing.assert_array_equal(tr1.data, tr2.data)
def test_read_with_gse2_option(self):
"""
Test that reading will still work if wrong option (of gse2)
verify_chksum is given. This is important if the read method is
called for an unknown file format.
"""
file = os.path.join(self.path, 'data', 'BW.BGLD.__.EHE.D.2008.001'
'.second_record')
tr = read(file, verify_chksum=True, starttime=None)[0]
data = np.array([-397, -387, -368, -381, -388])
np.testing.assert_array_equal(tr.data[0:5], data)
self.assertEqual(412, len(tr.data))
data = np.array([-406, -417, -403, -423, -413])
np.testing.assert_array_equal(tr.data[-5:], data)
def test_all_data_types_and_endians_in_multiple_files(self):
"""
Tests writing all different types. This is an test which is independent
of the read method. Only the data part is verified.
"""
file = os.path.join(self.path, "data",
"BW.BGLD.__.EHE.D.2008.001.second_record")
# Read the data and copy them
st = read(file)
data_copy = st[0].data.copy()
# Float64, Float32, Int32, Int24, Int16, Char
encodings = {5: "f8", 4: "f4", 3: "i4", 0: "S1", 1: "i2"}
byteorders = {0: '<', 1: '>'}
for byteorder, btype in byteorders.items():
for encoding, dtype in encodings.items():
# Convert data to floats and write them again
st[0].data = data_copy.astype(dtype)
with NamedTemporaryFile() as tf:
tempfile = tf.name
st.write(tempfile, format="MSEED", encoding=encoding,
reclen=256, byteorder=byteorder)
# Read the first record of data without header not using
# ObsPy
with open(tempfile, "rb") as fp:
s = fp.read()
data = from_buffer(s[56:256],
dtype=btype + dtype)
np.testing.assert_array_equal(data, st[0].data[:len(data)])
# Read the binary chunk of data with ObsPy
st2 = read(tempfile)
np.testing.assert_array_equal(st2[0].data, st[0].data)
def test_saving_small_ascii(self):
"""
Tests writing small ASCII strings.
"""
st = Stream()
st.append(Trace(data=from_buffer("A" * 8, "|S1")))
with NamedTemporaryFile() as tf:
tempfile = tf.name
st.write(tempfile, format="MSEED")
def test_all_data_types_and_endians_in_single_file(self):
"""
Tests all data and endian types into a single file.
"""
with NamedTemporaryFile() as tf:
tempfile = tf.name
st1 = Stream()
data = np.random.randint(-1000, 1000, 500)
for dtype in ["i2", "i4", "f4", "f8", "S1"]:
for enc in ["<", ">", "="]:
typed_data = data.astype(np.dtype(enc + dtype))
st1.append(Trace(data=typed_data))
# this will raise a UserWarning - ignoring for test
with warnings.catch_warnings(record=True):
warnings.simplefilter('ignore', UserWarning)
st1.write(tempfile, format="MSEED")
# read everything back (int16 gets converted into int32)
st2 = read(tempfile)
for dtype in ["i4", "i4", "f4", "f8", "S1"]:
for enc in ["<", ">", "="]:
tr = st2.pop(0).data
self.assertEqual(tr.dtype.kind +
str(tr.dtype.itemsize),
dtype)
# byte order is always native (=)
typed_data = data.astype("=" + dtype)
np.testing.assert_array_equal(tr, typed_data)
def test_enforce_steim2_with_steim1_as_encoding(self):
"""
This tests whether the encoding kwarg overwrites the encoding in
trace.stats.mseed.encoding.
"""
file = os.path.join(self.path, "data",
"BW.BGLD.__.EHE.D.2008.001.first_record")
st = read(file)
self.assertEqual(st[0].stats.mseed.encoding, 'STEIM1')
with NamedTemporaryFile() as tf:
tempfile = tf.name
st.write(tempfile, format='MSEED', encoding='STEIM2')
st2 = read(tempfile)
self.assertEqual(st2[0].stats.mseed.encoding, 'STEIM2')
def test_files_from_libmseed(self):
"""
Tests reading of files that are created by libmseed.
This test also checks the files created by libmseed to some extend.
"""
path = os.path.join(self.path, "data", "encoding")
# Dictionary. The key is the file name, the value a tuple: dtype,
# sampletype, encoding, content
def_content = np.arange(1, 51, dtype=np.int32)
files = {
os.path.join(path, "smallASCII.mseed"):
('|S1', 'a', 0,
from_buffer('ABCDEFGH', dtype='|S1')),
# Tests all ASCII letters.
os.path.join(path, "fullASCII.mseed"):
('|S1', 'a', 0, from_buffer(
r""" !"#$%&'()*+,-./""" +
r"""0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`""" +
r"""abcdefghijklmnopqrstuvwxyz{|}~""",
dtype='|S1')),
# Note: int16 array will also be returned as int32.
os.path.join(path, "int16_INT16.mseed"):
(np.int32, 'i', 1, def_content.astype(np.int16)),
os.path.join(path, "int32_INT32.mseed"):
(np.int32, 'i', 3, def_content),
os.path.join(path, "int32_Steim1.mseed"):
(np.int32, 'i', 10, def_content),
os.path.join(path, "int32_Steim2.mseed"):
(np.int32, 'i', 11, def_content),
os.path.join(path, "float32_Float32.mseed"):
(np.float32, 'f', 4, def_content.astype(np.float32)),
os.path.join(path, "float64_Float64.mseed"):
(np.float64, 'd', 5, def_content.astype(np.float64))
}
# Loop over all files and read them.
for file in files.keys():
# Check little and big Endian for each file.
for _i in ('littleEndian', 'bigEndian'):
cur_file = file[:-6] + '_' + _i + '.mseed'
st = read(os.path.join(cur_file))
# Check the array.
np.testing.assert_array_equal(st[0].data, files[file][3])
# Check the dtype.
self.assertEqual(st[0].data.dtype, files[file][0])
# Check byte order. Should always be native byte order. Byte
# order does not apply to ASCII arrays.
if 'ASCII' in cur_file:
self.assertEqual(st[0].data.dtype.byteorder, '|')
else:
self.assertEqual(st[0].data.dtype.byteorder, '=')
del st
# Read just the first record to check encoding. The sampletype
# should follow from the encoding. But libmseed seems not to
# read the sampletype when reading a file.
ms = _MSStruct(cur_file, init_msrmsf=False)
ms.read(-1, 0, 1, 0)
# Check values.
self.assertEqual(getattr(ms.msr.contents, 'encoding'),
files[file][2])
if _i == 'littleEndian':
self.assertEqual(getattr(ms.msr.contents, 'byteorder'), 0)
else:
self.assertEqual(getattr(ms.msr.contents, 'byteorder'), 1)
# Deallocate for debugging with valgrind
del ms
def test_writing_microseconds(self):
"""
Microseconds should be written.
"""
file = os.path.join(self.path, 'data',
'BW.UH3.__.EHZ.D.2010.171.first_record')
st = read(file)
# Read and write the record again with different microsecond times
for ms in [111111, 111110, 100000, 111100, 111000, 11111, 11110, 10000,
1111, 1110, 1000, 111, 110, 100, 11, 10, 1, 0,
999999, 999990, 900000, 999900, 999000, 99999, 99990, 90000,
9999, 9990, 999, 990, 99, 90, 9, 0, 100001, 900009]:
st[0].stats.starttime = UTCDateTime(2010, 8, 7, 0, 8, 52, ms)
with NamedTemporaryFile() as tf:
tempfile = tf.name
st.write(tempfile, format='MSEED', reclen=512)
st2 = read(tempfile)
# Should also be true for the stream objects.
self.assertEqual(st[0].stats.starttime, st2[0].stats.starttime)
# Should also be true for the stream objects.
self.assertEqual(st[0].stats, st2[0].stats)
def test_reading_and_writing_dataquality(self):
"""
Tests if the dataquality is written and read correctly. There is no
corresponding test in test_libmseed.py as it is just more convenient to
write it in here.
"""
np.random.seed(800) # make test reproducible
data = np.random.randint(-1000, 1000, 50).astype(np.int32)
# Create 4 different traces with 4 different dataqualities.
stats1 = {'network': 'BW', 'station': 'TEST', 'location': 'A',
'channel': 'EHE', 'npts': len(data), 'sampling_rate': 200.0,
'mseed': {'dataquality': 'D'}}
stats1['starttime'] = UTCDateTime(2000, 1, 1)
stats2 = copy.deepcopy(stats1)
stats2['mseed']['dataquality'] = 'R'
stats2['location'] = 'B'
stats3 = copy.deepcopy(stats1)
stats3['mseed']['dataquality'] = 'Q'
stats3['location'] = 'C'
stats4 = copy.deepcopy(stats1)
stats4['mseed']['dataquality'] = 'M'
stats4['location'] = 'D'
# Create the traces.
tr1 = Trace(data=data, header=stats1)
tr2 = Trace(data=data, header=stats2)
tr3 = Trace(data=data, header=stats3)
tr4 = Trace(data=data, header=stats4)
st = Stream([tr1, tr2, tr3, tr4])
with NamedTemporaryFile() as tf:
tempfile = tf.name
# Write it.
st.write(tempfile, format="MSEED")
# Read it again and delete the temporary file.
stream = read(tempfile)
stream.verify()
# Check all four dataqualities.
for tr_old, tr_new in zip(st, stream):
self.assertEqual(tr_old.stats.mseed.dataquality,
tr_new.stats.mseed.dataquality)
def test_writing_invalid_data_quality(self):
"""
Trying to write an invalid dataquality results in an error. Only D, R,
Q and M are allowed.
"""
data = np.zeros(10)
# Create 4 different traces with 4 different dataqualities.
stats1 = {'network': 'BW', 'station': 'TEST', 'location': 'A',
'channel': 'EHE', 'npts': len(data), 'sampling_rate': 200.0,
'mseed': {'dataquality': 'X'}}
st = Stream([Trace(data=data, header=stats1)])
with NamedTemporaryFile() as tf:
tempfile = tf.name
# Write it.
self.assertRaises(ValueError, st.write, tempfile, format="MSEED")
# Delete the file if it has been written, i.e. the test failed.
def test_is_invalid_mseed(self):
"""
Tests _is_mseed functionality.
"""
# invalid blockette length in first blockette
file = os.path.join(self.path, 'data', 'not.mseed')
self.assertFalse(_is_mseed(file))
# just "000001V"
file = os.path.join(self.path, 'data', 'not2.mseed')