text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _normalize_overlap(overlap, window, nfft, samp, method='welch'):
"""Normalise an overlap in physical units to a number of samples Parameters overlap : `float... |
if method == 'bartlett':
return 0
if overlap is None and isinstance(window, string_types):
return recommended_overlap(window, nfft)
if overlap is None:
return 0
return seconds_to_samples(overlap, samp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _normalize_window(window, nfft, library, dtype):
"""Normalise a window specification for a PSD calculation Parameters window : `str`, `numpy.ndarray`, `None`... |
if library == '_lal' and isinstance(window, numpy.ndarray):
from ._lal import window_from_array
return window_from_array(window)
if library == '_lal':
from ._lal import generate_window
return generate_window(nfft, window=window, dtype=dtype)
if isinstance(window, string_type... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_fft_params(func):
"""Decorate a method to automatically convert quantities to samples """ |
@wraps(func)
def wrapped_func(series, method_func, *args, **kwargs):
"""Wrap function to normalize FFT params before execution
"""
if isinstance(series, tuple):
data = series[0]
else:
data = series
# normalise FFT parmeters for all libraries
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def psd(timeseries, method_func, *args, **kwargs):
"""Generate a PSD using a method function All arguments are presumed to be given in physical units Parameters ... |
# decorator has translated the arguments for us, so just call psdn()
return _psdn(timeseries, method_func, *args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _psdn(timeseries, method_func, *args, **kwargs):
"""Generate a PSD using a method function with FFT arguments in samples All arguments are presumed to be in ... |
# unpack tuple of timeseries for cross spectrum
try:
timeseries, other = timeseries
# or just calculate PSD
except ValueError:
return method_func(timeseries, kwargs.pop('nfft'), *args, **kwargs)
else:
return method_func(timeseries, other, kwargs.pop('nfft'),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def average_spectrogram(timeseries, method_func, stride, *args, **kwargs):
"""Generate an average spectrogram using a method function Each time bin of the result... |
# unpack CSD TimeSeries pair, or single timeseries
try:
timeseries, other = timeseries
except ValueError:
timeseries = timeseries
other = None
from ...spectrogram import Spectrogram
nproc = kwargs.pop('nproc', 1)
# get params
epoch = timeseries.t0.value
nstrid... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spectrogram(timeseries, method_func, **kwargs):
"""Generate a spectrogram using a method function Each time bin of the resulting spectrogram is a PSD estimat... |
from ...spectrogram import Spectrogram
# get params
sampling = timeseries.sample_rate.to('Hz').value
nproc = kwargs.pop('nproc', 1)
nfft = kwargs.pop('nfft')
noverlap = kwargs.pop('noverlap')
nstride = nfft - noverlap
# sanity check parameters
if noverlap >= nfft:
raise Va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_color_label(self):
"""Text for colorbar label """ |
if self.args.norm:
return 'Normalized to {}'.format(self.args.norm)
if len(self.units) == 1 and self.usetex:
return r'ASD $\left({0}\right)$'.format(
self.units[0].to_string('latex').strip('$'))
elif len(self.units) == 1:
return 'ASD ({0})'.fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_stride(self):
"""Calculate the stride for the spectrogram This method returns the stride as a `float`, or `None` to indicate selected usage of `TimeSerie... |
fftlength = float(self.args.secpfft)
overlap = fftlength * self.args.overlap
stride = fftlength - overlap
nfft = self.duration / stride # number of FFTs
ffps = int(nfft / (self.width * 0.8)) # FFTs per second
if ffps > 3:
return max(2 * fftlength, ffps * st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_spectrogram(self):
"""Calculate the spectrogram to be plotted This exists as a separate method to allow subclasses to override this and not the entire `g... |
args = self.args
fftlength = float(args.secpfft)
overlap = fftlength * args.overlap
self.log(2, "Calculating spectrogram secpfft: %s, overlap: %s" %
(fftlength, overlap))
stride = self.get_stride()
if stride:
specgram = self.timeseries[0].... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_ylabel(self):
"""Text for y-axis label """ |
if len(self.units) == 1:
return r'ASD $\left({0}\right)$'.format(
self.units[0].to_string('latex').strip('$'))
return 'ASD' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(cls, source, *args, **kwargs):
"""Read data from a source into a `gwpy.timeseries` object. This method is just the internal worker for `TimeSeries.read`... |
# if reading a cache, read it now and sieve
if io_cache.is_cache(source):
from .cache import preformat_cache
source = preformat_cache(source, *args[1:],
start=kwargs.get('start'),
end=kwargs.get('end'))
# get join arguments
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _join_factory(cls, gap, pad):
"""Build a joiner for the given cls, and the given padding options """ |
if issubclass(cls, dict):
def _join(data):
out = cls()
data = list(data)
while data:
tsd = data.pop(0)
out.append(tsd, gap=gap, pad=pad)
del tsd
return out
else:
from .. import TimeSeriesBaseList
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def table_from_file(source, ifo=None, columns=None, selection=None, loudest=False, extended_metadata=True):
"""Read a `Table` from a PyCBC live HDF5 file Paramet... |
# find group
if isinstance(source, h5py.File):
source, ifo = _find_table_group(source, ifo=ifo)
# -- by this point 'source' is guaranteed to be an h5py.Group
# parse default columns
if columns is None:
columns = list(_get_columns(source))
readcols = set(columns)
# parse s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_table_group(h5file, ifo=None):
"""Find the right `h5py.Group` within the given `h5py.File` """ |
exclude = ('background',)
if ifo is None:
try:
ifo, = [key for key in h5file if key not in exclude]
except ValueError as exc:
exc.args = ("PyCBC live HDF5 file contains dataset groups "
"for multiple interferometers, please specify "
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_columns(h5group):
"""Find valid column names from a PyCBC HDF5 Group Returns a `set` of names. """ |
columns = set()
for name in sorted(h5group):
if (not isinstance(h5group[name], h5py.Dataset) or
name == 'template_boundaries'):
continue
if name.endswith('_template') and name[:-9] in columns:
continue
columns.add(name)
return columns - META_C... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_extended_metadata(h5group):
"""Extract the extended metadata for a PyCBC table in HDF5 This method packs non-table-column datasets in the given h5group ... |
meta = dict()
# get PSD
try:
psd = h5group['psd']
except KeyError:
pass
else:
from gwpy.frequencyseries import FrequencySeries
meta['psd'] = FrequencySeries(
psd[:], f0=0, df=psd.attrs['delta_f'], name='pycbc_live')
# get everything else
for key... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter_empty_files(files, ifo=None):
"""Remove empty PyCBC-HDF5 files from a list Parameters files : `list` A list of file paths to test. ifo : `str`, option... |
return type(files)([f for f in files if not empty_hdf5_file(f, ifo=ifo)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def empty_hdf5_file(h5f, ifo=None):
"""Determine whether PyCBC-HDF5 file is empty A file is considered empty if it contains no groups at the base level, or if th... |
# the decorator opens the HDF5 file for us, so h5f is guaranteed to
# be an h5py.Group object
h5f = h5f.file
if list(h5f) == []:
return True
if ifo is not None and (ifo not in h5f or list(h5f[ifo]) == ['psd']):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def identify_pycbc_live(origin, filepath, fileobj, *args, **kwargs):
"""Identify a PyCBC Live file as an HDF5 with the correct name """ |
if identify_hdf5(origin, filepath, fileobj, *args, **kwargs) and (
filepath is not None and PYCBC_FILENAME.match(basename(filepath))):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_new_snr(h5group, q=6., n=2.):
# pylint: disable=invalid-name """Calculate the 'new SNR' column for this PyCBC HDF5 table group """ |
newsnr = h5group['snr'][:].copy()
rchisq = h5group['chisq'][:]
idx = numpy.where(rchisq > 1.)[0]
newsnr[idx] *= _new_snr_scale(rchisq[idx], q=q, n=n)
return newsnr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_mchirp(h5group):
"""Calculate the chipr mass column for this PyCBC HDF5 table group """ |
mass1 = h5group['mass1'][:]
mass2 = h5group['mass2'][:]
return (mass1 * mass2) ** (3/5.) / (mass1 + mass2) ** (1/5.) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_nd_slice(item, ndim):
"""Preformat a getitem argument as an N-tuple """ |
if not isinstance(item, tuple):
item = (item,)
return item[:ndim] + (None,) * (ndim - len(item)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def slice_axis_attributes(old, oldaxis, new, newaxis, slice_):
"""Set axis metadata for ``new`` by slicing an axis of ``old`` This is primarily for internal use ... |
slice_ = as_slice(slice_)
# attribute names
index = '{}index'.format
origin = '{}0'.format
delta = 'd{}'.format
# if array has an index set already, use it
if hasattr(old, '_{}index'.format(oldaxis)):
setattr(new, index(newaxis), getattr(old, index(oldaxis))[slice_])
# otherw... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def null_slice(slice_):
"""Returns True if a slice will have no affect """ |
try:
slice_ = as_slice(slice_)
except TypeError:
return False
if isinstance(slice_, numpy.ndarray) and numpy.all(slice_):
return True
if isinstance(slice_, slice) and slice_ in (
slice(None, None, None), slice(0, None, 1)
):
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_slice(slice_):
"""Convert an object to a slice, if possible """ |
if isinstance(slice_, (Integral, numpy.integer, type(None))):
return slice(0, None, 1)
if isinstance(slice_, (slice, numpy.ndarray)):
return slice_
if isinstance(slice_, (list, tuple)):
return tuple(map(as_slice, slice_))
raise TypeError("Cannot format {!r} as slice".format(s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query(name, use_kerberos=None, debug=False):
"""Query the Channel Information System for details on the given channel name Parameters name : `~gwpy.detector.... |
url = '%s/?q=%s' % (CIS_API_URL, name)
more = True
out = ChannelList()
while more:
reply = _get(url, use_kerberos=use_kerberos, debug=debug)
try:
out.extend(map(parse_json, reply[u'results']))
except KeyError:
pass
except TypeError: # reply is a ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get(url, use_kerberos=None, debug=False):
"""Perform a GET query against the CIS """ |
from ligo.org import request
# perform query
try:
response = request(url, debug=debug, use_kerberos=use_kerberos)
except HTTPError:
raise ValueError("Channel not found at URL %s "
"Information System. Please double check the "
"name and... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_json(data):
"""Parse the input data dict into a `Channel`. Parameters data : `dict` input data from CIS json query Returns ------- c : `Channel` a `Cha... |
sample_rate = data['datarate']
unit = data['units']
dtype = CIS_DATA_TYPE[data['datatype']]
model = data['source']
url = data['displayurl']
return Channel(data['name'], sample_rate=sample_rate, unit=unit,
dtype=dtype, model=model, url=url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_ylabel(self):
"""Text for y-axis label, check if channel defines it """ |
units = self.units
if len(units) == 1 and str(units[0]) == '': # dimensionless
return ''
if len(units) == 1 and self.usetex:
return units[0].to_string('latex')
elif len(units) == 1:
return units[0].to_string()
elif len(units) > 1:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_fft_plan(length, level=None, dtype='float64', forward=True):
"""Build a `REAL8FFTPlan` for a fast Fourier transform. Parameters length : `int` numbe... |
from ...utils.lal import (find_typed_function, to_lal_type_str)
# generate key for caching plan
laltype = to_lal_type_str(dtype)
key = (length, bool(forward), laltype)
# find existing plan
try:
return LAL_FFTPLANS[key]
# or create one
except KeyError:
create = find_typ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_window(length, window=None, dtype='float64'):
"""Generate a time-domain window for use in a LAL FFT Parameters length : `int` length of window in sa... |
from ...utils.lal import (find_typed_function, to_lal_type_str)
if window is None:
window = ('kaiser', 24)
# generate key for caching window
laltype = to_lal_type_str(dtype)
key = (length, str(window), laltype)
# find existing window
try:
return LAL_WINDOWS[key]
# or ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def window_from_array(array):
"""Convert a `numpy.ndarray` into a LAL `Window` object """ |
from ...utils.lal import (find_typed_function)
dtype = array.dtype
# create sequence
seq = find_typed_function(dtype, 'Create', 'Sequence')(array.size)
seq.data = array
# create window from sequence
return find_typed_function(dtype, 'Create', 'WindowFromSequence')(seq) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _lal_spectrum(timeseries, segmentlength, noverlap=None, method='welch', window=None, plan=None):
"""Generate a PSD `FrequencySeries` using |lal|_ Parameters ... |
import lal
from ...utils.lal import find_typed_function
# default to 50% overlap
if noverlap is None:
noverlap = int(segmentlength // 2)
stride = segmentlength - noverlap
# get window
if window is None:
window = generate_window(segmentlength, dtype=timeseries.dtype)
#... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def welch(timeseries, segmentlength, noverlap=None, window=None, plan=None):
"""Calculate an PSD of this `TimeSeries` using Welch's method Parameters timeseries ... |
return _lal_spectrum(timeseries, segmentlength, noverlap=noverlap,
method='welch', window=window, plan=plan) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bartlett(timeseries, segmentlength, noverlap=None, window=None, plan=None):
# pylint: disable=unused-argument """Calculate an PSD of this `TimeSeries` using ... |
return _lal_spectrum(timeseries, segmentlength, noverlap=0,
method='welch', window=window, plan=plan) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def median(timeseries, segmentlength, noverlap=None, window=None, plan=None):
"""Calculate a PSD of this `TimeSeries` using a median average method The median av... |
return _lal_spectrum(timeseries, segmentlength, noverlap=noverlap,
method='median', window=window, plan=plan) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def median_mean(timeseries, segmentlength, noverlap=None, window=None, plan=None):
"""Calculate a PSD of this `TimeSeries` using a median-mean average method The... |
return _lal_spectrum(timeseries, segmentlength, noverlap=noverlap,
method='median-mean', window=window, plan=plan) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_data_source(source):
"""Open a GWF file source into a `lalframe.XLALFrStream` object Parameters source : `str`, `file`, `list` Data source to read. Retu... |
if isinstance(source, FILE_LIKE):
source = source.name
if isinstance(source, CacheEntry):
source = source.path
# read cache file
if (isinstance(source, string_types) and
source.endswith(('.lcf', '.cache'))):
return lalframe.FrStreamCacheOpen(lal.CacheImport(source))... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_stream_duration(stream):
"""Find the duration of time stored in a frame stream Parameters stream : `lal.FrStream` stream of data to search Returns ------... |
epoch = lal.LIGOTimeGPS(stream.epoch.gpsSeconds,
stream.epoch.gpsNanoSeconds)
# loop over each file in the stream cache and query its duration
nfile = stream.cache.length
duration = 0
for dummy_i in range(nfile):
for dummy_j in range(lalframe.FrFileQueryNFrame(st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(source, channels, start=None, end=None, series_class=TimeSeries, scaled=None):
"""Read data from one or more GWF files using the LALFrame API """ |
# scaled must be provided to provide a consistent API with frameCPP
if scaled is not None:
warnings.warn(
"the `scaled` keyword argument is not supported by lalframe, "
"if you require ADC scaling, please install "
"python-ldas-tools-framecpp",
)
stream ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(tsdict, outfile, start=None, end=None, name='gwpy', run=0):
"""Write data to a GWF file using the LALFrame API """ |
if not start:
start = list(tsdict.values())[0].xspan[0]
if not end:
end = list(tsdict.values())[0].xspan[1]
duration = end - start
# get ifos list
detectors = 0
for series in tsdict.values():
try:
idx = list(lalutils.LAL_DETECTORS.keys()).index(series.channe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def segment_content_handler():
"""Build a `~xml.sax.handlers.ContentHandler` to read segment XML tables """ |
from ligo.lw.lsctables import (SegmentTable, SegmentDefTable,
SegmentSumTable)
from ligo.lw.ligolw import PartialLIGOLWContentHandler
def _filter(name, attrs):
return reduce(
operator.or_,
[table_.CheckProperties(name, attrs) for
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_ligolw_dict(source, names=None, coalesce=False, **kwargs):
"""Read segments for the given flag from the LIGO_LW XML file. Parameters source : `file`, `s... |
xmldoc = read_ligolw(source, contenthandler=segment_content_handler())
# parse tables
with patch_ligotimegps(type(xmldoc.childNodes[0]).__module__):
out = DataQualityDict.from_ligolw_tables(
*xmldoc.childNodes,
names=names,
**kwargs
)
# coalesce
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_ligolw_flag(source, name=None, **kwargs):
"""Read a single `DataQualityFlag` from a LIGO_LW XML file """ |
name = [name] if name is not None else None
return list(read_ligolw_dict(source, names=name, **kwargs).values())[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_ligolw(flags, target, attrs=None, ilwdchar_compat=None, **kwargs):
"""Write this `DataQualityFlag` to the given LIGO_LW Document Parameters flags : `Da... |
if isinstance(flags, DataQualityFlag):
flags = DataQualityDict({flags.name: flags})
return write_tables(
target,
flags.to_ligolw_tables(ilwdchar_compat=ilwdchar_compat,
**attrs or dict()),
**kwargs
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scale_timeseries_unit(tsunit, scaling='density'):
"""Scale the unit of a `TimeSeries` to match that of a `FrequencySeries` Parameters tsunit : `~astropy.unit... |
# set units
if scaling == 'density':
baseunit = units.Hertz
elif scaling == 'spectrum':
baseunit = units.dimensionless_unscaled
else:
raise ValueError("Unknown scaling: %r" % scaling)
if tsunit:
specunit = tsunit ** 2 / baseunit
else:
specunit = baseunit ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _iter_cache(cachefile, gpstype=LIGOTimeGPS):
"""Internal method that yields a `_CacheEntry` for each line in the file This method supports reading LAL- and (... |
try:
path = os.path.abspath(cachefile.name)
except AttributeError:
path = None
for line in cachefile:
try:
yield _CacheEntry.parse(line, gpstype=LIGOTimeGPS)
except ValueError:
# virgo FFL format (seemingly) supports nested FFL files
parts... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_cache(cachefile, coltype=LIGOTimeGPS, sort=None, segment=None):
"""Read a LAL- or FFL-format cache file as a list of file paths Parameters cachefile : `... |
# open file
if not isinstance(cachefile, FILE_LIKE):
with open(file_path(cachefile), 'r') as fobj:
return read_cache(fobj, coltype=coltype, sort=sort,
segment=segment)
# read file
cache = [x.path for x in _iter_cache(cachefile, gpstype=coltype)]
#... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_cache(cache, fobj, format=None):
"""Write a `list` of cache entries to a file Parameters cache : `list` of `str` The list of file paths to write fobj :... |
# open file
if isinstance(fobj, string_types):
with open(fobj, 'w') as fobj2:
return write_cache(cache, fobj2, format=format)
if format is None:
formatter = str
elif format.lower() == "lal":
formatter = _format_entry_lal
elif format.lower() == "ffl":
for... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_cache(cache):
"""Returns `True` if ``cache`` is a readable cache file or object Parameters cache : `str`, `file`, `list` Object to detect as cache Returns... |
if isinstance(cache, string_types + FILE_LIKE):
try:
return bool(len(read_cache(cache)))
except (TypeError, ValueError, UnicodeDecodeError, ImportError):
# failed to parse cache
return False
if HAS_CACHE and isinstance(cache, Cache):
return True
i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_cache_entry(path):
"""Returns `True` if ``path`` can be represented as a cache entry In practice this just tests whether the input is |LIGO-T050017|_ comp... |
if HAS_CACHEENTRY and isinstance(path, CacheEntry):
return True
try:
file_segment(path)
except (ValueError, TypeError, AttributeError):
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filename_metadata(filename):
"""Return metadata parsed from a filename following LIGO-T050017 This method is lenient with regards to integers in the GPS star... |
from ..segments import Segment
name = Path(filename).name
try:
obs, desc, start, dur = name.split('-')
except ValueError as exc:
exc.args = ('Failed to parse {!r} as LIGO-T050017-compatible '
'filename'.format(name),)
raise
start = float(start)
dur = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def file_segment(filename):
"""Return the data segment for a filename following T050017 Parameters --------- filename : `str`, :class:`~lal.utils.CacheEntry` the... |
from ..segments import Segment
try: # CacheEntry
return Segment(filename.segment)
except AttributeError: # file path (str)
return filename_metadata(filename)[2] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatten(*caches):
"""Flatten a nested list of cache entries Parameters *caches : `list` One or more lists of file paths (`str` or :class:`~lal.utils.CacheEnt... |
return list(OrderedDict.fromkeys(e for c in caches for e in c)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_contiguous(*caches):
"""Separate one or more cache entry lists into time-contiguous sub-lists Parameters *caches : `list` One or more lists of file path... |
flat = flatten(*caches)
for segment in cache_segments(flat):
yield sieve(flat, segment=segment) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sieve(cache, segment=None):
"""Filter the cache to find those entries that overlap ``segment`` Parameters cache : `list` Input list of file paths segment : `... |
return type(cache)(e for e in cache if segment.intersects(file_segment(e))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def arg_qxform(cls, parser):
"""Add an `~argparse.ArgumentGroup` for Q-transform options """ |
group = parser.add_argument_group('Q-transform options')
group.add_argument('--plot', nargs='+', type=float, default=[.5],
help='One or more times to plot')
group.add_argument('--frange', nargs=2, type=float,
help='Frequency range to plot')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_title(self):
"""Default title for plot """ |
def fformat(x): # float format
if isinstance(x, (list, tuple)):
return '[{0}]'.format(', '.join(map(fformat, x)))
if isinstance(x, Quantity):
x = x.value
elif isinstance(x, str):
warnings.warn('WARNING: fformat called with a' ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_spectrogram(self):
"""Worked on a single timesharing and generates a single Q-transform spectrogram""" |
args = self.args
asd = self.timeseries[0].asd().value
if (asd.min() == 0):
self.log(0, 'Input data has a zero in ASD. '
'Q-transform not possible.')
self.got_error = True
qtrans = None
else:
gps = self.qxfrm_args['gps... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ligotimegps(s, ns=0):
"""Catch TypeError and cast `s` and `ns` to `int` """ |
from lal import LIGOTimeGPS
try:
return LIGOTimeGPS(s, ns)
except TypeError:
return LIGOTimeGPS(int(s), int(ns)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def patch_ligotimegps(module="ligo.lw.lsctables"):
"""Context manager to on-the-fly patch LIGOTimeGPS to accept all int types """ |
module = import_module(module)
orig = module.LIGOTimeGPS
module.LIGOTimeGPS = _ligotimegps
try:
yield
finally:
module.LIGOTimeGPS = orig |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_partial_contenthandler(element):
"""Build a `PartialLIGOLWContentHandler` to read only this element Parameters element : `type`, subclass of :class:`~lig... |
from ligo.lw.ligolw import PartialLIGOLWContentHandler
from ligo.lw.table import Table
if issubclass(element, Table):
def _element_filter(name, attrs):
return element.CheckProperties(name, attrs)
else:
def _element_filter(name, _):
return name == element.tagName... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_filtering_contenthandler(element):
"""Build a `FilteringLIGOLWContentHandler` to exclude this element Parameters element : `type`, subclass of :class:`~l... |
from ligo.lw.ligolw import FilteringLIGOLWContentHandler
from ligo.lw.table import Table
if issubclass(element, Table):
def _element_filter(name, attrs):
return ~element.CheckProperties(name, attrs)
else:
def _element_filter(name, _):
# pylint: disable=unused-ar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_content_handler(parent, filter_func):
"""Build a `~xml.sax.handler.ContentHandler` with a given filter """ |
from ligo.lw.lsctables import use_in
class _ContentHandler(parent):
# pylint: disable=too-few-public-methods
def __init__(self, document):
super(_ContentHandler, self).__init__(document, filter_func)
return use_in(_ContentHandler) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_ligolw(source, contenthandler=LIGOLWContentHandler, **kwargs):
"""Read one or more LIGO_LW format files Parameters source : `str`, `file` the open file ... |
from ligo.lw.ligolw import Document
from ligo.lw import types
from ligo.lw.lsctables import use_in
from ligo.lw.utils import (load_url, ligolw_add)
# mock ToPyType to link to numpy dtypes
topytype = types.ToPyType.copy()
for key in types.ToPyType:
if key in types.ToNumPyType:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def with_read_ligolw(func=None, contenthandler=None):
"""Decorate a LIGO_LW-reading function to open a filepath if needed ``func`` should be written to presume a... |
def decorator(func_):
# pylint: disable=missing-docstring
@wraps(func_)
def decorated_func(source, *args, **kwargs):
# pylint: disable=missing-docstring
from ligo.lw.ligolw import Document
from glue.ligolw.ligolw import Document as GlueDocument
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_xmldoc(fobj, **kwargs):
"""Try and open an existing LIGO_LW-format file, or create a new Document Parameters fobj : `str`, `file` file path or open file... |
from ligo.lw.ligolw import (Document, LIGOLWContentHandler)
from ligo.lw.lsctables import use_in
from ligo.lw.utils import (load_filename, load_fileobj)
use_in(kwargs.setdefault('contenthandler', LIGOLWContentHandler))
try: # try and load existing file
if isinstance(fobj, string_types):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_tables(target, tables, append=False, overwrite=False, **kwargs):
"""Write an LIGO_LW table to file Parameters target : `str`, `file`, :class:`~ligo.lw.... |
from ligo.lw.ligolw import (Document, LIGO_LW, LIGOLWContentHandler)
from ligo.lw import utils as ligolw_utils
# allow writing directly to XML
if isinstance(target, (Document, LIGO_LW)):
xmldoc = target
# open existing document, if possible
elif append:
xmldoc = open_xmldoc(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_table_type(val, cls, colname):
"""Cast a value to the correct type for inclusion in a LIGO_LW table This method returns the input unmodified if a type map... |
from ligo.lw.types import (
ToNumPyType as numpytypes,
ToPyType as pytypes,
)
# if nothing to do...
if val is None or colname not in cls.validcolumns:
return val
llwtype = cls.validcolumns[colname]
# don't mess with formatted IlwdChar
if llwtype == 'ilwd:char':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_ligolw(origin, filepath, fileobj, *args, **kwargs):
"""Identify a file object as LIGO_LW-format XML """ |
# pylint: disable=unused-argument
if fileobj is not None:
loc = fileobj.tell()
fileobj.seek(0)
try:
line1 = fileobj.readline().lower()
line2 = fileobj.readline().lower()
try:
return (line1.startswith(XML_SIGNATURE) and
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_hdf5_timeseries(h5f, path=None, start=None, end=None, **kwargs):
"""Read a `TimeSeries` from HDF5 """ |
# read data
kwargs.setdefault('array_type', TimeSeries)
series = read_hdf5_array(h5f, path=path, **kwargs)
# crop if needed
if start is not None or end is not None:
return series.crop(start, end)
return series |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_hdf5_dict(h5f, names=None, group=None, **kwargs):
"""Read a `TimeSeriesDict` from HDF5 """ |
# find group from which to read
if group:
h5g = h5f[group]
else:
h5g = h5f
# find list of names to read
if names is None:
names = [key for key in h5g if _is_timeseries_dataset(h5g[key])]
# read names
out = kwargs.pop('dict_type', TimeSeriesDict)()
kwargs.setdef... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_hdf5_dict(tsdict, h5f, group=None, **kwargs):
"""Write a `TimeSeriesBaseDict` to HDF5 Each series in the dict is written as a dataset in the group """ |
# create group if needed
if group and group not in h5f:
h5g = h5f.create_group(group)
elif group:
h5g = h5f[group]
else:
h5g = h5f
# write each timeseries
kwargs.setdefault('format', 'hdf5')
for key, series in tsdict.items():
series.write(h5g, path=str(key),... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def welch(timeseries, segmentlength, noverlap=None, scheme=None, **kwargs):
"""Calculate a PSD using Welch's method with a mean average Parameters timeseries : `... |
from pycbc.psd import welch as pycbc_welch
# default to 'standard' welch
kwargs.setdefault('avg_method', 'mean')
# get scheme
if scheme is None:
scheme = null_context()
# generate pycbc FrequencySeries
with scheme:
pycbc_fseries = pycbc_welch(timeseries.to_pycbc(copy=Fals... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ordinal(n):
"""Returns the ordinal string for a given integer See https://stackoverflow.com/a/20007730/1307974 Parameters n : `int` the number to convert to... |
idx = int((n//10 % 10 != 1) * (n % 10 < 4) * n % 10)
return '{}{}'.format(n, "tsnrhtdd"[idx::4]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ratio(self, operand):
"""Calculate the ratio of this `Spectrogram` against a reference Parameters operand : `str`, `FrequencySeries`, `Quantity` a `~gwpy.fre... |
if isinstance(operand, string_types):
if operand == 'mean':
operand = self.mean(axis=0)
elif operand == 'median':
operand = self.median(axis=0)
else:
raise ValueError("operand %r unrecognised, please give a "
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot(self, figsize=(12, 6), xscale='auto-gps', **kwargs):
"""Plot the data for this `Spectrogram` Parameters **kwargs all keyword arguments are passed along ... |
if 'imshow' in kwargs:
warnings.warn('the imshow keyword for Spectrogram.plot was '
'removed, please pass method=\'imshow\' instead',
DeprecationWarning)
kwargs.setdefault('method', 'imshow' if kwargs.pop('imshow') else
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_spectra(cls, *spectra, **kwargs):
"""Build a new `Spectrogram` from a list of spectra. Parameters *spectra any number of `~gwpy.frequencyseries.Frequenc... |
data = numpy.vstack([s.value for s in spectra])
spec1 = list(spectra)[0]
if not all(s.f0 == spec1.f0 for s in spectra):
raise ValueError("Cannot stack spectra with different f0")
if not all(s.df == spec1.df for s in spectra):
raise ValueError("Cannot stack spectr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def percentile(self, percentile):
"""Calculate a given spectral percentile for this `Spectrogram`. Parameters percentile : `float` percentile (0 - 100) of the bi... |
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,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def variance(self, bins=None, low=None, high=None, nbins=500, log=False, norm=False, density=False):
"""Calculate the `SpectralVariance` of this `Spectrogram`. P... |
from ..frequencyseries import SpectralVariance
return SpectralVariance.from_spectrogram(
self, bins=bins, low=low, high=high, nbins=nbins, log=log,
norm=norm, density=density) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def crop_frequencies(self, low=None, high=None, copy=False):
"""Crop this `Spectrogram` to the specified frequencies Parameters low : `float` lower frequency bou... |
if low is not None:
low = units.Quantity(low, self._default_yunit)
if high is not None:
high = units.Quantity(high, self._default_yunit)
# check low frequency
if low is not None and low == self.f0:
low = None
elif low is not None and low < sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_mappable(*axes):
"""Find the most recently added mappable layer in the given axes Parameters *axes : `~matplotlib.axes.Axes` one or more axes to search ... |
for ax in axes:
for aset in ('collections', 'images'):
try:
return getattr(ax, aset)[-1]
except (AttributeError, IndexError):
continue
raise ValueError("Cannot determine mappable layer on any axes "
"for this colorbar") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_read_format(cls, source, args, kwargs):
"""Determine the read format for a given input source """ |
ctx = None
if isinstance(source, FILE_LIKE):
fileobj = source
filepath = source.name if hasattr(source, 'name') else None
else:
filepath = source
try:
ctx = get_readable_fileobj(filepath, encoding='binary')
fileobj = ctx.__enter__() # pylint: disable... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(fobj, **kwargs):
"""Read a WAV file into a `TimeSeries` Parameters fobj : `file`, `str` open file-like object or filename to read from **kwargs all keyw... |
fsamp, arr = wavfile.read(fobj, **kwargs)
return TimeSeries(arr, sample_rate=fsamp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(series, output, scale=None):
"""Write a `TimeSeries` to a WAV file Parameters series : `TimeSeries` the series to write output : `file`, `str` the file... |
fsamp = int(series.sample_rate.decompose().value)
if scale is None:
scale = 1 / numpy.abs(series.value).max()
data = (series.value * scale).astype('float32')
return wavfile.write(output, fsamp, data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_wav(origin, filepath, fileobj, *args, **kwargs):
"""Identify a file as WAV See `astropy.io.registry` for details on how this function is used. """ |
# pylint: disable=unused-argument
if origin == 'read' and fileobj is not None:
loc = fileobj.tell()
fileobj.seek(0)
try:
riff, _, fmt = struct.unpack('<4sI4s', fileobj.read(12))
if isinstance(riff, bytes):
riff = riff.decode('utf-8')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_column_filter(definition):
"""Parse a `str` of the form 'column>50' Parameters definition : `str` a column filter definition of the form ``<name><opera... | # noqa
# parse definition into parts (skipping null tokens)
parts = list(generate_tokens(StringIO(definition.strip()).readline))
while parts[-1][0] in (token.ENDMARKER, token.NEWLINE):
parts = parts[:-1]
# parse simple definition: e.g: snr > 5
if len(parts) == 3:
a, b, c = parts ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_column_filters(*definitions):
"""Parse multiple compound column filter definitions Examples -------- [('snr', <function operator.gt>, 10.), ('frequency... | # noqa: E501
fltrs = []
for def_ in _flatten(definitions):
if is_filter_tuple(def_):
fltrs.append(def_)
else:
for splitdef in DELIM_REGEX.split(def_)[::2]:
fltrs.extend(parse_column_filter(splitdef))
return fltrs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _flatten(container):
"""Flatten arbitrary nested list of filters into a 1-D list """ |
if isinstance(container, string_types):
container = [container]
for elem in container:
if isinstance(elem, string_types) or is_filter_tuple(elem):
yield elem
else:
for elem2 in _flatten(elem):
yield elem2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_filter_tuple(tup):
"""Return whether a `tuple` matches the format for a column filter """ |
return isinstance(tup, (tuple, list)) and (
len(tup) == 3 and
isinstance(tup[0], string_types) and
callable(tup[1])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter_table(table, *column_filters):
"""Apply one or more column slice filters to a `Table` Multiple column filters can be given, and will be applied concur... |
keep = numpy.ones(len(table), dtype=bool)
for name, op_func, operand in parse_column_filters(*column_filters):
col = table[name].view(numpy.ndarray)
keep &= op_func(col, operand)
return table[keep] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_hdf5_array(source, path=None, array_type=Array):
"""Read an `Array` from the given HDF5 object Parameters source : `str`, :class:`h5py.HLObject` path to... |
dataset = io_hdf5.find_dataset(source, path=path)
attrs = dict(dataset.attrs)
# unpickle channel object
try:
attrs['channel'] = _unpickle_channel(attrs['channel'])
except KeyError: # no channel stored
pass
# unpack byte strings for python3
for key in attrs:
if isins... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _unpickle_channel(raw):
"""Try and unpickle a channel with sensible error handling """ |
try:
return pickle.loads(raw)
except (ValueError, pickle.UnpicklingError, EOFError, TypeError,
IndexError) as exc:
# maybe not pickled
if isinstance(raw, bytes):
raw = raw.decode('utf-8')
try: # test if this is a valid channel name
Channel.MA... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_metadata_attribute(value):
"""Format a value for writing to HDF5 as a `h5py.Dataset` attribute """ |
if (value is None or
(isinstance(value, Index) and value.regular)):
raise IgnoredAttribute
# map type to something HDF5 can handle
for typekey, func in ATTR_TYPE_MAP.items():
if issubclass(type(value), typekey):
return func(value)
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_array_metadata(dataset, array):
"""Write metadata for ``array`` into the `h5py.Dataset` """ |
for attr in ('unit',) + array._metadata_slots:
# format attribute
try:
value = _format_metadata_attribute(
getattr(array, '_%s' % attr, None))
except IgnoredAttribute:
continue
# store attribute
try:
dataset.attrs[attr] = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_hdf5_array(array, h5g, path=None, attrs=None, append=False, overwrite=False, compression='gzip', **kwargs):
"""Write the ``array`` to an `h5py.Dataset`... |
if path is None:
path = array.name
if path is None:
raise ValueError("Cannot determine HDF5 path for %s, "
"please set ``name`` attribute, or pass ``path=`` "
"keyword when writing" % type(array).__name__)
# create dataset
dset = io_hdf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_index_array_attrs(series):
"""Format metadata attributes for and indexed array This function is used to provide the necessary metadata to meet the (pr... |
attrs = {}
# loop through named axes
for i, axis in zip(range(series.ndim), ('x', 'y')):
# find property names
unit = '{}unit'.format(axis)
origin = '{}0'.format(axis)
delta = 'd{}'.format(axis)
# store attributes
aunit = getattr(series, unit)
attrs.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_hdf5_series(series, output, path=None, attrs=None, **kwargs):
"""Write a Series to HDF5. See :func:`write_hdf5_array` for details of arguments and keyw... |
if attrs is None:
attrs = format_index_array_attrs(series)
return write_hdf5_array(series, output, path=path, attrs=attrs, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_multi(flatten, cls, source, *args, **kwargs):
"""Read sources into a `cls` with multiprocessing This method should be called by `cls.read` and uses the ... |
verbose = kwargs.pop('verbose', False)
# parse input as a list of files
try: # try and map to a list of file-like objects
files = file_list(source)
except ValueError: # otherwise treat as single file
files = [source]
path = None # to pass to get_read_format()
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.