signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def pkg_config_header_strings(pkg_libraries): | _, _, header_dirs = pkg_config(pkg_libraries)<EOL>header_strings = []<EOL>for header_dir in header_dirs:<EOL><INDENT>header_strings.append("<STR_LIT>" + header_dir)<EOL><DEDENT>return header_strings<EOL> | Returns a list of header strings that could be passed to a compiler | f15951:m1 |
def pkg_config_libdirs(packages): | <EOL>if os.environ.get("<STR_LIT>", None):<EOL><INDENT>return []<EOL><DEDENT>try:<EOL><INDENT>FNULL = open(os.devnull, '<STR_LIT:w>')<EOL>subprocess.check_call(["<STR_LIT>", "<STR_LIT>"], stdout=FNULL, close_fds=True)<EOL><DEDENT>except:<EOL><INDENT>print("<STR_LIT>",<EOL>file=sys.stderr)<EOL>os.environ['<STR_LIT>'] = "<STR_LIT:1>"<EOL>return []<EOL><DEDENT>for pkg in packages:<EOL><INDENT>if not pkg_config_check_exists(pkg):<EOL><INDENT>raise ValueError("<STR_LIT>".format(pkg))<EOL><DEDENT><DEDENT>libdirs = []<EOL>for token in getoutput("<STR_LIT>".format('<STR_LIT:U+0020>'.join(packages))).split():<EOL><INDENT>if token.startswith("<STR_LIT>"):<EOL><INDENT>libdirs.append(token[<NUM_LIT:2>:])<EOL><DEDENT><DEDENT>return libdirs<EOL> | Returns a list of all library paths that pkg-config says should be included when
linking against the list of packages given as 'packages'. An empty return list means
that the package may be found in the standard system locations, irrespective of
pkg-config. | f15951:m3 |
def get_libpath_from_dirlist(libname, dirs): | dirqueue = deque(dirs)<EOL>while (len(dirqueue) > <NUM_LIT:0>):<EOL><INDENT>nextdir = dirqueue.popleft()<EOL>possible = []<EOL>try:<EOL><INDENT>for libfile in os.listdir(nextdir):<EOL><INDENT>if fnmatch.fnmatch(libfile,'<STR_LIT>'+libname+'<STR_LIT>') orfnmatch.fnmatch(libfile,'<STR_LIT>'+libname+'<STR_LIT>') orfnmatch.fnmatch(libfile,libname+'<STR_LIT>') orfnmatch.fnmatch(libfile,'<STR_LIT>'+libname+'<STR_LIT>'):<EOL><INDENT>possible.append(libfile)<EOL><DEDENT><DEDENT><DEDENT>except OSError:<EOL><INDENT>pass<EOL><DEDENT>if (len(possible) > <NUM_LIT:0>):<EOL><INDENT>possible.sort()<EOL>return os.path.join(nextdir,possible[-<NUM_LIT:1>])<EOL><DEDENT><DEDENT>return None<EOL> | This function tries to find the architecture-independent library given by libname in the first
available directory in the list dirs. 'Architecture-independent' means omitting any prefix such
as 'lib' or suffix such as 'so' or 'dylib' or version number. Within the first directory in which
a matching pattern can be found, the lexicographically first such file is returned, as a string
giving the full path name. The only supported OSes at the moment are posix and mac, and this
function does not attempt to determine which is being run. So if for some reason your directory
has both '.so' and '.dylib' libraries, who knows what will happen. If the library cannot be found,
None is returned. | f15951:m4 |
def get_ctypes_library(libname, packages, mode=None): | libdirs = []<EOL>if "<STR_LIT>" in os.environ:<EOL><INDENT>libdirs += os.environ["<STR_LIT>"].split("<STR_LIT::>")<EOL><DEDENT>try:<EOL><INDENT>libdirs += pkg_config_libdirs(packages)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT>fullpath = get_libpath_from_dirlist(libname,libdirs)<EOL>if fullpath is None:<EOL><INDENT>fullpath = find_library(libname)<EOL><DEDENT>if fullpath is None:<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>if mode is None:<EOL><INDENT>return ctypes.CDLL(fullpath)<EOL><DEDENT>else:<EOL><INDENT>return ctypes.CDLL(fullpath,mode=mode)<EOL><DEDENT><DEDENT> | This function takes a library name, specified in architecture-independent fashion (i.e.
omitting any prefix such as 'lib' or suffix such as 'so' or 'dylib' or version number) and
a list of packages that may provide that library, and according first to LD_LIBRARY_PATH,
then the results of pkg-config, and falling back to the system search path, will try to
return a CDLL ctypes object. If 'mode' is given it will be used when loading the library. | f15951:m5 |
def required_opts(opt, parser, opt_list, required_by=None): | for name in opt_list:<EOL><INDENT>attr = name[<NUM_LIT:2>:].replace('<STR_LIT:->', '<STR_LIT:_>')<EOL>if not hasattr(opt, attr) or (getattr(opt, attr) is None):<EOL><INDENT>err_str = "<STR_LIT>" % name<EOL>if required_by is not None:<EOL><INDENT>err_str += "<STR_LIT>" % required_by<EOL><DEDENT>parser.error(err_str)<EOL><DEDENT><DEDENT> | Check that all the opts are defined
Parameters
----------
opt : object
Result of option parsing
parser : object
OptionParser instance.
opt_list : list of strings
required_by : string, optional
the option that requires these options (if applicable) | f15955:m0 |
def required_opts_multi_ifo(opt, parser, ifo, opt_list, required_by=None): | for name in opt_list:<EOL><INDENT>attr = name[<NUM_LIT:2>:].replace('<STR_LIT:->', '<STR_LIT:_>')<EOL>try:<EOL><INDENT>if getattr(opt, attr)[ifo] is None:<EOL><INDENT>raise KeyError<EOL><DEDENT><DEDENT>except KeyError:<EOL><INDENT>err_str = "<STR_LIT>" % name<EOL>if required_by is not None:<EOL><INDENT>err_str += "<STR_LIT>" % required_by<EOL><DEDENT>parser.error(err_str)<EOL><DEDENT><DEDENT> | Check that all the opts are defined
Parameters
----------
opt : object
Result of option parsing
parser : object
OptionParser instance.
ifo : string
opt_list : list of strings
required_by : string, optional
the option that requires these options (if applicable) | f15955:m1 |
def ensure_one_opt(opt, parser, opt_list): | the_one = None<EOL>for name in opt_list:<EOL><INDENT>attr = name[<NUM_LIT:2>:].replace('<STR_LIT:->', '<STR_LIT:_>')<EOL>if hasattr(opt, attr) and (getattr(opt, attr) is not None):<EOL><INDENT>if the_one is None:<EOL><INDENT>the_one = name<EOL><DEDENT>else:<EOL><INDENT>parser.error("<STR_LIT>"% (the_one, name))<EOL><DEDENT><DEDENT><DEDENT>if the_one is None:<EOL><INDENT>parser.error("<STR_LIT>"% ('<STR_LIT:U+002CU+0020>'.join(opt_list)))<EOL><DEDENT> | Check that one and only one in the opt_list is defined in opt
Parameters
----------
opt : object
Result of option parsing
parser : object
OptionParser instance.
opt_list : list of strings | f15955:m2 |
def ensure_one_opt_multi_ifo(opt, parser, ifo, opt_list): | the_one = None<EOL>for name in opt_list:<EOL><INDENT>attr = name[<NUM_LIT:2>:].replace('<STR_LIT:->', '<STR_LIT:_>')<EOL>try:<EOL><INDENT>if getattr(opt, attr)[ifo] is None:<EOL><INDENT>raise KeyError<EOL><DEDENT><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if the_one is None:<EOL><INDENT>the_one = name<EOL><DEDENT>else:<EOL><INDENT>parser.error("<STR_LIT>"% (the_one, name))<EOL><DEDENT><DEDENT><DEDENT>if the_one is None:<EOL><INDENT>parser.error("<STR_LIT>"% ('<STR_LIT:U+002CU+0020>'.join(opt_list)))<EOL><DEDENT> | Check that one and only one in the opt_list is defined in opt
Parameters
----------
opt : object
Result of option parsing
parser : object
OptionParser instance.
opt_list : list of strings | f15955:m3 |
def copy_opts_for_single_ifo(opt, ifo): | opt = copy.deepcopy(opt)<EOL>for arg, val in vars(opt).items():<EOL><INDENT>if isinstance(val, DictWithDefaultReturn):<EOL><INDENT>setattr(opt, arg, getattr(opt, arg)[ifo])<EOL><DEDENT><DEDENT>return opt<EOL> | Takes the namespace object (opt) from the multi-detector interface and
returns a namespace object for a single ifo that can be used with
functions expecting output from the single-detector interface. | f15955:m4 |
def convert_to_process_params_dict(opt): | opt = copy.deepcopy(opt)<EOL>for arg, val in vars(opt).items():<EOL><INDENT>if isinstance(val, DictWithDefaultReturn):<EOL><INDENT>new_val = []<EOL>for key in val.keys():<EOL><INDENT>if isinstance(val[key], list):<EOL><INDENT>for item in val[key]:<EOL><INDENT>if item is not None:<EOL><INDENT>new_val.append('<STR_LIT::>'.join([key, str(item)]))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if val[key] is not None:<EOL><INDENT>new_val.append('<STR_LIT::>'.join([key, str(val[key])]))<EOL><DEDENT><DEDENT><DEDENT>setattr(opt, arg, new_val)<EOL><DEDENT><DEDENT>return vars(opt)<EOL> | Takes the namespace object (opt) from the multi-detector interface and
returns a dictionary of command line options that will be handled correctly
by the register_to_process_params ligolw function. | f15955:m5 |
def positive_float(s): | err_msg = "<STR_LIT>" % s<EOL>try:<EOL><INDENT>value = float(s)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise argparse.ArgumentTypeError(err_msg)<EOL><DEDENT>if value <= <NUM_LIT:0>:<EOL><INDENT>raise argparse.ArgumentTypeError(err_msg)<EOL><DEDENT>return value<EOL> | Ensure argument is a positive real number and return it as float.
To be used as type in argparse arguments. | f15955:m6 |
def nonnegative_float(s): | err_msg = "<STR_LIT>" % s<EOL>try:<EOL><INDENT>value = float(s)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise argparse.ArgumentTypeError(err_msg)<EOL><DEDENT>if value < <NUM_LIT:0>:<EOL><INDENT>raise argparse.ArgumentTypeError(err_msg)<EOL><DEDENT>return value<EOL> | Ensure argument is a positive real number or zero and return it as float.
To be used as type in argparse arguments. | f15955:m7 |
def load_timeseries(path, group=None): | ext = _os.path.splitext(path)[<NUM_LIT:1>]<EOL>if ext == '<STR_LIT>':<EOL><INDENT>data = _numpy.load(path)<EOL><DEDENT>elif ext == '<STR_LIT>':<EOL><INDENT>data = _numpy.loadtxt(path)<EOL><DEDENT>elif ext == '<STR_LIT>':<EOL><INDENT>key = '<STR_LIT:data>' if group is None else group<EOL>f = h5py.File(path)<EOL>data = f[key][:]<EOL>series = TimeSeries(data, delta_t=f[key].attrs['<STR_LIT>'],<EOL>epoch=f[key].attrs['<STR_LIT>'])<EOL>f.close()<EOL>return series<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if data.ndim == <NUM_LIT:2>:<EOL><INDENT>delta_t = (data[-<NUM_LIT:1>][<NUM_LIT:0>] - data[<NUM_LIT:0>][<NUM_LIT:0>]) / (len(data)-<NUM_LIT:1>)<EOL>epoch = _lal.LIGOTimeGPS(data[<NUM_LIT:0>][<NUM_LIT:0>])<EOL>return TimeSeries(data[:,<NUM_LIT:1>], delta_t=delta_t, epoch=epoch)<EOL><DEDENT>elif data.ndim == <NUM_LIT:3>:<EOL><INDENT>delta_t = (data[-<NUM_LIT:1>][<NUM_LIT:0>] - data[<NUM_LIT:0>][<NUM_LIT:0>]) / (len(data)-<NUM_LIT:1>)<EOL>epoch = _lal.LIGOTimeGPS(data[<NUM_LIT:0>][<NUM_LIT:0>])<EOL>return TimeSeries(data[:,<NUM_LIT:1>] + <NUM_LIT>*data[:,<NUM_LIT:2>],<EOL>delta_t=delta_t, epoch=epoch)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % data.ndim)<EOL><DEDENT> | Load a TimeSeries from a .hdf, .txt or .npy file. The
default data types will be double precision floating point.
Parameters
----------
path: string
source file path. Must end with either .npy or .txt.
group: string
Additional name for internal storage use. Ex. hdf storage uses
this as the key value.
Raises
------
ValueError
If path does not end in .npy or .txt. | f15956:m0 |
def prepend_zeros(self, num): | self.resize(len(self) + num)<EOL>self.roll(num)<EOL>self._epoch = self._epoch - num * self._delta_t<EOL> | Prepend num zeros onto the beginning of this TimeSeries. Update also
epoch to include this prepending. | f15956:c0:m4 |
def append_zeros(self, num): | self.resize(len(self) + num)<EOL> | Append num zeros onto the end of this TimeSeries. | f15956:c0:m5 |
def get_delta_t(self): | return self._delta_t<EOL> | Return time between consecutive samples in seconds. | f15956:c0:m6 |
def get_duration(self): | return len(self) * self._delta_t<EOL> | Return duration of time series in seconds. | f15956:c0:m7 |
def get_sample_rate(self): | return int(round(<NUM_LIT:1.0>/self.delta_t))<EOL> | Return the sample rate of the time series. | f15956:c0:m8 |
def time_slice(self, start, end): | if start < self.start_time:<EOL><INDENT>raise ValueError('<STR_LIT>' % start)<EOL><DEDENT>if end > self.end_time:<EOL><INDENT>raise ValueError('<STR_LIT>' % end)<EOL><DEDENT>start_idx = int((start - self.start_time) * self.sample_rate)<EOL>end_idx = int((end - self.start_time) * self.sample_rate)<EOL>return self[start_idx:end_idx]<EOL> | Return the slice of the time series that contains the time range
in GPS seconds. | f15956:c0:m9 |
@property<EOL><INDENT>def delta_f(self):<DEDENT> | return <NUM_LIT:1.0> / self.duration<EOL> | Return the delta_f this ts would have in the frequency domain | f15956:c0:m10 |
@property<EOL><INDENT>def start_time(self):<DEDENT> | return self._epoch<EOL> | Return time series start time as a LIGOTimeGPS. | f15956:c0:m11 |
@start_time.setter<EOL><INDENT>def start_time(self, time):<DEDENT> | self._epoch = _lal.LIGOTimeGPS(time)<EOL> | Set the start time | f15956:c0:m12 |
def get_end_time(self): | return self._epoch + self.get_duration()<EOL> | Return time series end time as a LIGOTimeGPS. | f15956:c0:m13 |
def get_sample_times(self): | if self._epoch is None:<EOL><INDENT>return Array(range(len(self))) * self._delta_t<EOL><DEDENT>else:<EOL><INDENT>return Array(range(len(self))) * self._delta_t + float(self._epoch)<EOL><DEDENT> | Return an Array containing the sample times. | f15956:c0:m14 |
def at_time(self, time, nearest_sample=False): | if nearest_sample:<EOL><INDENT>time += self.delta_t / <NUM_LIT><EOL><DEDENT>return self[int((time-self.start_time)*self.sample_rate)]<EOL> | Return the value at the specified gps time | f15956:c0:m15 |
def __eq__(self,other): | if super(TimeSeries,self).__eq__(other):<EOL><INDENT>return (self._epoch == other._epoch and self._delta_t == other._delta_t)<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT> | This is the Python special method invoked whenever the '=='
comparison is used. It will return true if the data of two
time series are identical, and all of the numeric meta-data
are identical, irrespective of whether or not the two
instances live in the same memory (for that comparison, the
Python statement 'a is b' should be used instead).
Thus, this method returns 'True' if the types of both 'self'
and 'other' are identical, as well as their lengths, dtypes,
epochs, delta_ts and the data in the arrays, element by element.
It will always do the comparison on the CPU, but will *not* move
either object to the CPU if it is not already there, nor change
the scheme of either object. It is possible to compare a CPU
object to a GPU object, and the comparison should be true if the
data and meta-data of the two objects are the same.
Note in particular that this function returns a single boolean,
and not an array of booleans as Numpy does. If the numpy
behavior is instead desired it can be obtained using the numpy()
method of the PyCBC type to get a numpy instance from each
object, and invoking '==' on those two instances.
Parameters
----------
other: another Python object, that should be tested for equality
with 'self'.
Returns
-------
boolean: 'True' if the types, dtypes, lengths, epochs, delta_ts
and data of the two objects are each identical. | f15956:c0:m16 |
def almost_equal_elem(self,other,tol,relative=True,dtol=<NUM_LIT:0.0>): | <EOL>if (dtol < <NUM_LIT:0.0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if super(TimeSeries,self).almost_equal_elem(other,tol=tol,relative=relative):<EOL><INDENT>if relative:<EOL><INDENT>return (self._epoch == other._epoch and<EOL>abs(self._delta_t-other._delta_t) <= dtol*self._delta_t)<EOL><DEDENT>else:<EOL><INDENT>return (self._epoch == other._epoch and<EOL>abs(self._delta_t-other._delta_t) <= dtol)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT> | Compare whether two time series are almost equal, element
by element.
If the 'relative' parameter is 'True' (the default) then the
'tol' parameter (which must be positive) is interpreted as a
relative tolerance, and the comparison returns 'True' only if
abs(self[i]-other[i]) <= tol*abs(self[i])
for all elements of the series.
If 'relative' is 'False', then 'tol' is an absolute tolerance,
and the comparison is true only if
abs(self[i]-other[i]) <= tol
for all elements of the series.
The method also checks that self.delta_t is within 'dtol' of
other.delta_t; if 'dtol' has its default value of 0 then exact
equality between the two is required.
Other meta-data (type, dtype, length, and epoch) must be exactly
equal. If either object's memory lives on the GPU it will be
copied to the CPU for the comparison, which may be slow. But the
original object itself will not have its memory relocated nor
scheme changed.
Parameters
----------
other: another Python object, that should be tested for
almost-equality with 'self', element-by-element.
tol: a non-negative number, the tolerance, which is interpreted
as either a relative tolerance (the default) or an absolute
tolerance.
relative: A boolean, indicating whether 'tol' should be interpreted
as a relative tolerance (if True, the default if this argument
is omitted) or as an absolute tolerance (if tol is False).
dtol: a non-negative number, the tolerance for delta_t. Like 'tol',
it is interpreted as relative or absolute based on the value of
'relative'. This parameter defaults to zero, enforcing exact
equality between the delta_t values of the two TimeSeries.
Returns
-------
boolean: 'True' if the data and delta_ts agree within the tolerance,
as interpreted by the 'relative' keyword, and if the types,
lengths, dtypes, and epochs are exactly the same. | f15956:c0:m17 |
def almost_equal_norm(self,other,tol,relative=True,dtol=<NUM_LIT:0.0>): | <EOL>if (dtol < <NUM_LIT:0.0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if super(TimeSeries,self).almost_equal_norm(other,tol=tol,relative=relative):<EOL><INDENT>if relative:<EOL><INDENT>return (self._epoch == other._epoch and<EOL>abs(self._delta_t-other._delta_t) <= dtol*self._delta_t)<EOL><DEDENT>else:<EOL><INDENT>return (self._epoch == other._epoch and<EOL>abs(self._delta_t-other._delta_t) <= dtol)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT> | Compare whether two time series are almost equal, normwise.
If the 'relative' parameter is 'True' (the default) then the
'tol' parameter (which must be positive) is interpreted as a
relative tolerance, and the comparison returns 'True' only if
abs(norm(self-other)) <= tol*abs(norm(self)).
If 'relative' is 'False', then 'tol' is an absolute tolerance,
and the comparison is true only if
abs(norm(self-other)) <= tol
The method also checks that self.delta_t is within 'dtol' of
other.delta_t; if 'dtol' has its default value of 0 then exact
equality between the two is required.
Other meta-data (type, dtype, length, and epoch) must be exactly
equal. If either object's memory lives on the GPU it will be
copied to the CPU for the comparison, which may be slow. But the
original object itself will not have its memory relocated nor
scheme changed.
Parameters
----------
other: another Python object, that should be tested for
almost-equality with 'self', based on their norms.
tol: a non-negative number, the tolerance, which is interpreted
as either a relative tolerance (the default) or an absolute
tolerance.
relative: A boolean, indicating whether 'tol' should be interpreted
as a relative tolerance (if True, the default if this argument
is omitted) or as an absolute tolerance (if tol is False).
dtol: a non-negative number, the tolerance for delta_t. Like 'tol',
it is interpreted as relative or absolute based on the value of
'relative'. This parameter defaults to zero, enforcing exact
equality between the delta_t values of the two TimeSeries.
Returns
-------
boolean: 'True' if the data and delta_ts agree within the tolerance,
as interpreted by the 'relative' keyword, and if the types,
lengths, dtypes, and epochs are exactly the same. | f15956:c0:m18 |
@_convert<EOL><INDENT>def lal(self):<DEDENT> | lal_data = None<EOL>if self._epoch is None:<EOL><INDENT>ep = _lal.LIGOTimeGPS(<NUM_LIT:0>,<NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>ep = self._epoch<EOL><DEDENT>if self._data.dtype == _numpy.float32:<EOL><INDENT>lal_data = _lal.CreateREAL4TimeSeries("<STR_LIT>",ep,<NUM_LIT:0>,self.delta_t,_lal.SecondUnit,len(self))<EOL><DEDENT>elif self._data.dtype == _numpy.float64:<EOL><INDENT>lal_data = _lal.CreateREAL8TimeSeries("<STR_LIT>",ep,<NUM_LIT:0>,self.delta_t,_lal.SecondUnit,len(self))<EOL><DEDENT>elif self._data.dtype == _numpy.complex64:<EOL><INDENT>lal_data = _lal.CreateCOMPLEX8TimeSeries("<STR_LIT>",ep,<NUM_LIT:0>,self.delta_t,_lal.SecondUnit,len(self))<EOL><DEDENT>elif self._data.dtype == _numpy.complex128:<EOL><INDENT>lal_data = _lal.CreateCOMPLEX16TimeSeries("<STR_LIT>",ep,<NUM_LIT:0>,self.delta_t,_lal.SecondUnit,len(self))<EOL><DEDENT>lal_data.data.data[:] = self.numpy()<EOL>return lal_data<EOL> | Produces a LAL time series object equivalent to self.
Returns
-------
lal_data : {lal.*TimeSeries}
LAL time series object containing the same data as self.
The actual type depends on the sample's dtype. If the epoch of
self is 'None', the epoch of the returned LAL object will be
LIGOTimeGPS(0,0); otherwise, the same as that of self.
Raises
------
TypeError
If time series is stored in GPU memory. | f15956:c0:m19 |
def crop(self, left, right): | if left + right > self.duration:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>s = int(left * self.sample_rate)<EOL>e = len(self) - int(right * self.sample_rate)<EOL>return self[s:e]<EOL> | Remove given seconds from either end of time series
Parameters
----------
left : float
Number of seconds of data to remove from the left of the time series.
right : float
Number of seconds of data to remove from the right of the time series.
Returns
-------
cropped : pycbc.types.TimeSeries
The reduced time series | f15956:c0:m20 |
def save_to_wav(self, file_name): | scaled = _numpy.int16(self.numpy()/max(abs(self)) * <NUM_LIT>)<EOL>write_wav(file_name, self.sample_rate, scaled)<EOL> | Save this time series to a wav format audio file.
Parameters
----------
file_name : string
The output file name | f15956:c0:m21 |
def psd(self, segment_duration, **kwds): | from pycbc.psd import welch<EOL>seg_len = int(segment_duration * self.sample_rate)<EOL>seg_stride = int(seg_len / <NUM_LIT:2>)<EOL>return welch(self, seg_len=seg_len,<EOL>seg_stride=seg_stride,<EOL>**kwds)<EOL> | Calculate the power spectral density of this time series.
Use the `pycbc.psd.welch` method to estimate the psd of this time segment.
For more complete options, please see that function.
Parameters
----------
segment_duration: float
Duration in seconds to use for each sample of the spectrum.
kwds : keywords
Additional keyword arguments are passed on to the `pycbc.psd.welch` method.
Returns
-------
psd : FrequencySeries
Frequency series containing the estimated PSD. | f15956:c0:m22 |
def whiten(self, segment_duration, max_filter_duration, trunc_method='<STR_LIT>',<EOL>remove_corrupted=True, low_frequency_cutoff=None,<EOL>return_psd=False, **kwds): | from pycbc.psd import inverse_spectrum_truncation, interpolate<EOL>psd = self.psd(segment_duration, **kwds)<EOL>psd = interpolate(psd, self.delta_f)<EOL>max_filter_len = int(max_filter_duration * self.sample_rate)<EOL>psd = inverse_spectrum_truncation(psd,<EOL>max_filter_len=max_filter_len,<EOL>low_frequency_cutoff=low_frequency_cutoff,<EOL>trunc_method=trunc_method)<EOL>white = (self.to_frequencyseries() / psd**<NUM_LIT:0.5>).to_timeseries()<EOL>if remove_corrupted:<EOL><INDENT>white = white[int(max_filter_len/<NUM_LIT:2>):int(len(self)-max_filter_len/<NUM_LIT:2>)]<EOL><DEDENT>if return_psd:<EOL><INDENT>return white, psd<EOL><DEDENT>return white<EOL> | Return a whitened time series
Parameters
----------
segment_duration: float
Duration in seconds to use for each sample of the spectrum.
max_filter_duration : int
Maximum length of the time-domain filter in seconds.
trunc_method : {None, 'hann'}
Function used for truncating the time-domain filter.
None produces a hard truncation at `max_filter_len`.
remove_corrupted : {True, boolean}
If True, the region of the time series corrupted by the whitening
is excised before returning. If false, the corrupted regions
are not excised and the full time series is returned.
low_frequency_cutoff : {None, float}
Low frequency cutoff to pass to the inverse spectrum truncation.
This should be matched to a known low frequency cutoff of the
data if there is one.
return_psd : {False, Boolean}
Return the estimated and conditioned PSD that was used to whiten
the data.
kwds : keywords
Additional keyword arguments are passed on to the `pycbc.psd.welch` method.
Returns
-------
whitened_data : TimeSeries
The whitened time series | f15956:c0:m23 |
def qtransform(self, delta_t=None, delta_f=None, logfsteps=None,<EOL>frange=None, qrange=(<NUM_LIT:4>,<NUM_LIT:64>), mismatch=<NUM_LIT>, return_complex=False): | from pycbc.filter.qtransform import qtiling, qplane<EOL>from scipy.interpolate import interp2d<EOL>if frange is None:<EOL><INDENT>frange = (<NUM_LIT:30>, int(self.sample_rate / <NUM_LIT:2> * <NUM_LIT:8>))<EOL><DEDENT>q_base = qtiling(self, qrange, frange, mismatch)<EOL>_, times, freqs, q_plane = qplane(q_base, self.to_frequencyseries(),<EOL>return_complex=return_complex)<EOL>if logfsteps and delta_f:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if delta_f or delta_t or logfsteps:<EOL><INDENT>if return_complex:<EOL><INDENT>interp_amp = interp2d(times, freqs, abs(q_plane))<EOL>interp_phase = interp2d(times, freqs, _numpy.angle(q_plane))<EOL><DEDENT>else:<EOL><INDENT>interp = interp2d(times, freqs, q_plane)<EOL><DEDENT><DEDENT>if delta_t:<EOL><INDENT>times = _numpy.arange(float(self.start_time),<EOL>float(self.end_time), delta_t)<EOL><DEDENT>if delta_f:<EOL><INDENT>freqs = _numpy.arange(int(frange[<NUM_LIT:0>]), int(frange[<NUM_LIT:1>]), delta_f)<EOL><DEDENT>if logfsteps:<EOL><INDENT>freqs = _numpy.logspace(_numpy.log10(frange[<NUM_LIT:0>]),<EOL>_numpy.log10(frange[<NUM_LIT:1>]),<EOL>logfsteps)<EOL><DEDENT>if delta_f or delta_t or logfsteps:<EOL><INDENT>if return_complex:<EOL><INDENT>q_plane = _numpy.exp(<NUM_LIT> * interp_phase(times, freqs))<EOL>q_plane *= interp_amp(times, freqs)<EOL><DEDENT>else:<EOL><INDENT>q_plane = interp(times, freqs)<EOL><DEDENT><DEDENT>return times, freqs, q_plane<EOL> | Return the interpolated 2d qtransform of this data
Parameters
----------
delta_t : {self.delta_t, float}
The time resolution to interpolate to
delta_f : float, Optional
The frequency resolution to interpolate to
logfsteps : int
Do a log interpolation (incompatible with delta_f option) and set
the number of steps to take.
frange : {(30, nyquist*0.8), tuple of ints}
frequency range
qrange : {(4, 64), tuple}
q range
mismatch : float
Mismatch between frequency tiles
return_complex: {False, bool}
return the raw complex series instead of the normalized power.
Returns
-------
times : numpy.ndarray
The time that the qtransform is sampled.
freqs : numpy.ndarray
The frequencies that the qtransform is sampled.
qplane : numpy.ndarray (2d)
The two dimensional interpolated qtransform of this time series. | f15956:c0:m24 |
def notch_fir(self, f1, f2, order, beta=<NUM_LIT>, remove_corrupted=True): | from pycbc.filter import notch_fir<EOL>ts = notch_fir(self, f1, f2, order, beta=beta)<EOL>if remove_corrupted:<EOL><INDENT>ts = ts[order:len(ts)-order]<EOL><DEDENT>return ts<EOL> | notch filter the time series using an FIR filtered generated from
the ideal response passed through a time-domain kaiser
window (beta = 5.0)
The suppression of the notch filter is related to the bandwidth and
the number of samples in the filter length. For a few Hz bandwidth,
a length corresponding to a few seconds is typically
required to create significant suppression in the notched band.
Parameters
----------
Time Series: TimeSeries
The time series to be notched.
f1: float
The start of the frequency suppression.
f2: float
The end of the frequency suppression.
order: int
Number of corrupted samples on each side of the time series
beta: float
Beta parameter of the kaiser window that sets the side lobe attenuation. | f15956:c0:m25 |
def lowpass_fir(self, frequency, order, beta=<NUM_LIT>, remove_corrupted=True): | from pycbc.filter import lowpass_fir<EOL>ts = lowpass_fir(self, frequency, order, beta=beta)<EOL>if remove_corrupted:<EOL><INDENT>ts = ts[order:len(ts)-order]<EOL><DEDENT>return ts<EOL> | Lowpass filter the time series using an FIR filtered generated from
the ideal response passed through a kaiser window (beta = 5.0)
Parameters
----------
Time Series: TimeSeries
The time series to be low-passed.
frequency: float
The frequency below which is suppressed.
order: int
Number of corrupted samples on each side of the time series
beta: float
Beta parameter of the kaiser window that sets the side lobe attenuation.
remove_corrupted : {True, boolean}
If True, the region of the time series corrupted by the filtering
is excised before returning. If false, the corrupted regions
are not excised and the full time series is returned. | f15956:c0:m26 |
def highpass_fir(self, frequency, order, beta=<NUM_LIT>, remove_corrupted=True): | from pycbc.filter import highpass_fir<EOL>ts = highpass_fir(self, frequency, order, beta=beta)<EOL>if remove_corrupted:<EOL><INDENT>ts = ts[order:len(ts)-order]<EOL><DEDENT>return ts<EOL> | Highpass filter the time series using an FIR filtered generated from
the ideal response passed through a kaiser window (beta = 5.0)
Parameters
----------
Time Series: TimeSeries
The time series to be high-passed.
frequency: float
The frequency below which is suppressed.
order: int
Number of corrupted samples on each side of the time series
beta: float
Beta parameter of the kaiser window that sets the side lobe attenuation.
remove_corrupted : {True, boolean}
If True, the region of the time series corrupted by the filtering
is excised before returning. If false, the corrupted regions
are not excised and the full time series is returned. | f15956:c0:m27 |
def fir_zero_filter(self, coeff): | from pycbc.filter import fir_zero_filter<EOL>return self._return(fir_zero_filter(coeff, self))<EOL> | Filter the timeseries with a set of FIR coefficients
Parameters
----------
coeff: numpy.ndarray
FIR coefficients. Should be and odd length and symmetric.
Returns
-------
filtered_series: pycbc.types.TimeSeries
Return the filtered timeseries, which has been properly shifted to account
for the FIR filter delay and the corrupted regions zeroed out. | f15956:c0:m28 |
def save(self, path, group = None): | ext = _os.path.splitext(path)[<NUM_LIT:1>]<EOL>if ext == '<STR_LIT>':<EOL><INDENT>output = _numpy.vstack((self.sample_times.numpy(), self.numpy())).T<EOL>_numpy.save(path, output)<EOL><DEDENT>elif ext == '<STR_LIT>':<EOL><INDENT>if self.kind == '<STR_LIT>':<EOL><INDENT>output = _numpy.vstack((self.sample_times.numpy(),<EOL>self.numpy())).T<EOL><DEDENT>elif self.kind == '<STR_LIT>':<EOL><INDENT>output = _numpy.vstack((self.sample_times.numpy(),<EOL>self.numpy().real,<EOL>self.numpy().imag)).T<EOL><DEDENT>_numpy.savetxt(path, output)<EOL><DEDENT>elif ext =='<STR_LIT>':<EOL><INDENT>key = '<STR_LIT:data>' if group is None else group<EOL>f = h5py.File(path)<EOL>ds = f.create_dataset(key, data=self.numpy(), compression='<STR_LIT>',<EOL>compression_opts=<NUM_LIT:9>, shuffle=True)<EOL>ds.attrs['<STR_LIT>'] = float(self.start_time)<EOL>ds.attrs['<STR_LIT>'] = float(self.delta_t)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT> | Save time series to a Numpy .npy, hdf, or text file. The first column
contains the sample times, the second contains the values.
In the case of a complex time series saved as text, the imaginary
part is written as a third column. When using hdf format, the data is stored
as a single vector, along with relevant attributes.
Parameters
----------
path: string
Destination file path. Must end with either .hdf, .npy or .txt.
group: string
Additional name for internal storage use. Ex. hdf storage uses
this as the key value.
Raises
------
ValueError
If path does not end in .npy or .txt. | f15956:c0:m29 |
@_nocomplex<EOL><INDENT>def to_frequencyseries(self, delta_f=None):<DEDENT> | from pycbc.fft import fft<EOL>if not delta_f:<EOL><INDENT>delta_f = <NUM_LIT:1.0> / self.duration<EOL><DEDENT>tlen = int(<NUM_LIT:1.0> / delta_f / self.delta_t + <NUM_LIT:0.5>)<EOL>flen = int(tlen / <NUM_LIT:2> + <NUM_LIT:1>)<EOL>if tlen < len(self):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (delta_f, <NUM_LIT:1.0> / self.duration))<EOL><DEDENT>if not delta_f:<EOL><INDENT>tmp = self<EOL><DEDENT>else:<EOL><INDENT>tmp = TimeSeries(zeros(tlen, dtype=self.dtype),<EOL>delta_t=self.delta_t, epoch=self.start_time)<EOL>tmp[:len(self)] = self[:]<EOL><DEDENT>f = FrequencySeries(zeros(flen,<EOL>dtype=complex_same_precision_as(self)),<EOL>delta_f=delta_f)<EOL>fft(tmp, f)<EOL>return f<EOL> | Return the Fourier transform of this time series
Parameters
----------
delta_f : {None, float}, optional
The frequency resolution of the returned frequency series. By
default the resolution is determined by the duration of the timeseries.
Returns
-------
FrequencySeries:
The fourier transform of this time series. | f15956:c0:m30 |
def add_into(self, other): | <EOL>if self.sample_rate != other.sample_rate:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if ((other.start_time > self.end_time) or<EOL>(self.start_time > other.end_time)):<EOL><INDENT>return self.copy()<EOL><DEDENT>other = other.copy()<EOL>dt = float((other.start_time - self.start_time) * self.sample_rate)<EOL>if not dt.is_integer():<EOL><INDENT>diff = (dt - _numpy.floor(dt))<EOL>other.resize(len(other) + (len(other) + <NUM_LIT:1>) % <NUM_LIT:2> + <NUM_LIT:1>)<EOL>other = other.cyclic_time_shift(diff)<EOL><DEDENT>ts = self.copy()<EOL>start = max(other.start_time, self.start_time)<EOL>end = min(other.end_time, self.end_time)<EOL>part = ts.time_slice(start, end)<EOL>part += other.time_slice(start, end)<EOL>return ts<EOL> | Return the sum of the two time series accounting for the time stamp.
The other vector will be resized and time shifted wiht sub-sample
precision before adding. This assumes that one can assume zeros
outside of the original vector range. | f15956:c0:m31 |
@_nocomplex<EOL><INDENT>def cyclic_time_shift(self, dt):<DEDENT> | <EOL>return self.to_frequencyseries().cyclic_time_shift(dt).to_timeseries()<EOL> | Shift the data and timestamps by a given number of seconds
Shift the data and timestamps in the time domain a given number of
seconds. To just change the time stamps, do ts.start_time += dt.
The time shift may be smaller than the intrinsic sample rate of the data.
Note that data will be cycliclly rotated, so if you shift by 2
seconds, the final 2 seconds of your data will now be at the
beginning of the data set.
Parameters
----------
dt : float
Amount of time to shift the vector.
Returns
-------
data : pycbc.types.TimeSeries
The time shifted time series. | f15956:c0:m32 |
def match(self, other, psd=None,<EOL>low_frequency_cutoff=None, high_frequency_cutoff=None): | return self.to_frequencyseries().match(other, psd=psd,<EOL>low_frequency_cutoff=low_frequency_cutoff,<EOL>high_frequency_cutoff=high_frequency_cutoff)<EOL> | Return the match between the two TimeSeries or FrequencySeries.
Return the match between two waveforms. This is equivelant to the overlap
maximized over time and phase. By default, the other vector will be
resized to match self. This may remove high frequency content or the
end of the vector.
Parameters
----------
other : TimeSeries or FrequencySeries
The input vector containing a waveform.
psd : Frequency Series
A power spectral density to weight the overlap.
low_frequency_cutoff : {None, float}, optional
The frequency to begin the match.
high_frequency_cutoff : {None, float}, optional
The frequency to stop the match.
Returns
-------
match: float
index: int
The number of samples to shift to get the match. | f15956:c0:m33 |
def detrend(self, type='<STR_LIT>'): | from scipy.signal import detrend<EOL>return self._return(detrend(self.numpy(), type=type))<EOL> | Remove linear trend from the data
Remove a linear trend from the data to improve the approximation that
the data is circularly convolved, this helps reduce the size of filter
transients from a circular convolution / filter.
Parameters
----------
type: str
The choice of detrending. The default ('linear') removes a linear
least squares fit. 'constant' removes only the mean of the data. | f15956:c0:m34 |
@schemed(BACKEND_PREFIX)<EOL>def _to_device(array): | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Move input to device | f15957:m6 |
@schemed(BACKEND_PREFIX)<EOL>def _copy_base_array(array): | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Copy a backend array | f15957:m7 |
@schemed(BACKEND_PREFIX)<EOL>def _scheme_matches_base_array(array): | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Check that input matches array type for scheme | f15957:m8 |
@_return_array<EOL>@schemed(BACKEND_PREFIX)<EOL>def zeros(length, dtype=float64): | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Return an Array filled with zeros. | f15957:m12 |
def load_array(path, group=None): | ext = _os.path.splitext(path)[<NUM_LIT:1>]<EOL>if ext == '<STR_LIT>':<EOL><INDENT>data = _numpy.load(path) <EOL><DEDENT>elif ext == '<STR_LIT>':<EOL><INDENT>data = _numpy.loadtxt(path)<EOL><DEDENT>elif ext == '<STR_LIT>':<EOL><INDENT>key = '<STR_LIT:data>' if group is None else group<EOL>return Array(h5py.File(path)[key]) <EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if data.ndim == <NUM_LIT:1>:<EOL><INDENT>return Array(data)<EOL><DEDENT>elif data.ndim == <NUM_LIT:2>:<EOL><INDENT>return Array(data[:,<NUM_LIT:0>] + <NUM_LIT>*data[:,<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % data.ndim)<EOL><DEDENT> | Load an Array from a .hdf, .txt or .npy file. The
default data types will be double precision floating point.
Parameters
----------
path : string
source file path. Must end with either .npy or .txt.
group: string
Additional name for internal storage use. Ex. hdf storage uses
this as the key value.
Raises
------
ValueError
If path does not end in .npy or .txt. | f15957:m13 |
def __init__(self, initial_array, dtype=None, copy=True): | self._scheme=_scheme.mgr.state<EOL>self._saved = LimitedSizeDict(size_limit=<NUM_LIT:2>**<NUM_LIT:5>)<EOL>if isinstance(initial_array, Array):<EOL><INDENT>initial_array = initial_array._data<EOL><DEDENT>if not copy:<EOL><INDENT>if not _scheme_matches_base_array(initial_array):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>elif issubclass(type(self._scheme), _scheme.CPUScheme):<EOL><INDENT>self._data = ArrayWithAligned(initial_array)<EOL><DEDENT>else:<EOL><INDENT>self._data = initial_array<EOL><DEDENT>if self._data.dtype not in _ALLOWED_DTYPES:<EOL><INDENT>raise TypeError(str(self._data.dtype) + '<STR_LIT>')<EOL><DEDENT>if dtype and dtype != self._data.dtype:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT><DEDENT>if copy:<EOL><INDENT>if not hasattr(initial_array, '<STR_LIT>'):<EOL><INDENT>initial_array = _numpy.array(initial_array)<EOL><DEDENT>if dtype is not None: <EOL><INDENT>dtype = _numpy.dtype(dtype)<EOL>if dtype not in _ALLOWED_DTYPES:<EOL><INDENT>raise TypeError(str(dtype) + '<STR_LIT>')<EOL><DEDENT>if dtype.kind != '<STR_LIT:c>' and initial_array.dtype.kind == '<STR_LIT:c>':<EOL><INDENT>raise TypeError(str(initial_array.dtype) + '<STR_LIT>' + str(dtype)) <EOL><DEDENT><DEDENT>elif initial_array.dtype in _ALLOWED_DTYPES:<EOL><INDENT>dtype = initial_array.dtype<EOL><DEDENT>else:<EOL><INDENT>if initial_array.dtype.kind == '<STR_LIT:c>':<EOL><INDENT>dtype = complex128<EOL><DEDENT>else:<EOL><INDENT>dtype = float64<EOL><DEDENT><DEDENT>if initial_array.dtype != dtype:<EOL><INDENT>initial_array = initial_array.astype(dtype)<EOL><DEDENT>if issubclass(type(self._scheme), _scheme.CPUScheme):<EOL><INDENT>if hasattr(initial_array, '<STR_LIT>'):<EOL><INDENT>self._data = ArrayWithAligned(_numpy.array(initial_array.get()))<EOL><DEDENT>else:<EOL><INDENT>self._data = ArrayWithAligned(_numpy.array(initial_array, <EOL>dtype=dtype, ndmin=<NUM_LIT:1>))<EOL><DEDENT><DEDENT>elif _scheme_matches_base_array(initial_array):<EOL><INDENT>self._data = _copy_base_array(initial_array) <EOL><DEDENT>else:<EOL><INDENT>initial_array = _numpy.array(initial_array, dtype=dtype, ndmin=<NUM_LIT:1>)<EOL>self._data = _to_device(initial_array)<EOL><DEDENT><DEDENT> | initial_array: An array-like object as specified by NumPy, this
also includes instances of an underlying data type as described in
section 3 or an instance of the PYCBC Array class itself. This
object is used to populate the data of the array.
dtype: A NumPy style dtype that describes the type of
encapsulated data (float32,compex64, etc)
copy: This defines whether the initial_array is copied to instantiate
the array or is simply referenced. If copy is false, new data is not
created, and so all arguments that would force a copy are ignored.
The default is to copy the given object. | f15957:c0:m0 |
def _return(self, ary): | if isinstance(ary, Array):<EOL><INDENT>return ary<EOL><DEDENT>return Array(ary, copy=False)<EOL> | Wrap the ary to return an Array type | f15957:c0:m6 |
@decorator<EOL><INDENT>def _icheckother(fn, self, other):<DEDENT> | self._typecheck(other) <EOL>if type(other) in _ALLOWED_SCALARS:<EOL><INDENT>if self.kind == '<STR_LIT>' and type(other) == complex:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>other = force_precision_to_match(other, self.precision)<EOL><DEDENT>elif isinstance(other, type(self)) or type(other) is Array:<EOL><INDENT>if len(other) != len(self):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if self.kind == '<STR_LIT>' and other.kind == '<STR_LIT>':<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if other.precision == self.precision:<EOL><INDENT>_convert_to_scheme(other)<EOL>other = other._data<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return NotImplemented<EOL><DEDENT>return fn(self, other)<EOL> | Checks the input to in-place operations | f15957:c0:m10 |
def _typecheck(self, other): | pass<EOL> | Additional typechecking for other. Placeholder for use by derived
types. | f15957:c0:m11 |
@_returntype<EOL><INDENT>@_convert<EOL>@_checkother<EOL>def __mul__(self,other):<DEDENT> | return self._data * other<EOL> | Multiply by an Array or a scalar and return an Array. | f15957:c0:m12 |
@_convert<EOL><INDENT>@_icheckother<EOL>def __imul__(self,other):<DEDENT> | self._data *= other<EOL>return self<EOL> | Multiply by an Array or a scalar and return an Array. | f15957:c0:m13 |
@_returntype<EOL><INDENT>@_convert<EOL>@_checkother<EOL>def __add__(self,other):<DEDENT> | return self._data + other<EOL> | Add Array to Array or scalar and return an Array. | f15957:c0:m14 |
@_convert<EOL><INDENT>@_icheckother<EOL>def __iadd__(self,other):<DEDENT> | self._data += other<EOL>return self<EOL> | Add Array to Array or scalar and return an Array. | f15957:c0:m16 |
@_convert<EOL><INDENT>@_checkother<EOL>@_returntype<EOL>def __truediv__(self,other):<DEDENT> | return self._data / other<EOL> | Divide Array by Array or scalar and return an Array. | f15957:c0:m17 |
@_returntype<EOL><INDENT>@_convert<EOL>@_checkother<EOL>def __rtruediv__(self,other):<DEDENT> | return self._data.__rtruediv__(other)<EOL> | Divide Array by Array or scalar and return an Array. | f15957:c0:m18 |
@_convert<EOL><INDENT>@_icheckother<EOL>def __itruediv__(self,other):<DEDENT> | self._data /= other<EOL>return self<EOL> | Divide Array by Array or scalar and return an Array. | f15957:c0:m19 |
@_returntype<EOL><INDENT>@_convert<EOL>@_checkother<EOL>def __sub__(self,other):<DEDENT> | return self._data - other<EOL> | Subtract Array or scalar from Array and return an Array. | f15957:c0:m20 |
@_returntype<EOL><INDENT>@_convert<EOL>@_checkother<EOL>def __rsub__(self,other):<DEDENT> | return self._data.__rsub__(other)<EOL> | Subtract Array or scalar from Array and return an Array. | f15957:c0:m21 |
@_convert<EOL><INDENT>@_icheckother<EOL>def __isub__(self,other):<DEDENT> | self._data -= other<EOL>return self<EOL> | Subtract Array or scalar from Array and return an Array. | f15957:c0:m22 |
@_returntype<EOL><INDENT>@_convert<EOL>@_checkother<EOL>def __pow__(self,other):<DEDENT> | return self._data ** other<EOL> | Exponentiate Array by scalar | f15957:c0:m23 |
@_returntype<EOL><INDENT>@_convert<EOL>def __abs__(self):<DEDENT> | return abs(self._data)<EOL> | Return absolute value of Array | f15957:c0:m24 |
def __len__(self): | return len(self._data)<EOL> | Return length of Array | f15957:c0:m25 |
def __eq__(self,other): | <EOL>if type(self) != type(other):<EOL><INDENT>return False<EOL><DEDENT>if self.dtype != other.dtype:<EOL><INDENT>return False<EOL><DEDENT>if len(self) != len(other):<EOL><INDENT>return False<EOL><DEDENT>sary = self.numpy()<EOL>oary = other.numpy()<EOL>return (sary == oary).all()<EOL> | This is the Python special method invoked whenever the '=='
comparison is used. It will return true if the data of two
PyCBC arrays are identical, and all of the numeric meta-data
are identical, irrespective of whether or not the two
instances live in the same memory (for that comparison, the
Python statement 'a is b' should be used instead).
Thus, this method returns 'True' if the types of both 'self'
and 'other' are identical, as well as their lengths, dtypes
and the data in the arrays, element by element. It will always
do the comparison on the CPU, but will *not* move either object
to the CPU if it is not already there, nor change the scheme of
either object. It is possible to compare a CPU object to a GPU
object, and the comparison should be true if the data and
meta-data of the two objects are the same.
Note in particular that this function returns a single boolean,
and not an array of booleans as Numpy does. If the numpy
behavior is instead desired it can be obtained using the numpy()
method of the PyCBC type to get a numpy instance from each
object, and invoking '==' on those two instances.
Parameters
----------
other: another Python object, that should be tested for equality
with 'self'.
Returns
-------
boolean: 'True' if the types, dtypes, lengths, and data of the
two objects are each identical. | f15957:c0:m28 |
def almost_equal_elem(self,other,tol,relative=True): | <EOL>if (tol<<NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if type(other) != type(self):<EOL><INDENT>return False<EOL><DEDENT>if self.dtype != other.dtype:<EOL><INDENT>return False<EOL><DEDENT>if len(self) != len(other):<EOL><INDENT>return False<EOL><DEDENT>diff = abs(self.numpy()-other.numpy())<EOL>if relative:<EOL><INDENT>cmpary = tol*abs(self.numpy())<EOL><DEDENT>else:<EOL><INDENT>cmpary = tol*ones(len(self),dtype=self.dtype)<EOL><DEDENT>return (diff<=cmpary).all()<EOL> | Compare whether two array types are almost equal, element
by element.
If the 'relative' parameter is 'True' (the default) then the
'tol' parameter (which must be positive) is interpreted as a
relative tolerance, and the comparison returns 'True' only if
abs(self[i]-other[i]) <= tol*abs(self[i])
for all elements of the array.
If 'relative' is 'False', then 'tol' is an absolute tolerance,
and the comparison is true only if
abs(self[i]-other[i]) <= tol
for all elements of the array.
Other meta-data (type, dtype, and length) must be exactly equal.
If either object's memory lives on the GPU it will be copied to
the CPU for the comparison, which may be slow. But the original
object itself will not have its memory relocated nor scheme
changed.
Parameters
----------
other
Another Python object, that should be tested for
almost-equality with 'self', element-by-element.
tol
A non-negative number, the tolerance, which is interpreted
as either a relative tolerance (the default) or an absolute
tolerance.
relative
A boolean, indicating whether 'tol' should be interpreted
as a relative tolerance (if True, the default if this argument
is omitted) or as an absolute tolerance (if tol is False).
Returns
-------
boolean
'True' if the data agree within the tolerance, as
interpreted by the 'relative' keyword, and if the types,
lengths, and dtypes are exactly the same. | f15957:c0:m29 |
def almost_equal_norm(self,other,tol,relative=True): | <EOL>if (tol<<NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if type(other) != type(self):<EOL><INDENT>return False<EOL><DEDENT>if self.dtype != other.dtype:<EOL><INDENT>return False<EOL><DEDENT>if len(self) != len(other):<EOL><INDENT>return False<EOL><DEDENT>diff = self.numpy()-other.numpy()<EOL>dnorm = norm(diff)<EOL>if relative:<EOL><INDENT>return (dnorm <= tol*norm(self))<EOL><DEDENT>else:<EOL><INDENT>return (dnorm <= tol)<EOL><DEDENT> | Compare whether two array types are almost equal, normwise.
If the 'relative' parameter is 'True' (the default) then the
'tol' parameter (which must be positive) is interpreted as a
relative tolerance, and the comparison returns 'True' only if
abs(norm(self-other)) <= tol*abs(norm(self)).
If 'relative' is 'False', then 'tol' is an absolute tolerance,
and the comparison is true only if
abs(norm(self-other)) <= tol
Other meta-data (type, dtype, and length) must be exactly equal.
If either object's memory lives on the GPU it will be copied to
the CPU for the comparison, which may be slow. But the original
object itself will not have its memory relocated nor scheme
changed.
Parameters
----------
other
another Python object, that should be tested for
almost-equality with 'self', based on their norms.
tol
a non-negative number, the tolerance, which is interpreted
as either a relative tolerance (the default) or an absolute
tolerance.
relative
A boolean, indicating whether 'tol' should be interpreted
as a relative tolerance (if True, the default if this argument
is omitted) or as an absolute tolerance (if tol is False).
Returns
-------
boolean
'True' if the data agree within the tolerance, as
interpreted by the 'relative' keyword, and if the types,
lengths, and dtypes are exactly the same. | f15957:c0:m30 |
@_returntype<EOL><INDENT>@_convert<EOL>def real(self):<DEDENT> | return Array(self._data.real, copy=True)<EOL> | Return real part of Array | f15957:c0:m31 |
@_returntype<EOL><INDENT>@_convert<EOL>def imag(self):<DEDENT> | return Array(self._data.imag, copy=True)<EOL> | Return imaginary part of Array | f15957:c0:m32 |
@_returntype<EOL><INDENT>@_convert<EOL>def conj(self):<DEDENT> | return self._data.conj()<EOL> | Return complex conjugate of Array. | f15957:c0:m33 |
@_returntype<EOL><INDENT>@_convert<EOL>@schemed(BACKEND_PREFIX)<EOL>def squared_norm(self):<DEDENT> | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Return the elementwise squared norm of the array | f15957:c0:m34 |
@_returntype<EOL><INDENT>@_checkother<EOL>@_convert<EOL>@schemed(BACKEND_PREFIX)<EOL>def multiply_and_add(self, other, mult_fac):<DEDENT> | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Return other multiplied by mult_fac and with self added.
Self is modified in place and returned as output.
Precisions of inputs must match. | f15957:c0:m35 |
@_vrcheckother<EOL><INDENT>@_convert<EOL>@schemed(BACKEND_PREFIX)<EOL>def inner(self, other):<DEDENT> | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Return the inner product of the array with complex conjugation. | f15957:c0:m36 |
@_vrcheckother<EOL><INDENT>@_convert<EOL>@schemed(BACKEND_PREFIX)<EOL>def vdot(self, other):<DEDENT> | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Return the inner product of the array with complex conjugation. | f15957:c0:m37 |
@_convert<EOL><INDENT>@schemed(BACKEND_PREFIX)<EOL>def clear(self):<DEDENT> | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Clear out the values of the array. | f15957:c0:m38 |
@_vrcheckother<EOL><INDENT>@_convert<EOL>@schemed(BACKEND_PREFIX)<EOL>def weighted_inner(self, other, weight):<DEDENT> | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Return the inner product of the array with complex conjugation. | f15957:c0:m39 |
@_convert<EOL><INDENT>@schemed(BACKEND_PREFIX)<EOL>def sum(self):<DEDENT> | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Return the sum of the the array. | f15957:c0:m40 |
@_returntype<EOL><INDENT>@_convert<EOL>@schemed(BACKEND_PREFIX)<EOL>def cumsum(self):<DEDENT> | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Return the cumulative sum of the the array. | f15957:c0:m41 |
@_convert<EOL><INDENT>@_nocomplex<EOL>@schemed(BACKEND_PREFIX)<EOL>def max(self):<DEDENT> | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Return the maximum value in the array. | f15957:c0:m42 |
@_convert<EOL><INDENT>@_nocomplex<EOL>@schemed(BACKEND_PREFIX)<EOL>def max_loc(self):<DEDENT> | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Return the maximum value in the array along with the index location | f15957:c0:m43 |
@_convert<EOL><INDENT>@schemed(BACKEND_PREFIX)<EOL>def abs_arg_max(self):<DEDENT> | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Return location of the maximum argument max | f15957:c0:m44 |
@_convert<EOL><INDENT>@schemed(BACKEND_PREFIX)<EOL>def abs_max_loc(self):<DEDENT> | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Return the maximum elementwise norm in the array along with the index location | f15957:c0:m45 |
@_convert<EOL><INDENT>@_nocomplex<EOL>@schemed(BACKEND_PREFIX)<EOL>def min(self):<DEDENT> | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Return the maximum value in the array. | f15957:c0:m46 |
@_convert<EOL><INDENT>@_vcheckother<EOL>@schemed(BACKEND_PREFIX)<EOL>def dot(self, other):<DEDENT> | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Return the dot product | f15957:c0:m48 |
@schemed(BACKEND_PREFIX)<EOL><INDENT>def _getvalue(self, index):<DEDENT> | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Helper function to return a single value from an array. May be very
slow if the memory is on a gpu. | f15957:c0:m49 |
@_convert<EOL><INDENT>def __getitem__(self, index):<DEDENT> | if isinstance(index, slice):<EOL><INDENT>return self._getslice(index)<EOL><DEDENT>else:<EOL><INDENT>return self._getvalue(index)<EOL><DEDENT> | Return items from the Array. This not guaranteed to be fast for
returning single values. | f15957:c0:m51 |
@_convert<EOL><INDENT>def resize(self, new_size):<DEDENT> | if new_size == len(self):<EOL><INDENT>return<EOL><DEDENT>else:<EOL><INDENT>self._saved = LimitedSizeDict(size_limit=<NUM_LIT:2>**<NUM_LIT:5>)<EOL>new_arr = zeros(new_size, dtype=self.dtype)<EOL>if len(self) <= new_size:<EOL><INDENT>new_arr[<NUM_LIT:0>:len(self)] = self<EOL><DEDENT>else:<EOL><INDENT>new_arr[:] = self[<NUM_LIT:0>:new_size]<EOL><DEDENT>self._data = new_arr._data<EOL><DEDENT> | Resize self to new_size | f15957:c0:m52 |
@_convert<EOL><INDENT>def roll(self, shift):<DEDENT> | self._saved = LimitedSizeDict(size_limit=<NUM_LIT:2>**<NUM_LIT:5>)<EOL>new_arr = zeros(len(self), dtype=self.dtype)<EOL>if shift < <NUM_LIT:0>:<EOL><INDENT>shift = shift - len(self) * (shift // len(self))<EOL><DEDENT>if shift == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>new_arr[<NUM_LIT:0>:shift] = self[len(self)-shift: len(self)]<EOL>new_arr[shift:len(self)] = self[<NUM_LIT:0>:len(self)-shift]<EOL>self._data = new_arr._data<EOL> | shift vector | f15957:c0:m53 |
@schemed(BACKEND_PREFIX)<EOL><INDENT>def _copy(self, self_ref, other_ref):<DEDENT> | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Helper function to copy between two arrays. The arrays references
should be bare array types and not `Array` class instances. | f15957:c0:m55 |
@property<EOL><INDENT>@_convert<EOL>def data(self):<DEDENT> | return self._data<EOL> | Returns the internal python array | f15957:c0:m59 |
@property<EOL><INDENT>@_convert<EOL>@schemed(BACKEND_PREFIX)<EOL>def ptr(self):<DEDENT> | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Returns a pointer to the memory of this array | f15957:c0:m61 |
@property<EOL><INDENT>@cpuonly<EOL>@_convert<EOL>def _swighelper(self):<DEDENT> | return self<EOL> | Used internally by SWIG typemaps to ensure @_convert
is called and scheme is correct | f15957:c0:m64 |
@_convert<EOL><INDENT>@schemed(BACKEND_PREFIX)<EOL>def numpy(self):<DEDENT> | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Returns a Numpy Array that contains this data | f15957:c0:m65 |
@_convert<EOL><INDENT>def lal(self):<DEDENT> | lal_data = None<EOL>if self._data.dtype == float32:<EOL><INDENT>lal_data = _lal.CreateREAL4Vector(len(self))<EOL><DEDENT>elif self._data.dtype == float64:<EOL><INDENT>lal_data = _lal.CreateREAL8Vector(len(self))<EOL><DEDENT>elif self._data.dtype == complex64:<EOL><INDENT>lal_data = _lal.CreateCOMPLEX8Vector(len(self))<EOL><DEDENT>elif self._data.dtype == complex128:<EOL><INDENT>lal_data = _lal.CreateCOMPLEX16Vector(len(self))<EOL><DEDENT>lal_data.data[:] = self.numpy()<EOL>return lal_data<EOL> | Returns a LAL Object that contains this data | f15957:c0:m66 |
def save(self, path, group=None): | ext = _os.path.splitext(path)[<NUM_LIT:1>]<EOL>if ext == '<STR_LIT>':<EOL><INDENT>_numpy.save(path, self.numpy())<EOL><DEDENT>elif ext == '<STR_LIT>':<EOL><INDENT>if self.kind == '<STR_LIT>':<EOL><INDENT>_numpy.savetxt(path, self.numpy())<EOL><DEDENT>elif self.kind == '<STR_LIT>':<EOL><INDENT>output = _numpy.vstack((self.numpy().real,<EOL>self.numpy().imag)).T<EOL>_numpy.savetxt(path, output)<EOL><DEDENT><DEDENT>elif ext == '<STR_LIT>':<EOL><INDENT>key = '<STR_LIT:data>' if group is None else group<EOL>f = h5py.File(path)<EOL>f.create_dataset(key, data=self.numpy(), compression='<STR_LIT>',<EOL>compression_opts=<NUM_LIT:9>, shuffle=True)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT> | Save array to a Numpy .npy, hdf, or text file. When saving a complex array as
text, the real and imaginary parts are saved as the first and second
column respectively. When using hdf format, the data is stored
as a single vector, along with relevant attributes.
Parameters
----------
path: string
Destination file path. Must end with either .hdf, .npy or .txt.
group: string
Additional name for internal storage use. Ex. hdf storage uses
this as the key value.
Raises
------
ValueError
If path does not end in .npy or .txt. | f15957:c0:m68 |
@_convert<EOL><INDENT>def trim_zeros(self):<DEDENT> | tmp = self.numpy()<EOL>f = len(self)-len(_numpy.trim_zeros(tmp, trim='<STR_LIT:f>'))<EOL>b = len(self)-len(_numpy.trim_zeros(tmp, trim='<STR_LIT:b>'))<EOL>return self[f:len(self)-b]<EOL> | Remove the leading and trailing zeros. | f15957:c0:m69 |
@_returntype<EOL><INDENT>@_convert<EOL>def view(self, dtype):<DEDENT> | return self._data.view(dtype)<EOL> | Return a 'view' of the array with its bytes now interpreted according
to 'dtype'. The location in memory is unchanged and changing elements
in a view of an array will also change the original array.
Parameters
----------
dtype : numpy dtype (one of float32, float64, complex64 or complex128)
The new dtype that should be used to interpret the bytes of self | f15957:c0:m70 |
def copy(self): | return self._return(self.data.copy())<EOL> | Return copy of this array | f15957:c0:m71 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.