-
Notifications
You must be signed in to change notification settings - Fork 529
/
response.py
2382 lines (2136 loc) · 101 KB
/
response.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 -*-
"""
Classes related to instrument responses.
:copyright:
Lion Krischer (krischer@geophysik.uni-muenchen.de), 2013
:license:
GNU Lesser General Public License, Version 3
(https://www.gnu.org/copyleft/lesser.html)
"""
import copy
import ctypes as C # NOQA
import collections.abc
from collections import defaultdict
from copy import deepcopy
import itertools
from math import pi
import warnings
import numpy as np
from obspy.core.util.base import ComparingObject
from obspy.core.util.deprecation_helpers import ObsPyDeprecationWarning
from obspy.core.util.obspy_types import (ComplexWithUncertainties,
FloatWithUncertainties,
FloatWithUncertaintiesAndUnit,
ObsPyException,
ZeroSamplingRate)
from .util import Angle, Frequency
class ResponseStage(ComparingObject):
"""
From the StationXML Definition:
This complex type represents channel response and covers SEED
blockettes 53 to 56.
"""
def __init__(self, stage_sequence_number, stage_gain,
stage_gain_frequency, input_units, output_units,
resource_id=None, resource_id2=None, name=None,
input_units_description=None,
output_units_description=None, description=None,
decimation_input_sample_rate=None, decimation_factor=None,
decimation_offset=None, decimation_delay=None,
decimation_correction=None):
"""
:type stage_sequence_number: int
:param stage_sequence_number: Stage sequence number, greater or equal
to zero. This is used in all the response SEED blockettes.
:type stage_gain: float
:param stage_gain: Value of stage gain.
:type stage_gain_frequency: float
:param stage_gain_frequency: Frequency of stage gain.
:type input_units: str
:param input_units: The units of the data as input from the
perspective of data acquisition. After correcting data for this
response, these would be the resulting units.
Name of units, e.g. "M/S", "V", "PA".
:type output_units: str
:param output_units: The units of the data as output from the
perspective of data acquisition. These would be the units of the
data prior to correcting for this response.
Name of units, e.g. "M/S", "V", "PA".
:type resource_id: str
:param resource_id: This field contains a string that should serve as a
unique resource identifier. This identifier can be interpreted
differently depending on the data center/software that generated
the document. Also, we recommend to use something like
GENERATOR:Meaningful ID. As a common behavior equipment with the
same ID should contains the same information/be derived from the
same base instruments.
:type resource_id2: str
:param resource_id2: This field contains a string that should serve as
a unique resource identifier. Resource identifier of the subgroup
of the response stage that varies across different response stage
types (e.g. the poles and zeros part or the FIR part).
:type name: str
:param name: A name given to the filter stage.
:type input_units_description: str, optional
:param input_units_description: The units of the data as input from the
perspective of data acquisition. After correcting data for this
response, these would be the resulting units.
Description of units, e.g. "Velocity in meters per second",
"Volts", "Pascals".
:type output_units_description: str, optional
:param output_units_description: The units of the data as output from
the perspective of data acquisition. These would be the units of
the data prior to correcting for this response.
Description of units, e.g. "Velocity in meters per second",
"Volts", "Pascals".
:type description: str, optional
:param description: A short description of of the filter.
:type decimation_input_sample_rate: float, optional
:param decimation_input_sample_rate: The sampling rate before the
decimation in samples per second.
:type decimation_factor: int, optional
:param decimation_factor: The applied decimation factor.
:type decimation_offset: int, optional
:param decimation_offset: The sample chosen for use. 0 denotes the
first sample, 1 the second, and so forth.
:type decimation_delay: float, optional
:param decimation_delay: The estimated pure delay from the decimation.
:type decimation_correction: float, optional
:param decimation_correction: The time shift applied to correct for the
delay at this stage.
.. note::
The stage gain (or stage sensitivity) is the gain at the stage of
the encapsulating response element and corresponds to SEED
blockette 58. In the SEED convention, stage 0 gain represents the
overall sensitivity of the channel. In this schema, stage 0 gains
are allowed but are considered deprecated. Overall sensitivity
should be specified in the InstrumentSensitivity element.
"""
self.stage_sequence_number = stage_sequence_number
self.input_units = input_units
self.output_units = output_units
self.input_units_description = input_units_description
self.output_units_description = output_units_description
self.resource_id = resource_id
self.resource_id2 = resource_id2
self.stage_gain = stage_gain
self.stage_gain_frequency = stage_gain_frequency
self.name = name
self.description = description
self.decimation_input_sample_rate = \
Frequency(decimation_input_sample_rate) \
if decimation_input_sample_rate is not None else None
self.decimation_factor = decimation_factor
self.decimation_offset = decimation_offset
self.decimation_delay = \
FloatWithUncertaintiesAndUnit(decimation_delay) \
if decimation_delay is not None else None
self.decimation_correction = \
FloatWithUncertaintiesAndUnit(decimation_correction) \
if decimation_correction is not None else None
def __str__(self):
ret = (
"Response type: {response_type}, Stage Sequence Number: "
"{response_stage}\n"
"{name_desc}"
"{resource_id}"
"\tFrom {input_units}{input_desc} to {output_units}{output_desc}\n"
"\tStage gain: {gain}, defined at {gain_freq} Hz\n"
"{decimation}").format(
response_type=self.__class__.__name__,
response_stage=self.stage_sequence_number,
gain=self.stage_gain if self.stage_gain is not None else "UNKNOWN",
gain_freq=("%.2f" % self.stage_gain_frequency) if
self.stage_gain_frequency is not None else "UNKNOWN",
name_desc="\t%s %s\n" % (
self.name, "(%s)" % self.description
if self.description else "") if self.name else "",
resource_id=("\tResource Id: %s" % self.resource_id
if self.resource_id else ""),
input_units=self.input_units if self.input_units else "UNKNOWN",
input_desc=(" (%s)" % self.input_units_description
if self.input_units_description else ""),
output_units=self.output_units if self.output_units else "UNKNOWN",
output_desc=(" (%s)" % self.output_units_description
if self.output_units_description else ""),
decimation=(
"\tDecimation:\n\t\tInput Sample Rate: %.2f Hz\n\t\t"
"Decimation Factor: %i\n\t\tDecimation Offset: %i\n\t\t"
"Decimation Delay: %.2f\n\t\tDecimation Correction: %.2f" % (
self.decimation_input_sample_rate, self.decimation_factor,
self.decimation_offset, self.decimation_delay,
self.decimation_correction)
if self.decimation_input_sample_rate is not None else ""))
return ret.strip()
def _repr_pretty_(self, p, cycle):
p.text(str(self))
class PolesZerosResponseStage(ResponseStage):
"""
From the StationXML Definition:
Response: complex poles and zeros. Corresponds to SEED blockette 53.
The response stage is used for the analog stages of the filter system and
the description of infinite impulse response (IIR) digital filters.
Has all the arguments of the parent class
:class:`~obspy.core.inventory.response.ResponseStage` and the following:
:type pz_transfer_function_type: str
:param pz_transfer_function_type: A string describing the type of transfer
function. Can be one of:
* ``LAPLACE (RADIANS/SECOND)``
* ``LAPLACE (HERTZ)``
* ``DIGITAL (Z-TRANSFORM)``
The function tries to match inputs to one of three types if it can.
:type normalization_frequency: float
:param normalization_frequency: The frequency at which the normalization
factor is normalized.
:type zeros: list[complex]
:param zeros: All zeros of the stage.
:type poles: list[complex]
:param poles: All poles of the stage.
:type normalization_factor: float, optional
:param normalization_factor:
"""
def __init__(self, stage_sequence_number, stage_gain,
stage_gain_frequency, input_units, output_units,
pz_transfer_function_type,
normalization_frequency, zeros, poles,
normalization_factor=1.0, resource_id=None, resource_id2=None,
name=None, input_units_description=None,
output_units_description=None, description=None,
decimation_input_sample_rate=None, decimation_factor=None,
decimation_offset=None, decimation_delay=None,
decimation_correction=None):
# Set the Poles and Zeros specific attributes. Special cases are
# handled by properties.
self.pz_transfer_function_type = pz_transfer_function_type
self.normalization_frequency = normalization_frequency
self.normalization_factor = float(normalization_factor)
self.zeros = zeros
self.poles = poles
super(PolesZerosResponseStage, self).__init__(
stage_sequence_number=stage_sequence_number,
input_units=input_units,
output_units=output_units,
input_units_description=input_units_description,
output_units_description=output_units_description,
resource_id=resource_id, resource_id2=resource_id2,
stage_gain=stage_gain,
stage_gain_frequency=stage_gain_frequency, name=name,
description=description,
decimation_input_sample_rate=decimation_input_sample_rate,
decimation_factor=decimation_factor,
decimation_offset=decimation_offset,
decimation_delay=decimation_delay,
decimation_correction=decimation_correction)
def __str__(self):
ret = super(PolesZerosResponseStage, self).__str__()
ret += (
"\n"
"\tTransfer function type: {transfer_fct_type}\n"
"\tNormalization factor: {norm_fact:g}, "
"Normalization frequency: {norm_freq:.2f} Hz\n"
"\tPoles: {poles}\n"
"\tZeros: {zeros}").format(
transfer_fct_type=self.pz_transfer_function_type,
norm_fact=self.normalization_factor,
norm_freq=self.normalization_frequency,
poles=", ".join(map(str, self.poles)),
zeros=", ".join(map(str, self.zeros)))
return ret
def _repr_pretty_(self, p, cycle):
p.text(str(self))
@property
def zeros(self):
return self._zeros
@zeros.setter
def zeros(self, value):
value = list(value)
for i, x in enumerate(value):
if not isinstance(x, ComplexWithUncertainties):
value[i] = ComplexWithUncertainties(x)
self._zeros = value
@property
def poles(self):
return self._poles
@poles.setter
def poles(self, value):
value = list(value)
for i, x in enumerate(value):
if not isinstance(x, ComplexWithUncertainties):
value[i] = ComplexWithUncertainties(x)
self._poles = value
@property
def normalization_frequency(self):
return self._normalization_frequency
@normalization_frequency.setter
def normalization_frequency(self, value):
self._normalization_frequency = Frequency(value)
@property
def pz_transfer_function_type(self):
return self._pz_transfer_function_type
@pz_transfer_function_type.setter
def pz_transfer_function_type(self, value):
"""
Setter for the transfer function type.
Rather permissive but should make it less awkward to use.
"""
msg = ("'%s' is not a valid value for 'pz_transfer_function_type'. "
"Valid one are:\n"
"\tLAPLACE (RADIANS/SECOND)\n"
"\tLAPLACE (HERTZ)\n"
"\tDIGITAL (Z-TRANSFORM)") % value
value = value.lower()
if "laplace" in value:
if "radian" in value:
self._pz_transfer_function_type = "LAPLACE (RADIANS/SECOND)"
elif "hertz" in value or "hz" in value:
self._pz_transfer_function_type = "LAPLACE (HERTZ)"
else:
raise ValueError(msg)
elif "digital" in value:
self._pz_transfer_function_type = "DIGITAL (Z-TRANSFORM)"
else:
raise ValueError(msg)
def to_radians_per_second(self):
"""
Convert to type 'LAPLACE (RADIANS/SECOND)'
"""
if self.pz_transfer_function_type == 'LAPLACE (RADIANS/SECOND)':
return
elif self.pz_transfer_function_type == 'LAPLACE (HERTZ)':
twopi = 2 * pi
self.normalization_factor *= twopi ** (
len(self.poles) - len(self.zeros))
self.poles = [
ComplexWithUncertainties(
x.real * twopi, x.imag * twopi,
upper_uncertainty=x.upper_uncertainty * twopi,
lower_uncertainty=x.lower_uncertainty * twopi)
for x in self.poles]
self.zeros = [
ComplexWithUncertainties(
x.real * twopi, x.imag * twopi,
upper_uncertainty=x.upper_uncertainty * twopi,
lower_uncertainty=x.lower_uncertainty * twopi)
for x in self.zeros]
self.pz_transfer_function_type = 'LAPLACE (RADIANS/SECOND)'
else:
msg = (f"Can not convert transfer function type "
f"'{self.pz_transfer_function_type}' to "
f"'LAPLACE (RADIANS/SECOND)'")
raise ValueError(msg)
class CoefficientsTypeResponseStage(ResponseStage):
"""
This response type can describe coefficients for FIR filters. Laplace
transforms and IIR filters can also be expressed using this type but should
rather be described using the PolesZerosResponseStage class. Effectively
corresponds to SEED blockette 54.
Has all the arguments of the parent class
:class:`~obspy.core.inventory.response.ResponseStage` and the following:
:type cf_transfer_function_type: str
:param cf_transfer_function_type: A string describing the type of transfer
function. Can be one of:
* ``ANALOG (RADIANS/SECOND)``
* ``ANALOG (HERTZ)``
* ``DIGITAL``
The function tries to match inputs to one of three types if it can.
:type numerator: list of
:class:`~obspy.core.inventory.response.CoefficientWithUncertainties`
:param numerator: Numerator of the coefficient response stage.
:type denominator: list of
:class:`~obspy.core.inventory.response.CoefficientWithUncertainties`
:param denominator: Denominator of the coefficient response stage.
"""
def __init__(self, stage_sequence_number, stage_gain,
stage_gain_frequency, input_units, output_units,
cf_transfer_function_type, resource_id=None,
resource_id2=None, name=None, numerator=None,
denominator=None, input_units_description=None,
output_units_description=None, description=None,
decimation_input_sample_rate=None, decimation_factor=None,
decimation_offset=None, decimation_delay=None,
decimation_correction=None):
# Set the Coefficients type specific attributes. Special cases are
# handled by properties.
self.cf_transfer_function_type = cf_transfer_function_type
self.numerator = numerator
self.denominator = denominator
super(CoefficientsTypeResponseStage, self).__init__(
stage_sequence_number=stage_sequence_number,
input_units=input_units,
output_units=output_units,
input_units_description=input_units_description,
output_units_description=output_units_description,
resource_id=resource_id, resource_id2=resource_id2,
stage_gain=stage_gain,
stage_gain_frequency=stage_gain_frequency, name=name,
description=description,
decimation_input_sample_rate=decimation_input_sample_rate,
decimation_factor=decimation_factor,
decimation_offset=decimation_offset,
decimation_delay=decimation_delay,
decimation_correction=decimation_correction)
def __str__(self):
ret = super(CoefficientsTypeResponseStage, self).__str__()
ret += (
"\n"
"\tTransfer function type: {transfer_fct_type}\n"
"\tContains {num_count} numerators and {den_count} denominators")\
.format(
transfer_fct_type=self.cf_transfer_function_type,
num_count=len(self.numerator), den_count=len(self.denominator))
return ret
def _repr_pretty_(self, p, cycle):
p.text(str(self))
@property
def numerator(self):
return self._numerator
@numerator.setter
def numerator(self, value):
if value == []:
self._numerator = []
return
value = list(value) if isinstance(
value, collections.abc.Iterable) else [value]
if any(getattr(x, 'unit', None) is not None for x in value):
msg = 'Setting Numerator/Denominator with a unit is deprecated.'
warnings.warn(msg, ObsPyDeprecationWarning)
for _i, x in enumerate(value):
if not isinstance(x, CoefficientWithUncertainties):
value[_i] = CoefficientWithUncertainties(x)
self._numerator = value
@property
def denominator(self):
return self._denominator
@denominator.setter
def denominator(self, value):
if value == []:
self._denominator = []
return
value = list(value) if isinstance(
value, collections.abc.Iterable) else [value]
if any(getattr(x, 'unit', None) is not None for x in value):
msg = 'Setting Numerator/Denominator with a unit is deprecated.'
warnings.warn(msg, ObsPyDeprecationWarning)
for _i, x in enumerate(value):
if not isinstance(x, CoefficientWithUncertainties):
value[_i] = CoefficientWithUncertainties(x)
self._denominator = value
@property
def cf_transfer_function_type(self):
return self._cf_transfer_function_type
@cf_transfer_function_type.setter
def cf_transfer_function_type(self, value):
"""
Setter for the transfer function type.
Rather permissive but should make it less awkward to use.
"""
msg = ("'%s' is not a valid value for 'cf_transfer_function_type'. "
"Valid one are:\n"
"\tANALOG (RADIANS/SECOND)\n"
"\tANALOG (HERTZ)\n"
"\tDIGITAL") % value
value = value.lower()
if "analog" in value:
if "rad" in value:
self._cf_transfer_function_type = "ANALOG (RADIANS/SECOND)"
elif "hertz" in value or "hz" in value:
self._cf_transfer_function_type = "ANALOG (HERTZ)"
else:
raise ValueError(msg)
elif "digital" in value:
self._cf_transfer_function_type = "DIGITAL"
else:
raise ValueError(msg)
class ResponseListResponseStage(ResponseStage):
"""
This response type gives a list of frequency, amplitude and phase value
pairs. Effectively corresponds to SEED blockette 55.
Has all the arguments of the parent class
:class:`~obspy.core.inventory.response.ResponseStage` and the following:
:type response_list_elements: list of
:class:`~obspy.core.inventory.response.ResponseListElement`
:param response_list_elements: A list of single discrete frequency,
amplitude and phase response values.
"""
def __init__(self, stage_sequence_number, stage_gain,
stage_gain_frequency, input_units, output_units,
resource_id=None, resource_id2=None, name=None,
response_list_elements=None,
input_units_description=None, output_units_description=None,
description=None, decimation_input_sample_rate=None,
decimation_factor=None, decimation_offset=None,
decimation_delay=None, decimation_correction=None):
self.response_list_elements = response_list_elements or []
super(ResponseListResponseStage, self).__init__(
stage_sequence_number=stage_sequence_number,
input_units=input_units,
output_units=output_units,
input_units_description=input_units_description,
output_units_description=output_units_description,
resource_id=resource_id, resource_id2=resource_id2,
stage_gain=stage_gain,
stage_gain_frequency=stage_gain_frequency, name=name,
description=description,
decimation_input_sample_rate=decimation_input_sample_rate,
decimation_factor=decimation_factor,
decimation_offset=decimation_offset,
decimation_delay=decimation_delay,
decimation_correction=decimation_correction)
class ResponseListElement(ComparingObject):
"""
Describes the amplitude and phase response value for a discrete frequency
value.
"""
def __init__(self, frequency, amplitude, phase):
"""
:type frequency: float
:param frequency: The frequency for which the response is valid.
:type amplitude: float
:param amplitude: The value for the amplitude response at this
frequency.
:type phase: float
:param phase: The value for the phase response at this frequency.
"""
self.frequency = frequency
self.amplitude = amplitude
self.phase = phase
@property
def frequency(self):
return self._frequency
@frequency.setter
def frequency(self, value):
if not isinstance(value, Frequency):
value = Frequency(value)
self._frequency = value
@property
def amplitude(self):
return self._amplitude
@amplitude.setter
def amplitude(self, value):
if not isinstance(value, FloatWithUncertaintiesAndUnit):
value = FloatWithUncertaintiesAndUnit(value)
self._amplitude = value
@property
def phase(self):
return self._phase
@phase.setter
def phase(self, value):
if not isinstance(value, Angle):
value = Angle(value)
self._phase = value
class FIRResponseStage(ResponseStage):
"""
From the StationXML Definition:
Response: FIR filter. Corresponds to SEED blockette 61. FIR filters are
also commonly documented using the CoefficientsType element.
Has all the arguments of the parent class
:class:`~obspy.core.inventory.response.ResponseStage` and the following:
:type symmetry: str
:param symmetry: A string describing the symmetry. Can be one of:
* ``NONE``
* ``EVEN``
* ``ODD``
:type coefficients: list[float]
:param coefficients: List of FIR coefficients.
"""
def __init__(self, stage_sequence_number, stage_gain,
stage_gain_frequency, input_units, output_units,
symmetry="NONE", resource_id=None, resource_id2=None,
name=None,
coefficients=None, input_units_description=None,
output_units_description=None, description=None,
decimation_input_sample_rate=None, decimation_factor=None,
decimation_offset=None, decimation_delay=None,
decimation_correction=None):
self._symmetry = symmetry
self.coefficients = coefficients or []
super(FIRResponseStage, self).__init__(
stage_sequence_number=stage_sequence_number,
input_units=input_units,
output_units=output_units,
input_units_description=input_units_description,
output_units_description=output_units_description,
resource_id=resource_id, resource_id2=resource_id2,
stage_gain=stage_gain,
stage_gain_frequency=stage_gain_frequency, name=name,
description=description,
decimation_input_sample_rate=decimation_input_sample_rate,
decimation_factor=decimation_factor,
decimation_offset=decimation_offset,
decimation_delay=decimation_delay,
decimation_correction=decimation_correction)
@property
def symmetry(self):
return self._symmetry
@symmetry.setter
def symmetry(self, value):
value = str(value).upper()
allowed = ("NONE", "EVEN", "ODD")
if value not in allowed:
msg = ("Value '%s' for FIR Response symmetry not allowed. "
"Possible values are: '%s'")
msg = msg % (value, "', '".join(allowed))
raise ValueError(msg)
self._symmetry = value
@property
def coefficients(self):
return self._coefficients
@coefficients.setter
def coefficients(self, value):
new_values = []
for x in value:
if not isinstance(x, FilterCoefficient):
x = FilterCoefficient(x)
new_values.append(x)
self._coefficients = new_values
class PolynomialResponseStage(ResponseStage):
"""
From the StationXML Definition:
Response: expressed as a polynomial (allows non-linear sensors to be
described). Corresponds to SEED blockette 62. Can be used to describe a
stage of acquisition or a complete system.
Has all the arguments of the parent class
:class:`~obspy.core.inventory.response.ResponseStage` and the following:
:type approximation_type: str
:param approximation_type: Approximation type. Currently restricted to
'MACLAURIN' by StationXML definition.
:type frequency_lower_bound: float
:param frequency_lower_bound: Lower frequency bound.
:type frequency_upper_bound: float
:param frequency_upper_bound: Upper frequency bound.
:type approximation_lower_bound: float
:param approximation_lower_bound: Lower bound of approximation.
:type approximation_upper_bound: float
:param approximation_upper_bound: Upper bound of approximation.
:type maximum_error: float
:param maximum_error: Maximum error.
:type coefficients: list[float]
:param coefficients: List of polynomial coefficients.
"""
def __init__(self, stage_sequence_number, stage_gain,
stage_gain_frequency, input_units, output_units,
frequency_lower_bound,
frequency_upper_bound, approximation_lower_bound,
approximation_upper_bound, maximum_error, coefficients,
approximation_type='MACLAURIN', resource_id=None,
resource_id2=None, name=None,
input_units_description=None,
output_units_description=None, description=None,
decimation_input_sample_rate=None, decimation_factor=None,
decimation_offset=None, decimation_delay=None,
decimation_correction=None):
# XXX remove stage_gain and stage_gain_frequency completely, since
# changes in StationXML 1.1?
self._approximation_type = approximation_type
self.frequency_lower_bound = frequency_lower_bound
self.frequency_upper_bound = frequency_upper_bound
self.approximation_lower_bound = approximation_lower_bound
self.approximation_upper_bound = approximation_upper_bound
self.maximum_error = maximum_error
self.coefficients = coefficients
# XXX StationXML 1.1 does not allow stage gain in Polynomial response
# stages. Maybe we should we warn here.. but this could get very
# verbose when reading StationXML 1.0 files, so maybe not
super(PolynomialResponseStage, self).__init__(
stage_sequence_number=stage_sequence_number,
input_units=input_units,
output_units=output_units,
input_units_description=input_units_description,
output_units_description=output_units_description,
resource_id=resource_id, resource_id2=resource_id2,
stage_gain=stage_gain,
stage_gain_frequency=stage_gain_frequency, name=name,
description=description,
decimation_input_sample_rate=decimation_input_sample_rate,
decimation_factor=decimation_factor,
decimation_offset=decimation_offset,
decimation_delay=decimation_delay,
decimation_correction=decimation_correction)
@property
def approximation_type(self):
return self._approximation_type
@approximation_type.setter
def approximation_type(self, value):
value = str(value).upper()
allowed = ("MACLAURIN",)
if value not in allowed:
msg = ("Value '%s' for polynomial response approximation type not "
"allowed. Possible values are: '%s'")
msg = msg % (value, "', '".join(allowed))
raise ValueError(msg)
self._approximation_type = value
@property
def coefficients(self):
return self._coefficients
@coefficients.setter
def coefficients(self, value):
new_values = []
for x in value:
if not isinstance(x, CoefficientWithUncertainties):
x = CoefficientWithUncertainties(x)
new_values.append(x)
self._coefficients = new_values
def __str__(self):
ret = super(PolynomialResponseStage, self).__str__()
ret += (
"\n"
"\tPolynomial approximation type: {approximation_type}\n"
"\tFrequency lower bound: {lower_freq_bound}\n"
"\tFrequency upper bound: {upper_freq_bound}\n"
"\tApproximation lower bound: {lower_approx_bound}\n"
"\tApproximation upper bound: {upper_approx_bound}\n"
"\tMaximum error: {max_error}\n"
"\tNumber of coefficients: {coeff_count}".format(
approximation_type=self._approximation_type,
lower_freq_bound=self.frequency_lower_bound,
upper_freq_bound=self.frequency_upper_bound,
lower_approx_bound=self.approximation_lower_bound,
upper_approx_bound=self.approximation_upper_bound,
max_error=self.maximum_error,
coeff_count=len(self.coefficients)))
return ret
class Response(ComparingObject):
"""
The root response object.
"""
def __init__(self, resource_id=None, instrument_sensitivity=None,
instrument_polynomial=None, response_stages=None):
"""
:type resource_id: str
:param resource_id: This field contains a string that should serve as a
unique resource identifier. This identifier can be interpreted
differently depending on the data center/software that generated
the document. Also, we recommend to use something like
GENERATOR:Meaningful ID. As a common behavior equipment with the
same ID should contains the same information/be derived from the
same base instruments.
:type instrument_sensitivity:
:class:`~obspy.core.inventory.response.InstrumentSensitivity`
:param instrument_sensitivity: The total sensitivity for the given
channel, representing the complete acquisition system expressed as
a scalar.
:type instrument_polynomial:
:class:`~obspy.core.inventory.response.InstrumentPolynomial`
:param instrument_polynomial: The total sensitivity for the given
channel, representing the complete acquisition system expressed as
a polynomial.
:type response_stages: list of
:class:`~obspy.core.inventory.response.ResponseStage` objects
:param response_stages: A list of the response stages. Covers SEED
blockettes 53 to 56.
"""
self.resource_id = resource_id
self.instrument_sensitivity = instrument_sensitivity
self.instrument_polynomial = instrument_polynomial
if response_stages is None:
self.response_stages = []
elif hasattr(response_stages, "__iter__"):
self.response_stages = response_stages
else:
msg = "response_stages must be an iterable."
raise ValueError(msg)
def _attempt_to_fix_units(self):
"""
Internal helper function that will add units to gain only stages based
on the units of surrounding stages.
Should be called when parsing from file formats that don't have units
for identity stages.
"""
previous_output_units = None
previous_output_units_description = None
# Potentially set the input units of the first stage to the units of
# the overall sensitivity and the output units of the second stage.
if self.response_stages and self.response_stages[0] and \
hasattr(self, "instrument_sensitivity"):
s = self.instrument_sensitivity
if s:
if self.response_stages[0].input_units is None:
self.response_stages[0].input_units = s.input_units
if self.response_stages[0].input_units_description is None:
self.response_stages[0].input_units_description = \
s.input_units_description
if len(self.response_stages) >= 2 and self.response_stages[1]:
if self.response_stages[0].output_units is None:
self.response_stages[0].output_units = \
self.response_stages[1].input_units
if self.response_stages[0].output_units_description is None:
self.response_stages[0].output_units_description = \
self.response_stages[1].input_units_description
# Front to back.
for r in self.response_stages:
# Only for identity/stage only.
if type(r) is ResponseStage:
if not r.input_units and not r.output_units and \
previous_output_units:
r.input_units = previous_output_units
r.output_units = previous_output_units
if not r.input_units_description and \
not r.output_units_description \
and previous_output_units_description:
r.input_units_description = \
previous_output_units_description
r.output_units_description = \
previous_output_units_description
previous_output_units = r.output_units
previous_output_units_description = r.output_units_description
# Back to front.
previous_input_units = None
previous_input_units_description = None
for r in reversed(self.response_stages):
# Only for identity/stage only.
if type(r) is ResponseStage:
if not r.input_units and not r.output_units and \
previous_input_units:
r.input_units = previous_input_units
r.output_units = previous_input_units
if not r.input_units_description and \
not r.output_units_description \
and previous_input_units_description:
r.input_units_description = \
previous_input_units_description
r.output_units_description = \
previous_input_units_description
previous_input_units = r.input_units
previous_input_units_description = r.input_units_description
def get_sampling_rates(self):
"""
Computes the input and output sampling rates of each stage.
For well defined files this will just read the decimation attributes
of each stage. For others it will attempt to infer missing values
from the surrounding stages.
:returns: A nested dictionary detailing the sampling rates of each
response stage.
:rtype: dict
>>> import obspy
>>> inv = obspy.read_inventory("AU.MEEK.xml") # doctest: +SKIP
>>> inv[0][0][0].response.get_sampling_rates() # doctest: +SKIP
{1: {'decimation_factor': 1,
'input_sampling_rate': 600.0,
'output_sampling_rate': 600.0},
2: {'decimation_factor': 1,
'input_sampling_rate': 600.0,
'output_sampling_rate': 600.0},
3: {'decimation_factor': 1,
'input_sampling_rate': 600.0,
'output_sampling_rate': 600.0},
4: {'decimation_factor': 3,
'input_sampling_rate': 600.0,
'output_sampling_rate': 200.0},
5: {'decimation_factor': 10,
'input_sampling_rate': 200.0,
'output_sampling_rate': 20.0}}
"""
# Get all stages, but skip stage 0.
stages = [_i.stage_sequence_number for _i in self.response_stages
if _i.stage_sequence_number]
if not stages:
return {}
if list(range(1, len(stages) + 1)) != stages:
raise ValueError("Can only determine sampling rates if response "
"stages are in order.")
# First fill in all the set values.
sampling_rates = {}
for stage in self.response_stages:
input_sr = None
output_sr = None
factor = None
if stage.decimation_input_sample_rate:
input_sr = stage.decimation_input_sample_rate
if stage.decimation_factor:
factor = stage.decimation_factor
output_sr = input_sr / float(factor)
sampling_rates[stage.stage_sequence_number] = {
"input_sampling_rate": input_sr,
"output_sampling_rate": output_sr,
"decimation_factor": factor}
# Nothing might be set - just return in that case.
if set(itertools.chain.from_iterable(v.values()
for v in sampling_rates.values())) == {None}:
return sampling_rates
# Find the first set input sampling rate. The output sampling rate
# cannot be set without it. Set all prior input and output sampling
# rates to it.
for i in stages:
sr = sampling_rates[i]["input_sampling_rate"]
if sr:
for j in range(1, i):
sampling_rates[j]["input_sampling_rate"] = sr
sampling_rates[j]["output_sampling_rate"] = sr
sampling_rates[j]["decimation_factor"] = 1
break
# This should guarantee that the input and output sampling rate of the
# the first stage are set.
output_sr = sampling_rates[1]["output_sampling_rate"]
if not output_sr: # pragma: no cover
raise NotImplementedError
for i in stages:
si = sampling_rates[i]
if not si["input_sampling_rate"]:
si["input_sampling_rate"] = output_sr
if not si["output_sampling_rate"]:
if not si["decimation_factor"]:
si["output_sampling_rate"] = si["input_sampling_rate"]
si["decimation_factor"] = 1
else:
si["output_sampling_rate"] = si["input_sampling_rate"] / \
float(si["decimation_factor"])
if not si["decimation_factor"]:
si["decimation_factor"] = int(round(
si["input_sampling_rate"] / si["output_sampling_rate"]))
output_sr = si["output_sampling_rate"]
def is_close(a, b):
return abs(a - b) < 1e-5
# Final consistency checks.
sr = sampling_rates[stages[0]]["input_sampling_rate"]
for i in stages:
si = sampling_rates[i]
if not is_close(si["input_sampling_rate"], sr): # pragma: no cover
msg = ("Input sampling rate of stage %i is inconsistent "
"with the previous stages' output sampling rate")
warnings.warn(msg % i)
if not is_close(
si["input_sampling_rate"] / si["output_sampling_rate"],
si["decimation_factor"]): # pragma: no cover
msg = ("Decimation factor in stage %i is inconsistent with "
"input and output sampling rates.")
warnings.warn(msg % i)
sr = si["output_sampling_rate"]
return sampling_rates
def recalculate_overall_sensitivity(self, frequency=None):