本文整理汇总了Python中obspy.signal.spectral_estimation.PPSD类的典型用法代码示例。如果您正苦于以下问题:Python PPSD类的具体用法?Python PPSD怎么用?Python PPSD使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了PPSD类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_ppsd
def _get_ppsd():
"""
Returns ready computed ppsd for testing purposes.
"""
tr, paz = _get_sample_data()
st = Stream([tr])
ppsd = PPSD(tr.stats, paz, db_bins=(-200, -50, 0.5))
ppsd.add(st)
return ppsd
示例2: test_PPSD_w_IRIS
def test_PPSD_w_IRIS(self):
# Bands to be used this is the upper and lower frequency band pairs
fres = zip([0.1, 0.05], [0.2, 0.1])
file_dataANMO = os.path.join(self.path, 'IUANMO.seed')
# Read in ANMO data for one day
st = read(file_dataANMO)
# Use a canned ANMO response which will stay static
paz = {'gain': 86298.5, 'zeros': [0, 0],
'poles': [-59.4313, -22.7121 + 27.1065j, -22.7121 + 27.1065j,
-0.0048004, -0.073199], 'sensitivity': 3.3554*10**9}
# Make an empty PPSD and add the data
ppsd = PPSD(st[0].stats, paz)
ppsd.add(st)
# Get the 50th percentile from the PPSD
(per, perval) = ppsd.get_percentile(percentile=50)
# Read in the results obtained from a Mustang flat file
file_dataIRIS = os.path.join(self.path, 'IRISpdfExample')
freq, power, hits = np.genfromtxt(file_dataIRIS, comments='#',
delimiter=',', unpack=True)
# For each frequency pair we want to compare the mean of the bands
for fre in fres:
pervalGoodOBSPY = []
# Get the values for the bands from the PPSD
perinv = 1 / per
mask = (fre[0] < perinv) & (perinv < fre[1])
pervalGoodOBSPY = perval[mask]
# Now we sort out all of the data from the IRIS flat file
mask = (fre[0] < freq) & (freq < fre[1])
triples = list(zip(freq[mask], hits[mask], power[mask]))
# We now have all of the frequency values of interest
# We will get the distinct frequency values
freqdistinct = sorted(list(set(freq[mask])), reverse=True)
percenlist = []
# We will loop through the frequency values and compute a
# 50th percentile
for curfreq in freqdistinct:
tempvalslist = []
for triple in triples:
if np.isclose(curfreq, triple[0], atol=1e-3, rtol=0.0):
tempvalslist += [int(triple[2])] * int(triple[1])
percenlist.append(np.percentile(tempvalslist, 50))
# Here is the actual test
np.testing.assert_allclose(np.mean(pervalGoodOBSPY),
np.mean(percenlist), rtol=0.0, atol=1.0)
示例3: test_ppsd_w_iris_against_obspy_results
def test_ppsd_w_iris_against_obspy_results(self):
"""
Test against results obtained after merging of #1108.
"""
# Read in ANMO data for one day
st = read(os.path.join(self.path, "IUANMO.seed"))
# Read in metadata in various different formats
paz = {
"gain": 86298.5,
"zeros": [0, 0],
"poles": [-59.4313, -22.7121 + 27.1065j, -22.7121 + 27.1065j, -0.0048004, -0.073199],
"sensitivity": 3.3554 * 10 ** 9,
}
resp = os.path.join(self.path, "IUANMO.resp")
parser = Parser(os.path.join(self.path, "IUANMO.dataless"))
inv = read_inventory(os.path.join(self.path, "IUANMO.xml"))
# load expected results, for both only PAZ and full response
filename_paz = os.path.join(self.path, "IUANMO_ppsd_paz.npz")
results_paz = PPSD.load_npz(filename_paz, metadata=None)
filename_full = os.path.join(self.path, "IUANMO_ppsd_fullresponse.npz")
results_full = PPSD.load_npz(filename_full, metadata=None)
# Calculate the PPSDs and test against expected results
# first: only PAZ
ppsd = PPSD(st[0].stats, paz)
ppsd.add(st)
# commented code to generate the test data:
# ## np.savez(filename_paz,
# ## **dict([(k, getattr(ppsd, k))
# ## for k in PPSD.NPZ_STORE_KEYS]))
for key in PPSD.NPZ_STORE_KEYS_ARRAY_TYPES:
np.testing.assert_allclose(getattr(ppsd, key), getattr(results_paz, key), rtol=1e-5)
for key in PPSD.NPZ_STORE_KEYS_LIST_TYPES:
for got, expected in zip(getattr(ppsd, key), getattr(results_paz, key)):
np.testing.assert_allclose(got, expected, rtol=1e-5)
for key in PPSD.NPZ_STORE_KEYS_SIMPLE_TYPES:
if key in ["obspy_version", "numpy_version", "matplotlib_version"]:
continue
self.assertEqual(getattr(ppsd, key), getattr(results_paz, key))
# second: various methods for full response
for metadata in [parser, inv, resp]:
ppsd = PPSD(st[0].stats, metadata)
ppsd.add(st)
# commented code to generate the test data:
# ## np.savez(filename_full,
# ## **dict([(k, getattr(ppsd, k))
# ## for k in PPSD.NPZ_STORE_KEYS]))
for key in PPSD.NPZ_STORE_KEYS_ARRAY_TYPES:
np.testing.assert_allclose(getattr(ppsd, key), getattr(results_full, key), rtol=1e-5)
for key in PPSD.NPZ_STORE_KEYS_LIST_TYPES:
for got, expected in zip(getattr(ppsd, key), getattr(results_full, key)):
np.testing.assert_allclose(got, expected, rtol=1e-5)
for key in PPSD.NPZ_STORE_KEYS_SIMPLE_TYPES:
if key in ["obspy_version", "numpy_version", "matplotlib_version"]:
continue
self.assertEqual(getattr(ppsd, key), getattr(results_full, key))
示例4: test_ppsd_temporal_plot
def test_ppsd_temporal_plot(self):
"""
Test plot of several period bins over time
"""
ppsd = PPSD.load_npz(self.example_ppsd_npz)
restrictions = {'starttime': UTCDateTime(2011, 2, 6, 1, 1),
'endtime': UTCDateTime(2011, 2, 7, 21, 12),
'year': [2011],
'time_of_weekday': [(-1, 2, 23)]}
# add some gaps in the middle
for i in sorted(list(range(30, 40)) + list(range(8, 18)) + [4])[::-1]:
ppsd._times_processed.pop(i)
ppsd._binned_psds.pop(i)
with ImageComparison(self.path_images, 'ppsd_temporal.png',
reltol=1.5) as ic:
fig = ppsd.plot_temporal([0.1, 1, 10], filename=None, show=False,
**restrictions)
fig.savefig(ic.name)
with ImageComparison(self.path_images, 'ppsd_temporal.png',
reltol=1.5) as ic:
ppsd.plot_temporal([0.1, 1, 10], filename=ic.name, show=False,
**restrictions)
示例5: test_ppsd
def test_ppsd(self):
"""
Test PPSD routine with some real data.
"""
# paths of the expected result data
file_histogram = os.path.join(
self.path,
'BW.KW1._.EHZ.D.2011.090_downsampled__ppsd_hist_stack.npy')
file_binning = os.path.join(
self.path, 'BW.KW1._.EHZ.D.2011.090_downsampled__ppsd_mixed.npz')
file_mode_mean = os.path.join(
self.path,
'BW.KW1._.EHZ.D.2011.090_downsampled__ppsd_mode_mean.npz')
tr, _paz = _get_sample_data()
st = Stream([tr])
ppsd = _get_ppsd()
# read results and compare
result_hist = np.load(file_histogram)
self.assertEqual(len(ppsd.times_processed), 4)
self.assertEqual(ppsd.nfft, 65536)
self.assertEqual(ppsd.nlap, 49152)
np.testing.assert_array_equal(ppsd.current_histogram, result_hist)
# add the same data a second time (which should do nothing at all) and
# test again - but it will raise UserWarnings, which we omit for now
with warnings.catch_warnings(record=True):
warnings.simplefilter('ignore', UserWarning)
ppsd.add(st)
np.testing.assert_array_equal(ppsd.current_histogram, result_hist)
# test the binning arrays
binning = np.load(file_binning)
np.testing.assert_array_equal(ppsd.db_bin_edges, binning['spec_bins'])
np.testing.assert_array_equal(ppsd.period_bin_centers,
binning['period_bins'])
# test the mode/mean getter functions
per_mode, mode = ppsd.get_mode()
per_mean, mean = ppsd.get_mean()
result_mode_mean = np.load(file_mode_mean)
np.testing.assert_array_equal(per_mode, result_mode_mean['per_mode'])
np.testing.assert_array_equal(mode, result_mode_mean['mode'])
np.testing.assert_array_equal(per_mean, result_mode_mean['per_mean'])
np.testing.assert_array_equal(mean, result_mode_mean['mean'])
# test saving and loading of the PPSD (using a temporary file)
with NamedTemporaryFile(suffix=".npz") as tf:
filename = tf.name
# test saving and loading to npz
ppsd.save_npz(filename)
ppsd_loaded = PPSD.load_npz(filename)
ppsd_loaded.calculate_histogram()
self.assertEqual(len(ppsd_loaded.times_processed), 4)
self.assertEqual(ppsd_loaded.nfft, 65536)
self.assertEqual(ppsd_loaded.nlap, 49152)
np.testing.assert_array_equal(ppsd_loaded.current_histogram,
result_hist)
np.testing.assert_array_equal(ppsd_loaded.db_bin_edges,
binning['spec_bins'])
np.testing.assert_array_equal(ppsd_loaded.period_bin_centers,
binning['period_bins'])
示例6: test_issue1216
def test_issue1216(self):
tr, paz = _get_sample_data()
st = Stream([tr])
ppsd = PPSD(tr.stats, paz, db_bins=(-200, -50, 0.5))
ppsd.add(st)
# After adding data internal representation of hist stack is None
self.assertIsNone(ppsd._current_hist_stack)
# Accessing the current_histogram property calculates the default stack
self.assertIsNotNone(ppsd.current_histogram)
self.assertIsNotNone(ppsd._current_hist_stack)
# Adding the same data again does not invalidate the internal stack
# but raises "UserWarning: Already covered time spans detected"
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always', UserWarning)
ppsd.add(st)
self.assertEqual(len(w), 4)
for w_ in w:
self.assertTrue(str(w_.message).startswith(
"Already covered time spans detected"))
self.assertIsNotNone(ppsd._current_hist_stack)
# Adding new data invalidates the internal stack
tr.stats.starttime += 3600
st2 = Stream([tr])
# raises "UserWarning: Already covered time spans detected"
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always', UserWarning)
ppsd.add(st2)
self.assertEqual(len(w), 2)
for w_ in w:
self.assertTrue(str(w_.message).startswith(
"Already covered time spans detected"))
self.assertIsNone(ppsd._current_hist_stack)
# Accessing current_histogram again calculates the stack
self.assertIsNotNone(ppsd.current_histogram)
self.assertIsNotNone(ppsd._current_hist_stack)
示例7: test_exclude_last_sample
def test_exclude_last_sample(self):
start = UTCDateTime("2017-01-01T00:00:00")
header = {
"starttime": start,
"network": "GR",
"station": "FUR",
"channel": "BHZ"
}
# 49 segments of 30 minutes to allow 30 minutes overlap in next day
tr = Trace(data=np.arange(30 * 60 * 4, dtype=np.int32), header=header)
ppsd = PPSD(tr.stats, read_inventory())
ppsd.add(tr)
self.assertEqual(3, len(ppsd._times_processed))
self.assertEqual(3600, ppsd.len)
for i, time in enumerate(ppsd._times_processed):
current = start.ns + (i * 30 * 60) * 1e9
self.assertTrue(time == current)
示例8: test_PPSD_w_IRIS_against_obspy_results
def test_PPSD_w_IRIS_against_obspy_results(self):
"""
Test against results obtained after merging of #1108.
"""
# Read in ANMO data for one day
st = read(os.path.join(self.path, 'IUANMO.seed'))
# Read in metadata in various different formats
paz = {'gain': 86298.5, 'zeros': [0, 0],
'poles': [-59.4313, -22.7121 + 27.1065j, -22.7121 + 27.1065j,
-0.0048004, -0.073199], 'sensitivity': 3.3554*10**9}
resp = os.path.join(self.path, 'IUANMO.resp')
parser = Parser(os.path.join(self.path, 'IUANMO.dataless'))
inv = read_inventory(os.path.join(self.path, 'IUANMO.xml'))
# load expected results, for both only PAZ and full response
filename_paz = os.path.join(self.path, 'IUANMO_ppsd_paz.npz')
results_paz = np.load(filename_paz)
filename_full = os.path.join(self.path, 'IUANMO_ppsd_fullresponse.npz')
results_full = np.load(filename_full)
arrays_to_check = ['_times_data', '_times_processed', '_times_gaps',
'_spec_octaves', 'per_octaves', 'per_octaves_right',
'per_octaves_left', 'period_bin_centers',
'spec_bins', 'period_bins']
arrays_to_check = [native_str(key) for key in arrays_to_check]
# Calculate the PPSDs and test against expected results
# first: only PAZ
ppsd = PPSD(st[0].stats, paz)
ppsd.add(st)
# commented code to generate the test data:
# ## np.savez(filename_paz,
# ## **dict([(k, getattr(ppsd, k)) for k in arrays_to_check]))
for key in arrays_to_check:
self.assertTrue(np.allclose(
getattr(ppsd, key), results_paz[key], rtol=1e-5))
# second: various methods for full response
# (also test various means of initialization, basically testing the
# decorator that maps the deprecated keywords)
for metadata in [parser, inv, resp]:
ppsd = PPSD(st[0].stats, paz=metadata)
ppsd = PPSD(st[0].stats, parser=metadata)
ppsd = PPSD(st[0].stats, metadata)
ppsd.add(st)
# commented code to generate the test data:
# ## np.savez(filename_full,
# ## **dict([(k, getattr(ppsd, k))
# ## for k in arrays_to_check]))
for key in arrays_to_check:
self.assertTrue(np.allclose(
getattr(ppsd, key), results_full[key], rtol=1e-5))
示例9: test_exception_reading_newer_npz
def test_exception_reading_newer_npz(self):
"""
Checks that an exception is properly raised when trying to read a npz
that was written on a more recent ObsPy version (specifically that has
a higher 'ppsd_version' number which is used to keep track of changes
in PPSD and the npz file used for serialization).
"""
msg = ("Trying to read/add a PPSD npz with 'ppsd_version=100'. This "
"file was written on a more recent ObsPy version that very "
"likely has incompatible changes in PPSD internal structure "
"and npz serialization. It can not safely be read with this "
"ObsPy version (current 'ppsd_version' is {!s}). Please "
"consider updating your ObsPy installation.".format(
PPSD(stats=Stats(), metadata=None).ppsd_version))
# 1 - loading a npz
data = np.load(self.example_ppsd_npz)
# we have to load, modify 'ppsd_version' and save the npz file for the
# test..
items = {key: data[key] for key in data.files}
# deliberately set a higher ppsd_version number
items['ppsd_version'] = items['ppsd_version'].copy()
items['ppsd_version'].fill(100)
with NamedTemporaryFile() as tf:
filename = tf.name
with open(filename, 'wb') as fh:
np.savez(fh, **items)
with self.assertRaises(ObsPyException) as e:
PPSD.load_npz(filename)
self.assertEqual(str(e.exception), msg)
# 2 - adding a npz
ppsd = PPSD.load_npz(self.example_ppsd_npz)
for method in (ppsd.add_npz, ppsd._add_npz):
with NamedTemporaryFile() as tf:
filename = tf.name
with open(filename, 'wb') as fh:
np.savez(fh, **items)
with self.assertRaises(ObsPyException) as e:
method(filename)
self.assertEqual(str(e.exception), msg)
示例10: test_wrong_trace_id_message
def test_wrong_trace_id_message(self):
"""
Test that we get the expected warning message on waveform/metadata
mismatch.
"""
tr, _paz = _get_sample_data()
inv = read_inventory(os.path.join(self.path, 'IUANMO.xml'))
st = Stream([tr])
ppsd = PPSD(tr.stats, inv)
# metadata doesn't fit the trace ID specified via stats
# should show a warning..
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
ret = ppsd.add(st)
# the trace is sliced into four segments, so we get the warning
# message four times..
self.assertEqual(len(w), 4)
for w_ in w:
self.assertTrue(str(w_.message).startswith(
"Error getting response from provided metadata"))
# should not add the data to the ppsd
self.assertFalse(ret)
示例11: test_ppsd_time_checks
def test_ppsd_time_checks(self):
"""
Some tests that make sure checking if a new PSD slice to be addded to
existing PPSD has an invalid overlap or not works as expected.
"""
ppsd = PPSD(Stats(), Response())
one_second = 1000000000
t0 = 946684800000000000 # 2000-01-01T00:00:00
time_diffs = [
0, one_second, one_second * 2, one_second * 3,
one_second * 8, one_second * 9, one_second * 10]
ppsd._times_processed = [t0 + td for td in time_diffs]
ppsd.ppsd_length = 2
ppsd.overlap = 0.5
# valid time stamps to insert data for (i.e. data that overlaps with
# existing data at most "overlap" times "ppsd_length")
ns_ok = [
t0 - 3 * one_second,
t0 - 1.01 * one_second,
t0 - one_second,
t0 + 4 * one_second,
t0 + 4.01 * one_second,
t0 + 6 * one_second,
t0 + 7 * one_second,
t0 + 6.99 * one_second,
t0 + 11 * one_second,
t0 + 11.01 * one_second,
t0 + 15 * one_second,
]
for ns in ns_ok:
t = UTCDateTime(ns=int(ns))
# getting False means time is not present yet and a PSD slice would
# be added to the PPSD data
self.assertFalse(ppsd._PPSD__check_time_present(t))
# invalid time stamps to insert data for (i.e. data that overlaps with
# existing data more than "overlap" times "ppsd_length")
ns_bad = [
t0 - 0.99 * one_second,
t0 - 0.5 * one_second,
t0,
t0 + 1.1 * one_second,
t0 + 3.99 * one_second,
t0 + 7.01 * one_second,
t0 + 7.5 * one_second,
t0 + 8 * one_second,
t0 + 8.8 * one_second,
t0 + 10 * one_second,
t0 + 10.99 * one_second,
]
for ns in ns_bad:
t = UTCDateTime(ns=int(ns))
# getting False means time is not present yet and a PSD slice would
# be added to the PPSD data
self.assertTrue(ppsd._PPSD__check_time_present(t))
示例12: test_PPSD_save_and_load_npz
def test_PPSD_save_and_load_npz(self):
"""
Test PPSD.load_npz() and PPSD.save_npz()
"""
_, paz = _get_sample_data()
ppsd = _get_ppsd()
# save results to npz file
with NamedTemporaryFile(suffix=".npz") as tf:
filename = tf.name
# test saving and loading an uncompressed file
ppsd.save_npz(filename)
ppsd_loaded = PPSD.load_npz(filename, metadata=paz)
for key in NPZ_STORE_KEYS:
np.testing.assert_equal(getattr(ppsd, key),
getattr(ppsd_loaded, key))
示例13: test_ppsd_spectrogram_plot
def test_ppsd_spectrogram_plot(self):
"""
Test spectrogram type plot of PPSD
"""
ppsd = PPSD.load_npz(self.example_ppsd_npz)
# add some gaps in the middle
for i in sorted(list(range(30, 40)) + list(range(8, 18)) + [4])[::-1]:
ppsd._times_processed.pop(i)
ppsd._binned_psds.pop(i)
with ImageComparison(self.path_images, 'ppsd_spectrogram.png',
reltol=1.5) as ic:
fig = ppsd.plot_spectrogram(filename=None, show=False)
fig.savefig(ic.name)
with ImageComparison(self.path_images, 'ppsd_spectrogram.png',
reltol=1.5) as ic:
ppsd.plot_spectrogram(filename=ic.name, show=False)
示例14: test_ppsd_save_and_load_npz
def test_ppsd_save_and_load_npz(self):
"""
Test PPSD.load_npz() and PPSD.save_npz()
"""
_, paz = _get_sample_data()
ppsd = _get_ppsd()
# save results to npz file
with NamedTemporaryFile(suffix=".npz") as tf:
filename = tf.name
# test saving and loading an uncompressed file
ppsd.save_npz(filename)
ppsd_loaded = PPSD.load_npz(filename, metadata=paz)
for key in PPSD.NPZ_STORE_KEYS:
if isinstance(getattr(ppsd, key), np.ndarray) or key == "_binned_psds":
np.testing.assert_equal(getattr(ppsd, key), getattr(ppsd_loaded, key))
else:
self.assertEqual(getattr(ppsd, key), getattr(ppsd_loaded, key))
示例15: test_ppsd_spectrogram_plot
def test_ppsd_spectrogram_plot(self):
"""
Test spectrogram type plot of PPSD
Matplotlib version 3 shifts the x-axis labels but everything else looks
the same. Skipping test for matplotlib >= 3 on 05/12/2018.
"""
ppsd = PPSD.load_npz(self.example_ppsd_npz)
# add some gaps in the middle
for i in sorted(list(range(30, 40)) + list(range(8, 18)) + [4])[::-1]:
ppsd._times_processed.pop(i)
ppsd._binned_psds.pop(i)
with ImageComparison(self.path_images, 'ppsd_spectrogram.png',
reltol=1.5) as ic:
fig = ppsd.plot_spectrogram(filename=None, show=False)
fig.savefig(ic.name)
with ImageComparison(self.path_images, 'ppsd_spectrogram.png',
reltol=1.5) as ic:
ppsd.plot_spectrogram(filename=ic.name, show=False)