Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# generate output spectrum
create = find_typed_function(timeseries.dtype, 'Create', 'FrequencySeries')
lalfs = create(timeseries.name, lal.LIGOTimeGPS(timeseries.epoch.gps), 0,
1 / segmentlength, lal.StrainUnit,
int(segmentlength // 2 + 1))
# find LAL method (e.g. median-mean -> lal.REAL8AverageSpectrumMedianMean)
methodname = ''.join(map(str.title, re.split('[-_]', method)))
spec_func = find_typed_function(timeseries.dtype, '',
'AverageSpectrum{}'.format(methodname))
# calculate spectrum
spec_func(lalfs, timeseries.to_lal(), segmentlength, stride, window, plan)
# format and return
spec = FrequencySeries.from_lal(lalfs)
spec.name = timeseries.name
spec.channel = timeseries.channel
spec.override_unit(scale_timeseries_unit(
timeseries.unit, scaling='density'))
return spec
spectrum : `~gwpy.frequencyseries.FrequencySeries`
average power `FrequencySeries`
See also
--------
scipy.signal.welch
"""
# calculate PSD
freqs, psd_ = scipy.signal.welch(
timeseries.value, noverlap=noverlap,
fs=timeseries.sample_rate.decompose().value,
nperseg=segmentlength, **kwargs)
# generate FrequencySeries and return
unit = scale_timeseries_unit(timeseries.unit,
kwargs.get('scaling', 'density'))
return FrequencySeries(psd_, unit=unit, frequencies=freqs,
name=timeseries.name, epoch=timeseries.epoch,
channel=timeseries.channel)
title = kwargs.pop('title', None)
for key in ['figsize', 'dpi', 'frameon', 'subplotpars',
'tight_layout']:
if key in kwargs:
figargs[key] = kwargs.pop(key)
# generate figure
super(BodePlot, self).__init__(**figargs)
# delete the axes, and create two more
self.add_subplot(2, 1, 1)
self.add_subplot(2, 1, 2, sharex=self.maxes)
# add filters
for filter_ in filters:
if isinstance(filter_, FrequencySeries):
self.add_frequencyseries(filter_, dB=dB, **kwargs)
else:
self.add_filter(filter_, frequencies=frequencies,
dB=dB, **kwargs)
# format plots
if dB:
self.maxes.set_ylabel('Magnitude [dB]')
ylim = self.maxes.get_ylim()
if ylim[1] == 0:
self.maxes.set_ybound(
upper=ylim[1] + (ylim[1] - ylim[0]) * 0.1)
else:
self.maxes.set_yscale('log')
self.maxes.set_ylabel('Amplitude')
self.paxes.set_xlabel('Frequency [Hz]')
allow passing of sub-classes by the array generator
Notes
-----
Key methods:
.. autosummary::
~Spectrogram.read
~Spectrogram.write
~Spectrogram.plot
~Spectrogram.zpk
"""
_metadata_slots = Series._metadata_slots + ('y0', 'dy', 'yindex')
_default_xunit = TimeSeries._default_xunit
_default_yunit = FrequencySeries._default_xunit
_rowclass = TimeSeries
_columnclass = FrequencySeries
def __new__(cls, data, unit=None, t0=None, dt=None, f0=None, df=None,
times=None, frequencies=None,
name=None, channel=None, **kwargs):
"""Generate a new Spectrogram.
"""
# parse t0 or epoch
epoch = kwargs.pop('epoch', None)
if epoch is not None and t0 is not None:
raise ValueError("give only one of epoch or t0")
if epoch is None and t0 is not None:
kwargs['x0'] = _format_time(t0)
elif epoch is not None:
kwargs['x0'] = _format_time(epoch)
--------
numpy.fft.rfft : The FFT implementation used in this method.
Notes
-----
This method, in constrast to the :func:`numpy.fft.rfft` method
it calls, applies the necessary normalisation such that the
amplitude of the output `~gwpy.frequencyseries.FrequencySeries` is
correct.
"""
from ..frequencyseries import FrequencySeries
if nfft is None:
nfft = self.size
dft = npfft.rfft(self.value, n=nfft) / nfft
dft[1:] *= 2.0
new = FrequencySeries(dft, epoch=self.epoch, unit=self.unit,
name=self.name, channel=self.channel)
try:
new.frequencies = npfft.rfftfreq(nfft, d=self.dx.value)
except AttributeError:
new.frequencies = numpy.arange(new.size) / (nfft * self.dx.value)
return new
from ..types import Array2D
from ..types.sliceutils import null_slice
from ..segments import Segment
from . import FrequencySeries
__author__ = 'Duncan Macleod '
__all__ = ['SpectralVariance']
class SpectralVariance(Array2D):
"""A 2-dimensional array containing the variance histogram of a
frequency-series `FrequencySeries`
"""
_metadata_slots = FrequencySeries._metadata_slots + ('bins',)
_default_xunit = FrequencySeries._default_xunit
_rowclass = FrequencySeries
def __new__(cls, data, bins, unit=None,
f0=None, df=None, frequencies=None,
name=None, channel=None, epoch=None, **kwargs):
"""Generate a new SpectralVariance histogram
"""
# parse x-axis params
if f0 is not None:
kwargs['x0'] = f0
if df is not None:
kwargs['dx'] = df
if frequencies is not None:
kwargs['xindex'] = frequencies
# generate SpectralVariance using the Series constructor
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GWpy. If not, see .
"""ASCII I/O registrations for gwpy.frequencyseries objects
"""
from ...types.io.ascii import register_ascii_series_io
from .. import FrequencySeries
# -- registration -------------------------------------------------------------
register_ascii_series_io(FrequencySeries, format='txt')
register_ascii_series_io(FrequencySeries, format='csv', delimiter=',')
----------
percentile : `float`
percentile (0 - 100) of the bins to compute
Returns
-------
spectrum : `~gwpy.frequencyseries.FrequencySeries`
the given percentile `FrequencySeries` calculated from this
`SpectralVaraicence`
"""
out = scipy.percentile(self.value, percentile, axis=0)
if self.name is not None:
name = '{}: {} percentile'.format(self.name, _ordinal(percentile))
else:
name = None
return FrequencySeries(
out, epoch=self.epoch, channel=self.channel, name=name,
f0=self.f0, df=self.df, unit=self.unit, frequencies=(
hasattr(self, '_frequencies') and self.frequencies or None))
--------
numpy.fft.rfft : The FFT implementation used in this method.
Notes
-----
This method, in constrast to the :func:`numpy.fft.rfft` method
it calls, applies the necessary normalisation such that the
amplitude of the output `~gwpy.frequencyseries.FrequencySeries` is
correct.
"""
from ..frequencyseries import FrequencySeries
if nfft is None:
nfft = self.size
dft = npfft.rfft(self.value, n=nfft) / nfft
dft[1:] *= 2.0
new = FrequencySeries(dft, epoch=self.epoch, unit=self.unit,
name=self.name, channel=self.channel)
try:
new.frequencies = npfft.rfftfreq(nfft, d=self.dx.value)
except AttributeError:
new.frequencies = numpy.arange(new.size) / (nfft * self.dx.value)
return new