-
Notifications
You must be signed in to change notification settings - Fork 530
/
trace.py
3060 lines (2639 loc) · 121 KB
/
trace.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 -*-
"""
Module for handling ObsPy :class:`~obspy.core.trace.Trace` and
:class:`~obspy.core.trace.Stats` objects.
:copyright:
The ObsPy Development Team (devs@obspy.org)
:license:
GNU Lesser General Public License, Version 3
(https://www.gnu.org/copyleft/lesser.html)
"""
import inspect
import math
import warnings
from copy import copy, deepcopy
import numpy as np
from decorator import decorator
from obspy.core import compatibility
from obspy.core.utcdatetime import UTCDateTime
from obspy.core.util import AttribDict, create_empty_data_chunk, NUMPY_VERSION
from obspy.core.util.base import _get_function_from_entry_point
from obspy.core.util.decorator import raise_if_masked, skip_if_no_data
from obspy.core.util.misc import (flat_not_masked_contiguous, get_window_times,
limit_numpy_fft_cache)
class Stats(AttribDict):
"""
A container for additional header information of a ObsPy
:class:`~obspy.core.trace.Trace` object.
A ``Stats`` object may contain all header information (also known as meta
data) of a :class:`~obspy.core.trace.Trace` object. Those headers may be
accessed or modified either in the dictionary style or directly via a
corresponding attribute. There are various default attributes which are
required by every waveform import and export modules within ObsPy such as
:mod:`obspy.io.mseed`.
:type header: dict or :class:`~obspy.core.trace.Stats`, optional
:param header: Dictionary containing meta information of a single
:class:`~obspy.core.trace.Trace` object. Possible keywords are
summarized in the following `Default Attributes`_ section.
.. rubric:: Basic Usage
>>> stats = Stats()
>>> stats.network = 'BW'
>>> print(stats['network'])
BW
>>> stats['station'] = 'MANZ'
>>> print(stats.station)
MANZ
.. rubric:: _`Default Attributes`
``sampling_rate`` : float, optional
Sampling rate in hertz (default value is 1.0).
``delta`` : float, optional
Sample distance in seconds (default value is 1.0).
``calib`` : float, optional
Calibration factor (default value is 1.0).
``npts`` : int, optional
Number of sample points (default value is 0, which implies that no data
is present).
``network`` : string, optional
Network code (default is an empty string).
``location`` : string, optional
Location code (default is an empty string).
``station`` : string, optional
Station code (default is an empty string).
``channel`` : string, optional
Channel code (default is an empty string).
``starttime`` : :class:`~obspy.core.utcdatetime.UTCDateTime`, optional
Date and time of the first data sample given in UTC (default value is
"1970-01-01T00:00:00.0Z").
``endtime`` : :class:`~obspy.core.utcdatetime.UTCDateTime`, optional
Date and time of the last data sample given in UTC
(default value is "1970-01-01T00:00:00.0Z").
.. rubric:: Notes
(1) The attributes ``sampling_rate`` and ``delta`` are linked to each
other. If one of the attributes is modified the other will be
recalculated.
>>> stats = Stats()
>>> stats.sampling_rate
1.0
>>> stats.delta = 0.005
>>> stats.sampling_rate
200.0
(2) The attributes ``starttime``, ``npts``, ``sampling_rate`` and ``delta``
are monitored and used to automatically calculate the ``endtime``.
>>> stats = Stats()
>>> stats.npts = 60
>>> stats.delta = 1.0
>>> stats.starttime = UTCDateTime(2009, 1, 1, 12, 0, 0)
>>> stats.endtime
UTCDateTime(2009, 1, 1, 12, 0, 59)
>>> stats.delta = 0.5
>>> stats.endtime
UTCDateTime(2009, 1, 1, 12, 0, 29, 500000)
(3) The attribute ``endtime`` is read only and can not be modified.
>>> stats = Stats()
>>> stats.endtime = UTCDateTime(2009, 1, 1, 12, 0, 0)
Traceback (most recent call last):
...
AttributeError: Attribute "endtime" in Stats object is read only!
>>> stats['endtime'] = UTCDateTime(2009, 1, 1, 12, 0, 0)
Traceback (most recent call last):
...
AttributeError: Attribute "endtime" in Stats object is read only!
(4)
The attribute ``npts`` will be automatically updated from the
:class:`~obspy.core.trace.Trace` object.
>>> trace = Trace()
>>> trace.stats.npts
0
>>> trace.data = np.array([1, 2, 3, 4])
>>> trace.stats.npts
4
(5)
The attribute ``component`` can be used to get or set the component,
i.e. the last character of the ``channel`` attribute.
>>> stats = Stats()
>>> stats.channel = 'HHZ'
>>> stats.component # doctest: +SKIP
'Z'
>>> stats.component = 'L'
>>> stats.channel # doctest: +SKIP
'HHL'
"""
# set of read only attrs
readonly = ['endtime']
# default values
defaults = {
'sampling_rate': 1.0,
'delta': 1.0,
'starttime': UTCDateTime(0),
'endtime': UTCDateTime(0),
'npts': 0,
'calib': 1.0,
'network': '',
'station': '',
'location': '',
'channel': '',
}
# keys which need to refresh derived values
_refresh_keys = {'delta', 'sampling_rate', 'starttime', 'npts'}
# dict of required types for certain attrs
_types = {
'network': str,
'station': str,
'location': str,
'channel': str,
}
def __init__(self, header={}):
"""
"""
super(Stats, self).__init__(header)
def __setitem__(self, key, value):
"""
"""
if key in self._refresh_keys:
# ensure correct data type
if key == 'delta':
key = 'sampling_rate'
try:
value = 1.0 / float(value)
except ZeroDivisionError:
value = 0.0
elif key == 'sampling_rate':
value = float(value)
elif key == 'starttime':
value = UTCDateTime(value)
elif key == 'npts':
if not isinstance(value, int):
value = int(value)
# set current key
super(Stats, self).__setitem__(key, value)
# set derived value: delta
try:
delta = 1.0 / float(self.sampling_rate)
except ZeroDivisionError:
delta = 0
self.__dict__['delta'] = delta
# set derived value: endtime
if self.npts == 0:
timediff = 0
else:
timediff = float(self.npts - 1) * delta
self.__dict__['endtime'] = self.starttime + timediff
return
if key == 'component':
key = 'channel'
value = str(value)
if len(value) != 1:
msg = 'Component must be set with single character'
raise ValueError(msg)
value = self.channel[:-1] + value
# prevent a calibration factor of 0
if key == 'calib' and value == 0:
msg = 'Calibration factor set to 0.0!'
warnings.warn(msg, UserWarning)
# all other keys
if isinstance(value, dict):
super(Stats, self).__setitem__(key, AttribDict(value))
else:
super(Stats, self).__setitem__(key, value)
__setattr__ = __setitem__
def __getitem__(self, key, default=None):
"""
"""
if key == 'component':
return super(Stats, self).__getitem__('channel', default)[-1:]
else:
return super(Stats, self).__getitem__(key, default)
def __str__(self):
"""
Return better readable string representation of Stats object.
"""
priorized_keys = ['network', 'station', 'location', 'channel',
'starttime', 'endtime', 'sampling_rate', 'delta',
'npts', 'calib']
return self._pretty_str(priorized_keys)
def _repr_pretty_(self, p, cycle):
p.text(str(self))
def __getstate__(self):
state = self.__dict__.copy()
# Remove the unneeded entries
state.pop('delta', None)
state.pop('endtime', None)
return state
def __setstate__(self, state):
self.__dict__.update(state)
# trigger refreshing
self.__setitem__('sampling_rate', state['sampling_rate'])
@decorator
def _add_processing_info(func, *args, **kwargs):
"""
This is a decorator that attaches information about a processing call as a
string to the Trace.stats.processing list.
"""
callargs = inspect.getcallargs(func, *args, **kwargs)
callargs.pop("self")
kwargs_ = callargs.pop("kwargs", {})
from obspy import __version__
info = "ObsPy {version}: {function}(%s)".format(
version=__version__,
function=func.__name__)
arguments = []
arguments += \
["%s=%s" % (k, repr(v)) if not isinstance(v, str) else
"%s='%s'" % (k, v) for k, v in callargs.items()]
arguments += \
["%s=%s" % (k, repr(v)) if not isinstance(v, str) else
"%s='%s'" % (k, v) for k, v in kwargs_.items()]
arguments.sort()
info = info % "::".join(arguments)
self = args[0]
result = func(*args, **kwargs)
# Attach after executing the function to avoid having it attached
# while the operation failed.
self._internal_add_processing_info(info)
return result
class Trace(object):
"""
An object containing data of a continuous series, such as a seismic trace.
:type data: :class:`~numpy.ndarray` or :class:`~numpy.ma.MaskedArray`
:param data: Array of data samples
:type header: dict or :class:`~obspy.core.trace.Stats`
:param header: Dictionary containing header fields
:var id: A SEED compatible identifier of the trace.
:var stats: A container :class:`~obspy.core.trace.Stats` for additional
header information of the trace.
:var data: Data samples in a :class:`~numpy.ndarray` or
:class:`~numpy.ma.MaskedArray`
.. note::
The ``.data`` attribute containing the time series samples as a
:class:`numpy.ndarray` will always be made contiguous in memory. This
way it is always safe to use ``.data`` in routines that internally pass
the array to C code. On the other hand this might result in some
unwanted copying of data in memory. Experts can opt-out by setting
``Trace._always_contiguous = False``, in this case the user has to make
sure themselves that no C operations are performed on potentially
incontiguous data.
.. rubric:: Supported Operations
``trace = traceA + traceB``
Merges traceA and traceB into one new trace object.
See also: :meth:`Trace.__add__`.
``len(trace)``
Returns the number of samples contained in the trace. That is
it es equal to ``len(trace.data)``.
See also: :meth:`Trace.__len__`.
``str(trace)``
Returns basic information about the trace object.
See also: :meth:`Trace.__str__`.
"""
_always_contiguous = True
_max_processing_info = 100
def __init__(self, data=np.array([]), header=None):
# make sure Trace gets initialized with suitable ndarray as self.data
# otherwise we could end up with e.g. a list object in self.data
_data_sanity_checks(data)
# set some defaults if not set yet
if header is None:
header = {}
header = deepcopy(header)
header.setdefault('npts', len(data))
self.stats = Stats(header)
# set data without changing npts in stats object (for headonly option)
super(Trace, self).__setattr__('data', data)
@property
def meta(self):
return self.stats
@meta.setter
def meta(self, value):
self.stats = value
def __eq__(self, other):
"""
Implements rich comparison of Trace objects for "==" operator.
Traces are the same, if both their data and stats are the same.
"""
# check if other object is a Trace
if not isinstance(other, Trace):
return False
# comparison of Stats objects is supported by underlying AttribDict
if not self.stats == other.stats:
return False
# comparison of ndarrays is supported by NumPy
if not np.array_equal(self.data, other.data):
return False
return True
def __ne__(self, other):
"""
Implements rich comparison of Trace objects for "!=" operator.
Calls __eq__() and returns the opposite.
"""
return not self.__eq__(other)
def __lt__(self, other):
"""
Too ambiguous, throw an Error.
"""
raise NotImplementedError("Too ambiguous, therefore not implemented.")
def __le__(self, other):
"""
Too ambiguous, throw an Error.
"""
raise NotImplementedError("Too ambiguous, therefore not implemented.")
def __gt__(self, other):
"""
Too ambiguous, throw an Error.
"""
raise NotImplementedError("Too ambiguous, therefore not implemented.")
def __ge__(self, other):
"""
Too ambiguous, throw an Error.
"""
raise NotImplementedError("Too ambiguous, therefore not implemented.")
def __nonzero__(self):
"""
No data means no trace.
"""
return bool(len(self.data))
def __str__(self, id_length=None):
"""
Return short summary string of the current trace.
:rtype: str
:return: Short summary string of the current trace containing the SEED
identifier, start time, end time, sampling rate and number of
points of the current trace.
.. rubric:: Example
>>> tr = Trace(header={'station':'FUR', 'network':'GR'})
>>> str(tr) # doctest: +ELLIPSIS
'GR.FUR.. | 1970-01-01T00:00:00.000000Z - ... | 1.0 Hz, 0 samples'
"""
# set fixed id width
if id_length:
out = "%%-%ds" % (id_length)
trace_id = out % self.id
else:
trace_id = "%s" % self.id
out = ''
# output depending on delta or sampling rate bigger than one
if self.stats.sampling_rate < 0.1:
if hasattr(self.stats, 'preview') and self.stats.preview:
out = out + ' | '\
"%(starttime)s - %(endtime)s | " + \
"%(delta).1f s, %(npts)d samples [preview]"
else:
out = out + ' | '\
"%(starttime)s - %(endtime)s | " + \
"%(delta).1f s, %(npts)d samples"
else:
if hasattr(self.stats, 'preview') and self.stats.preview:
out = out + ' | '\
"%(starttime)s - %(endtime)s | " + \
"%(sampling_rate).1f Hz, %(npts)d samples [preview]"
else:
out = out + ' | '\
"%(starttime)s - %(endtime)s | " + \
"%(sampling_rate).1f Hz, %(npts)d samples"
# check for masked array
if np.ma.count_masked(self.data):
out += ' (masked)'
return trace_id + out % (self.stats)
def _repr_pretty_(self, p, cycle):
p.text(str(self))
def __len__(self):
"""
Return number of data samples of the current trace.
:rtype: int
:return: Number of data samples.
.. rubric:: Example
>>> trace = Trace(data=np.array([1, 2, 3, 4]))
>>> trace.count()
4
>>> len(trace)
4
"""
return len(self.data)
count = __len__
def __setattr__(self, key, value):
"""
__setattr__ method of Trace object.
"""
# any change in Trace.data will dynamically set Trace.stats.npts
if key == 'data':
_data_sanity_checks(value)
if self._always_contiguous:
value = np.require(value, requirements=['C_CONTIGUOUS'])
self.stats.npts = len(value)
return super(Trace, self).__setattr__(key, value)
def __getitem__(self, index):
"""
__getitem__ method of Trace object.
:rtype: list
:return: List of data points
"""
return self.data[index]
def __mul__(self, num):
"""
Create a new Stream containing num copies of this trace.
:type num: int
:param num: Number of copies.
:returns: New ObsPy Stream object.
.. rubric:: Example
>>> from obspy import read
>>> tr = read()[0]
>>> st = tr * 5
>>> len(st)
5
"""
if not isinstance(num, int):
raise TypeError("Integer expected")
from obspy import Stream
st = Stream()
for _i in range(num):
st += self.copy()
return st
def __truediv__(self, num):
"""
Split Trace into new Stream containing num Traces of the same size.
:type num: int
:param num: Number of traces in returned Stream. Last trace may contain
lesser samples.
:returns: New ObsPy Stream object.
.. rubric:: Example
>>> from obspy import read
>>> tr = read()[0]
>>> print(tr) # doctest: +ELLIPSIS
BW.RJOB..EHZ | 2009-08-24T00:20:03.000000Z ... | 100.0 Hz, 3000 samples
>>> st = tr / 7
>>> print(st) # doctest: +ELLIPSIS
7 Trace(s) in Stream:
BW.RJOB..EHZ | 2009-08-24T00:20:03.000000Z ... | 100.0 Hz, 429 samples
BW.RJOB..EHZ | 2009-08-24T00:20:07.290000Z ... | 100.0 Hz, 429 samples
BW.RJOB..EHZ | 2009-08-24T00:20:11.580000Z ... | 100.0 Hz, 429 samples
BW.RJOB..EHZ | 2009-08-24T00:20:15.870000Z ... | 100.0 Hz, 429 samples
BW.RJOB..EHZ | 2009-08-24T00:20:20.160000Z ... | 100.0 Hz, 429 samples
BW.RJOB..EHZ | 2009-08-24T00:20:24.450000Z ... | 100.0 Hz, 429 samples
BW.RJOB..EHZ | 2009-08-24T00:20:28.740000Z ... | 100.0 Hz, 426 samples
"""
if not isinstance(num, int):
raise TypeError("Integer expected")
from obspy import Stream
total_length = np.size(self.data)
rest_length = total_length % num
if rest_length:
packet_length = (total_length // num)
else:
packet_length = (total_length // num) - 1
tstart = self.stats.starttime
tend = tstart + (self.stats.delta * packet_length)
st = Stream()
for _i in range(num):
st.append(self.slice(tstart, tend).copy())
tstart = tend + self.stats.delta
tend = tstart + (self.stats.delta * packet_length)
return st
def __mod__(self, num):
"""
Split Trace into new Stream containing Traces with num samples.
:type num: int
:param num: Number of samples in each trace in returned Stream. Last
trace may contain lesser samples.
:returns: New ObsPy Stream object.
.. rubric:: Example
>>> from obspy import read
>>> tr = read()[0]
>>> print(tr) # doctest: +ELLIPSIS
BW.RJOB..EHZ | 2009-08-24T00:20:03.000000Z ... | 100.0 Hz, 3000 samples
>>> st = tr % 800
>>> print(st) # doctest: +ELLIPSIS
4 Trace(s) in Stream:
BW.RJOB..EHZ | 2009-08-24T00:20:03.000000Z ... | 100.0 Hz, 800 samples
BW.RJOB..EHZ | 2009-08-24T00:20:11.000000Z ... | 100.0 Hz, 800 samples
BW.RJOB..EHZ | 2009-08-24T00:20:19.000000Z ... | 100.0 Hz, 800 samples
BW.RJOB..EHZ | 2009-08-24T00:20:27.000000Z ... | 100.0 Hz, 600 samples
"""
if not isinstance(num, int):
raise TypeError("Integer expected")
elif num <= 0:
raise ValueError("Positive Integer expected")
from obspy import Stream
st = Stream()
total_length = np.size(self.data)
if num >= total_length:
st.append(self.copy())
return st
tstart = self.stats.starttime
tend = tstart + (self.stats.delta * (num - 1))
while True:
st.append(self.slice(tstart, tend).copy())
tstart = tend + self.stats.delta
tend = tstart + (self.stats.delta * (num - 1))
if tstart > self.stats.endtime:
break
return st
def __add__(self, trace, method=0, interpolation_samples=0,
fill_value=None, sanity_checks=True):
"""
Add another Trace object to current trace.
:type method: int, optional
:param method: Method to handle overlaps of traces. Defaults to ``0``.
See the `Handling Overlaps`_ section below for further details.
:type fill_value: int, float, str or ``None``, optional
:param fill_value: Fill value for gaps. Defaults to ``None``. Traces
will be converted to NumPy masked arrays if no value is given and
gaps are present. If the keyword ``'latest'`` is provided it will
use the latest value before the gap. If keyword ``'interpolate'``
is provided, missing values are linearly interpolated (not
changing the data type e.g. of integer valued traces).
See the `Handling Gaps`_ section below for further details.
:type interpolation_samples: int, optional
:param interpolation_samples: Used only for ``method=1``. It specifies
the number of samples which are used to interpolate between
overlapping traces. Defaults to ``0``. If set to ``-1`` all
overlapping samples are interpolated.
:type sanity_checks: bool, optional
:param sanity_checks: Enables some sanity checks before merging traces.
Defaults to ``True``.
Trace data will be converted into a NumPy masked array data type if
any gaps are present. This behavior may be prevented by setting the
``fill_value`` parameter. The ``method`` argument controls the
handling of overlapping data values.
Sampling rate, data type and trace.id of both traces must match.
.. rubric:: _`Handling Overlaps`
====== ===============================================================
Method Description
====== ===============================================================
0 Discard overlapping data. Overlaps are essentially treated the
same way as gaps::
Trace 1: AAAAAAAA
Trace 2: FFFFFFFF
1 + 2 : AAAA----FFFF
Contained traces with differing data will be marked as gap::
Trace 1: AAAAAAAAAAAA
Trace 2: FF
1 + 2 : AAAA--AAAAAA
Missing data can be merged in from a different trace::
Trace 1: AAAA--AAAAAA (contained trace, missing samples)
Trace 2: FF
1 + 2 : AAAAFFAAAAAA
1 Discard data of the previous trace assuming the following trace
contains data with a more correct time value. The parameter
``interpolation_samples`` specifies the number of samples used
to linearly interpolate between the two traces in order to
prevent steps. Note that if there are gaps inside, the
returned array is still a masked array, only if ``fill_value``
is set, the returned array is a normal array and gaps are
filled with fill value.
No interpolation (``interpolation_samples=0``)::
Trace 1: AAAAAAAA
Trace 2: FFFFFFFF
1 + 2 : AAAAFFFFFFFF
Interpolate first two samples (``interpolation_samples=2``)::
Trace 1: AAAAAAAA
Trace 2: FFFFFFFF
1 + 2 : AAAACDFFFFFF (interpolation_samples=2)
Interpolate all samples (``interpolation_samples=-1``)::
Trace 1: AAAAAAAA
Trace 2: FFFFFFFF
1 + 2 : AAAABCDEFFFF
Any contained traces with different data will be discarded::
Trace 1: AAAAAAAAAAAA (contained trace)
Trace 2: FF
1 + 2 : AAAAAAAAAAAA
Missing data can be merged in from a different trace::
Trace 1: AAAA--AAAAAA (contained trace, missing samples)
Trace 2: FF
1 + 2 : AAAAFFAAAAAA
====== ===============================================================
.. rubric:: _`Handling gaps`
1. Traces with gaps and ``fill_value=None`` (default)::
Trace 1: AAAA
Trace 2: FFFF
1 + 2 : AAAA----FFFF
2. Traces with gaps and given ``fill_value=0``::
Trace 1: AAAA
Trace 2: FFFF
1 + 2 : AAAA0000FFFF
3. Traces with gaps and given ``fill_value='latest'``::
Trace 1: ABCD
Trace 2: FFFF
1 + 2 : ABCDDDDDFFFF
4. Traces with gaps and given ``fill_value='interpolate'``::
Trace 1: AAAA
Trace 2: FFFF
1 + 2 : AAAABCDEFFFF
"""
if sanity_checks:
if not isinstance(trace, Trace):
raise TypeError
# check id
if self.get_id() != trace.get_id():
raise TypeError("Trace ID differs: %s vs %s" %
(self.get_id(), trace.get_id()))
# check sample rate
if self.stats.sampling_rate != trace.stats.sampling_rate:
raise TypeError("Sampling rate differs: %s vs %s" %
(self.stats.sampling_rate,
trace.stats.sampling_rate))
# check calibration factor
if self.stats.calib != trace.stats.calib:
raise TypeError("Calibration factor differs: %s vs %s" %
(self.stats.calib, trace.stats.calib))
# check data type
if self.data.dtype != trace.data.dtype:
raise TypeError("Data type differs: %s vs %s" %
(self.data.dtype, trace.data.dtype))
# check times
if self.stats.starttime <= trace.stats.starttime:
lt = self
rt = trace
else:
rt = self
lt = trace
# check whether to use the latest value to fill a gap
if fill_value == "latest":
fill_value = lt.data[-1]
elif fill_value == "interpolate":
fill_value = (lt.data[-1], rt.data[0])
sr = self.stats.sampling_rate
delta = (rt.stats.starttime - lt.stats.endtime) * sr
delta = int(compatibility.round_away(delta)) - 1
delta_endtime = lt.stats.endtime - rt.stats.endtime
# create the returned trace
out = self.__class__(header=deepcopy(lt.stats))
# check if overlap or gap
if delta < 0 and delta_endtime < 0:
# overlap
delta = abs(delta)
if np.all(np.equal(lt.data[-delta:], rt.data[:delta])):
# check if data are the same
data = [lt.data[:-delta], rt.data]
elif method == 0:
overlap = create_empty_data_chunk(delta, lt.data.dtype,
fill_value)
data = [lt.data[:-delta], overlap, rt.data[delta:]]
elif method == 1 and interpolation_samples >= -1:
try:
ls = lt.data[-delta - 1]
except Exception:
ls = lt.data[0]
if interpolation_samples == -1:
interpolation_samples = delta
elif interpolation_samples > delta:
interpolation_samples = delta
try:
rs = rt.data[interpolation_samples]
except IndexError:
# contained trace
data = [lt.data]
else:
# include left and right sample (delta + 2)
interpolation = np.linspace(ls, rs,
interpolation_samples + 2)
# cut ls and rs and ensure correct data type
interpolation = np.require(interpolation[1:-1],
lt.data.dtype)
data = [lt.data[:-delta], interpolation,
rt.data[interpolation_samples:]]
else:
raise NotImplementedError
elif delta < 0 and delta_endtime >= 0:
# contained trace
delta = abs(delta)
lenrt = len(rt)
t1 = len(lt) - delta
t2 = t1 + lenrt
# check if data are the same
data_equal = (lt.data[t1:t2] == rt.data)
# force a masked array and fill it for check of equality of valid
# data points
if np.all(np.ma.masked_array(data_equal).filled()):
# if all (unmasked) data are equal,
if isinstance(data_equal, np.ma.masked_array):
x = np.ma.masked_array(lt.data[t1:t2])
y = np.ma.masked_array(rt.data)
data_same = np.choose(x.mask, [x, y])
data = np.choose(x.mask & y.mask, [data_same, np.nan])
if np.any(np.isnan(data)):
data = np.ma.masked_invalid(data)
# convert back to maximum dtype of original data
dtype = np.max((x.dtype, y.dtype))
data = data.astype(dtype)
data = [lt.data[:t1], data, lt.data[t2:]]
else:
data = [lt.data]
elif method == 0:
gap = create_empty_data_chunk(lenrt, lt.data.dtype, fill_value)
data = [lt.data[:t1], gap, lt.data[t2:]]
elif method == 1:
data = [lt.data]
else:
raise NotImplementedError
elif delta == 0:
# exact fit - merge both traces
data = [lt.data, rt.data]
else:
# gap
# use fixed value or interpolate in between
gap = create_empty_data_chunk(delta, lt.data.dtype, fill_value)
data = [lt.data, gap, rt.data]
# merge traces depending on NumPy array type
if True in [isinstance(_i, np.ma.masked_array) for _i in data]:
data = np.ma.concatenate(data)
else:
data = np.concatenate(data)
data = np.require(data, dtype=lt.data.dtype)
# Check if we can downgrade to normal ndarray
if isinstance(data, np.ma.masked_array) and \
np.ma.count_masked(data) == 0:
data = data.compressed()
out.data = data
return out
def get_id(self):
"""
Return a SEED compatible identifier of the trace.
:rtype: str
:return: SEED identifier
The SEED identifier contains the network, station, location and channel
code for the current Trace object.
.. rubric:: Example
>>> meta = {'station': 'MANZ', 'network': 'BW', 'channel': 'EHZ'}
>>> tr = Trace(header=meta)
>>> print(tr.get_id())
BW.MANZ..EHZ
>>> print(tr.id)
BW.MANZ..EHZ
"""
return '.'.join((self.stats.network, self.stats.station,
self.stats.location, self.stats.channel))
id = property(get_id)
@id.setter
def id(self, value):
"""
Set network, station, location and channel codes from a SEED ID.
Raises an Exception if the provided ID does not contain exactly three
dots (or is not of type `str`).
>>> from obspy import read
>>> tr = read()[0]
>>> print(tr) # doctest: +ELLIPSIS
BW.RJOB..EHZ | 2009-08-24T00:20:03.000000Z ... | 100.0 Hz, 3000 samples
>>> tr.id = "GR.FUR..HHZ"
>>> print(tr) # doctest: +ELLIPSIS
GR.FUR..HHZ | 2009-08-24T00:20:03.000000Z ... | 100.0 Hz, 3000 samples
:type value: str
:param value: SEED ID to use for setting `self.stats.network`,
`self.stats.station`, `self.stats.location` and
`self.stats.channel`.
"""
try:
net, sta, loc, cha = value.split(".")
except AttributeError:
msg = ("Can only set a Trace's SEED ID from a string "
"(and not from {})").format(type(value))
raise TypeError(msg)
except ValueError:
msg = ("Not a valid SEED ID: '{}'").format(value)
raise ValueError(msg)
self.stats.network = net
self.stats.station = sta
self.stats.location = loc
self.stats.channel = cha
def plot(self, **kwargs):
"""
Create a simple graph of the current trace.
Various options are available to change the appearance of the waveform
plot. Please see :meth:`~obspy.core.stream.Stream.plot` method for all
possible options.
.. rubric:: Example
>>> from obspy import read
>>> st = read()
>>> tr = st[0]
>>> tr.plot() # doctest: +SKIP
.. plot::
from obspy import read
st = read()
tr = st[0]
tr.plot()
"""
from obspy.imaging.waveform import WaveformPlotting
waveform = WaveformPlotting(stream=self, **kwargs)
return waveform.plot_waveform(**kwargs)
def spectrogram(self, **kwargs):
"""
Create a spectrogram plot of the trace.
For details on kwargs that can be used to customize the spectrogram
plot see :func:`~obspy.imaging.spectrogram.spectrogram`.
.. rubric:: Example
>>> from obspy import read
>>> st = read()
>>> tr = st[0]
>>> tr.spectrogram() # doctest: +SKIP
.. plot::
from obspy import read
st = read()
tr = st[0]
tr.spectrogram()
"""
# set some default values
if 'samp_rate' not in kwargs:
kwargs['samp_rate'] = self.stats.sampling_rate
if 'title' not in kwargs:
kwargs['title'] = str(self)
from obspy.imaging.spectrogram import spectrogram
return spectrogram(data=self.data, **kwargs)
def write(self, filename, format=None, **kwargs):
"""
Save current trace into a file.
:type filename: str
:param filename: The name of the file to write.
:type format: str, optional
:param format: The format of the file to write. See
:meth:`obspy.core.stream.Stream.write` method for possible
formats. If format is set to ``None`` it will be deduced
from file extension, whenever possible.
:param kwargs: Additional keyword arguments passed to the underlying
waveform writer method.
.. rubric:: Example
>>> tr = Trace()
>>> tr.write("out.mseed", format="MSEED") # doctest: +SKIP
The ``format`` argument can be omitted, and the file format will be
deduced from file extension, whenever possible.
>>> tr.write("out.mseed") # doctest: +SKIP
"""
# we need to import here in order to prevent a circular import of
# Stream and Trace classes
from obspy import Stream
Stream([self]).write(filename, format, **kwargs)
def _ltrim(self, starttime, pad=False, nearest_sample=True,
fill_value=None):