code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# if target file doesn't exist, we must generate it if not os.path.isfile(filename): return False # if we can interact with git, we can regenerate it, so we may as well try: import git except ImportError: return True else: try: git.Repo().tags ...
def reuse_dist_file(filename)
Returns `True` if a distribution file can be reused Otherwise it should be regenerated
5.189032
5.187344
1.000325
# if not in git clone, it doesn't matter if not in_git_clone(): return 'GitPython' # otherwise, call out to get the git version try: gitv = subprocess.check_output('git --version', shell=True) except (OSError, IOError, subprocess.CalledProcessError): # no git installati...
def get_gitpython_version()
Determine the required version of GitPython Because of target systems running very, very old versions of setuptools, we only specify the actual version we need when we need it.
3.157759
3.159362
0.999493
# don't force requirements if just asking for help if {'--help', '--help-commands'}.intersection(sys.argv): return list() # otherwise collect all requirements for all known commands reqlist = [] for cmd, dependencies in SETUP_REQUIRES.items(): if cmd in sys.argv: re...
def get_setup_requires()
Return the list of packages required for this setup.py run
5.757967
5.756772
1.000208
scripts = [] for (dirname, _, filenames) in os.walk(scripts_dir): scripts.extend([os.path.join(dirname, fn) for fn in filenames]) return scripts
def get_scripts(scripts_dir='bin')
Get relative file paths for all files under the ``scripts_dir``
2.286194
2.286692
0.999782
result = [] for part in years.split(','): if '-' in part: a, b = part.split('-') a, b = int(a), int(b) result.extend(range(a, b + 1)) else: a = int(part) result.append(a) return result
def _parse_years(years)
Parse string of ints include ranges into a `list` of `int` Source: https://stackoverflow.com/a/6405228/1307974
1.898205
1.713871
1.107554
def sub(x): return x[1] - x[0] ranges = [] for k, iterable in groupby(enumerate(sorted(years)), sub): rng = list(iterable) if len(rng) == 1: s = str(rng[0][1]) else: s = "{}-{}".format(rng[0][1], rng[-1][1]) ranges.append(s) return ",...
def _format_years(years)
Format a list of ints into a string including ranges Source: https://stackoverflow.com/a/9471386/1307974
2.923335
2.542873
1.149619
with open(path, "r") as fobj: text = fobj.read().rstrip() match = COPYRIGHT_REGEX.search(text) x = match.start("years") y = match.end("years") if text[y-1] == " ": # don't strip trailing whitespace y -= 1 yearstr = match.group("years") years = set(_parse_years(yearstr))...
def update_copyright(path, year)
Update a file's copyright statement to include the given year
3.376858
3.500925
0.964562
# parse args and kwargs if not spectrograms: raise ValueError("Must give at least one Spectrogram") bins = kwargs.pop('bins', None) low = kwargs.pop('low', None) high = kwargs.pop('high', None) nbins = kwargs.pop('nbins', 500) log = kwargs.pop...
def from_spectrogram(cls, *spectrograms, **kwargs)
Calculate a new `SpectralVariance` from a :class:`~gwpy.spectrogram.Spectrogram` Parameters ---------- spectrogram : `~gwpy.spectrogram.Spectrogram` input `Spectrogram` data bins : `~numpy.ndarray`, optional array of histogram bin edges, including the ri...
2.404007
2.172431
1.106598
rows, columns = self.shape out = numpy.zeros(rows) # Loop over frequencies for i in range(rows): # Calculate cumulative sum for array cumsumvals = numpy.cumsum(self.value[i, :]) # Find value nearest requested percentile abs_cumsum...
def percentile(self, percentile)
Calculate a given spectral percentile for this `SpectralVariance` Parameters ---------- percentile : `float` percentile (0 - 100) of the bins to compute Returns ------- spectrum : `~gwpy.frequencyseries.FrequencySeries` the given percentile `Freq...
4.532392
3.993667
1.134895
if self.type is not None: return io_nds2.Nds2ChannelType.find(self.type).value
def ndstype(self)
NDS type integer for this channel. This property is mapped to the `Channel.type` string.
17.677505
13.372629
1.321917
if self.type not in [None, 'raw', 'reduced', 'online']: return '%s,%s' % (self.name, self.type) return self.name
def ndsname(self)
Name of this channel as stored in the NDS database
6.269231
6.091815
1.029124
channellist = ChannelList.query(name, use_kerberos=use_kerberos, debug=debug) if not channellist: raise ValueError("No channels found matching '%s'" % name) if len(channellist) > 1: raise ValueError("%d channels found match...
def query(cls, name, use_kerberos=None, debug=False)
Query the LIGO Channel Information System for the `Channel` matching the given name Parameters ---------- name : `str` name of channel use_kerberos : `bool`, optional use an existing Kerberos ticket as the authentication credential, default b...
3.111103
3.245557
0.958573
return ChannelList.query_nds2([name], host=host, port=port, connection=connection, type=type, unique=True)[0]
def query_nds2(cls, name, host=None, port=None, connection=None, type=None)
Query an NDS server for channel information Parameters ---------- name : `str` name of requested channel host : `str`, optional name of NDS2 server. port : `int`, optional port number for NDS2 connection connection : `nds2.connection` ...
5.230217
7.931287
0.659441
# extract metadata name = nds2channel.name sample_rate = nds2channel.sample_rate unit = nds2channel.signal_units if not unit: unit = None ctype = nds2channel.channel_type_to_string(nds2channel.channel_type) # get dtype dtype = { # pyl...
def from_nds2(cls, nds2channel)
Generate a new channel using an existing nds2.channel object
2.221241
2.242755
0.990407
match = cls.MATCH.search(name) if match is None or (strict and ( match.start() != 0 or match.end() != len(name))): raise ValueError("Cannot parse channel name according to LIGO " "channel-naming convention T990033") return match.g...
def parse_channel_name(cls, name, strict=True)
Decompose a channel name string into its components Parameters ---------- name : `str` name to parse strict : `bool`, optional require exact matching of format, with no surrounding text, default `True` Returns ------- match : ...
6.822338
8.991736
0.758734
return datafind.find_frametype( self, gpstime=gpstime, frametype_match=frametype_match, host=host, port=port, return_all=return_all, allow_tape=allow_tape)
def find_frametype(self, gpstime=None, frametype_match=None, host=None, port=None, return_all=False, allow_tape=True)
Find the containing frametype(s) for this `Channel` Parameters ---------- gpstime : `int` a reference GPS time at which to search for frame files frametype_match : `str` a regular expression string to use to down-select from the list of all available ...
2.003092
2.908418
0.688722
new = type(self)(str(self)) new._init_from_channel(self) return new
def copy(self)
Returns a copy of this channel
8.794706
6.890396
1.276372
new = cls() for namestr in names: for name in cls._split_names(namestr): new.append(Channel(name)) return new
def from_names(cls, *names)
Create a new `ChannelList` from a list of names The list of names can include comma-separated sets of names, in which case the return will be a flattened list of all parsed channel names.
5.40339
4.236933
1.275307
out = [] namestr = QUOTE_REGEX.sub('', namestr) while True: namestr = namestr.strip('\' \n') if ',' not in namestr: break for nds2type in io_nds2.Nds2ChannelType.names() + ['']: if nds2type and ',%s' % nds2type in names...
def _split_names(namestr)
Split a comma-separated list of channel names.
3.755205
3.513886
1.068676
for i, chan in enumerate(self): if name == chan.name: return i raise ValueError(name)
def find(self, name)
Find the `Channel` with a specific name in this `ChannelList`. Parameters ---------- name : `str` name of the `Channel` to find Returns ------- index : `int` the position of the first `Channel` in this `ChannelList` whose `~Channel.na...
5.030659
4.271799
1.177644
# format name regex if isinstance(name, Pattern): flags = name.flags name = name.pattern else: flags = 0 if exact_match: name = name if name.startswith(r'\A') else r"\A%s" % name name = name if name.endswith(r'\Z') else...
def sieve(self, name=None, sample_rate=None, sample_range=None, exact_match=False, **others)
Find all `Channels <Channel>` in this list matching the specified criteria. Parameters ---------- name : `str`, or regular expression any part of the channel name against which to match (or full name if `exact_match=False` is given) sample_rate : `float` ...
2.212012
2.252137
0.982184
from .io import cis return cis.query(name, use_kerberos=use_kerberos, debug=debug)
def query(cls, name, use_kerberos=None, debug=False)
Query the LIGO Channel Information System a `ChannelList`. Parameters ---------- name : `str` name of channel, or part of it. use_kerberos : `bool`, optional use an existing Kerberos ticket as the authentication credential, default behaviour will che...
5.364487
7.306065
0.734251
ndschannels = io_nds2.find_channels(names, host=host, port=port, connection=connection, type=type, unique=unique) return cls(map(Channel.from_nds2, ndschannels))
def query_nds2(cls, names, host=None, port=None, connection=None, type=io_nds2.Nds2ChannelType.any(), unique=False)
Query an NDS server for channel information Parameters ---------- name : `str` name of requested channel host : `str`, optional name of NDS2 server. port : `int`, optional port number for NDS2 connection connection : `nds2.connection` ...
2.866861
4.805436
0.596587
start = int(to_gps(start)) end = int(ceil(to_gps(end))) chans = io_nds2.find_channels(channels, connection=connection, unique=True, epoch=(start, end), type=ctype) availability = io_nds2.get_availability...
def query_nds2_availability(cls, channels, start, end, ctype=126, connection=None, host=None, port=None)
Query for when data are available for these channels in NDS2 Parameters ---------- channels : `list` list of `Channel` or `str` for which to search start : `int` GPS start time of search, or any acceptable input to :meth:`~gwpy.time.to_gps` ...
5.085903
5.891138
0.863314
from sqlalchemy.engine import create_engine from sqlalchemy.exc import ProgrammingError # connect if needed if engine is None: conn_kw = {} for key in ('db', 'host', 'user', 'passwd'): try: conn_kw[key] = kwargs.pop(key) except KeyError: ...
def get_gravityspy_triggers(tablename, engine=None, **kwargs)
Fetch data into an `GravitySpyTable` Parameters ---------- table : `str`, The name of table you are attempting to receive triggers from. selection other filters you would like to supply underlying reader method for the given format .. note:: For now it will...
3.196382
3.16039
1.011388
if (not user) or (not passwd): user = os.getenv('GRAVITYSPY_DATABASE_USER', None) passwd = os.getenv('GRAVITYSPY_DATABASE_PASSWD', None) if (not user) or (not passwd): raise ValueError('Remember to either pass ' 'or export GRAVITYSPY_DATABASE_USER ' ...
def get_connection_str(db='gravityspy', host='gravityspy.ciera.northwestern.edu', user=None, passwd=None)
Create string to pass to create_engine Parameters ---------- db : `str`, default: ``gravityspy`` The name of the SQL database your connecting to. host : `str`, default: ``gravityspy.ciera.northwestern.edu`` The name of the server the database you are connecting to lives on. ...
3.770517
4.128802
0.913223
import pytz dt = dt or datetime.datetime.now() offset = pytz.timezone(get_timezone(ifo)).utcoffset(dt) return offset.days * 86400 + offset.seconds + offset.microseconds * 1e-6
def get_timezone_offset(ifo, dt=None)
Return the offset in seconds between UTC and the given interferometer Parameters ---------- ifo : `str` prefix of interferometer, e.g. ``'X1'`` dt : `datetime.datetime`, optional the time at which to calculate the offset, defaults to now Returns ------- offset : `int` ...
2.310876
2.870042
0.805172
# parse keywords if kwargs is None: kwargs = dict() samp = series.sample_rate fftlength = kwargs.pop('fftlength', None) or series.duration overlap = kwargs.pop('overlap', None) window = kwargs.pop('window', None) # parse function library and name if func is None: me...
def normalize_fft_params(series, kwargs=None, func=None)
Normalize a set of FFT parameters for processing This method reads the ``fftlength`` and ``overlap`` keyword arguments (presumed to be values in seconds), works out sensible defaults, then updates ``kwargs`` in place to include ``nfft`` and ``noverlap`` as values in sample counts. If a ``window`` ...
3.956865
4.028536
0.982209
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)
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...
5.085263
5.281792
0.962791
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_...
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 ro...
3.45319
3.806815
0.907107
@wraps(func) def wrapped_func(series, method_func, *args, **kwargs): 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) ...
def set_fft_params(func)
Decorate a method to automatically convert quantities to samples
4.592635
4.694556
0.97829
# decorator has translated the arguments for us, so just call psdn() return _psdn(timeseries, method_func, *args, **kwargs)
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 cal...
12.612483
21.379608
0.589931
# 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'), ...
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 : `call...
5.296835
5.763454
0.919038
# 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 ns...
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
5.196319
5.235093
0.992593
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: rais...
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
4.183105
4.227568
0.989482
re_name_def = re.compile(r'^\s*%\s+(?P<colname>\w+)') self.names = [] for line in lines: if not line: # ignore empty lines in header (windows) continue if not line.startswith('%'): # end of header lines break match = ...
def get_cols(self, lines)
Initialize Column objects from a multi-line ASCII header Parameters ---------- lines : `list` List of table lines
3.333544
3.301822
1.009608
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 (...
def get_color_label(self)
Text for colorbar label
4.609358
4.168011
1.105889
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, f...
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`.
8.457479
8.691771
0.973044
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.timese...
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`.
3.833516
3.671339
1.044174
args = self.args # constant input causes unhelpful (weird) error messages # translate them to English inmin = self.timeseries[0].min().value if inmin == self.timeseries[0].max().value: if not self.got_error: self.log(0, 'ERROR: Input has cons...
def make_plot(self)
Generate the plot from time series and arguments
9.551649
9.230311
1.034813
if len(self.units) == 1: return r'ASD $\left({0}\right)$'.format( self.units[0].to_string('latex').strip('$')) return 'ASD'
def get_ylabel(self)
Text for y-axis label
5.87254
5.668336
1.036025
args = self.args fftlength = float(args.secpfft) overlap = args.overlap self.log(2, "Calculating spectrum secpfft: {0}, overlap: {1}".format( fftlength, overlap)) overlap *= fftlength # create plot plot = Plot(figsize=self.figsize, dpi=self....
def make_plot(self)
Generate the plot from time series and arguments
4.933257
4.807483
1.026162
# get tight limits for X-axis if self.args.xmin is None: self.args.xmin = min(fs.xspan[0] for fs in self.spectra) if self.args.xmax is None: self.args.xmax = max(fs.xspan[1] for fs in self.spectra) # autoscale view for Y-axis cropped = [fs.crop(s...
def scale_axes_from_data(self)
Restrict data limits for Y-axis based on what you can see
3.13328
2.982123
1.050687
# 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 argume...
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.
7.040054
7.161863
0.982992
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_factory(cls, gap, pad)
Build a joiner for the given cls, and the given padding options
4.494005
4.503016
0.997999
# 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) # par...
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...
4.292508
4.349437
0.986911
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 " ...
def _find_table_group(h5file, ifo=None)
Find the right `h5py.Group` within the given `h5py.File`
4.938243
4.845187
1.019206
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 - ME...
def _get_columns(h5group)
Find valid column names from a PyCBC HDF5 Group Returns a `set` of names.
4.334207
4.621003
0.937936
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...
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
4.121046
4.357939
0.945641
return type(files)([f for f in files if not empty_hdf5_file(f, ifo=ifo)])
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...
5.786528
7.676573
0.753791
# 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
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 t...
5.417045
5.665971
0.956066
if identify_hdf5(origin, filepath, fileobj, *args, **kwargs) and ( filepath is not None and PYCBC_FILENAME.match(basename(filepath))): return True return False
def identify_pycbc_live(origin, filepath, fileobj, *args, **kwargs)
Identify a PyCBC Live file as an HDF5 with the correct name
5.259977
4.641081
1.133352
def get_new_snr(h5group, q=6., n=2.): # pylint: disable=invalid-name 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
Calculate the 'new SNR' column for this PyCBC HDF5 table group
null
null
null
mass1 = h5group['mass1'][:] mass2 = h5group['mass2'][:] return (mass1 * mass2) ** (3/5.) / (mass1 + mass2) ** (1/5.)
def get_mchirp(h5group)
Calculate the chipr mass column for this PyCBC HDF5 table group
3.079647
2.983162
1.032343
if not isinstance(item, tuple): item = (item,) return item[:ndim] + (None,) * (ndim - len(item))
def format_nd_slice(item, ndim)
Preformat a getitem argument as an N-tuple
2.740594
2.706557
1.012576
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_]) # ot...
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 ne...
3.828182
4.261489
0.89832
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
def null_slice(slice_)
Returns True if a slice will have no affect
3.131219
2.991912
1.046561
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".form...
def as_slice(slice_)
Convert an object to a slice, if possible
3.145234
3.069124
1.024798
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 i...
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
3.639685
3.743507
0.972266
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...
def _get(url, use_kerberos=None, debug=False)
Perform a GET query against the CIS
6.245858
6.224207
1.003478
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)
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
5.815801
5.078989
1.145071
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: ...
def get_ylabel(self)
Text for y-axis label, check if channel defines it
3.566445
3.369139
1.058563
plot = Plot(figsize=self.figsize, dpi=self.dpi) ax = plot.gca(xscale='auto-gps') # handle user specified plot labels if self.args.legend: nlegargs = len(self.args.legend[0]) else: nlegargs = 0 if nlegargs > 0 and nlegargs != self.n_datase...
def make_plot(self)
Generate the plot from time series and arguments
4.467722
4.309464
1.036723
# get tight limits for X-axis if self.args.xmin is None: self.args.xmin = min(ts.xspan[0] for ts in self.timeseries) if self.args.xmax is None: self.args.xmax = max(ts.xspan[1] for ts in self.timeseries) # autoscale view for Y-axis cropped = [ts....
def scale_axes_from_data(self)
Restrict data limits for Y-axis based on what you can see
3.099314
2.943221
1.053035
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...
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:`nump...
4.383822
4.052071
1.081872
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] #...
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 compli...
4.955379
4.629022
1.070502
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)
def window_from_array(array)
Convert a `numpy.ndarray` into a LAL `Window` object
7.332073
6.357369
1.153319
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) ...
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 samp...
4.700131
4.37315
1.07477
return _lal_spectrum(timeseries, segmentlength, noverlap=noverlap, method='welch', window=window, plan=plan)
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, d...
4.01445
5.897809
0.680668
# pylint: disable=unused-argument return _lal_spectrum(timeseries, segmentlength, noverlap=0, method='welch', window=window, plan=plan)
def bartlett(timeseries, segmentlength, noverlap=None, window=None, plan=None)
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...
5.554236
9.257452
0.599975
return _lal_spectrum(timeseries, segmentlength, noverlap=noverlap, method='median', window=window, plan=plan)
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 o...
4.615837
6.524323
0.707481
return _lal_spectrum(timeseries, segmentlength, noverlap=noverlap, method='median-mean', window=window, plan=plan)
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...
4.247206
5.773282
0.735666
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(sour...
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 id...
4.343031
3.872535
1.121496
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.FrFileQueryNFram...
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
7.303968
7.234735
1.00957
# 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", ) str...
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
6.445489
6.311217
1.021275
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.ch...
def write(tsdict, outfile, start=None, end=None, name='gwpy', run=0)
Write data to a GWF file using the LALFrame API
5.103479
4.824402
1.057847
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 ...
def segment_content_handler()
Build a `~xml.sax.handlers.ContentHandler` to read segment XML tables
9.586926
10.05608
0.953346
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...
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 ...
9.817524
7.654399
1.282599
name = [name] if name is not None else None return list(read_ligolw_dict(source, names=name, **kwargs).values())[0]
def read_ligolw_flag(source, name=None, **kwargs)
Read a single `DataQualityFlag` from a LIGO_LW XML file
4.590827
4.705293
0.975673
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 )
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 ...
6.341293
4.225077
1.500871
# 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 = baseu...
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 ...
3.955378
3.975545
0.994927
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 p...
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.
4.345787
3.360662
1.293134
# 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)] ...
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 t...
4.768357
4.574959
1.042273
# 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": ...
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 e...
3.175042
2.687367
1.181469
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 ...
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`
4.645636
4.888706
0.950279
if HAS_CACHEENTRY and isinstance(path, CacheEntry): return True try: file_segment(path) except (ValueError, TypeError, AttributeError): return False return True
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`...
6.222993
7.643209
0.814186
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) du...
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 Retu...
5.272496
3.83671
1.374223
from ..segments import Segment try: # CacheEntry return Segment(filename.segment) except AttributeError: # file path (str) return filename_metadata(filename)[2]
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 -...
20.600485
12.98062
1.587019
from ..segments import SegmentList out = SegmentList() for cache in caches: out.extend(file_segment(e) for e in cache) return out.coalesce()
def cache_segments(*caches)
Returns the segments of data covered by entries in the cache(s). Parameters ---------- *caches : `list` One or more lists of file paths (`str` or :class:`~lal.utils.CacheEntry`). Returns ------- segments : `~gwpy.segments.SegmentList` A list of segments for when data sh...
7.603915
10.777946
0.705507
return list(OrderedDict.fromkeys(e for c in caches for e in c))
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.
6.699638
15.519653
0.431687
flat = flatten(*caches) for segment in cache_segments(flat): yield sieve(flat, segment=segment)
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
11.335654
22.0786
0.513423
return type(cache)(e for e in cache if segment.intersects(file_segment(e)))
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.
15.303133
15.00766
1.019688
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...
def arg_qxform(cls, parser)
Add an `~argparse.ArgumentGroup` for Q-transform options
4.508719
3.971705
1.13521
gps = args.gps search = args.search # ensure we have enough data for filter settling max_plot = max(args.plot) search = max(search, max_plot * 2 + 8) args.search = search self.log(3, "Search window: {0:.0f} sec, max plot window {1:.0f}". ...
def _finalize_arguments(self, args)
Derive standard args from our weird ones :type args: Namespace with command line arguments
7.836951
7.820472
1.002107
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 ...
def get_title(self)
Default title for plot
4.156477
4.034821
1.030152
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_a...
def get_spectrogram(self)
Worked on a single timesharing and generates a single Q-transform spectrogram
7.415803
7.048828
1.052062
from lal import LIGOTimeGPS try: return LIGOTimeGPS(s, ns) except TypeError: return LIGOTimeGPS(int(s), int(ns))
def _ligotimegps(s, ns=0)
Catch TypeError and cast `s` and `ns` to `int`
3.160939
2.38328
1.326297
module = import_module(module) orig = module.LIGOTimeGPS module.LIGOTimeGPS = _ligotimegps try: yield finally: module.LIGOTimeGPS = orig
def patch_ligotimegps(module="ligo.lw.lsctables")
Context manager to on-the-fly patch LIGOTimeGPS to accept all int types
2.420704
2.314279
1.045986
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.tag...
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.PartialLIGOLWContentH...
6.65189
4.243205
1.567657
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=unuse...
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.F...
7.143211
4.791013
1.49096