/
test_nordic.py
1406 lines (1326 loc) · 63.2 KB
/
test_nordic.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Functions for testing the obspy.io.nordic functions
"""
import io
import os
import warnings
from itertools import cycle
import numpy as np
from obspy import read_events, Catalog, UTCDateTime, read
from obspy.core.event import (
Pick, WaveformStreamID, Arrival, Amplitude, Event, Origin, Magnitude,
OriginQuality, EventDescription, CreationInfo, OriginUncertainty,
ConfidenceEllipsoid, QuantityError, FocalMechanism, MomentTensor,
NodalPlane, NodalPlanes, ResourceIdentifier, Tensor)
from obspy.core.util.base import NamedTemporaryFile
from obspy.core.util.misc import TemporaryWorkingDirectory
from obspy.io.nordic import NordicParsingError
from obspy.io.nordic.core import (
_is_sfile, read_spectral_info, read_nordic, readwavename, blanksfile,
_write_nordic, nordpick, readheader, _readheader, write_select)
from obspy.io.nordic.utils import (
_int_conv, _float_conv, _str_conv, _nortoevmag, _evmagtonor,
_get_line_tags)
from obspy.io.nordic.ellipse import Ellipse
import pytest
class TestNordicMethods:
"""
Test suite for nordic io operations.
"""
def test_read_write(self):
"""
Function to test the read and write capabilities of sfile_util.
"""
# Set-up a test event
test_event = full_test_event()
# Sort the magnitudes - they are sorted on writing and we need to check
# like-for-like
test_event.magnitudes.sort(key=lambda obj: obj['mag'], reverse=True)
# Add the event to a catalogue which can be used for QuakeML testing
test_cat = Catalog()
test_cat += test_event
for nordic_format in ['OLD', 'NEW']:
# Check the read-write s-file functionality
with TemporaryWorkingDirectory():
with warnings.catch_warnings():
# Evaluation mode mapping warning
warnings.simplefilter('ignore', UserWarning)
sfile = _write_nordic(
test_cat[0], filename=None, userid='TEST', evtype='L',
outdir='.', wavefiles='test', explosion=True,
overwrite=True, nordic_format=nordic_format)
assert readwavename(sfile) == ['test']
read_cat = Catalog()
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
read_cat += read_nordic(sfile)
read_ev = read_cat[0]
test_ev = test_cat[0]
for read_pick, test_pick in zip(read_ev.picks, test_ev.picks):
assert read_pick.time == test_pick.time
assert read_pick.backazimuth == test_pick.backazimuth
assert read_pick.onset == test_pick.onset
assert read_pick.phase_hint == test_pick.phase_hint
if test_pick.polarity == "undecidable":
assert read_pick.polarity is None
elif read_pick.polarity == "undecidable":
assert test_pick.polarity is None
else:
assert read_pick.polarity == test_pick.polarity
assert read_pick.waveform_id.station_code == \
test_pick.waveform_id.station_code
assert read_pick.waveform_id.channel_code[-1] == \
test_pick.waveform_id.channel_code[-1]
# assert read_ev.origins[0].resource_id ==\
# test_ev.origins[0].resource_id
assert read_ev.origins[0].time == \
test_ev.origins[0].time
# Note that time_residual_RMS is not a quakeML format
assert read_ev.origins[0].longitude == \
test_ev.origins[0].longitude
assert read_ev.origins[0].latitude == \
test_ev.origins[0].latitude
assert read_ev.origins[0].depth == \
test_ev.origins[0].depth
assert read_ev.magnitudes[0].mag == \
test_ev.magnitudes[0].mag
assert read_ev.magnitudes[1].mag == \
test_ev.magnitudes[1].mag
assert read_ev.magnitudes[2].mag == \
test_ev.magnitudes[2].mag
assert read_ev.magnitudes[0].creation_info == \
test_ev.magnitudes[0].creation_info
assert read_ev.magnitudes[1].creation_info == \
test_ev.magnitudes[1].creation_info
assert read_ev.magnitudes[2].creation_info == \
test_ev.magnitudes[2].creation_info
assert read_ev.magnitudes[0].magnitude_type == \
test_ev.magnitudes[0].magnitude_type
assert read_ev.magnitudes[1].magnitude_type == \
test_ev.magnitudes[1].magnitude_type
assert read_ev.magnitudes[2].magnitude_type == \
test_ev.magnitudes[2].magnitude_type
assert read_ev.event_descriptions == \
test_ev.event_descriptions
# assert read_ev.amplitudes[0].resource_id ==\
# test_ev.amplitudes[0].resource_id
assert read_ev.amplitudes[0].period == \
test_ev.amplitudes[0].period
assert read_ev.amplitudes[0].snr == \
test_ev.amplitudes[0].snr
assert read_ev.amplitudes[2].period == \
test_ev.amplitudes[2].period
assert read_ev.amplitudes[2].snr == \
test_ev.amplitudes[2].snr
# Check coda magnitude pick
# Resource ids get overwritten because you can't have two the same
# in memory
# self.assertEqual(read_ev.amplitudes[1].resource_id,
# test_ev.amplitudes[1].resource_id)
assert read_ev.amplitudes[1].type == \
test_ev.amplitudes[1].type
assert read_ev.amplitudes[1].unit == \
test_ev.amplitudes[1].unit
assert read_ev.amplitudes[1].generic_amplitude == \
test_ev.amplitudes[1].generic_amplitude
# Resource ids get overwritten because you can't have two the same
# in memory
# self.assertEqual(read_ev.amplitudes[1].pick_id,
# test_ev.amplitudes[1].pick_id)
assert read_ev.amplitudes[1].waveform_id.station_code == \
test_ev.amplitudes[1].waveform_id.station_code
if nordic_format == 'OLD':
assert read_ev.amplitudes[1].waveform_id.channel_code == \
test_ev.amplitudes[1].waveform_id.channel_code[0] + \
test_ev.amplitudes[1].waveform_id.channel_code[-1]
assert read_ev.amplitudes[1].magnitude_hint == \
test_ev.amplitudes[1].magnitude_hint
# snr is not supported in s-file
# self.assertEqual(read_ev.amplitudes[1].snr,
# test_ev.amplitudes[1].snr)
assert read_ev.amplitudes[1].category == \
test_ev.amplitudes[1].category
def test_write_read_quakeml(self, testdata):
"""
Test whether all properties are set properly such that file can be
written to Quakeml and read back in.
"""
testing_path = testdata['03-0345-23L.S202101']
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
cat = read_nordic(testing_path)
with NamedTemporaryFile(suffix='.qml') as tf:
cat.write(tf.name, format='QUAKEML')
cat_back = read_events(tf.name)
for event_1, event_2 in zip(cat, cat_back):
_assert_similarity(event_1=event_1, event_2=event_2,
strict=False)
with NamedTemporaryFile(suffix='.out') as tf:
cat.write(tf.name, format='NORDIC', nordic_format='NEW')
cat_back = read_events(tf.name)
for event_1, event_2 in zip(cat, cat_back):
_assert_similarity(event_1=event_1, event_2=event_2,
strict=False)
def test_fail_writing(self):
"""
Test a deliberate fail.
"""
test_event = full_test_event()
# Add the event to a catalogue which can be used for QuakeML testing
test_cat = Catalog()
test_cat += test_event
test_ev = test_cat[0]
test_cat.append(full_test_event())
with pytest.raises(NordicParsingError):
# Raises error due to multiple events in catalog
with warnings.catch_warnings():
# Evaluation mode mapping warning
warnings.simplefilter('ignore', UserWarning)
_write_nordic(test_cat, filename=None, userid='TEST',
evtype='L', outdir='.',
wavefiles='test', explosion=True,
overwrite=True)
with pytest.raises(NordicParsingError):
# Raises error due to too long userid
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
_write_nordic(test_ev, filename=None, userid='TESTICLE',
evtype='L', outdir='.',
wavefiles='test', explosion=True,
overwrite=True)
with pytest.raises(NordicParsingError):
# Raises error due to unrecognised event type
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
_write_nordic(test_ev, filename=None, userid='TEST',
evtype='U', outdir='.',
wavefiles='test', explosion=True,
overwrite=True)
with pytest.raises(NordicParsingError):
# Raises error due to no output directory
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
_write_nordic(test_ev, filename=None, userid='TEST',
evtype='L', outdir='albatross',
wavefiles='test', explosion=True,
overwrite=True)
invalid_origin = test_ev.copy()
invalid_origin.origins = []
with pytest.raises(NordicParsingError):
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
_write_nordic(invalid_origin, filename=None, userid='TEST',
evtype='L', outdir='.', wavefiles='test',
explosion=True, overwrite=True)
invalid_origin = test_ev.copy()
invalid_origin.origins[0].time = None
with pytest.raises(NordicParsingError):
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
_write_nordic(invalid_origin, filename=None, userid='TEST',
evtype='L', outdir='.', wavefiles='test',
explosion=True, overwrite=True)
# Write a near empty origin
valid_origin = test_ev.copy()
valid_origin.origins[0].latitude = None
valid_origin.origins[0].longitude = None
valid_origin.origins[0].depth = None
with NamedTemporaryFile() as tf:
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
_write_nordic(
valid_origin, filename=tf.name, userid='TEST',
evtype='L', outdir='.', wavefiles='test',
explosion=True, overwrite=True)
assert os.path.isfile(tf.name)
def test_blanksfile(self):
st = read()
with TemporaryWorkingDirectory():
testing_path = 'Temporary_wavefile'
st.write(testing_path, format='MSEED')
sfile = blanksfile(testing_path, 'L', 'TEST', overwrite=True)
assert os.path.isfile(sfile)
os.remove(sfile)
sfile = blanksfile(testing_path, 'L', 'TEST', overwrite=True,
evtime=UTCDateTime())
assert os.path.isfile(sfile)
os.remove(sfile)
with pytest.raises(NordicParsingError):
# No wavefile
blanksfile('albert', 'L', 'TEST', overwrite=True)
with pytest.raises(NordicParsingError):
# USER ID too long
blanksfile(testing_path, 'L', 'TESTICLE', overwrite=True)
with pytest.raises(NordicParsingError):
# Unknown event type
blanksfile(testing_path, 'U', 'TEST', overwrite=True)
# Check that it breaks when writing multiple versions
sfiles = []
for _i in range(10):
# raises UserWarning: Desired sfile exists, will not overwrite
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
sfiles.append(blanksfile(testing_path, 'L', 'TEST'))
with pytest.raises(NordicParsingError):
# raises UserWarning: Desired sfile exists, will not overwrite
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
blanksfile(testing_path, 'L', 'TEST')
for sfile in sfiles:
assert os.path.isfile(sfile)
def test_write_empty(self):
"""
Function to check that writing a blank event works as it should.
"""
test_event = Event()
with pytest.raises(NordicParsingError):
_write_nordic(test_event, filename=None, userid='TEST', evtype='L',
outdir='.', wavefiles='test')
test_event.origins.append(Origin())
with pytest.raises(NordicParsingError):
_write_nordic(test_event, filename=None, userid='TEST', evtype='L',
outdir='.', wavefiles='test')
test_event.origins[0].time = UTCDateTime()
with TemporaryWorkingDirectory():
test_sfile = _write_nordic(test_event, filename=None,
userid='TEST', evtype='L', outdir='.',
wavefiles='test')
assert os.path.isfile(test_sfile)
def test_read_empty_header(self, testdata):
"""
Function to check a known issue, empty header info S-file: Bug found \
by Dominic Evanzia.
"""
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
test_event = read_nordic(testdata['Sfile_no_location'])[0]
assert not test_event.origins[0].latitude
assert not test_event.origins[0].longitude
assert not test_event.origins[0].depth
def test_read_extra_header(self, testdata):
testing_path = testdata['Sfile_extra_header']
not_extra_header = testdata['01-0411-15L.S201309']
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
test_event = read_nordic(testing_path)[0]
header_event = read_nordic(not_extra_header)[0]
assert len(header_event.origins) == 2
assert test_event.origins[0].time == \
header_event.origins[0].time
assert test_event.origins[0].latitude == \
header_event.origins[0].latitude
assert test_event.origins[0].longitude == \
header_event.origins[0].longitude
assert test_event.origins[0].depth == \
header_event.origins[0].depth
def test_header_mapping(self, testdata):
# Raise "UserWarning: Lines of type I..."
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
head_1 = readheader(testdata['01-0411-15L.S201309'])
with open(testdata['01-0411-15L.S201309'], 'r') as f:
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
tagged_lines = _get_line_tags(f=f)
head_2, _ = _readheader(head_lines=tagged_lines['1'])
_assert_similarity(head_1, head_2, strict=True)
def test_missing_header(self, testdata):
# Check that a suitable error is raised
with pytest.raises(NordicParsingError):
# Raises AIN warning
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
readheader(testdata['Sfile_no_header'])
def test_reading_string_io(self, testdata):
filename = testdata['01-0411-15L.S201309']
with open(filename, "rt") as fh:
file_object = io.StringIO(fh.read())
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
cat = read_events(file_object)
file_object.close()
ref_cat = read_events(filename)
_assert_similarity(cat[0], ref_cat[0], strict=True)
def test_reading_bytes_io(self, testdata):
filename = testdata['01-0411-15L.S201309']
with open(filename, "rb") as fh:
file_object = io.BytesIO(fh.read())
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
cat = read_events(file_object)
file_object.close()
ref_cat = read_events(filename)
_assert_similarity(cat[0], ref_cat[0], strict=True)
def test_corrupt_header(self, testdata):
filename = testdata['01-0411-15L.S201309']
f = open(filename, 'r')
with NamedTemporaryFile(suffix='.sfile') as tmp_file:
fout = open(tmp_file.name, 'w')
for line in f:
fout.write(line[0:78])
f.close()
fout.close()
with pytest.raises(NordicParsingError):
readheader(tmp_file.name)
def test_multi_writing(self):
event = full_test_event()
# Try to write the same event multiple times, but not overwrite
sfiles = []
with TemporaryWorkingDirectory():
for _i in range(59):
with warnings.catch_warnings():
# Evaluation mode mapping warning
warnings.simplefilter('ignore', UserWarning)
sfiles.append(_write_nordic(event=event, filename=None,
overwrite=False))
with pytest.raises(NordicParsingError):
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
_write_nordic(event=event, filename=None, overwrite=False)
def test_mag_conv(self):
"""
Check that we convert magnitudes as we should!
"""
magnitude_map = [
('L', 'ML'), ('B', 'mB'), ('S', 'MS'), ('W', 'MW'), ('G', 'MbLg'),
('C', 'Mc'), ('s', 'Ms')]
for magnitude in magnitude_map:
assert magnitude[0] == _evmagtonor(magnitude[1])
assert _nortoevmag(magnitude[0]) == magnitude[1]
def test_str_conv(self):
"""
Test the simple string conversions.
"""
assert _int_conv('albert') is None
assert _float_conv('albert') is None
assert _str_conv('albert') == 'albert'
assert _int_conv('1') == 1
assert _float_conv('1') == 1.0
assert _str_conv(1) == '1'
assert _int_conv('1.0256') is None
assert _float_conv('1.0256') == 1.0256
assert _str_conv(1.0256) == '1.0256'
def test_read_wavename(self, testdata):
testing_path = testdata['01-0411-15L.S201309']
wavefiles = readwavename(testing_path)
assert len(wavefiles) == 1
# Check that read_nordic reads wavname when return_wavnames=True
cat, wavefiles = read_nordic(testing_path, return_wavnames=True)
assert wavefiles == [['2013-09-01-0410-35.DFDPC_024_00']]
# Test that full paths are handled
test_event = full_test_event()
# Add the event to a catalogue which can be used for QuakeML testing
test_cat = Catalog()
test_cat += test_event
# Check the read-write s-file functionality
with TemporaryWorkingDirectory():
with warnings.catch_warnings():
# Evaluation mode mapping warning
warnings.simplefilter('ignore', UserWarning)
sfile = _write_nordic(
test_cat[0], filename=None, userid='TEST', evtype='L',
outdir='.', wavefiles=['walrus/test'], explosion=True,
overwrite=True)
assert readwavename(sfile) == ['test']
# Check that multiple wavefiles are read properly
with TemporaryWorkingDirectory():
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
sfile = _write_nordic(
test_cat[0], filename=None, userid='TEST', evtype='L',
outdir='.', wavefiles=['walrus/test', 'albert'],
explosion=True, overwrite=True)
assert readwavename(sfile) == ['test', 'albert']
def test_read_event(self, testdata):
"""
Test the wrapper.
"""
testing_path = testdata['01-0411-15L.S201309']
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
event = read_nordic(testing_path)[0]
assert len(event.origins) == 2
assert len(event.picks) == 17
def test_read_event_new(self, testdata):
"""
Test the wrapper for New Nordic format reading.
"""
testing_path = testdata['03-0345-23L.S202101']
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
event = read_nordic(testing_path)[0]
assert len(event.origins) == 1
assert len(event.picks) == 53
assert len(event.origins[0].arrivals) == 35
def test_read_latin1(self, testdata):
"""
Check that we can read dos formatted, latin1 encoded files.
"""
with warnings.catch_warnings():
# Lots of unsupported line warnings
warnings.simplefilter('ignore', UserWarning)
dos_file = testdata['dos-file.sfile']
assert _is_sfile(dos_file)
event = readheader(dos_file)
assert event.origins[0].latitude == 60.328
cat = read_events(dos_file)
assert cat[0].origins[0].latitude == 60.328
wavefiles = readwavename(dos_file)
assert wavefiles[0] == "90121311.0851W41"
spectral_info = read_spectral_info(dos_file)
assert len(spectral_info.keys()) == 10
assert spectral_info[('AVERAGE', '')]['stress_drop'] == 27.7
with pytest.raises(UnicodeDecodeError):
readheader(dos_file, 'ASCII')
def test_read_many_events(self, testdata):
testing_path = testdata['select.out']
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
catalog = read_nordic(testing_path)
assert len(catalog) == 50
def test_write_select(self):
cat = read_events()
with NamedTemporaryFile(suffix='.out') as tf:
# raises "UserWarning: mb is not convertible"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
write_select(cat, filename=tf.name, nordic_format='OLD')
assert _is_sfile(tf.name)
with warnings.catch_warnings():
# Type I warning
warnings.simplefilter('ignore', UserWarning)
cat_back = read_events(tf.name)
for event_1, event_2 in zip(cat, cat_back):
_assert_similarity(event_1=event_1, event_2=event_2, strict=False)
def test_write_select_new(self):
cat = read_events()
with NamedTemporaryFile(suffix='.out') as tf:
# raises "UserWarning: mb is not convertible"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
write_select(cat, filename=tf.name, nordic_format='NEW')
assert _is_sfile(tf.name)
with warnings.catch_warnings():
# Type I warning
warnings.simplefilter('ignore', UserWarning)
cat_back = read_events(tf.name)
for event_1, event_2 in zip(cat, cat_back):
_assert_similarity(event_1=event_1, event_2=event_2, strict=False)
def test_write_plugin(self):
cat = read_events()
cat.append(full_test_event())
with NamedTemporaryFile(suffix='.out') as tf:
# raises UserWarning: mb is not convertible
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
cat.write(tf.name, format='nordic')
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
cat_back = read_events(tf.name)
for event_1, event_2 in zip(cat, cat_back):
_assert_similarity(event_1=event_1, event_2=event_2,
strict=False)
def test_more_than_three_mags(self):
cat = Catalog()
cat += full_test_event()
cat[0].magnitudes.append(Magnitude(
mag=0.9, magnitude_type='MS', creation_info=CreationInfo('TES'),
origin_id=cat[0].origins[0].resource_id))
with NamedTemporaryFile(suffix='.out') as tf:
# raises UserWarning: mb is not convertible
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
cat.write(tf.name, format='nordic')
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
cat_back = read_events(tf.name)
for event_1, event_2 in zip(cat, cat_back):
assert len(event_1.magnitudes) == len(event_2.magnitudes)
_assert_similarity(event_1, event_2, strict=False)
def test_inaccurate_picks(self, testdata):
testing_path = testdata['bad_picks.sfile']
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
cat = read_nordic(testing_path)
pick_string = nordpick(cat[0])
for pick in pick_string:
assert len(pick) == 80
def test_round_len(self, testdata):
testing_path = testdata['round_len_undef.sfile']
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
event = read_nordic(testing_path)[0]
pick_string = nordpick(event)
for pick in pick_string:
assert len(pick) == 80
def test_read_moment(self, testdata):
"""
Test the reading of seismic moment from the s-file.
"""
testing_path = testdata['automag.out']
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
event = read_nordic(testing_path)[0]
mag = [m for m in event.magnitudes if m.magnitude_type == 'MW']
assert len(mag) == 1
assert mag[0].mag == 0.7
def test_read_moment_info(self, testdata):
"""
Test reading the info from spectral analysis.
"""
testing_path = testdata['automag.out']
with warnings.catch_warnings():
# Userwarning, type I
warnings.simplefilter('ignore', UserWarning)
spec_inf = read_spectral_info(testing_path)
assert len(spec_inf) == 5
# This should actually test that what we are reading in is correct.
average = spec_inf[('AVERAGE', '')]
check_av = {u'channel': '', u'corner_freq': 5.97, u'decay': 0.0,
u'moment': 12589254117.941662, u'moment_mag': 0.7,
u'source_radius': 0.231,
u'spectral_level': 0.3981071705534972,
u'station': 'AVERAGE', u'stress_drop': 0.006,
u'window_length': 1.6}
for key in average.keys():
if isinstance(average.get(key), str):
assert average.get(key) == check_av.get(key)
else:
assert round(average.get(key), 4) == \
round(check_av.get(key), 4)
def test_is_sfile(self, datapath, testdata):
sfiles = ['01-0411-15L.S201309', 'automag.out', 'bad_picks.sfile',
'round_len_undef.sfile', 'Sfile_extra_header',
'Sfile_no_location']
for sfile in sfiles:
assert _is_sfile(testdata[sfile])
no_header_path = testdata['Sfile_no_header']
assert not _is_sfile(no_header_path)
assert not _is_sfile(
datapath.parent.parent.parent /
'nlloc' / 'tests' / 'data' / 'nlloc.hyp')
def test_read_picks_across_day_end(self, testdata):
testing_path = testdata['sfile_over_day']
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
event = read_nordic(testing_path)[0]
pick_times = [pick.time for pick in event.picks]
for pick in event.picks:
# Pick should come after origin time
assert pick.time > event.origins[0].time
# All picks in this event are within 60s of origin time
assert (pick.time - event.origins[0].time) <= 60
# Make sure zero hours and 24 hour picks are handled the same.
testing_path = testdata['sfile_over_day_zeros']
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
event_2 = read_nordic(testing_path)[0]
for pick in event_2.picks:
# Pick should come after origin time
assert pick.time > event_2.origins[0].time
# All picks in this event are within 60s of origin time
assert (pick.time - event_2.origins[0].time) <= 60
# Each pick should be the same as one pick in the previous event
assert pick.time in pick_times
assert event_2.origins[0].time == event.origins[0].time
def test_distance_conversion(self, testdata):
"""
Check that distances are converted properly.
"""
testing_path = testdata['01-0411-15L.S201309']
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
cat = read_events(testing_path)
event = cat[0]
dist = sorted(event.origins[0].arrivals, key=lambda x: x.distance)[0]
assert round(abs(dist.distance - 0.035972864236749225), 7) == 0
pick_strings = nordpick(event)
assert int([p for p in pick_strings if p.split()[0] == 'GCSZ' and
p.split()[1] == 'SZ'][0].split()[-1]) == 304
assert int([p for p in pick_strings if p.split()[0] == 'WZ11' and
p.split()[1] == 'HZ'][0].split()[-1]) == 30
def test_large_negative_longitude(self):
event = full_test_event()
event.origins[0].longitude = -120
with NamedTemporaryFile(suffix=".out") as tf:
with warnings.catch_warnings():
# Evaluation mode mapping warning
warnings.simplefilter('ignore', UserWarning)
event.write(tf.name, format="NORDIC")
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
event_back = read_events(tf.name)
_assert_similarity(event, event_back[0], strict=True)
def test_write_preferred_origin(self):
event = full_test_event()
preferred_origin = Origin(
time=UTCDateTime("2012-03-26") + 2.2, latitude=47.0,
longitude=35.0, depth=18000)
event.origins.append(preferred_origin)
event.preferred_origin_id = preferred_origin.resource_id
with NamedTemporaryFile(suffix=".out") as tf:
with warnings.catch_warnings():
# Evaluation mode mapping warning
warnings.simplefilter('ignore', UserWarning)
event.write(tf.name, format="NORDIC")
with warnings.catch_warnings():
# Type I warning
warnings.simplefilter('ignore', UserWarning)
event_back = read_events(tf.name)
assert preferred_origin.latitude == event_back[0].origins[0].latitude
assert preferred_origin.longitude == event_back[0].origins[0].longitude
assert preferred_origin.depth == event_back[0].origins[0].depth
assert preferred_origin.time == event_back[0].origins[0].time
def test_read_high_precision_pick(self, testdata):
"""
Nordic supports writing to milliseconds in high-precision mode,
obspy < 1.2.0 did not properly read this, see #2348.
"""
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
cat = read_events(
testdata['sfile_high_precision_picks'])
event = cat[0]
pick_times = {
"LSd1": UTCDateTime(2010, 11, 26, 1, 28, 46.859),
"LSd3": UTCDateTime(2010, 11, 26, 1, 28, 48.132),
"LSd2": UTCDateTime(2010, 11, 26, 1, 28, 48.183),
"LSd4": UTCDateTime(2010, 11, 26, 1, 28, 49.744)}
for key, value in pick_times.items():
pick = [p for p in event.picks
if p.waveform_id.station_code == key]
assert len(pick) == 1
assert pick[0].time == value
def test_high_precision_read_write(self, testdata):
""" Test that high-precision writing works. """
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
cat = read_events(testdata['sfile_high_precision_picks'])
event = cat[0]
pick_times = {
"LSd1": UTCDateTime(2010, 11, 26, 1, 28, 46.859),
"LSd3": UTCDateTime(2010, 11, 26, 1, 28, 48.132),
"LSd2": UTCDateTime(2010, 11, 26, 1, 28, 48.183),
"LSd4": UTCDateTime(2010, 11, 26, 1, 28, 49.744)}
for key, value in pick_times.items():
pick = [p for p in event.picks
if p.waveform_id.station_code == key]
assert len(pick) == 1
assert pick[0].time == value
with NamedTemporaryFile(suffix=".out") as tf:
write_select(cat, filename=tf.name, nordic_format='OLD')
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
cat_back = read_events(tf.name)
assert len(cat_back) == 1
for key, value in pick_times.items():
pick = [p for p in cat_back[0].picks
if p.waveform_id.station_code == key]
assert len(pick) == 1
assert pick[0].time == value
# Check that writing to standard accuracy just gives a rounded version
with NamedTemporaryFile(suffix=".out") as tf:
cat.write(format="NORDIC", filename=tf.name, high_accuracy=False)
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
cat_back = read_events(tf.name)
assert len(cat_back) == 1
for key, value in pick_times.items():
pick = [p for p in cat_back[0].picks
if p.waveform_id.station_code == key]
assert len(pick) == 1
rounded_pick_time = UTCDateTime(
value.year, value.month, value.day, value.hour, value.minute)
rounded_pick_time += round(
value.second + (value.microsecond / 1e6), 2)
assert pick[0].time == rounded_pick_time
def test_long_phase_name(self, testdata):
""" Nordic format supports 8 char phase names, sometimes. """
# raises "UserWarning: AIN in header, currently unsupported"
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
cat = read_events(testdata['sfile_long_phase'])
# This file has one event with one pick
pick = cat[0].picks[0]
arrival = cat[0].origins[0].arrivals[0]
assert pick.phase_hint == "PKiKP"
assert arrival.time_weight == 1
with NamedTemporaryFile(suffix=".out") as tf:
write_select(cat, filename=tf.name, nordic_format='OLD')
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
cat_back = read_events(tf.name)
pick = cat_back[0].picks[0]
arrival = cat_back[0].origins[0].arrivals[0]
assert pick.phase_hint == "PKiKP"
assert arrival.time_weight == 1
def test_read_write_over_day(self):
"""
Nordic picks are relative to origin time - check that this works
over day boundaries.
"""
event = full_test_event()
event.origins[0].time -= 3600
assert event.picks[0].time.date > event.origins[0].time.date
with NamedTemporaryFile(suffix=".out") as tf:
with warnings.catch_warnings():
# Evaluation mode mapping warning
warnings.simplefilter('ignore', UserWarning)
write_select(Catalog([event]), filename=tf.name,
nordic_format='OLD')
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
event_back = read_events(tf.name)[0]
_assert_similarity(event, event_back, strict=True)
def test_seconds_overflow(self, testdata):
"""
#2348 indicates that SEISAN sometimes overflows seconds into column 29.
"""
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
cat = read_events(testdata['sfile_seconds_overflow'])
event = cat[0]
pick_times = {
"LSb2": UTCDateTime(2009, 7, 2, 6, 49) + 100.24}
for key, value in pick_times.items():
pick = [p for p in event.picks
if p.waveform_id.station_code == key]
assert len(pick) == 1
assert pick[0].time == value
with NamedTemporaryFile(suffix=".out") as tf:
write_select(cat, filename=tf.name, nordic_format='OLD')
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
cat_back = read_events(tf.name)
assert len(cat_back) == 1
for key, value in pick_times.items():
pick = [p for p in cat_back[0].picks
if p.waveform_id.station_code == key]
assert len(pick) == 1
assert pick[0].time == value
def test_read_bad_covariance(self, testdata):
"""
Verify graceful exit if covariance matrix is not positive-definite
"""
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
cat = read_events(testdata['sfile_bad_covariance'])
assert cat[0].origins[0].origin_uncertainty is None
def test_read_high_accuracy(self, testdata):
"""
Verify that high-accuracy locations are read, if present
"""
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
cat = read_events(testdata['sfile_highaccuracy'])
event = cat[0]
event_time = event.origins[0].time
event_lat = event.origins[0].latitude
event_lon = event.origins[0].longitude
event_depth = event.origins[0].depth
event_rms = event.origins[0].quality.standard_error
assert event_time == UTCDateTime(2015, 4, 24, 15, 25, 37) + 0.676
assert event_lat == 37.29242
assert event_lon == -32.26983
assert event_depth == 1969.
assert event_rms == 0.051
def test_ellipse_from__to_uncerts(self):
"""
Verify ellipse is properly calculated and inverted using uncertainties
tests Ellipse.from_uncerts and Ellipse.to_uncerts()
"""
center = (20, 30)
# First try simple cases without correlation
x_errs = (0.5, 1.33, 1.0)
y_errs = (1.33, 0.5, 1.0)
for c_xy in [0, 0.2, 0.4, 0.6]:
for (x_err, y_err) in zip(x_errs, y_errs):
ell = Ellipse.from_uncerts(x_err, y_err, c_xy, center)
(x_err_out, y_err_out, c_xy_out, center_out) = ell.to_uncerts()
assert round(abs(x_err-x_err_out), 7) == 0
assert round(abs(y_err-y_err_out), 7) == 0
assert round(abs(c_xy-c_xy_out), 7) == 0
assert np.allclose(np.array(center), np.array(center_out))
# Now a specific case with a finite covariance
x_err = 0.5
y_err = 1.1
c_xy = -0.2149
# Calculate ellipse
ell = Ellipse.from_uncerts(x_err, y_err, c_xy, center)
assert round(abs(ell.a-1.120674193646), 7) == 0
assert round(abs(ell.b-0.451762494786), 7) == 0
assert round(abs(ell.theta-167.9407699), 7) == 0
# Calculate covariance error from ellipse
(x_err_out, y_err_out, c_xy_out, center_out) = ell.to_uncerts()
assert round(abs(x_err-x_err_out), 7) == 0
assert round(abs(y_err-y_err_out), 7) == 0
assert round(abs(c_xy-c_xy_out), 7) == 0
assert np.allclose(np.array(center), np.array(center_out))
def test_ellipse_from_to_cov(self):
"""
Verify ellipse is properly calculated and inverted using covariance
tests Ellipse.from_uncerts and Ellipse.to_uncerts()
"""
center = (20, 30)
x_err = 0.5
y_err = 1.1
c_xy = -0.2149
cov = [[x_err**2, c_xy], [c_xy, y_err**2]]
# Calculate ellipse
ell = Ellipse.from_cov(cov, center)
assert round(abs(ell.a-1.120674193646), 7) == 0
assert round(abs(ell.b-0.451762494786), 7) == 0
assert round(abs(ell.theta-167.9407699), 7) == 0
# Calculate covariance error from ellipse
cov_out, center_out = ell.to_cov()
assert round(abs(cov[0][0]-cov_out[0][0]), 7) == 0
assert round(abs(cov[0][1]-cov_out[0][1]), 7) == 0
assert round(abs(cov[1][0]-cov_out[1][0]), 7) == 0
assert round(abs(cov[1][1]-cov_out[1][1]), 7) == 0
def test_ellipse_from_uncerts_baz(self, debug=False):
"""
Verify alternative ellipse creator
tests Ellipse.from_uncerts_baz
"""
# Now a specific case with a finite covariance
x_err = 0.5
y_err = 1.1
c_xy = -0.2149
dist = 10
baz = 90
viewpoint = (5, 5)
# Calculate ellipse
ell = Ellipse.from_uncerts_baz(x_err, y_err, c_xy,
dist, baz, viewpoint)
assert round(abs(ell.a-1.120674193646), 7) == 0
assert round(abs(ell.b-0.451762494786), 7) == 0
assert round(abs(ell.theta-167.9407699), 7) == 0
assert round(abs(ell.x-15), 7) == 0
assert round(abs(ell.y-5), 7) == 0
baz = 180
ell = Ellipse.from_uncerts_baz(x_err, y_err, c_xy,
dist, baz, viewpoint)
assert round(abs(ell.x-5), 7) == 0
assert round(abs(ell.y--5), 7) == 0
def test_ellipse_is_inside(self, debug=False):
"""
Verify Ellipse.is_inside()
"""
ell = Ellipse(20, 10, 90)
assert ell.is_inside((0, 0)) is True
assert not ell.is_inside((100, 100))
assert ell.is_inside((-19.9, 0))
assert ell.is_inside((19.9, 0))
assert not ell.is_inside((-20.1, 0))
assert not ell.is_inside((20.1, 0))
assert ell.is_inside((0, 9.9))
assert ell.is_inside((0, -9.9))
assert not ell.is_inside((0, 10.1))
assert not ell.is_inside((0, -10.1))