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 _find_channel(connection, name, ctype, dtype, sample_rate, unique=False): """Internal method to find a single channel Parameters connection : `nds2.connectio...
# parse channel type from name, # e.g. 'L1:GDS-CALIB_STRAIN,reduced' -> 'L1:GDS-CALIB_STRAIN', 'reduced' name, ctype = _strip_ctype(name, ctype, connection.get_protocol()) # query NDS2 found = connection.find_channels(name, ctype, dtype, *sample_rate) # if don't care about defaults, just retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _strip_ctype(name, ctype, protocol=2): """Strip the ctype from a channel name for the given nds server version This is needed because NDS1 servers store tren...
# parse channel type from name (e.g. 'L1:GDS-CALIB_STRAIN,reduced') try: name, ctypestr = name.rsplit(',', 1) except ValueError: pass else: ctype = Nds2ChannelType.find(ctypestr).value # NDS1 stores channels with trend suffix, so we put it back: if protocol == 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 get_availability(channels, start, end, connection=None, host=None, port=None): # pylint: disable=unused-argument """Query an NDS2 server for data availabilit...
from ..segments import (Segment, SegmentList, SegmentListDict) connection.set_epoch(start, end) # map user-given real names to NDS names names = list(map( _get_nds2_name, find_channels(channels, epoch=(start, end), connection=connection, unique=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 minute_trend_times(start, end): """Expand a [start, end) interval for use in querying for minute trends NDS2 requires start and end times for minute trends t...
if start % 60: start = int(start) // 60 * 60 if end % 60: end = int(end) // 60 * 60 + 60 return int(start), int(end)
<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(cls, name): """Returns the NDS2 channel type corresponding to the given name """
try: return cls._member_map_[name] except KeyError: for ctype in cls._member_map_.values(): if ctype.name == name: return ctype raise ValueError('%s is not a valid %s' % (name, cls.__name__))
<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(cls, dtype): """Returns the NDS2 type corresponding to the given python type """
try: return cls._member_map_[dtype] except KeyError: try: dtype = numpy.dtype(dtype).type except TypeError: for ndstype in cls._member_map_.values(): if ndstype.value is dtype: return ndstype...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reconnect(connection): """Open a new datafind connection based on an existing connection This is required because of https://git.ligo.org/lscsoft/glue/issues...
if isinstance(connection, FflConnection): return type(connection)(connection.ffldir) kw = {'context': connection._context} if connection.port != 80 else {} return connection.__class__(connection.host, port=connection.port, **kw)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _type_priority(ifo, ftype, trend=None): """Prioritise the given GWF type based on its name or trend status. This is essentially an ad-hoc ordering function b...
# if looking for a trend channel, prioritise the matching type for trendname, trend_regex in [ ('m-trend', MINUTE_TREND_TYPE), ('s-trend', SECOND_TREND_TYPE), ]: if trend == trendname and trend_regex.match(ftype): return 0, len(ftype) # otherwise rank this t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_tape(*files): """Determine whether any of the given files are on tape Parameters *files : `str` one or more paths to GWF files Returns ------- True/False ...
for path in files: try: if os.stat(path).st_blocks == 0: return True except AttributeError: # windows doesn't have st_blocks return False 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 with_connection(func): """Decorate a function to open a new datafind connection if required This method will inspect the ``connection`` keyword, and if `None...
@wraps(func) def wrapped(*args, **kwargs): if kwargs.get('connection') is None: kwargs['connection'] = _choose_connection(host=kwargs.get('host'), port=kwargs.get('port')) try: return func(*args, **kwargs) exc...
<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_best_frametype(channel, start, end, frametype_match=None, allow_tape=True, connection=None, host=None, port=None): """Intelligently select the best fram...
try: return find_frametype(channel, gpstime=(start, end), frametype_match=frametype_match, allow_tape=allow_tape, on_gaps='error', connection=connection, host=host, port=port) except RuntimeError: # gaps (or some...
<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_types(observatory, match=None, trend=None, connection=None, **connection_kw): """Find the available data types for a given observatory. See also -------...
return sorted(connection.find_types(observatory, match=match), key=lambda x: _type_priority(observatory, x, trend=trend))
<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_urls(observatory, frametype, start, end, on_gaps='error', connection=None, **connection_kw): """Find the URLs of files of a given data type in a GPS int...
return connection.find_urls(observatory, frametype, start, end, on_gaps=on_gaps)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ffl_path(self, site, frametype): """Returns the path of the FFL file for the given site and frametype Examples -------- /virgoData/ffl/V1Online.ffl """
try: return self.paths[(site, frametype)] except KeyError: self._find_paths() return self.paths[(site, frametype)]
<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_types(self, site=None, match=r'^(?!lastfile|spectro|\.).*'): """Return the list of known data types. This is just the basename of each FFL file found in...
self._find_paths() types = [tag for (site_, tag) in self.paths if site in (None, site_)] if match is not None: match = re.compile(match) return list(filter(match.search, types)) return 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 find_urls(self, site, frametype, gpsstart, gpsend, match=None, on_gaps='warn'): """Find all files of the given type in the [start, end) GPS interval. """
span = Segment(gpsstart, gpsend) cache = [e for e in self._read_ffl_cache(site, frametype) if e.observatory == site and e.description == frametype and e.segment.intersects(span)] urls = [e.path for e in cache] missing = SegmentList([span]) - cache_segme...
<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_series(source, name, match=None): """Read a `Series` from LIGO_LW-XML Parameters source : `file`, `str`, :class:`~ligo.lw.ligolw.Document` file path or ...
from ligo.lw.ligolw import (LIGO_LW, Time, Array, Dim) from ligo.lw.param import get_param # read document xmldoc = read_ligolw(source, contenthandler=series_contenthandler()) # parse match dict if match is None: match = dict() def _is_match(elem): try: if ele...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_plot(self): """Generate the coherence plot from all time series """
args = self.args fftlength = float(args.secpfft) overlap = args.overlap self.log(2, "Calculating spectrum secpfft: %s, overlap: %s" % (fftlength, overlap)) if overlap is not None: overlap *= fftlength self.log(3, 'Reference channel: ' + sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_legend(self): """Create a legend for this product """
leg = super(Coherence, self).set_legend() if leg is not None: leg.set_title('Coherence with:') return leg
<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_unit(name, parse_strict='warn', format='gwpy'): """Attempt to intelligently parse a `str` as a `~astropy.units.Unit` Parameters name : `str` unit name ...
if name is None or isinstance(name, units.UnitBase): return name try: # have we already identified this unit as unrecognised? return UNRECOGNIZED_UNITS[name] except KeyError: # no, this is new # pylint: disable=unexpected-keyword-arg try: return units.Unit(nam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _row_from_frevent(frevent, columns, selection): """Generate a table row from an FrEvent Filtering (``selection``) is done here, rather than in the table read...
# read params params = dict(frevent.GetParam()) params['time'] = float(LIGOTimeGPS(*frevent.GetGTime())) params['amplitude'] = frevent.GetAmplitude() params['probability'] = frevent.GetProbability() params['timeBefore'] = frevent.GetTimeBefore() params['timeAfter'] = frevent.GetTimeAfter() ...
<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_to_gwf(table, filename, name, **kwargs): """Create a new `~frameCPP.FrameH` and fill it with data Parameters table : `~astropy.table.Table` the data to...
from LDAStools.frameCPP import (FrEvent, GPSTime) # create frame write_kw = {key: kwargs.pop(key) for key in ('compression', 'compression_level') if key in kwargs} frame = io_gwf.create_frame(name=name, **kwargs) # append row by row names = table.dtype.names for row in tab...
<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 into a `FrequencySeries` Arguments and keywords depend on the output format, see the online documentation fo...
return io_registry.read(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 ifft(self): """Compute the one-dimensional discrete inverse Fourier transform of this `FrequencySeries`. Returns ------- out : :class:`~gwpy.timeseries.TimeS...
from ..timeseries import TimeSeries nout = (self.size - 1) * 2 # Undo normalization from TimeSeries.fft # The DC component does not have the factor of two applied # so we account for it here dift = npfft.irfft(self.value * nout) / 2 new = TimeSeries(dift, epoch=s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interpolate(self, df): """Interpolate this `FrequencySeries` to a new resolution. Parameters df : `float` desired frequency resolution of the interpolated `F...
f0 = self.f0.decompose().value N = (self.size - 1) * (self.df.decompose().value / df) + 1 fsamples = numpy.arange(0, numpy.rint(N), dtype=self.dtype) * df + f0 out = type(self)(numpy.interp(fsamples, self.frequencies.value, self.value)) 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 from_lal(cls, lalfs, copy=True): """Generate a new `FrequencySeries` from a LAL `FrequencySeries` of any type """
from ..utils.lal import from_lal_unit try: unit = from_lal_unit(lalfs.sampleUnits) except TypeError: unit = None channel = Channel(lalfs.name, unit=unit, dtype=lalfs.data.data.dtype) return cls(lalfs.data.data, channel=channel, f...
<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_pycbc(cls, fs, copy=True): """Convert a `pycbc.types.frequencyseries.FrequencySeries` into a `FrequencySeries` Parameters fs : `pycbc.types.frequencyser...
return cls(fs.data, f0=0, df=fs.delta_f, epoch=fs.epoch, copy=copy)
<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_pycbc(self, copy=True): """Convert this `FrequencySeries` into a `~pycbc.types.frequencyseries.FrequencySeries` Parameters copy : `bool`, optional, defaul...
from pycbc import types if self.epoch is None: epoch = None else: epoch = self.epoch.gps return types.FrequencySeries(self.value, delta_f=self.df.to('Hz').value, epoch=epoch, copy=copy)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fetch_losc_data_file(url, *args, **kwargs): """Internal function for fetching a single LOSC file and returning a Series """
cls = kwargs.pop('cls', TimeSeries) cache = kwargs.pop('cache', None) verbose = kwargs.pop('verbose', False) # match file format if url.endswith('.gz'): ext = os.path.splitext(url[:-3])[-1] else: ext = os.path.splitext(url)[-1] if ext == '.hdf5': kwargs.setdefault('...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _overlapping(files): """Quick method to see if a file list contains overlapping files """
segments = set() for path in files: seg = file_segment(path) for s in segments: if seg.intersects(s): return True segments.add(seg) 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 fetch_losc_data(detector, start, end, cls=TimeSeries, **kwargs): """Fetch LOSC data for a given detector This function is for internal purposes only, all use...
# format arguments start = to_gps(start) end = to_gps(end) span = Segment(start, end) kwargs.update({ 'start': start, 'end': end, }) # find URLs (requires gwopensci) url_kw = {key: kwargs.pop(key) for key in GWOSC_LOCATE_KWARGS if key in kwargs} if 'sa...
<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_losc_hdf5(h5f, path='strain/Strain', start=None, end=None, copy=False): """Read a `TimeSeries` from a LOSC-format HDF file. Parameters h5f : `str`, `h5p...
dataset = io_hdf5.find_dataset(h5f, path) # read data nddata = dataset[()] # read metadata xunit = parse_unit(dataset.attrs['Xunits']) epoch = dataset.attrs['Xstart'] dt = Quantity(dataset.attrs['Xspacing'], xunit) unit = dataset.attrs['Yunits'] # build and return return TimeSer...
<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_losc_hdf5_state(f, path='quality/simple', start=None, end=None, copy=False): """Read a `StateVector` from a LOSC-format HDF file. Parameters f : `str`, ...
# find data dataset = io_hdf5.find_dataset(f, '%s/DQmask' % path) maskset = io_hdf5.find_dataset(f, '%s/DQDescriptions' % path) # read data nddata = dataset[()] bits = [bytes.decode(bytes(b), 'utf-8') for b in maskset[()]] # read metadata epoch = dataset.attrs['Xstart'] try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _gwf_channel(path, series_class=TimeSeries, verbose=False): """Find the right channel name for a LOSC GWF file """
channels = list(io_gwf.iter_channel_names(file_path(path))) if issubclass(series_class, StateVector): regex = DQMASK_CHANNEL_REGEX else: regex = STRAIN_CHANNEL_REGEX found, = list(filter(regex.match, channels)) if verbose: print("Using channel {0!r}".format(found)) retur...
<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_segwizard(source, gpstype=LIGOTimeGPS, strict=True): """Read segments from a segwizard format file into a `SegmentList` Parameters source : `file`, `str...
# read file path if isinstance(source, string_types): with open(source, 'r') as fobj: return from_segwizard(fobj, gpstype=gpstype, strict=strict) # read file object out = SegmentList() fmt_pat = None for line in source: if line.startswith(('#', ';')): # comment ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _line_format(line): """Determine the column format pattern for a line in an ASCII segment file. """
for pat in (FOUR_COL_REGEX, THREE_COL_REGEX, TWO_COL_REGEX): if pat.match(line): return pat raise ValueError("unable to parse segment from line {!r}".format(line))
<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_segment(tokens, strict=True, gpstype=LIGOTimeGPS): """Format a list of tokens parsed from an ASCII file into a segment. """
try: start, end, dur = tokens except ValueError: # two-columns return Segment(*map(gpstype, tokens)) seg = Segment(gpstype(start), gpstype(end)) if strict and not float(abs(seg)) == float(dur): raise ValueError( "segment {0!r} has incorrect duration {1!r}".format(se...
<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_segwizard(segs, target, header=True, coltype=LIGOTimeGPS): """Write the given `SegmentList` to a file in SegWizard format. Parameters segs : :class:`~gwpy...
# write file path if isinstance(target, string_types): with open(target, 'w') as fobj: return to_segwizard(segs, fobj, header=header, coltype=coltype) # write file object if header: print('# seg\tstart\tstop\tduration', file=target) for i, seg in enumerate(segs): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gopen(name, *args, **kwargs): """Open a file handling optional gzipping If ``name`` endswith ``'.gz'``, or if the GZIP file signature is found at the beginni...
# filename declares gzip if name.endswith('.gz'): return gzip.open(name, *args, **kwargs) # open regular file fobj = open(name, *args, **kwargs) sig = fobj.read(3) fobj.seek(0) if sig == GZIP_SIGNATURE: # file signature declares gzip fobj.close() # GzipFile won't close or...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_list(flist): """Parse a number of possible input types into a list of filepaths. Parameters flist : `file-like` or `list-like` iterable the input data c...
# open a cache file and return list of paths if (isinstance(flist, string_types) and flist.endswith(('.cache', '.lcf', '.ffl'))): from .cache import read_cache return read_cache(flist) # separate comma-separate list of names if isinstance(flist, string_types): retur...
<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_path(fobj): """Determine the path of a file. This doesn't do any sanity checking to check that the file actually exists, or is readable. Parameters the ...
if isinstance(fobj, string_types) and fobj.startswith("file:"): return urlparse(fobj).path if isinstance(fobj, string_types): return fobj if (isinstance(fobj, FILE_LIKE) and hasattr(fobj, "name")): return fobj.name try: return fobj.path except AttributeError: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_in_out_queues(func, q_in, q_out): """Iterate through a Queue, call, ``func`, and Queue the result Parameters func : `callable` any function that can ...
while True: # pick item out of input wqueue idx, arg = q_in.get() if idx is None: # sentinel break # execute method and put the result in the output queue q_out.put((idx, func(arg)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multiprocess_with_queues(nproc, func, inputs, verbose=False, **progress_kw): """Map a function over a list of inputs using multiprocess This essentially dupl...
if nproc != 1 and os.name == 'nt': warnings.warn( "multiprocessing is currently not supported on Windows, see " "https://github.com/gwpy/gwpy/issues/880, will continue with " "serial procesing (nproc=1)") nproc = 1 if progress_kw.pop('raise_exceptions', 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 epoch(self): """GPS epoch associated with these data :type: `~astropy.time.Time` """
try: if self._epoch is None: return None return Time(*modf(self._epoch)[::-1], format='gps', scale='utc') except AttributeError: self._epoch = None return self._epoch
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def override_unit(self, unit, parse_strict='raise'): """Forcefully reset the unit of these data Use of this method is discouraged in favour of `to()`, which perf...
self._unit = parse_unit(unit, parse_strict=parse_strict)
<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(self, order='C'): """Return a copy of the array collapsed into one dimension. Any index information is removed as part of the flattening, and the res...
return super(Array, self).flatten(order=order).view(Quantity)
<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_timeseries(ts1, ts2, stride, fftlength=None, overlap=None, window=None, nproc=1, **kwargs): """Calculate the coherence `Spectrogram` between two `TimeSe...
# format FFT parameters if fftlength is None: fftlength = stride / 2. # get size of spectrogram nsteps = int(ts1.size // (stride * ts1.sample_rate.value)) nproc = min(nsteps, nproc) # single-process return if nsteps == 0 or nproc == 1: return _from_timeseries(ts1, ts2, str...
<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_channel_list_file(*source): """Read a `~gwpy.detector.ChannelList` from a Channel List File """
# read file(s) config = configparser.ConfigParser(dict_type=OrderedDict) source = file_list(source) success_ = config.read(*source) if len(success_) != len(source): raise IOError("Failed to read one or more CLF files") # create channel list out = ChannelList() out.source = sourc...
<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_channel_list_file(channels, fobj): """Write a `~gwpy.detector.ChannelList` to a INI-format channel list file """
if not isinstance(fobj, FILE_LIKE): with open(fobj, "w") as fobj: return write_channel_list_file(channels, fobj) out = configparser.ConfigParser(dict_type=OrderedDict) for channel in channels: group = channel.group if not out.has_section(group): out.add_sect...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_method(func, name=None, deprecated=False): """Register a method of calculating an average spectrogram. Parameters func : `callable` function to exec...
# warn about deprecated functions if deprecated: func = deprecated_function( func, "the {0!r} PSD methods is deprecated, and will be removed " "in a future release, please consider using {1!r} instead".format( name, name.split('-', 1)[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 get_method(name): """Return the PSD method registered with the given name. """
# find method name = _format_name(name) try: return METHODS[name] except KeyError as exc: exc.args = ("no PSD method registered with name {0!r}".format(name),) 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 inspiral_range_psd(psd, snr=8, mass1=1.4, mass2=1.4, horizon=False): """Compute the inspiral sensitive distance PSD from a GW strain PSD Parameters psd : `~g...
# compute chirp mass and symmetric mass ratio mass1 = units.Quantity(mass1, 'solMass').to('kg') mass2 = units.Quantity(mass2, 'solMass').to('kg') mtotal = mass1 + mass2 mchirp = (mass1 * mass2) ** (3/5.) / mtotal ** (1/5.) # compute ISCO fisco = (constants.c ** 3 / (constants.G * 6**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 inspiral_range(psd, snr=8, mass1=1.4, mass2=1.4, fmin=None, fmax=None, horizon=False): """Calculate the inspiral sensitive distance from a GW strain PSD The ...
mass1 = units.Quantity(mass1, 'solMass').to('kg') mass2 = units.Quantity(mass2, 'solMass').to('kg') mtotal = mass1 + mass2 # compute ISCO fisco = (constants.c ** 3 / (constants.G * 6**1.5 * pi * mtotal)).to('Hz') # format frequency limits fmax = units.Quantity(fmax or fisco, 'Hz') if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def burst_range_spectrum(psd, snr=8, energy=1e-2): """Calculate the frequency-dependent GW burst range from a strain PSD Parameters psd : `~gwpy.frequencyseries....
# calculate frequency dependent range in parsecs a = (constants.G * energy * constants.M_sun * 0.4 / (pi**2 * constants.c))**(1/2.) dspec = psd ** (-1/2.) * a / (snr * psd.frequencies) # convert to output unit rspec = dspec.to('Mpc') # rescale 0 Hertz (which has 0 range always) i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def burst_range(psd, snr=8, energy=1e-2, fmin=100, fmax=500): """Calculate the integrated GRB-like GW burst range from a strain PSD Parameters psd : `~gwpy.frequ...
freqs = psd.frequencies.value # restrict integral if not fmin: fmin = psd.f0 if not fmax: fmax = psd.span[1] condition = (freqs >= fmin) & (freqs < fmax) # calculate integrand and integrate integrand = burst_range_spectrum( psd[condition], snr=snr, energy=energy) ** ...
<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_norm(kwargs, current=None): """Format a `~matplotlib.colors.Normalize` from a set of kwargs Returns ------- norm, kwargs the formatted `Normalize` ins...
norm = kwargs.pop('norm', current) or 'linear' vmin = kwargs.pop('vmin', None) vmax = kwargs.pop('vmax', None) clim = kwargs.pop('clim', (vmin, vmax)) or (None, None) clip = kwargs.pop('clip', None) if norm == 'linear': norm = colors.Normalize() elif norm == 'log': norm = 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 identify_gwf(origin, filepath, fileobj, *args, **kwargs): """Identify a filename or file object as GWF This function is overloaded in that it will also ident...
# pylint: disable=unused-argument # try and read file descriptor if fileobj is not None: loc = fileobj.tell() fileobj.seek(0) try: if fileobj.read(4) == GWF_SIGNATURE: return True finally: fileobj.seek(loc) if filepath is not 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 open_gwf(filename, mode='r'): """Open a filename for reading or writing GWF format data Parameters filename : `str` the path to read from, or write to mode :...
if mode not in ('r', 'w'): raise ValueError("mode must be either 'r' or 'w'") from LDAStools import frameCPP filename = urlparse(filename).path # strip file://localhost or similar if mode == 'r': return frameCPP.IFrameFStream(str(filename)) return frameCPP.OFrameFStream(str(filenam...
<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_frames(filename, frames, compression=257, compression_level=6): """Write a list of frame objects to a file **Requires:** |LDAStools.frameCPP|_ Paramete...
from LDAStools import frameCPP # open stream stream = open_gwf(filename, 'w') # write frames one-by-one if isinstance(frames, frameCPP.FrameH): frames = [frames] for frame in frames: stream.WriteFrame(frame, compression, compression_level)
<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_channel_type(channel, framefile): """Find the channel type in a given GWF file **Requires:** |LDAStools.frameCPP|_ Parameters channel : `str`, `~gwpy.det...
channel = str(channel) for name, type_ in _iter_channels(framefile): if channel == name: return type_ raise ValueError("%s not found in table-of-contents for %s" % (channel, framefile))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def channel_in_frame(channel, framefile): """Determine whether a channel is stored in this framefile **Requires:** |LDAStools.frameCPP|_ Parameters channel : `st...
channel = str(channel) for name in iter_channel_names(framefile): if channel == name: 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 _iter_channels(framefile): """Yields the name and type of each channel in a GWF file TOC **Requires:** |LDAStools.frameCPP|_ Parameters framefile : `str`, `L...
from LDAStools import frameCPP if not isinstance(framefile, frameCPP.IFrameFStream): framefile = open_gwf(framefile, 'r') toc = framefile.GetTOC() for typename in ('Sim', 'Proc', 'ADC'): typen = typename.lower() for name in getattr(toc, 'Get{0}'.format(typename))(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data_segments(paths, channel, warn=True): """Returns the segments containing data for a channel **Requires:** |LDAStools.frameCPP|_ A frame is considered to ...
segments = SegmentList() for path in paths: segments.extend(_gwf_channel_segments(path, channel, warn=warn)) return segments.coalesce()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _gwf_channel_segments(path, channel, warn=True): """Yields the segments containing data for ``channel`` in this GWF path """
stream = open_gwf(path) # get segments for frames toc = stream.GetTOC() secs = toc.GetGTimeS() nano = toc.GetGTimeN() dur = toc.GetDt() readers = [getattr(stream, 'ReadFr{0}Data'.format(type_.title())) for type_ in ("proc", "sim", "adc")] # for each segment, try and rea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fdfilter(data, *filt, **kwargs): """Filter a frequency-domain data object See Also -------- gwpy.frequencyseries.FrequencySeries.filter gwpy.spectrogram.Spec...
# parse keyword args inplace = kwargs.pop('inplace', False) analog = kwargs.pop('analog', False) fs = kwargs.pop('sample_rate', None) if kwargs: raise TypeError("filter() got an unexpected keyword argument '%s'" % list(kwargs.keys())[0]) # parse filter if fs...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(args=None): """Parse command-line arguments, tconvert inputs, and print """
# define command line arguments parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("-V", "--version", action="version", version=__version__, help="show version number and exit") parser.add_argument("-l", "--local", action="store_tru...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def timer(func): """Time a method and print its duration after return """
name = func.__name__ @wraps(func) def timed_func(self, *args, **kwargs): # pylint: disable=missing-docstring _start = time.time() out = func(self, *args, **kwargs) self.log(2, '{0} took {1:.1f} sec'.format(name, time.time() - _start)) return out return timed_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 to_float(unit): """Factory to build a converter from quantity string to float Examples -------- """
def converter(x): """Convert the input to a `float` in %s """ return Quantity(x, unit).value converter.__doc__ %= str(unit) # pylint: disable=no-member return converter
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_norm(func): """Wrap ``func`` to handle custom gwpy keywords for a LogNorm colouring """
@wraps(func) def decorated_func(*args, **kwargs): norm, kwargs = format_norm(kwargs) kwargs['norm'] = norm return func(*args, **kwargs) return decorated_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 xlim_as_gps(func): """Wrap ``func`` to handle pass limit inputs through `gwpy.time.to_gps` """
@wraps(func) def wrapped_func(self, left=None, right=None, **kw): if right is None and numpy.iterable(left): left, right = left kw['left'] = left kw['right'] = right gpsscale = self.get_xscale() in GPS_SCALES for key in ('left', 'right'): if gpssc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore_grid(func): """Wrap ``func`` to preserve the Axes current grid settings. """
@wraps(func) def wrapped_func(self, *args, **kwargs): grid = (self.xaxis._gridOnMinor, self.xaxis._gridOnMajor, self.yaxis._gridOnMinor, self.yaxis._gridOnMajor) try: return func(self, *args, **kwargs) finally: # reset grid self.xaxis....
<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_epoch(self, epoch): """Set the epoch for the current GPS scale. This method will fail if the current X-axis scale isn't one of the GPS scales. See :ref:`...
scale = self.get_xscale() return self.set_xscale(scale, epoch=epoch)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def imshow(self, array, *args, **kwargs): """Display an image, i.e. data on a 2D regular raster. If ``array`` is a :class:`~gwpy.types.Array2D` (e.g. a :class:`~...
if isinstance(array, Array2D): return self._imshow_array2d(array, *args, **kwargs) image = super(Axes, self).imshow(array, *args, **kwargs) self.autoscale(enable=None, axis='both', tight=None) return image
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _imshow_array2d(self, array, origin='lower', interpolation='none', aspect='auto', **kwargs): """Render an `~gwpy.types.Array2D` using `Axes.imshow` """
# NOTE: If you change the defaults for this method, please update # the docstring for `imshow` above. # calculate extent extent = tuple(array.xspan) + tuple(array.yspan) if self.get_xscale() == 'log' and extent[0] == 0.: extent = (1e-300,) + extent[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 pcolormesh(self, *args, **kwargs): """Create a pseudocolor plot with a non-regular rectangular grid. When using GWpy, this method can be called with a single...
if len(args) == 1 and isinstance(args[0], Array2D): return self._pcolormesh_array2d(*args, **kwargs) return super(Axes, self).pcolormesh(*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 _pcolormesh_array2d(self, array, *args, **kwargs): """Render an `~gwpy.types.Array2D` using `Axes.pcolormesh` """
x = numpy.concatenate((array.xindex.value, array.xspan[-1:])) y = numpy.concatenate((array.yindex.value, array.yspan[-1:])) xcoord, ycoord = numpy.meshgrid(x, y, copy=False, sparse=True) return self.pcolormesh(xcoord, ycoord, array.value.T, *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 plot_mmm(self, data, lower=None, upper=None, **kwargs): """Plot a `Series` as a line, with a shaded region around it. The ``data`` `Series` is drawn, while t...
alpha = kwargs.pop('alpha', .1) # plot mean line, = self.plot(data, **kwargs) out = [line] # modify keywords for shading kwargs.update({ 'label': '', 'linewidth': line.get_linewidth() / 2, 'color': line.get_color(), 'alph...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tile(self, x, y, w, h, color=None, anchor='center', edgecolors='face', linewidth=0.8, **kwargs): """Plot rectanguler tiles based onto these `Axes`. ``x`` and...
# get color and sort if color is not None and kwargs.get('c_sort', True): sortidx = color.argsort() x = x[sortidx] y = y[sortidx] w = w[sortidx] h = h[sortidx] color = color[sortidx] # define how to make a polygon for each...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def colorbar(self, mappable=None, **kwargs): """Add a `~matplotlib.colorbar.Colorbar` to these `Axes` Parameters mappable : matplotlib data collection, optional ...
fig = self.get_figure() if kwargs.get('use_axesgrid', True): kwargs.setdefault('fraction', 0.) if kwargs.get('fraction', 0.) == 0.: kwargs.setdefault('use_axesgrid', True) mappable, kwargs = gcbar.process_colorbar_kwargs( fig, mappable=mappable, ax=se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tconvert(gpsordate='now'): """Convert GPS times to ISO-format date-times and vice-versa. Parameters input gps or date to convert, many input types are suppor...
# convert from GPS into datetime try: float(gpsordate) # if we can 'float' it, then its probably a GPS time except (TypeError, ValueError): return to_gps(gpsordate) return from_gps(gpsordate)
<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_gps(gps): """Convert a GPS time into a `datetime.datetime`. Parameters gps : `LIGOTimeGPS`, `int`, `float` GPS time to convert Returns ------- datetime ...
try: gps = LIGOTimeGPS(gps) except (ValueError, TypeError, RuntimeError): gps = LIGOTimeGPS(float(gps)) sec, nano = gps.gpsSeconds, gps.gpsNanoSeconds date = Time(sec, format='gps', scale='utc').datetime return date + datetime.timedelta(microseconds=nano*1e-3)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _str_to_datetime(datestr): """Convert `str` to `datetime.datetime`. """
# try known string try: return DATE_STRINGS[str(datestr).lower()]() except KeyError: # any other string pass # use maya try: import maya return maya.when(datestr).datetime() except ImportError: pass # use dateutil.parse with warnings.catch_warn...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _time_to_gps(time): """Convert a `Time` into `LIGOTimeGPS`. This method uses `datetime.datetime` underneath, which restricts Parameters time : `~astropy.time...
time = time.utc date = time.datetime micro = date.microsecond if isinstance(date, datetime.datetime) else 0 return LIGOTimeGPS(int(time.gps), int(micro*1e3))
<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_hdf5(func): """Decorate an HDF5-reading function to open a filepath if needed ``func`` should be written to presume an `h5py.Group` as the first po...
@wraps(func) def decorated_func(fobj, *args, **kwargs): # pylint: disable=missing-docstring if not isinstance(fobj, h5py.HLObject): if isinstance(fobj, FILE_LIKE): fobj = fobj.name with h5py.File(fobj, 'r') as h5f: return func(h5f, *args, ...
<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_dataset(h5o, path=None): """Find and return the relevant dataset inside the given H5 object If ``path=None`` is given, and ``h5o`` contains a single dat...
# find dataset if isinstance(h5o, h5py.Dataset): return h5o elif path is None and len(h5o) == 1: path = list(h5o.keys())[0] elif path is None: raise ValueError("Please specify the HDF5 path via the " "``path=`` keyword argument") return h5o[path]
<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_write_hdf5(func): """Decorate an HDF5-writing function to open a filepath if needed ``func`` should be written to take the object to be written as the f...
@wraps(func) def decorated_func(obj, fobj, *args, **kwargs): # pylint: disable=missing-docstring if not isinstance(fobj, h5py.HLObject): append = kwargs.get('append', False) overwrite = kwargs.get('overwrite', False) if os.path.exists(fobj) and not (overwrite...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_dataset(parent, path, overwrite=False, **kwargs): """Create a new dataset inside the parent HDF5 object Parameters parent : `h5py.Group`, `h5py.File` ...
# force deletion of existing dataset if path in parent and overwrite: del parent[path] # create new dataset with improved error handling try: return parent.create_dataset(path, **kwargs) except RuntimeError as exc: if str(exc) == 'Unable to create link (Name already exists)...
<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_db_selection(selection, engine=None): """Format a column filter selection as a SQL database WHERE string """
# parse selection for SQL query if selection is None: return '' selections = [] for col, op_, value in parse_column_filters(selection): if engine and engine.name == 'postgresql': col = '"%s"' % col try: opstr = [key for key in OPERATORS if OPERATORS[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 fetch(engine, tablename, columns=None, selection=None, **kwargs): """Fetch data from an SQL table into an `EventTable` Parameters engine : `sqlalchemy.engine...
import pandas as pd # parse columns for SQL query if columns is None: columnstr = '*' else: columnstr = ', '.join('"%s"' % c for c in columns) # parse selection for SQL query selectionstr = format_db_selection(selection, engine=engine) # build SQL query qstr = 'SELECT...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def q_scan(data, mismatch=DEFAULT_MISMATCH, qrange=DEFAULT_QRANGE, frange=DEFAULT_FRANGE, duration=None, sampling=None, **kwargs): """Transform data by scanning ...
from gwpy.timeseries import TimeSeries # prepare input if isinstance(data, TimeSeries): duration = abs(data.span) sampling = data.sample_rate.to('Hz').value kwargs.update({'epoch': data.t0.value}) data = data.fft().value # return a raw Q-transform and its significance ...
<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_qs(self): """Iterate over the Q values """
# work out how many Qs we need cumum = log(self.qrange[1] / self.qrange[0]) / 2**(1/2.) nplanes = int(max(ceil(cumum / self.deltam), 1)) dq = cumum / nplanes # pylint: disable=invalid-name for i in xrange(nplanes): yield self.qrange[0] * exp(2**(1/2.) * dq * (i + .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 transform(self, fseries, **kwargs): """Compute the time-frequency plane at fixed Q with the most significant tile Parameters fseries : `~gwpy.timeseries.Freq...
weight = 1 + numpy.log10(self.qrange[1]/self.qrange[0]) / numpy.sqrt(2) nind, nplanes, peak, result = (0, 0, 0, None) # identify the plane with the loudest tile for plane in self: nplanes += 1 nind += sum([1 + row.ntiles * row.deltam for row in plane]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def farray(self): """Array of frequencies for the lower-edge of each frequency bin :type: `numpy.ndarray` """
bandwidths = 2 * pi ** (1/2.) * self.frequencies / self.q return self.frequencies - bandwidths / 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 ntiles(self): """The number of tiles in this row :type: `int` """
tcum_mismatch = self.duration * 2 * pi * self.frequency / self.q return next_power_of_two(tcum_mismatch / self.deltam)
<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_window(self): """Generate the bi-square window for this row Returns ------- window : `numpy.ndarray` """
# real frequencies wfrequencies = self._get_indices() / self.duration # dimensionless frequencies xfrequencies = wfrequencies * self.qprime / self.frequency # normalize and generate bi-square window norm = self.ntiles / (self.duration * self.sampling) * ( 315...
<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_data_indices(self): """Returns the index array of interesting frequencies for this row """
return numpy.round(self._get_indices() + 1 + self.frequency * self.duration).astype(int)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interpolate(self, tres="<default>", fres="<default>", logf=False, outseg=None): """Interpolate this `QGram` over a regularly-gridded spectrogram Parameters t...
from scipy.interpolate import (interp2d, InterpolatedUnivariateSpline) from ..spectrogram import Spectrogram if outseg is None: outseg = self.energies[0].span frequencies = self.plane.frequencies dtype = self.energies[0].dtype # build regular Spectrogram from...
<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(self, snrthresh=5.5): """Represent this `QPlane` as an `EventTable` Parameters snrthresh : `float`, optional lower inclusive threshold on individual ti...
from ..table import EventTable # get plane properties freqs = self.plane.frequencies bws = 2 * (freqs - self.plane.farray) # collect table data as a recarray names = ('time', 'frequency', 'duration', 'bandwidth', 'energy') rec = numpy.recarray((0,), names=names, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def define(cls, start, step, num, dtype=None): """Define a new `Index`. The output is basically:: start + numpy.arange(num) * step Parameters start : `Number` Th...
if dtype is None: dtype = max( numpy.array(start, subok=True, copy=False).dtype, numpy.array(step, subok=True, copy=False).dtype, ) start = start.astype(dtype, copy=False) step = step.astype(dtype, copy=False) return cls(start + nu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def regular(self): """`True` if this index is linearly increasing """
try: return self.info.meta['regular'] except (TypeError, KeyError): if self.info.meta is None: self.info.meta = {} self.info.meta['regular'] = self.is_regular() return self.info.meta['regular']