/
test_mass_downloader.py
2828 lines (2483 loc) · 118 KB
/
test_mass_downloader.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 -*-
"""
The obspy.clients.fdsn.download_helpers test suite.
:copyright:
Lion Krischer (krischer@geophysik.uni-muenchen.de), 2014-2105
:license:
GNU Lesser General Public License, Version 3
(https://www.gnu.org/copyleft/lesser.html)
"""
import collections
import copy
import logging
import os
import shutil
from socket import timeout as socket_timeout
import sys
import tempfile
import unittest
from unittest import mock
import pytest
if sys.version_info.major == 2:
from httplib import HTTPException
else:
from http.client import HTTPException
import numpy as np
import obspy
from obspy.core.util.base import NamedTemporaryFile
from obspy.clients.fdsn import Client
from obspy.clients.fdsn.mass_downloader import (domain, Restrictions,
MassDownloader)
from obspy.clients.fdsn.mass_downloader.utils import (
filter_channel_priority, get_stationxml_filename, get_mseed_filename,
get_stationxml_contents, SphericalNearestNeighbour, safe_delete,
download_stationxml, download_and_split_mseed_bulk,
_get_stationxml_contents_slow)
from obspy.clients.fdsn.mass_downloader.download_helpers import (
Channel, TimeInterval, Station, STATUS, ClientDownloadHelper)
pytestmark = pytest.mark.network
class DomainTestCase(unittest.TestCase):
"""
Test case for the domain definitions.
"""
def test_rectangular_domain(self):
"""
Test the rectangular domain.
"""
dom = domain.RectangularDomain(-10, 10, -20, 20)
query_params = dom.get_query_parameters()
self.assertEqual(query_params, {
"minlatitude": -10,
"maxlatitude": 10,
"minlongitude": -20,
"maxlongitude": 20})
# The rectangular domain is completely defined by the query parameters.
self.assertRaises(NotImplementedError, dom.is_in_domain, 0, 0)
def test_circular_domain(self):
"""
Test the circular domain.
"""
dom = domain.CircularDomain(10, 20, 30, 40)
query_params = dom.get_query_parameters()
self.assertEqual(query_params, {
"latitude": 10,
"longitude": 20,
"minradius": 30,
"maxradius": 40})
# The circular domain is completely defined by the query parameters.
self.assertRaises(NotImplementedError, dom.is_in_domain, 0, 0)
def test_global_domain(self):
"""
Test the global domain.
"""
dom = domain.GlobalDomain()
query_params = dom.get_query_parameters()
self.assertEqual(query_params, {})
# Obviously every point is in the domain.
self.assertRaises(NotImplementedError, dom.is_in_domain, 0, 0)
def test_subclassing_without_abstract_method(self):
"""
Subclassing without implementing the get_query_parameters method
results in a TypeError upon instantiation time.
"""
class NewDom(domain.Domain):
pass
self.assertRaises(TypeError, NewDom)
def test_instantiating_root_domain_object_fails(self):
"""
Trying to create a root domain object should fail.
"""
self.assertRaises(TypeError, domain.Domain)
class RestrictionsTestCase(unittest.TestCase):
"""
Test case for the restrictions object.
"""
def __init__(self, *args, **kwargs):
super(RestrictionsTestCase, self).__init__(*args, **kwargs)
self.path = os.path.dirname(__file__)
self.data = os.path.join(self.path, "data")
def test_passing_string_as_priority_list_raises(self):
"""
Users reported errors as they used "tuples" with single items as
priority lists. Python semantics mean that a "tuple" without a comma
is not tuple. Thus '("HH[NEZ")' is actually just a string which is
not what the users expected. Thus this should raise an exception.
"""
start = obspy.UTCDateTime(2014, 1, 1)
end = start + 10
# Test for the channel_priorities key.
with self.assertRaises(TypeError) as e:
Restrictions(starttime=start, endtime=end,
channel_priorities="HHE")
self.assertEqual(e.exception.args[0],
"'channel_priorities' must be a list or other "
"iterable container.")
with self.assertRaises(TypeError) as e:
Restrictions(starttime=start, endtime=end,
channel_priorities=("HHE"))
self.assertEqual(e.exception.args[0],
"'channel_priorities' must be a list or other "
"iterable container.")
with self.assertRaises(TypeError) as e:
Restrictions(starttime=start, endtime=end,
channel_priorities="HHE")
self.assertEqual(e.exception.args[0],
"'channel_priorities' must be a list or other "
"iterable container.")
with self.assertRaises(TypeError) as e:
Restrictions(starttime=start, endtime=end,
channel_priorities="HHE")
self.assertEqual(e.exception.args[0],
"'channel_priorities' must be a list or other "
"iterable container.")
# And for the location priorities key.
with self.assertRaises(TypeError) as e:
Restrictions(starttime=start, endtime=end,
location_priorities="00")
self.assertEqual(e.exception.args[0],
"'location_priorities' must be a list or other "
"iterable container.")
with self.assertRaises(TypeError) as e:
Restrictions(starttime=start, endtime=end,
location_priorities=("00"))
self.assertEqual(e.exception.args[0],
"'location_priorities' must be a list or other "
"iterable container.")
with self.assertRaises(TypeError) as e:
Restrictions(starttime=start, endtime=end,
location_priorities="00")
self.assertEqual(e.exception.args[0],
"'location_priorities' must be a list or other "
"iterable container.")
with self.assertRaises(TypeError) as e:
Restrictions(starttime=start, endtime=end,
location_priorities=("00"))
self.assertEqual(e.exception.args[0],
"'location_priorities' must be a list or other "
"iterable container.")
# All other valid things should of course still work.
Restrictions(starttime=start, endtime=end,
channel_priorities=("HHE",))
Restrictions(starttime=start, endtime=end,
channel_priorities=["HHE"])
Restrictions(starttime=start, endtime=end,
channel_priorities=("HHE", "BHE"))
Restrictions(starttime=start, endtime=end,
channel_priorities=["HHE", "BHE"])
Restrictions(starttime=start, endtime=end,
channel_priorities=("HHE",))
Restrictions(starttime=start, endtime=end,
channel_priorities=["HHE"])
Restrictions(starttime=start, endtime=end,
channel_priorities=("HHE",
"BHE"))
Restrictions(starttime=start, endtime=end,
channel_priorities=["HHE",
"BHE"])
Restrictions(starttime=start, endtime=end,
location_priorities=("00",))
Restrictions(starttime=start, endtime=end,
location_priorities=["00"])
Restrictions(starttime=start, endtime=end,
location_priorities=("00", "10"))
Restrictions(starttime=start, endtime=end,
location_priorities=["00", "10"])
Restrictions(starttime=start, endtime=end,
location_priorities=("00",))
Restrictions(starttime=start, endtime=end,
location_priorities=["00"])
Restrictions(starttime=start, endtime=end,
location_priorities=("00",
"10"))
Restrictions(starttime=start, endtime=end,
location_priorities=["00",
"10"])
def test_restrictions_object(self):
"""
Tests the restrictions object.
"""
start = obspy.UTCDateTime(2014, 1, 1)
res = Restrictions(starttime=start, endtime=start + 10)
# No chunklength means it should just return one item.
chunks = list(res)
self.assertEqual(len(chunks), 1)
self.assertEqual(chunks[0], (start, start + 10))
# One with chunklength should return the chunked pieces.
res = Restrictions(starttime=start, endtime=start + 10,
chunklength_in_sec=1)
chunks = list(res)
self.assertEqual(len(chunks), 10)
self.assertEqual(
[_i[0] for _i in chunks],
[start + _i * 1 for _i in range(10)])
self.assertEqual(
[_i[1] for _i in chunks],
[start + _i * 1 for _i in range(1, 11)])
self.assertEqual(chunks[0][0], start)
self.assertEqual(chunks[-1][1], start + 10)
# Make sure the last piece is cut if it needs to be.
start = obspy.UTCDateTime(2012, 1, 1)
end = obspy.UTCDateTime(2012, 2, 1)
res = Restrictions(starttime=start, endtime=end,
chunklength_in_sec=86400 * 10)
chunks = list(res)
self.assertEqual(chunks, [
(start, start + 86400 * 10),
(start + 86400 * 10, start + 86400 * 20),
(start + 86400 * 20, start + 86400 * 30),
(start + 86400 * 30, end)])
# No station start-and endtime by default
res = Restrictions(starttime=start, endtime=start + 10)
self.assertEqual(res.station_starttime, None)
self.assertEqual(res.station_endtime, None)
# One can only set one of the two.
res = Restrictions(starttime=start, endtime=start + 10,
station_starttime=start - 10)
self.assertEqual(res.station_starttime, start - 10)
self.assertEqual(res.station_endtime, None)
res = Restrictions(starttime=start, endtime=start + 10,
station_endtime=start + 20)
self.assertEqual(res.station_starttime, None)
self.assertEqual(res.station_endtime, start + 20)
# Will raise a ValueError if either within the time interval of the
# normal start- and endtime.
self.assertRaises(ValueError, Restrictions, starttime=start,
endtime=start + 10, station_starttime=start + 1)
self.assertRaises(ValueError, Restrictions, starttime=start,
endtime=start + 10, station_endtime=start + 9)
# Fine if they are equal with both.
Restrictions(starttime=start, endtime=start + 10,
station_starttime=start, station_endtime=start + 10)
def test_inventory_parsing(self):
"""
Test the inventory parsing if an inventory is given.
"""
# Nothing is given.
r = Restrictions(starttime=obspy.UTCDateTime(2011, 1, 1),
endtime=obspy.UTCDateTime(2011, 2, 1))
self.assertIs(r.limit_stations_to_inventory, None)
# An inventory object is given.
inv = obspy.read_inventory(os.path.join(
self.data, "channel_level_fdsn.txt"))
r = Restrictions(starttime=obspy.UTCDateTime(2011, 1, 1),
endtime=obspy.UTCDateTime(2011, 2, 1),
limit_stations_to_inventory=inv)
self.assertEqual({("AK", "BAGL"), ("AK", "BWN"), ("AZ", "BZN")},
r.limit_stations_to_inventory)
class DownloadHelpersUtilTestCase(unittest.TestCase):
"""
Test cases for utility functionality for the download helpers.
"""
def __init__(self, *args, **kwargs):
super(DownloadHelpersUtilTestCase, self).__init__(*args, **kwargs)
self.path = os.path.dirname(__file__)
self.data = os.path.join(self.path, "data")
def test_channel_priority_filtering(self):
"""
Tests the channel priority filtering.
"""
st = obspy.UTCDateTime(2015, 1, 1)
time_intervals = [
TimeInterval(st + _i * 60, st + (_i + 1) * 60)
for _i in range(10)]
c1 = Channel("", "BHE", time_intervals)
c2 = Channel("10", "SHE", time_intervals)
c3 = Channel("00", "BHZ", time_intervals)
c4 = Channel("", "HHE", time_intervals)
c5 = Channel("", "ELZ", time_intervals)
channels = [c1, c2, c3, c4, c5]
filtered_channels = filter_channel_priority(
channels, key="channel", priorities=[
"HH[ZNE]", "BH[ZNE]", "MH[ZNE]", "EH[ZNE]",
"LH[ZNE]"])
self.assertEqual(filtered_channels, [c4])
filtered_channels = filter_channel_priority(
channels, key="channel", priorities=[
"BH[ZNE]", "MH[ZNE]", "EH[ZNE]", "LH[ZNE]"])
self.assertEqual(filtered_channels, [c1, c3])
filtered_channels = filter_channel_priority(
channels, key="channel", priorities=["LH[ZNE]"])
self.assertEqual(filtered_channels, [])
filtered_channels = filter_channel_priority(
channels, key="channel", priorities=["*"])
self.assertEqual(filtered_channels, channels)
filtered_channels = filter_channel_priority(
channels, key="channel", priorities=[
"BH*", "MH[ZNE]", "EH[ZNE]", "LH[ZNE]"])
self.assertEqual(filtered_channels, [c1, c3])
filtered_channels = filter_channel_priority(
channels, key="channel", priorities=[
"BH[NZ]", "MH[ZNE]", "EH[ZNE]", "LH[ZNE]"])
self.assertEqual(filtered_channels, [c3])
filtered_channels = filter_channel_priority(
channels, key="channel", priorities=["S*", "BH*"])
self.assertEqual(filtered_channels, [c2])
# Different ways to not filter.
filtered_channels = filter_channel_priority(
channels, key="channel", priorities=["*"])
self.assertEqual(filtered_channels, channels)
filtered_channels = filter_channel_priority(
channels, key="channel", priorities=None)
self.assertEqual(filtered_channels, channels)
def test_location_priority_filtering(self):
"""
Tests the channel priority filtering.
"""
st = obspy.UTCDateTime(2015, 1, 1)
time_intervals = [
TimeInterval(st + _i * 60, st + (_i + 1) * 60)
for _i in range(10)]
c1 = Channel("", "BHE", time_intervals)
c2 = Channel("10", "SHE", time_intervals)
c3 = Channel("00", "BHZ", time_intervals)
c4 = Channel("", "HHE", time_intervals)
channels = [c1, c2, c3, c4]
filtered_channels = filter_channel_priority(
channels, key="location", priorities=["*0"])
self.assertEqual(filtered_channels, [c2, c3])
filtered_channels = filter_channel_priority(
channels, key="location", priorities=["00"])
self.assertEqual(filtered_channels, [c3])
filtered_channels = filter_channel_priority(
channels, key="location", priorities=[""])
self.assertEqual(filtered_channels, [c1, c4])
filtered_channels = filter_channel_priority(
channels, key="location", priorities=["1?"])
self.assertEqual(filtered_channels, [c2])
filtered_channels = filter_channel_priority(
channels, key="location", priorities=["", "*0"])
self.assertEqual(filtered_channels, [c1, c4])
filtered_channels = filter_channel_priority(
channels, key="location", priorities=["*0", ""])
self.assertEqual(filtered_channels, [c2, c3])
# Different ways to not filter.
filtered_channels = filter_channel_priority(
channels, key="location", priorities=["*"])
self.assertEqual(filtered_channels, channels)
filtered_channels = filter_channel_priority(
channels, key="location", priorities=None)
self.assertEqual(filtered_channels, channels)
def test_spherical_nearest_neighbour(self):
"""
Tests the spherical kd-tree.
"""
# Get the distance of a point to itself.
point = Station("", "", 10.0, 20.0, [])
tree = SphericalNearestNeighbour(data=[point])
result = tree.query(points=[point])
distance, indices = result[0][0], result[1][0]
np.testing.assert_allclose(distance, [0])
np.testing.assert_allclose(indices, [0])
# Two points, one 50 km, the other 150 km distant.
point_a = Station("", "", 0.0, -0.5, [])
point_b = Station("", "", 0.0, 1.5, [])
tree = SphericalNearestNeighbour(data=[point_a, point_b])
result = tree.query(points=[Station("", "", 0.0, 0.0, [])])
distance, indices = result[0][0], result[1][0]
np.testing.assert_allclose(distance, [55597.36],
atol=1, rtol=1E-5)
np.testing.assert_allclose(indices, [0])
# Query pairs.
point_a = Station("", "", 0.0, -0.5, [])
point_b = Station("", "", 0.0, 1.5, [])
point_c = Station("", "", 0.0, 0.0, [])
tree = SphericalNearestNeighbour(data=[point_a, point_b, point_c])
# 100 km apart. Only contains points a and c.
self.assertEqual(tree.query_pairs(100000), {(0, 2)})
def test_safe_delete(self):
"""
Test the safe-delete function.
"""
dir = tempfile.mkdtemp()
try:
# If the file does not exist, nothing happens.
safe_delete(os.path.join(dir, "non-existant"))
# If not a file, an error will be raised.
name = os.path.join(dir, "tmpdir")
os.makedirs(name)
self.assertRaises(ValueError, safe_delete, name)
# Otherwise it can delete a file just fine.
name = os.path.join(dir, "tmpfile")
with open(name, "wt") as fh:
fh.write("0")
self.assertTrue(os.path.exists(name))
safe_delete(name)
self.assertFalse(os.path.exists(name))
finally:
shutil.rmtree(dir)
def test_download_stationxml(self):
"""
Mock test for the StationXML downloading.
Does not do much and is not a proper test but it's something and
makes sure there is not obvious logic error.
"""
bulk = [
["BW", "ALTM"],
["BW", "ALTM"],
]
filename = "temp.xml"
client_name = "mock"
client = mock.MagicMock()
logger = mock.MagicMock()
# Normal call.
ret_val = download_stationxml(client, client_name, bulk, filename,
logger)
self.assertEqual(ret_val, (("BW", "ALTM"), filename))
self.assertEqual(logger.info.call_count, 1)
self.assertEqual(logger.info.call_args[0][0],
"Client 'mock' - Successfully downloaded 'temp.xml'.")
self.assertEqual(client.get_stations_bulk.call_count, 1)
self.assertEqual(
client.get_stations_bulk.call_args[1]["bulk"], bulk)
self.assertEqual(
client.get_stations_bulk.call_args[1]["level"], "response")
self.assertEqual(
client.get_stations_bulk.call_args[1]["filename"], filename)
# Call that raises.
client.reset_mock()
logger.reset_mock()
def raise_exception():
raise ValueError("Test")
client.get_stations_bulk.side_effect = raise_exception
ret_val = download_stationxml(client, client_name, bulk, filename,
logger)
self.assertEqual(ret_val, None)
self.assertEqual(logger.info.call_count, 1)
self.assertEqual(
logger.info.call_args[0][0],
"Failed to download StationXML from 'mock' for station 'BW.ALTM'.")
self.assertEqual(client.get_stations_bulk.call_count, 1)
self.assertEqual(
client.get_stations_bulk.call_args[1]["bulk"], bulk)
self.assertEqual(
client.get_stations_bulk.call_args[1]["level"], "response")
self.assertEqual(
client.get_stations_bulk.call_args[1]["filename"], filename)
def test_download_and_split_mseed(self):
"""
Largely mocked test for the download_and_split_mseed() function.
"""
client_name = "mock"
client = mock.MagicMock()
logger = mock.MagicMock()
def get_waveforms_bulk_mock(bulk, filename):
"""
Actually create the requested MiniSEED file.
"""
st = obspy.Stream()
for item in bulk:
tr = obspy.Trace()
tr.stats.network = item[0]
tr.stats.station = item[1]
tr.stats.location = item[2]
tr.stats.channel = item[3]
tr.stats.starttime = item[4]
tr.stats.delta = 1.0
tr.data = np.empty(int(item[5] - item[4]) + 1)
st.traces.append(tr)
st.write(filename, format="mseed")
client.get_waveforms_bulk.side_effect = get_waveforms_bulk_mock
tmpdir = tempfile.mkdtemp()
try:
chunks = [
["BW", "ALTM", "", "EHE", obspy.UTCDateTime(0),
obspy.UTCDateTime(10), os.path.join(tmpdir, "file_1.mseed")],
["BW", "ALTM", "", "EHN", obspy.UTCDateTime(0),
obspy.UTCDateTime(10), os.path.join(tmpdir, "file_2.mseed")],
["BW", "ALTM", "", "EHZ", obspy.UTCDateTime(0),
obspy.UTCDateTime(10), os.path.join(tmpdir, "file_3.mseed")],
]
ret_val = download_and_split_mseed_bulk(
client=client, client_name=client_name, chunks=chunks,
logger=logger)
contents = [("file_1.mseed", "BW.ALTM..EHE"),
("file_2.mseed", "BW.ALTM..EHN"),
("file_3.mseed", "BW.ALTM..EHZ")]
self.assertEqual(ret_val,
sorted([os.path.join(tmpdir, _i[0])
for _i in contents]))
# Make sure all files have been written.
self.assertEqual(sorted(os.listdir(tmpdir)),
["file_1.mseed", "file_2.mseed", "file_3.mseed"])
# Check the actual files.
for filename, id, in contents:
st = obspy.read(os.path.join(tmpdir, filename))
self.assertEqual(len(st), 1)
tr = st[0]
self.assertEqual(tr.id, id)
self.assertEqual(tr.stats.starttime, obspy.UTCDateTime(0))
self.assertEqual(tr.stats.endtime, obspy.UTCDateTime(10))
finally:
shutil.rmtree(tmpdir)
# Same as before but now add some random other things so make sure
# they get filtered out.
client.reset_mock()
logger.reset_mock()
def get_waveforms_bulk_mock(bulk, filename):
"""
Actually create the requested MiniSEED file.
"""
st = obspy.Stream()
for item in bulk:
tr = obspy.Trace()
tr.stats.network = item[0]
tr.stats.station = item[1]
tr.stats.location = item[2]
tr.stats.channel = item[3]
tr.stats.starttime = item[4]
tr.stats.delta = 1.0
tr.data = np.empty(int(item[5] - item[4]) + 1)
st.traces.append(tr)
# Add some random other stuff to mess with things.
tr = obspy.Trace()
tr.stats.network = "HM"
tr.stats.channel = "EHE"
tr.data = np.empty(12)
st.traces.append(tr)
tr = obspy.Trace()
tr.stats.network = "HM"
tr.stats.channel = "BHE"
tr.data = np.empty(12)
st.traces.append(tr)
# This time same id as above, but different time span.
tr = obspy.Trace()
tr.stats.network = bulk[0][0]
tr.stats.station = bulk[0][1]
tr.stats.location = bulk[0][2]
tr.stats.channel = bulk[0][3]
tr.data = np.empty(34)
tr.stats.starttime += 1234567.345
st.traces.append(tr)
st.write(filename, format="mseed")
client.get_waveforms_bulk.side_effect = get_waveforms_bulk_mock
tmpdir = tempfile.mkdtemp()
try:
chunks = [
["BW", "ALTM", "", "EHE", obspy.UTCDateTime(0),
obspy.UTCDateTime(10), os.path.join(tmpdir, "file_1.mseed")],
["BW", "ALTM", "", "EHN", obspy.UTCDateTime(0),
obspy.UTCDateTime(10), os.path.join(tmpdir, "file_2.mseed")],
["BW", "ALTM", "", "EHZ", obspy.UTCDateTime(0),
obspy.UTCDateTime(10), os.path.join(tmpdir, "file_3.mseed")],
]
ret_val = download_and_split_mseed_bulk(
client=client, client_name=client_name, chunks=chunks,
logger=logger)
contents = [("file_1.mseed", "BW.ALTM..EHE"),
("file_2.mseed", "BW.ALTM..EHN"),
("file_3.mseed", "BW.ALTM..EHZ")]
self.assertEqual(ret_val,
sorted([os.path.join(tmpdir, _i[0])
for _i in contents]))
# Make sure all files have been written.
self.assertEqual(sorted(os.listdir(tmpdir)),
["file_1.mseed", "file_2.mseed", "file_3.mseed"])
# Check the actual files.
for filename, id, in contents:
st = obspy.read(os.path.join(tmpdir, filename))
self.assertEqual(len(st), 1)
tr = st[0]
self.assertEqual(tr.id, id)
self.assertEqual(tr.stats.starttime, obspy.UTCDateTime(0))
self.assertEqual(tr.stats.endtime, obspy.UTCDateTime(10))
finally:
shutil.rmtree(tmpdir)
# Now simulate a request of lots of data from the same channel.
client.reset_mock()
logger.reset_mock()
def get_waveforms_bulk_mock(bulk, filename):
"""
Actually create the requested MiniSEED file.
"""
st = obspy.Stream()
for item in bulk:
tr = obspy.Trace()
tr.stats.network = item[0]
tr.stats.station = item[1]
tr.stats.location = item[2]
tr.stats.channel = item[3]
tr.stats.starttime = item[4]
tr.stats.delta = 1.0
tr.data = np.empty(int(item[5] - item[4]) + 1)
st.traces.append(tr)
st.write(filename, format="mseed")
client.get_waveforms_bulk.side_effect = get_waveforms_bulk_mock
tmpdir = tempfile.mkdtemp()
try:
chunks = [
["BW", "ALTM", "", "EHE", obspy.UTCDateTime(0),
obspy.UTCDateTime(1E5), os.path.join(tmpdir, "file_1.mseed")],
["BW", "ALTM", "", "EHE", obspy.UTCDateTime(1E5),
obspy.UTCDateTime(2E5), os.path.join(tmpdir, "file_2.mseed")],
["BW", "ALTM", "", "EHE", obspy.UTCDateTime(2E5),
obspy.UTCDateTime(3E5), os.path.join(tmpdir, "file_3.mseed")],
["BW", "ALTM", "", "EHE", obspy.UTCDateTime(3E5),
obspy.UTCDateTime(4E5), os.path.join(tmpdir, "file_4.mseed")],
["BW", "ALTM", "", "EHE", obspy.UTCDateTime(4E5),
obspy.UTCDateTime(5E5), os.path.join(tmpdir, "file_5.mseed")],
["BW", "ALTM", "", "EHE", obspy.UTCDateTime(6E5),
obspy.UTCDateTime(7E5), os.path.join(tmpdir, "file_6.mseed")]
]
ret_val = download_and_split_mseed_bulk(
client=client, client_name=client_name, chunks=chunks,
logger=logger)
# Now five files but all the same channel.
contents = [("file_1.mseed", "BW.ALTM..EHE"),
("file_2.mseed", "BW.ALTM..EHE"),
("file_3.mseed", "BW.ALTM..EHE"),
("file_4.mseed", "BW.ALTM..EHE"),
("file_5.mseed", "BW.ALTM..EHE"),
("file_6.mseed", "BW.ALTM..EHE")]
self.assertEqual(ret_val,
sorted([os.path.join(tmpdir, _i[0])
for _i in contents]))
# Make sure all files have been written.
self.assertEqual(sorted(os.listdir(tmpdir)),
[_i[0] for _i in contents])
# The interesting thing here is that it should only send a
# request for single time span and then split again on the
# client side. Here is two time spans as one segment is further
# away.
call_args = client.get_waveforms_bulk.call_args[0][0]
self.assertEqual(
call_args, [
['BW', 'ALTM', '', 'EHE', obspy.UTCDateTime(0),
obspy.UTCDateTime(5E5)],
['BW', 'ALTM', '', 'EHE', obspy.UTCDateTime(6E5),
obspy.UTCDateTime(7E5)]])
finally:
shutil.rmtree(tmpdir)
# Last one attempting to get overlapping filenames.
client.reset_mock()
logger.reset_mock()
def get_waveforms_bulk_mock(bulk, filename):
"""
Actually create the requested MiniSEED file.
"""
st = obspy.Stream()
for item in bulk:
tr = obspy.Trace()
tr.stats.network = item[0]
tr.stats.station = item[1]
tr.stats.location = item[2]
tr.stats.channel = item[3]
tr.stats.starttime = item[4]
tr.stats.delta = 1.0
tr.data = np.empty(int(item[5] - item[4]) + 1)
st.traces.append(tr)
st.write(filename, format="mseed")
client.get_waveforms_bulk.side_effect = get_waveforms_bulk_mock
tmpdir = tempfile.mkdtemp()
try:
chunks = [
["BW", "ALTM", "", "EHE", obspy.UTCDateTime(0),
obspy.UTCDateTime(1E5), os.path.join(tmpdir, "file_1.mseed")],
["BW", "ALTM", "", "EHE", obspy.UTCDateTime(0.4E5),
obspy.UTCDateTime(1.6E5),
os.path.join(tmpdir, "file_2.mseed")],
["BW", "ALTM", "", "EHE", obspy.UTCDateTime(1.2E5),
obspy.UTCDateTime(2.2E5),
os.path.join(tmpdir, "file_3.mseed")]]
ret_val = download_and_split_mseed_bulk(
client=client, client_name=client_name, chunks=chunks,
logger=logger)
contents = [("file_1.mseed", "BW.ALTM..EHE"),
("file_2.mseed", "BW.ALTM..EHE"),
("file_3.mseed", "BW.ALTM..EHE")]
self.assertEqual(ret_val,
sorted([os.path.join(tmpdir, _i[0])
for _i in contents]))
# Make sure all files have been written.
self.assertEqual(sorted(os.listdir(tmpdir)),
["file_1.mseed", "file_2.mseed", "file_3.mseed"])
# Check the actual files. There will be no overlap of data in
# the files but the data should be distributed across
# files according to some heuristics.
st = obspy.read(os.path.join(tmpdir, "file_1.mseed"))
self.assertEqual(len(st), 1)
tr = st[0]
self.assertEqual(tr.id, "BW.ALTM..EHE")
self.assertEqual(tr.stats.starttime, obspy.UTCDateTime(0))
# Record length of 512.
self.assertTrue(
abs(tr.stats.endtime - obspy.UTCDateTime(1E5)) < 512)
st = obspy.read(os.path.join(tmpdir, "file_2.mseed"))
self.assertEqual(len(st), 1)
tr = st[0]
self.assertEqual(tr.id, "BW.ALTM..EHE")
# Record length of 512.
self.assertTrue(
abs(tr.stats.starttime - obspy.UTCDateTime(1E5)) < 512)
self.assertTrue(
abs(tr.stats.endtime - obspy.UTCDateTime(1.6E5)) < 512)
st = obspy.read(os.path.join(tmpdir, "file_3.mseed"))
self.assertEqual(len(st), 1)
tr = st[0]
self.assertEqual(tr.id, "BW.ALTM..EHE")
# Record length of 512.
self.assertTrue(
abs(tr.stats.starttime - obspy.UTCDateTime(1.6E5)) < 512)
# End time is exact again as no more overlaps occur.
self.assertEqual(tr.stats.endtime, obspy.UTCDateTime(2.2E5))
finally:
shutil.rmtree(tmpdir)
def test_stationxml_filename_helper(self):
"""
Tests the get_stationxml_filename() function.
"""
c1 = ("", "BHE")
c2 = ("10", "SHE")
starttime = obspy.UTCDateTime(2012, 1, 1)
endtime = obspy.UTCDateTime(2012, 1, 2)
channels = [c1, c2]
# A normal string is considered a path.
self.assertEqual(get_stationxml_filename(
"FOLDER", network="BW", station="FURT", channels=channels,
starttime=starttime, endtime=endtime),
os.path.join("FOLDER", "BW.FURT.xml"))
self.assertEqual(get_stationxml_filename(
"stations", network="BW", station="FURT", channels=channels,
starttime=starttime, endtime=endtime),
os.path.join("stations", "BW.FURT.xml"))
# Passing a format string causes it to be used.
self.assertEqual(get_stationxml_filename(
"{network}_{station}.xml", network="BW", station="FURT",
channels=channels, starttime=starttime, endtime=endtime),
"BW_FURT.xml")
self.assertEqual(get_stationxml_filename(
"TEMP/{network}/{station}.xml", network="BW", station="FURT",
channels=channels, starttime=starttime, endtime=endtime),
"TEMP/BW/FURT.xml")
# A passed function will be executed. A string should just be returned.
def get_name(network, station, channels, starttime, endtime):
return "network" + "__" + station
self.assertEqual(get_stationxml_filename(
get_name, network="BW", station="FURT", channels=channels,
starttime=starttime, endtime=endtime), "network__FURT")
# A dictionary with certain keys is also acceptable.
def get_name(network, station, channels, starttime, endtime):
return {"missing_channels": [c1],
"available_channels": [c2],
"filename": "test.xml"}
self.assertEqual(get_stationxml_filename(
get_name, network="BW", station="FURT", channels=channels,
starttime=starttime, endtime=endtime),
{"missing_channels": [c1], "available_channels": [c2],
"filename": "test.xml"})
# Missing keys raise.
def get_name(network, station, channels, starttime, endtime):
return {"missing_channels": [c1],
"available_channels": [c2]}
self.assertRaises(ValueError, get_stationxml_filename, get_name,
"BW", "FURT", channels, starttime, endtime)
# Wrong value types should also raise.
def get_name(network, station, channels, starttime, endtime):
return {"missing_channels": [c1],
"available_channels": [c2],
"filename": True}
self.assertRaises(ValueError, get_stationxml_filename, get_name,
"BW", "FURT", channels, starttime, endtime)
def get_name(network, station, channels, starttime, endtime):
return {"missing_channels": True,
"available_channels": [c2],
"filename": "test.xml"}
self.assertRaises(ValueError, get_stationxml_filename, get_name,
"BW", "FURT", channels, starttime, endtime)
def get_name(network, station, channels, starttime, endtime):
return {"missing_channels": [c1],
"available_channels": True,
"filename": "test.xml"}
self.assertRaises(ValueError, get_stationxml_filename, get_name,
"BW", "FURT", channels, starttime, endtime)
# It will raise a type error, if the function does not return the
# proper type.
self.assertRaises(TypeError, get_stationxml_filename, lambda x: 1,
"BW", "FURT", starttime, endtime)
def test_mseed_filename_helper(self):
"""
Tests the get_mseed_filename() function.
"""
starttime = obspy.UTCDateTime(2014, 1, 2, 3, 4, 5)
endtime = obspy.UTCDateTime(2014, 2, 3, 4, 5, 6)
# A normal string is considered a path.
self.assertEqual(
get_mseed_filename("FOLDER", network="BW", station="FURT",
location="", channel="BHE",
starttime=starttime, endtime=endtime),
os.path.join(
"FOLDER", "BW.FURT..BHE__20140102T030405Z__"
"20140203T040506Z.mseed"))
self.assertEqual(
get_mseed_filename("waveforms", network="BW", station="FURT",
location="00", channel="BHE",
starttime=starttime, endtime=endtime),
os.path.join("waveforms", "BW.FURT.00.BHE__20140102T030405Z__"
"20140203T040506Z.mseed"))
# Passing a format string causes it to be used.
self.assertEqual(get_mseed_filename(
"{network}_{station}_{location}_{channel}_"
"{starttime}_{endtime}.ms", network="BW", station="FURT",
location="", channel="BHE", starttime=starttime, endtime=endtime),
"BW_FURT__BHE_20140102T030405Z_20140203T040506Z.ms")
self.assertEqual(get_mseed_filename(
"{network}_{station}_{location}_{channel}_"
"{starttime}_{endtime}.ms", network="BW", station="FURT",
location="00", channel="BHE", starttime=starttime,
endtime=endtime),
"BW_FURT_00_BHE_20140102T030405Z_20140203T040506Z.ms")
# A passed function will be executed.
def get_name(network, station, location, channel, starttime, endtime):
if network == "AH":
return True
return "network" + "__" + station + location + channel
# Returning a filename is possible.
self.assertEqual(
get_mseed_filename(get_name, network="BW", station="FURT",
location="", channel="BHE",
starttime=starttime, endtime=endtime),
"network__FURTBHE")
# 'True' can also be returned. This indicates that the file already
# exists.
self.assertEqual(
get_mseed_filename(get_name, network="AH", station="FURT",
location="", channel="BHE",
starttime=starttime, endtime=endtime), True)
# It will raise a type error, if the function does not return the
# proper type.
self.assertRaises(TypeError, get_mseed_filename, lambda x: 1,
"BW", "FURT", "", "BHE")
def test_get_stationxml_contents(self):
"""
Tests the fast get_stationxml_contents() function.
"""
ChannelAvailability = collections.namedtuple(
"ChannelAvailability",
["network", "station", "location", "channel", "starttime",
"endtime", "filename"])
filename = os.path.join(self.data, "AU.MEEK.xml")