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`, `Quantity`, `None` the overlap in some physical unit (seconds) window : `str` the name of the window function that will be used, only used if `overlap=None` is given nfft : `int` the number of samples that will be used in the fast Fourier transform samp : `Quantity` the sampling rate (Hz) of the data that will be transformed method : `str` the name of the averaging method, default: `'welch'`, only used to return `0` for `'bartlett'` averaging Returns ------- noverlap : `int` the number of samples to be be used for the overlap """
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` the input window specification nfft : `int` the length of the Fourier transform, in samples library : `str` the name of the library that provides the PSD routine dtype : `type` the required type of the window array, only used if `library='lal'` is given Returns ------- window : `numpy.ndarray`, `lal.REAL8Window` a numpy-, or `LAL`-format window array """
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_types): window = canonical_name(window) if isinstance(window, string_types + (tuple,)): return get_window(window, nfft) return None
<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 normalize_fft_params(data, kwargs=kwargs, func=method_func) return func(series, method_func, *args, **kwargs) return wrapped_func
<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 timeseries : `~gwpy.timeseries.TimeSeries`, `tuple` the data to process, or a 2-tuple of series to correlate method_func : `callable` the function that will be called to perform the signal processing *args, **kwargs other arguments to pass to ``method_func`` when calling """
# 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 sample counts, not physical units Parameters timeseries : `~gwpy.timeseries.TimeSeries`, `tuple` the data to process, or a 2-tuple of series to correlate method_func : `callable` the function that will be called to perform the signal processing *args, **kwargs other arguments to pass to ``method_func`` when calling """
# 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'), *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 average_spectrogram(timeseries, method_func, stride, *args, **kwargs): """Generate an average spectrogram using a method function Each time bin of the resulting spectrogram is a PSD generated using the method_func """
# 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 nstride = seconds_to_samples(stride, timeseries.sample_rate) kwargs['fftlength'] = kwargs.pop('fftlength', stride) or stride normalize_fft_params(timeseries, kwargs=kwargs, func=method_func) nfft = kwargs['nfft'] noverlap = kwargs['noverlap'] # sanity check parameters if nstride > timeseries.size: raise ValueError("stride cannot be greater than the duration of " "this TimeSeries") if nfft > nstride: raise ValueError("fftlength cannot be greater than stride") if noverlap >= nfft: raise ValueError("overlap must be less than fftlength") # set up single process Spectrogram method def _psd(series): """Calculate a single PSD for a spectrogram """ psd_ = _psdn(series, method_func, *args, **kwargs) del psd_.epoch # fixes Segmentation fault (no idea why it faults) return psd_ # define chunks tschunks = _chunk_timeseries(timeseries, nstride, noverlap) if other is not None: otherchunks = _chunk_timeseries(other, nstride, noverlap) tschunks = zip(tschunks, otherchunks) # calculate PSDs psds = mp_utils.multiprocess_with_queues(nproc, _psd, tschunks) # recombobulate PSDs into a spectrogram return Spectrogram.from_spectra(*psds, epoch=epoch, dt=stride)
<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 estimate using a single FFT """
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 ValueError("overlap must be less than fftlength") # set up single process Spectrogram method def _psd(series): """Calculate a single PSD for a spectrogram """ return method_func(series, nfft=nfft, **kwargs)[1] # define chunks chunks = [] x = 0 while x + nfft <= timeseries.size: y = min(timeseries.size, x + nfft) chunks.append((x, y)) x += nstride tschunks = (timeseries.value[i:j] for i, j in chunks) # calculate PSDs with multiprocessing psds = mp_utils.multiprocess_with_queues(nproc, _psd, tschunks) # convert PSDs to array with spacing for averages numtimes = 1 + int((timeseries.size - nstride) / nstride) numfreqs = int(nfft / 2 + 1) data = numpy.zeros((numtimes, numfreqs), dtype=timeseries.dtype) data[:len(psds)] = psds # create output spectrogram unit = fft_utils.scale_timeseries_unit( timeseries.unit, scaling=kwargs.get('scaling', 'density')) out = Spectrogram(numpy.empty((numtimes, numfreqs), dtype=timeseries.dtype), copy=False, dt=nstride * timeseries.dt, t0=timeseries.t0, f0=0, df=sampling/nfft, unit=unit, name=timeseries.name, channel=timeseries.channel) # normalize over-dense grid density = nfft // nstride weights = get_window('triangle', density) for i in range(numtimes): # get indices of overlapping columns x = max(0, i+1-density) y = min(i+1, numtimes-density+1) if x == 0: wgt = weights[-y:] elif y == numtimes - density + 1: wgt = weights[:y-x] else: wgt = weights # calculate weighted average out.value[i, :] = numpy.average(data[x:y], axis=0, weights=wgt) return out
<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})'.format(self.units[0].to_string('generic')) return super(Spectrogram, self).get_color_label()
<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 `TimeSeries.spectrogram2`. """
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 * stride + fftlength - 1) return None
<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 `get_plot` method, e.g. `Coherencegram`. This method should not apply the normalisation from `args.norm`. """
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].spectrogram( stride, fftlength=fftlength, overlap=overlap, window=args.window) nfft = stride * (stride // (fftlength - overlap)) self.log(3, 'Spectrogram calc, stride: %s, fftlength: %s, ' 'overlap: %sf, #fft: %d' % (stride, fftlength, overlap, nfft)) else: specgram = self.timeseries[0].spectrogram2( fftlength=fftlength, overlap=overlap, window=args.window) nfft = specgram.shape[0] self.log(3, 'HR-Spectrogram calc, fftlength: %s, overlap: %s, ' '#fft: %d' % (fftlength, overlap, nfft)) return specgram ** (1/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 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`, and `TimeSeriesDict.read`, and isn't meant to be called directly. """
# 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 pad = kwargs.pop('pad', None) gap = kwargs.pop('gap', 'raise' if pad is None else 'pad') joiner = _join_factory(cls, gap, pad) # read return io_read_multi(joiner, cls, source, *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 _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 def _join(arrays): list_ = TimeSeriesBaseList(*arrays) return list_.join(pad=pad, gap=gap) return _join
<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 Parameters source : `str`, `h5py.File`, `h5py.Group` the file path of open `h5py` object from which to read the data ifo : `str`, optional the interferometer prefix (e.g. ``'G1'``) to read; this is required if reading from a file path or `h5py.File` and the containing file stores data for multiple interferometers columns : `list` or `str`, optional the list of column names to read, defaults to all in group loudest : `bool`, optional read only those events marked as 'loudest', default: `False` (read all) extended_metadata : `bool`, optional record non-column datasets found in the H5 group (e.g. ``'psd'``) in the ``meta`` dict, default: `True` Returns ------- table : `~gwpy.table.EventTable` """
# 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 selections selection = parse_column_filters(selection or []) if selection: readcols.update(list(zip(*selection))[0]) # set up meta dict meta = {'ifo': ifo} meta.update(source.attrs) if extended_metadata: meta.update(_get_extended_metadata(source)) if loudest: loudidx = source['loudest'][:] # map data to columns data = [] for name in readcols: # convert hdf5 dataset into Column try: arr = source[name][:] except KeyError: if name in GET_COLUMN: arr = GET_COLUMN[name](source) else: raise if loudest: arr = arr[loudidx] data.append(Table.Column(arr, name=name)) # read, applying selection filters, and column filters return filter_table(Table(data, meta=meta), selection)[columns]
<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 " "the prefix of the relevant interferometer via " "the `ifo` keyword argument, e.g: `ifo=G1`",) raise try: return h5file[ifo], ifo except KeyError as exc: exc.args = ("No group for ifo %r in PyCBC live HDF5 file" % ifo,) raise
<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_COLUMNS
<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 into a metadata `dict` Returns ------- meta : `dict` the metadata dict """
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 in META_COLUMNS - {'psd'}: try: value = h5group[key][:] except KeyError: pass else: meta[key] = value return meta
<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`, optional prefix for the interferometer of interest (e.g. ``'L1'``), include this for a more robust test of 'emptiness' Returns ------- nonempty : `list` the subset of the input ``files`` that are considered not empty See also -------- empty_hdf5_file for details of the 'emptiness' test """
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 the ``ifo`` group contains only the ``psd`` dataset. Parameters h5f : `str` path of the pycbc_live file to test ifo : `str`, optional prefix for the interferometer of interest (e.g. ``'L1'``), include this for a more robust test of 'emptiness' Returns ------- empty : `bool` `True` if the file looks to have no content, otherwise `False` """
# 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 in slice functions (__getitem__) Parameters old : `Array` array being sliced oldaxis : ``'x'`` or ``'y'`` the axis to slice new : `Array` product of slice newaxis : ``'x'`` or ``'y'`` the target axis slice_ : `slice`, `numpy.ndarray` the slice to apply to old (or an index array) See Also -------- Series.__getitem__ Array2D.__getitem__ """
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_]) # otherwise if using a slice, use origin and delta properties elif isinstance(slice_, slice) or not numpy.sum(slice_): if isinstance(slice_, slice): offset = slice_.start or 0 step = slice_.step or 1 else: # empty ndarray slice (so just set attributes) offset = 0 step = 1 dx = getattr(old, delta(oldaxis)) x0 = getattr(old, origin(oldaxis)) # set new.x0 / new.y0 setattr(new, origin(newaxis), x0 + offset * dx) # set new.dx / new.dy setattr(new, delta(newaxis), dx * step) # otherwise slice with an index array else: setattr(new, index(newaxis), getattr(old, index(oldaxis))[slice_]) return new
<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(slice_))
<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.Channel`, or `str` Name of the channel of interest Returns ------- channel : `~gwpy.detector.Channel` Channel with all details as acquired from the CIS """
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 list out.extend(map(parse_json, reply)) break more = 'next' in reply and reply['next'] is not None if more: url = reply['next'] else: break out.sort(key=lambda c: c.name) return out
<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 try again." % url) if isinstance(response, bytes): response = response.decode('utf-8') return json.loads(response)
<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 `Channel` built from the data """
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: return 'Multiple units' return super(TimeSeries, self).get_ylabel()
<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` number of samples to plan for in each FFT. level : `int`, optional amount of work to do when planning the FFT, default set by `LAL_FFTPLAN_LEVEL` module variable. dtype : :class:`numpy.dtype`, `type`, `str`, optional numeric type of data to plan for forward : bool, optional, default: `True` whether to create a forward or reverse FFT plan Returns ------- plan : `REAL8FFTPlan` or similar FFT plan of the relevant data type """
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_typed_function(dtype, 'Create', 'FFTPlan') if level is None: level = LAL_FFTPLAN_LEVEL LAL_FFTPLANS[key] = create(length, int(bool(forward)), level) return LAL_FFTPLANS[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 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 samples. window : `str`, `tuple` name of window to generate, default: ``('kaiser', 24)``. Give `str` for simple windows, or tuple of ``(name, *args)`` for complicated windows dtype : :class:`numpy.dtype` numeric type of window, default `numpy.dtype(numpy.float64)` Returns ------- `window` : `REAL8Window` or similar time-domain window to use for FFT """
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 create one except KeyError: # parse window as name and arguments, e.g. ('kaiser', 24) if isinstance(window, (list, tuple)): window, beta = window else: beta = 0 window = canonical_name(window) # create window create = find_typed_function(dtype, 'CreateNamed', 'Window') LAL_WINDOWS[key] = create(window, beta, length) return LAL_WINDOWS[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 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 timeseries : `~gwpy.timeseries.TimeSeries` input `TimeSeries` data. segmentlength : `int` number of samples in single average. method : `str` average PSD method noverlap : `int` number of samples to overlap between segments, defaults to 50%. window : `lal.REAL8Window`, optional window to apply to timeseries prior to FFT plan : `lal.REAL8FFTPlan`, optional LAL FFT plan to use when generating average spectrum Returns ------- spectrum : `~gwpy.frequencyseries.FrequencySeries` average power `FrequencySeries` """
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) # get FFT plan if plan is None: plan = generate_fft_plan(segmentlength, dtype=timeseries.dtype) method = method.lower() # check data length size = timeseries.size numsegs = 1 + int((size - segmentlength) / stride) if method == 'median-mean' and numsegs % 2: numsegs -= 1 if not numsegs: raise ValueError("Cannot calculate median-mean spectrum with " "this small a TimeSeries.") required = int((numsegs - 1) * stride + segmentlength) if size != required: warnings.warn("Data array is the wrong size for the correct number " "of averages given the input parameters. The trailing " "%d samples will not be used in this calculation." % (size - required)) timeseries = timeseries[:required] # 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
<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 : `~gwpy.timeseries.TimeSeries` input `TimeSeries` data. segmentlength : `int` number of samples in single average. noverlap : `int` number of samples to overlap between segments, defaults to 50%. window : `tuple`, `str`, optional window parameters to apply to timeseries prior to FFT plan : `REAL8FFTPlan`, optional LAL FFT plan to use when generating average spectrum Returns ------- spectrum : `~gwpy.frequencyseries.FrequencySeries` average power `FrequencySeries` See also -------- lal.REAL8AverageSpectrumWelch """
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 Bartlett's method Parameters timeseries : `~gwpy.timeseries.TimeSeries` input `TimeSeries` data. segmentlength : `int` number of samples in single average. noverlap : `int` number of samples to overlap between segments, defaults to 50%. window : `tuple`, `str`, optional window parameters to apply to timeseries prior to FFT plan : `REAL8FFTPlan`, optional LAL FFT plan to use when generating average spectrum Returns ------- spectrum : `~gwpy.frequencyseries.FrequencySeries` average power `FrequencySeries` See also -------- lal.REAL8AverageSpectrumWelch """
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 average is similar to Welch's method, using a median average rather than mean. Parameters timeseries : `~gwpy.timeseries.TimeSeries` input `TimeSeries` data. segmentlength : `int` number of samples in single average. noverlap : `int` number of samples to overlap between segments, defaults to 50%. window : `tuple`, `str`, optional window parameters to apply to timeseries prior to FFT plan : `REAL8FFTPlan`, optional LAL FFT plan to use when generating average spectrum Returns ------- spectrum : `~gwpy.frequencyseries.FrequencySeries` average power `FrequencySeries` See also -------- lal.REAL8AverageSpectrumMedian """
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 median-mean average method divides overlapping segments into "even" and "odd" segments, and computes the bin-by-bin median of the "even" segments and the "odd" segments, and then takes the bin-by-bin average of these two median averages. Parameters timeseries : `~gwpy.timeseries.TimeSeries` input `TimeSeries` data. segmentlength : `int` number of samples in single average. noverlap : `int` number of samples to overlap between segments, defaults to 50%. window : `tuple`, `str`, optional window parameters to apply to timeseries prior to FFT plan : `REAL8FFTPlan`, optional LAL FFT plan to use when generating average spectrum Returns ------- spectrum : `~gwpy.frequencyseries.FrequencySeries` average power `FrequencySeries` See also -------- lal.REAL8AverageSpectrumMedianMean """
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. Returns ------- stream : `lalframe.FrStream` An open `FrStream`. Raises ------ ValueError If the input format cannot be identified. """
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)) # read glue cache object if isinstance(source, list) and is_cache(source): cache = lal.Cache() for entry in file_list(source): cache = lal.CacheMerge(cache, lal.CacheGlob(*os.path.split(entry))) return lalframe.FrStreamCacheOpen(cache) # read lal cache object if isinstance(source, lal.Cache): return lalframe.FrStreamCacheOpen(source) # read single file if isinstance(source, string_types): return lalframe.FrStreamOpen(*map(str, os.path.split(source))) raise ValueError("Don't know how to open data source of type %r" % type(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 ------- duration : `float` the duration (seconds) of the data for this channel """
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(stream.file)): duration += lalframe.FrFileQueryDt(stream.file, 0) lalframe.FrStreamNext(stream) # rewind stream and return lalframe.FrStreamSeek(stream, epoch) return duration
<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 = open_data_source(source) # parse times and restrict to available data epoch = lal.LIGOTimeGPS(stream.epoch.gpsSeconds, stream.epoch.gpsNanoSeconds) streamdur = get_stream_duration(stream) if start is None: start = epoch else: start = max(epoch, lalutils.to_lal_ligotimegps(start)) if end is None: offset = float(start - epoch) duration = streamdur - offset else: end = min(epoch + streamdur, lalutils.to_lal_ligotimegps(end)) duration = float(end - start) # read data out = series_class.DictClass() for name in channels: out[name] = series_class.from_lal( _read_channel(stream, str(name), start=start, duration=duration), copy=False) lalframe.FrStreamSeek(stream, epoch) return out
<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.channel.ifo) detectors |= 1 << 2*idx except (KeyError, AttributeError): continue # create new frame frame = lalframe.FrameNew(start, duration, name, run, 0, detectors) for series in tsdict.values(): # convert to LAL lalseries = series.to_lal() # find adder add_ = lalutils.find_typed_function( series.dtype, 'FrameAdd', 'TimeSeriesProcData', module=lalframe) # add time series to frame add_(frame, lalseries) # write frame lalframe.FrameWrite(frame, outfile)
<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 table_ in (SegmentTable, SegmentDefTable, SegmentSumTable)]) return build_content_handler(PartialLIGOLWContentHandler, _filter)
<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`, `str`, :class:`~ligo.lw.ligolw.Document`, `list` one (or more) open files or file paths, or LIGO_LW `Document` objects names : `list`, `None`, optional list of names to read or `None` to read all into a single `DataQualityFlag`. coalesce : `bool`, optional if `True`, coalesce all parsed `DataQualityFlag` objects before returning, default: `False` **kwargs other keywords are passed to :meth:`DataQualityDict.from_ligolw_tables` Returns ------- flagdict : `DataQualityDict` a new `DataQualityDict` of `DataQualityFlag` entries with ``active`` and ``known`` segments seeded from the XML tables in the given file ``fp``. """
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 if coalesce: for flag in out: out[flag].coalesce() return out
<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 : `DataQualityFlag`, `DataQualityDict` `gwpy.segments` object to write target : `str`, `file`, :class:`~ligo.lw.ligolw.Document` the file or document to write into attrs : `dict`, optional extra attributes to write into segment tables **kwargs keyword arguments to use when writing See also -------- gwpy.io.ligolw.write_ligolw_tables for details of acceptable keyword arguments """
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.units.UnitBase` input unit from `TimeSeries` scaling : `str` type of frequency series, either 'density' for a PSD, or 'spectrum' for a power spectrum. Returns ------- unit : `~astropy.units.Unit` unit to be applied to the resulting `FrequencySeries`. """
# 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 ** -1 return specunit
<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 (nested) FFL-format cache files. """
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 = line.split() if len(parts) == 3 and os.path.abspath(parts[0]) != path: with open(parts[0], 'r') as cache2: for entry in _iter_cache(cache2): yield entry else: raise
<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 : `str`, `file` Input file or file path to read. coltype : `LIGOTimeGPS`, `int`, optional Type for GPS times. sort : `callable`, optional A callable key function by which to sort the output list of file paths segment : `gwpy.segments.Segment`, optional A GPS `[start, stop)` interval, if given only files overlapping this interval will be returned. Returns ------- paths : `list` of `str` A list of file paths as read from the cache file. """
# 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)] # sieve and sort if segment: cache = sieve(cache, segment=segment) if sort: cache.sort(key=sort) # read simple paths return cache
<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 : `file`, `str` The open file object, or file path to write to. format : `str`, optional The format to write to, one of - `None` : format each entry using `str` - ``'lal'`` : write a LAL-format cache - ``'ffl'`` : write an FFL-format cache """
# 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": formatter = _format_entry_ffl else: raise ValueError("Unrecognised cache format {!r}".format(format)) # write file for line in map(formatter, cache): try: print(line, file=fobj) except TypeError: # bytes-mode fobj.write("{}\n".format(line).encode("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 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 ------- iscache : `bool` `True` if the input object is a cache, or a file in LAL cache format, otherwise `False` """
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 if (isinstance(cache, (list, tuple)) and cache and all(map(is_cache_entry, cache))): 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 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|_ compliant. Parameters path : `str`, :class:`lal.utils.CacheEntry` The input to test Returns ------- isentry : `bool` `True` if ``path`` is an instance of `CacheEntry`, or can be parsed using |LIGO-T050017|_. """
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 start time of the file, as opposed to `gwdatafind.utils.filename_metadata`, which is strict. Parameters filename : `str` the path name of a file Returns ------- obs : `str` the observatory metadata tag : `str` the file tag segment : `gwpy.segments.Segment` the GPS ``[float, float)`` interval for this file Notes ----- `LIGO-T050017 <https://dcc.ligo.org/LIGO-T050017>`__ declares a file naming convention that includes documenting the GPS start integer and integer duration of a file, see that document for more details. Examples -------- ('A', 'B', Segment(0, 1)) ("A", "B", Segment(0.456, 1.801)) """
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 = dur.rsplit('.', 1)[0] while True: # recursively remove extension components try: dur = float(dur) except ValueError: if '.' not in dur: raise dur = dur.rsplit('.', 1)[0] else: break return obs, desc, Segment(start, 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 path name of a file Returns ------- segment : `~gwpy.segments.Segment` the ``[start, stop)`` GPS segment covered by the given file Notes ----- |LIGO-T050017|_ declares a filenaming convention that includes documenting the GPS start integer and integer duration of a file, see that document for more details. """
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.CacheEntry`). Returns ------- flat : `list` A flat `list` containing the unique set of entries across each input. """
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 paths (`str` or :class:`~lal.utils.CacheEntry`). Returns ------- caches : `iter` of `list` an interable yielding each contiguous cache """
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 : `~gwpy.segments.Segment` The ``[start, stop)`` interval to match against. """
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') group.add_argument('--qrange', nargs=2, type=float, help='Search Q range') group.add_argument('--nowhiten', action='store_true', help='do not whiten input before transform')
<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' + ' string. This has ' + 'been depricated and may disappear ' + 'in a future release.') x = float(x) return '{0:.2f}'.format(x) bits = [('Q', fformat(self.result.q))] bits.append(('tres', '{:.3g}'.format(self.qxfrm_args['tres']))) if self.qxfrm_args.get('qrange'): bits.append(('q-range', fformat(self.qxfrm_args['qrange']))) if self.qxfrm_args['whiten']: bits.append(('whitened',)) bits.extend([ ('f-range', fformat(self.result.yspan)), ('e-range', '[{:.3g}, {:.3g}]'.format(self.result.min(), self.result.max())), ]) return ', '.join([': '.join(bit) for bit in bits])
<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'] outseg = Segment(gps, gps).protract(args.plot[self.plot_num]) # This section tries to optimize the amount of data that is # processed and the time resolution needed to create a good # image. NB:For each time span specified # NB: the timeseries h enough data for the longest plot inseg = outseg.protract(4) & self.timeseries[0].span proc_ts = self.timeseries[0].crop(*inseg) # time resolution is calculated to provide about 4 times # the number of output pixels for interpolation tres = float(outseg.end - outseg.start) / 4 / self.args.nx self.qxfrm_args['tres'] = tres self.qxfrm_args['search'] = int(len(proc_ts) * proc_ts.dt.value) self.log(3, 'Q-transform arguments:') self.log(3, '{0:>15s} = {1}'.format('outseg', outseg)) for key in sorted(self.qxfrm_args): self.log(3, '{0:>15s} = {1}'.format(key, self.qxfrm_args[key])) qtrans = proc_ts.q_transform(outseg=outseg, **self.qxfrm_args) if args.ymin is None: # set before Spectrogram.make_plot args.ymin = qtrans.yspan[0] return qtrans
<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:`~ligo.lw.ligolw.Element` the element class to be read, Returns ------- contenthandler : `type` a subclass of :class:`~ligo.lw.ligolw.PartialLIGOLWContentHandler` to read only the given `element` """
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 return build_content_handler(PartialLIGOLWContentHandler, _element_filter)
<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:`~ligo.lw.ligolw.Element` the element to exclude (and its children) Returns ------- contenthandler : `type` a subclass of :class:`~ligo.lw.ligolw.FilteringLIGOLWContentHandler` to exclude an element and its children """
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-argument return name != element.tagName return build_content_handler(FilteringLIGOLWContentHandler, _element_filter)
<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 or file path to read contenthandler : `~xml.sax.handler.ContentHandler`, optional content handler used to parse document verbose : `bool`, optional be verbose when reading files, default: `False` Returns ------- xmldoc : :class:`~ligo.lw.ligolw.Document` the document object as parsed from the file(s) """
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: types.ToPyType[key] = numpy.dtype(types.ToNumPyType[key]).type contenthandler = use_in(contenthandler) # read one or more files into a single Document source = file_list(source) try: if len(source) == 1: return load_url( source[0], contenthandler=contenthandler, **kwargs ) return ligolw_add.ligolw_add( Document(), source, contenthandler=contenthandler, **kwargs ) except LigolwElementError as exc: # failed to read with ligo.lw, # try again with glue.ligolw (ilwdchar_compat) if LIGO_LW_COMPAT_ERROR.search(str(exc)): try: return read_ligolw( source, contenthandler=contenthandler, ilwdchar_compat=True, **kwargs ) except Exception: # if fails for any reason, use original error pass raise finally: # replace ToPyType types.ToPyType = topytype
<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 :class:`~ligo.lw.ligolw.Document` as the first positional argument """
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 if not isinstance(source, (Document, GlueDocument)): read_kw = { 'contenthandler': kwargs.pop('contenthandler', contenthandler), 'verbose': kwargs.pop('verbose', False), } return func_(read_ligolw(source, **read_kw), *args, **kwargs) return func_(source, *args, **kwargs) return decorated_func if func is not None: return decorator(func) return decorator
<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 object to read **kwargs other keyword arguments to pass to :func:`~ligo.lw.utils.load_filename`, or :func:`~ligo.lw.utils.load_fileobj` as appropriate Returns -------- xmldoc : :class:`~ligo.lw.ligolw.Document` either the `Document` as parsed from an existing file, or a new, empty `Document` """
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): return load_filename(fobj, **kwargs) if isinstance(fobj, FILE_LIKE): return load_fileobj(fobj, **kwargs)[0] except (OSError, IOError): # or just create a new Document return Document() except LigolwElementError as exc: if LIGO_LW_COMPAT_ERROR.search(str(exc)): try: return open_xmldoc(fobj, ilwdchar_compat=True, **kwargs) except Exception: # for any reason, raise original pass raise
<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.ligolw.Document` the file or document to write into tables : `list`, `tuple` of :class:`~ligo.lw.table.Table` the tables to write append : `bool`, optional, default: `False` if `True`, append to an existing file/table, otherwise `overwrite` overwrite : `bool`, optional, default: `False` if `True`, delete an existing instance of the table type, otherwise append new rows **kwargs other keyword arguments to pass to :func:`~ligo.lw.utils.load_filename`, or :func:`~ligo.lw.utils.load_fileobj` as appropriate """
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( target, contenthandler=kwargs.pop('contenthandler', LIGOLWContentHandler)) # fail on existing document and not overwriting elif (not overwrite and isinstance(target, string_types) and os.path.isfile(target)): raise IOError("File exists: {}".format(target)) else: # or create a new document xmldoc = Document() # convert table to format write_tables_to_document(xmldoc, tables, overwrite=overwrite) # write file if isinstance(target, string_types): kwargs.setdefault('gz', target.endswith('.gz')) ligolw_utils.write_filename(xmldoc, target, **kwargs) elif isinstance(target, FILE_LIKE): kwargs.setdefault('gz', target.name.endswith('.gz')) ligolw_utils.write_fileobj(xmldoc, target, **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 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 mapping for ``colname`` isn't found. Parameters val : `object` The input object to convert, of any type cls : `type`, subclass of :class:`~ligo.lw.table.Table` the table class to map against colname : `str` The name of the mapping column Returns ------- obj : `object` The input ``val`` cast to the correct type Examples -------- 1.0 ID integers are converted to fancy ILWD objects sngl_burst:process_id:1 Formatted fancy ILWD objects are left untouched: process:process_id:1 """
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': return _to_ilwd(val, cls.tableName, colname, ilwdchar_compat=_is_glue_ligolw_object(cls)) # otherwise map to numpy or python types try: return numpy.typeDict[numpytypes[llwtype]](val) except KeyError: return pytypes[llwtype](val)
<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 line2.startswith((LIGOLW_SIGNATURE, LIGOLW_ELEMENT))) except TypeError: # bytes vs str return (line1.startswith(XML_SIGNATURE.decode('utf-8')) and line2.startswith((LIGOLW_SIGNATURE.decode('utf-8'), LIGOLW_ELEMENT.decode('utf-8')))) finally: fileobj.seek(loc) try: from ligo.lw.ligolw import Element except ImportError: return False try: from glue.ligolw.ligolw import Element as GlueElement except ImportError: element_types = (Element,) else: element_types = (Element, GlueElement) return len(args) > 0 and isinstance(args[0], element_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 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.setdefault('array_type', out.EntryClass) for name in names: out[name] = read_hdf5_timeseries(h5g[name], **kwargs) return out
<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), **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 welch(timeseries, segmentlength, noverlap=None, scheme=None, **kwargs): """Calculate a PSD using Welch's method with a mean average Parameters timeseries : `~gwpy.timeseries.TimeSeries` input `TimeSeries` data. segmentlength : `int` number of samples in single average. noverlap : `int` number of samples to overlap between segments, defaults to 50%. scheme : `pycbc.scheme.Scheme`, optional processing scheme in which to execute FFT, default: `None` **kwargs other keyword arguments to pass to :func:`pycbc.psd.welch` Returns ------- spectrum : `~gwpy.frequencyseries.FrequencySeries` average power `FrequencySeries` See also -------- pycbc.psd.welch """
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=False), seg_len=segmentlength, seg_stride=segmentlength-noverlap, **kwargs) # return GWpy FrequencySeries fseries = FrequencySeries.from_pycbc(pycbc_fseries, copy=False) fseries.name = timeseries.name fseries.override_unit(scale_timeseries_unit( timeseries.unit, scaling='density')) return fseries
<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 ordinal Examples -------- '11th' '102nd' """
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.frequencyseries.FrequencySeries` or `~astropy.units.Quantity` to weight against, or one of - ``'mean'`` : weight against the mean of each spectrum in this Spectrogram - ``'median'`` : weight against the median of each spectrum in this Spectrogram Returns ------- spectrogram : `Spectrogram` a new `Spectrogram` Raises ------ ValueError if ``operand`` is given as a `str` that isn't supported """
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 " "Quantity or one of: 'mean', 'median'" % operand) out = self / operand return out
<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 to underlying functions, see below for references Returns ------- plot : `~gwpy.plot.Plot` the `Plot` containing the data See Also -------- matplotlib.pyplot.figure for documentation of keyword arguments used to create the figure matplotlib.figure.Figure.add_subplot for documentation of keyword arguments used to create the axes gwpy.plot.Axes.imshow or gwpy.plot.Axes.pcolormesh for documentation of keyword arguments used in rendering the `Spectrogram` data """
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 'pcolormesh') kwargs.update(figsize=figsize, xscale=xscale) return super(Spectrogram, self).plot(**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 from_spectra(cls, *spectra, **kwargs): """Build a new `Spectrogram` from a list of spectra. Parameters *spectra any number of `~gwpy.frequencyseries.FrequencySeries` series dt : `float`, `~astropy.units.Quantity`, optional stride between given spectra Returns ------- Spectrogram a new `Spectrogram` from a vertical stacking of the spectra The new object takes the metadata from the first given `~gwpy.frequencyseries.FrequencySeries` if not given explicitly Notes ----- Each `~gwpy.frequencyseries.FrequencySeries` passed to this constructor must be the same length. """
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 spectra with different df") kwargs.setdefault('name', spec1.name) kwargs.setdefault('channel', spec1.channel) kwargs.setdefault('epoch', spec1.epoch) kwargs.setdefault('f0', spec1.f0) kwargs.setdefault('df', spec1.df) kwargs.setdefault('unit', spec1.unit) if not ('dt' in kwargs or 'times' in kwargs): try: kwargs.setdefault('dt', spectra[1].epoch.gps - spec1.epoch.gps) except (AttributeError, IndexError): raise ValueError("Cannot determine dt (time-spacing) for " "Spectrogram from inputs") return Spectrogram(data, **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 percentile(self, percentile): """Calculate a given spectral percentile for this `Spectrogram`. Parameters 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, frequencies=(hasattr(self, '_frequencies') and self.frequencies or None))
<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`. Parameters bins : `~numpy.ndarray`, optional, default `None` array of histogram bin edges, including the rightmost edge low : `float`, optional, default: `None` left edge of lowest amplitude bin, only read if ``bins`` is not given high : `float`, optional, default: `None` right edge of highest amplitude bin, only read if ``bins`` is not given nbins : `int`, optional, default: `500` number of bins to generate, only read if ``bins`` is not given log : `bool`, optional, default: `False` calculate amplitude bins over a logarithmic scale, only read if ``bins`` is not given norm : `bool`, optional, default: `False` normalise bin counts to a unit sum density : `bool`, optional, default: `False` normalise bin counts to a unit integral Returns ------- specvar : `SpectralVariance` 2D-array of spectral frequency-amplitude counts See Also -------- :func:`numpy.histogram` for details on specifying bins and weights """
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 bound for cropped `Spectrogram` high : `float` upper frequency bound for cropped `Spectrogram` copy : `bool` if `False` return a view of the original data, otherwise create a fresh memory copy Returns ------- spec : `Spectrogram` A new `Spectrogram` with a subset of data from the frequency axis """
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 < self.f0: warnings.warn('Spectrogram.crop_frequencies given low frequency ' 'cutoff below f0 of the input Spectrogram. Low ' 'frequency crop will have no effect.') # check high frequency if high is not None and high.value == self.band[1]: high = None elif high is not None and high.value > self.band[1]: warnings.warn('Spectrogram.crop_frequencies given high frequency ' 'cutoff above cutoff of the input Spectrogram. High ' 'frequency crop will have no effect.') # find low index if low is None: idx0 = None else: idx0 = int(float(low.value - self.f0.value) // self.df.value) # find high index if high is None: idx1 = None else: idx1 = int(float(high.value - self.f0.value) // self.df.value) # crop if copy: return self[:, idx0:idx1].copy() return self[:, idx0:idx1]
<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 a mappable """
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=no-member except IOError: raise except Exception: # pylint: disable=broad-except fileobj = None try: return get_format('read', cls, filepath, fileobj, args, kwargs) finally: if ctx is not None: ctx.__exit__(*sys.exc_info())
<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 keyword arguments are passed onto :func:`scipy.io.wavfile.read` See also -------- scipy.io.wavfile.read for details on how the WAV file is actually read Examples -------- """
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 object or filename to write to scale : `float`, optional the factor to apply to scale the data to (-1.0, 1.0), pass `scale=1` to not apply any scale, otherwise the data will be auto-scaled See also -------- scipy.io.wavfile.write for details on how the WAV file is actually written Examples -------- """
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') fmt = fmt.decode('utf-8') return riff == WAV_SIGNATURE[0] and fmt == WAV_SIGNATURE[1] except (UnicodeDecodeError, struct.error): return False finally: fileobj.seek(loc) elif filepath is not None: return filepath.endswith(('.wav', '.wave')) else: try: wave.open(args[0]) except (wave.Error, AttributeError): return False else: 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 parse_column_filter(definition): """Parse a `str` of the form 'column>50' Parameters definition : `str` a column filter definition of the form ``<name><operator><threshold>`` or ``<threshold><operator><name><operator><threshold>``, e.g. ``frequency >= 10``, or ``50 < snr < 100`` Returns ------- filters : `list` of `tuple` a `list` of filter 3-`tuple`s, where each `tuple` contains the following elements: - ``column`` (`str`) - the name of the column on which to operate - ``operator`` (`callable`) - the operator to call when evaluating the filter - ``operand`` (`anything`) - the argument to the operator function Raises ------ ValueError if the filter definition cannot be parsed KeyError if any parsed operator string cannnot be mapped to a function from the `operator` module Notes ----- Strings that contain non-alphanumeric characters (e.g. hyphen `-`) should be quoted inside the filter definition, to prevent such characters being interpreted as operators, e.g. ``channel = X1:TEST`` should always be passed as ``channel = "X1:TEST"``. Examples -------- [('frequency', <function operator.gt>, 10.)] [('snr', <function operator.gt>, 50.), ('snr', <function operator.lt>, 100.)] [('channel', <function operator.eq>, 'H1:TEST')] """
# 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 # pylint: disable=invalid-name if a[0] in [token.NAME, token.STRING]: # string comparison name = QUOTE_REGEX.sub('', a[1]) oprtr = OPERATORS[b[1]] value = _float_or_str(c[1]) return [(name, oprtr, value)] elif b[0] in [token.NAME, token.STRING]: name = QUOTE_REGEX.sub('', b[1]) oprtr = OPERATORS_INV[b[1]] value = _float_or_str(a[1]) return [(name, oprtr, value)] # parse between definition: e.g: 5 < snr < 10 elif len(parts) == 5: a, b, c, d, e = list(zip(*parts))[1] # pylint: disable=invalid-name name = QUOTE_REGEX.sub('', c) return [(name, OPERATORS_INV[b], _float_or_str(a)), (name, OPERATORS[d], _float_or_str(e))] raise ValueError("Cannot parse filter definition from %r" % definition)
<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', <function operator.lt>, 1000.)] [('snr', <function operator.gt>, 10.), ('frequency', <function operator.lt>, 1000.)] """
# 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 concurrently Parameters table : `~astropy.table.Table` the table to filter column_filter : `str`, `tuple` a column slice filter definition, in one of two formats: - `str` - e.g. ``'snr > 10`` - `tuple` - ``(<column>, <operator>, <operand>)``, e.g. ``('snr', operator.gt, 10)`` multiple filters can be given and will be applied in order Returns ------- table : `~astropy.table.Table` a view of the input table with only those rows matching the filters Examples -------- custom operations can be defined using filter tuple definitions: """
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 HDF file on disk, or open `h5py.HLObject`. path : `str` path in HDF hierarchy of dataset. array_type : `type` desired return type """
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 isinstance(attrs[key], bytes): attrs[key] = attrs[key].decode('utf-8') return array_type(dataset[()], **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 _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.MATCH.match(raw) except ValueError: raise exc return raw
<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] = value except (TypeError, ValueError, RuntimeError) as exc: exc.args = ("Failed to store {} ({}) for {}: {}".format( attr, type(value).__name__, type(array).__name__, str(exc))) raise
<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` Parameters array : `gwpy.types.Array` the data object to write h5g : `str`, `h5py.Group` a file path to write to, or an `h5py.Group` in which to create a new dataset path : `str`, optional the path inside the group at which to create the new dataset, defaults to ``array.name`` attrs : `dict`, optional extra metadata to write into `h5py.Dataset.attrs`, on top of the default metadata append : `bool`, default: `False` if `True`, write new dataset to existing file, otherwise an exception will be raised if the output file exists (only used if ``f`` is `str`) overwrite : `bool`, default: `False` if `True`, overwrite an existing dataset in an existing file, otherwise an exception will be raised if a dataset exists with the given name (only used if ``f`` is `str`) compression : `str`, `int`, optional compression option to pass to :meth:`h5py.Group.create_dataset` **kwargs other keyword arguments for :meth:`h5py.Group.create_dataset` Returns ------- datasets : `h5py.Dataset` the newly created 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_hdf5.create_dataset(h5g, path, overwrite=overwrite, data=array.value, compression=compression, **kwargs) # write default metadata write_array_metadata(dset, array) # allow caller to specify their own metadata dict if attrs: for key in attrs: dset.attrs[key] = attrs[key] return dset
<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 (proposed) LIGO Common Data Format specification for series data in HDF5. """
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.update({ unit: str(aunit), origin: getattr(series, origin).to(aunit).value, delta: getattr(series, delta).to(aunit).value, }) return 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 keywords. """
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 `nproc` keyword to enable and handle pool-based multiprocessing of multiple source files, using `flatten` to combine the chunked data into a single object of the correct type. Parameters flatten : `callable` a method to take a list of ``cls`` instances, and combine them into a single ``cls`` instance cls : `type` the object type to read the input data source, can be of in many different forms *args positional arguments to pass to the reader **kwargs keyword arguments to pass to the reader """
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: path = files[0] if files else None # determine input format (so we don't have to do it multiple times) if kwargs.get('format', None) is None: kwargs['format'] = get_read_format(cls, path, (source,) + args, kwargs) # calculate maximum number of processes nproc = min(kwargs.pop('nproc', 1), len(files)) # define multiprocessing method def _read_single_file(fobj): try: return fobj, io_read(cls, fobj, *args, **kwargs) # pylint: disable=broad-except,redefine-in-handler except Exception as exc: if nproc == 1: raise if isinstance(exc, SAXException): # SAXExceptions don't pickle return fobj, exc.getException() # pylint: disable=no-member return fobj, exc # format verbosity if verbose is True: verbose = 'Reading ({})'.format(kwargs['format']) # read files output = mp_utils.multiprocess_with_queues( nproc, _read_single_file, files, verbose=verbose, unit='files') # raise exceptions (from multiprocessing, single process raises inline) for fobj, exc in output: if isinstance(exc, Exception): exc.args = ('Failed to read %s: %s' % (fobj, str(exc)),) raise exc # return combined object _, out = zip(*output) return flatten(out)