signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def load_frequencyseries(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, '<STR_LIT:r>')<EOL>data = f[key][:]<EOL>series = FrequencySeries(data, delta_f=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_f = (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 FrequencySeries(data[:,<NUM_LIT:1>], delta_f=delta_f, epoch=epoch)<EOL><DEDENT>elif data.ndim == <NUM_LIT:3>:<EOL><INDENT>delta_f = (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 FrequencySeries(data[:,<NUM_LIT:1>] + <NUM_LIT>*data[:,<NUM_LIT:2>], delta_f=delta_f,<EOL>epoch=epoch)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % data.ndim)<EOL><DEDENT> | Load a FrequencySeries 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. | f15958:m0 |
def get_delta_f(self): | return self._delta_f<EOL> | Return frequency between consecutive samples in Hertz. | f15958:c0:m3 |
def get_epoch(self): | return self._epoch<EOL> | Return frequency series epoch as a LIGOTimeGPS. | f15958:c0:m4 |
def get_sample_frequencies(self): | return Array(range(len(self))) * self._delta_f<EOL> | Return an Array containing the sample frequencies. | f15958:c0:m5 |
def at_frequency(self, freq): | return self[int(freq / self.delta_f)]<EOL> | Return the value at the specified frequency | f15958:c0:m7 |
@property<EOL><INDENT>def start_time(self):<DEDENT> | return self.epoch<EOL> | Return the start time of this vector | f15958:c0:m8 |
@start_time.setter<EOL><INDENT>def start_time(self, time):<DEDENT> | self._epoch = _lal.LIGOTimeGPS(time)<EOL> | Set the start time | f15958:c0:m9 |
@property<EOL><INDENT>def end_time(self):<DEDENT> | return self.start_time + self.duration<EOL> | Return the end time of this vector | f15958:c0:m10 |
@property<EOL><INDENT>def duration(self):<DEDENT> | return <NUM_LIT:1.0> / self.delta_f<EOL> | Return the time duration of this vector | f15958:c0:m11 |
@property<EOL><INDENT>def delta_t(self):<DEDENT> | return <NUM_LIT:1.0> / self.sample_rate<EOL> | Return the time between samples if this were a time series.
This assume the time series is even in length! | f15958:c0:m12 |
@property<EOL><INDENT>def sample_rate(self):<DEDENT> | return (len(self) - <NUM_LIT:1>) * self.delta_f * <NUM_LIT><EOL> | Return the sample rate this would have in the time domain. This
assumes even length time series! | f15958:c0:m13 |
def __eq__(self,other): | if super(FrequencySeries,self).__eq__(other):<EOL><INDENT>return (self._epoch == other._epoch and self._delta_f == other._delta_f)<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
frequency 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_fs 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_fs
and data of the two objects are each identical. | f15958:c0:m14 |
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(FrequencySeries,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_f-other._delta_f) <= dtol*self._delta_f)<EOL><DEDENT>else:<EOL><INDENT>return (self._epoch == other._epoch and<EOL>abs(self._delta_f-other._delta_f) <= dtol)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT> | Compare whether two frequency 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_f is within 'dtol' of
other.delta_f; 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_f. 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_f values of the two FrequencySeries.
Returns
-------
boolean: 'True' if the data and delta_fs agree within the tolerance,
as interpreted by the 'relative' keyword, and if the types,
lengths, dtypes, and epochs are exactly the same. | f15958:c0:m15 |
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(FrequencySeries,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_f-other._delta_f) <= dtol*self._delta_f)<EOL><DEDENT>else:<EOL><INDENT>return (self._epoch == other._epoch and<EOL>abs(self._delta_f-other._delta_f) <= dtol)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT> | Compare whether two frequency 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_f is within 'dtol' of
other.delta_f; 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_f. 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_f values of the two FrequencySeries.
Returns
-------
boolean: 'True' if the data and delta_fs agree within the tolerance,
as interpreted by the 'relative' keyword, and if the types,
lengths, dtypes, and epochs are exactly the same. | f15958:c0:m16 |
@_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.CreateREAL4FrequencySeries("<STR_LIT>",ep,<NUM_LIT:0>,self.delta_f,_lal.SecondUnit,len(self))<EOL><DEDENT>elif self._data.dtype == _numpy.float64:<EOL><INDENT>lal_data = _lal.CreateREAL8FrequencySeries("<STR_LIT>",ep,<NUM_LIT:0>,self.delta_f,_lal.SecondUnit,len(self))<EOL><DEDENT>elif self._data.dtype == _numpy.complex64:<EOL><INDENT>lal_data = _lal.CreateCOMPLEX8FrequencySeries("<STR_LIT>",ep,<NUM_LIT:0>,self.delta_f,_lal.SecondUnit,len(self))<EOL><DEDENT>elif self._data.dtype == _numpy.complex128:<EOL><INDENT>lal_data = _lal.CreateCOMPLEX16FrequencySeries("<STR_LIT>",ep,<NUM_LIT:0>,self.delta_f,_lal.SecondUnit,len(self))<EOL><DEDENT>lal_data.data.data[:] = self.numpy()<EOL>return lal_data<EOL> | Produces a LAL frequency series object equivalent to self.
Returns
-------
lal_data : {lal.*FrequencySeries}
LAL frequency series object containing the same data as self.
The actual type depends on the sample's dtype. If the epoch of
self was 'None', the epoch of the returned LAL object will be
LIGOTimeGPS(0,0); otherwise, the same as that of self.
Raises
------
TypeError
If frequency series is stored in GPU memory. | f15958:c0:m17 |
def save(self, path, group=None, ifo='<STR_LIT>'): | ext = _os.path.splitext(path)[<NUM_LIT:1>]<EOL>if ext == '<STR_LIT>':<EOL><INDENT>output = _numpy.vstack((self.sample_frequencies.numpy(),<EOL>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_frequencies.numpy(),<EOL>self.numpy())).T<EOL><DEDENT>elif self.kind == '<STR_LIT>':<EOL><INDENT>output = _numpy.vstack((self.sample_frequencies.numpy(),<EOL>self.numpy().real,<EOL>self.numpy().imag)).T<EOL><DEDENT>_numpy.savetxt(path, output)<EOL><DEDENT>elif ext == '<STR_LIT>' or path.endswith('<STR_LIT>'):<EOL><INDENT>from pycbc.io.live import make_psd_xmldoc<EOL>from glue.ligolw import utils<EOL>if self.kind != '<STR_LIT>':<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>output = self.lal()<EOL>data_lal = output.data.data<EOL>first_idx = _numpy.argmax(data_lal><NUM_LIT:0>)<EOL>if not first_idx == <NUM_LIT:0>:<EOL><INDENT>data_lal[:first_idx] = data_lal[first_idx]<EOL><DEDENT>psddict = {ifo: output}<EOL>utils.write_filename(make_psd_xmldoc(psddict), path,<EOL>gz=path.endswith("<STR_LIT>"))<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.epoch)<EOL>ds.attrs['<STR_LIT>'] = float(self.delta_f)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT> | Save frequency series to a Numpy .npy, hdf, or text file. The first column
contains the sample frequencies, the second contains the values.
In the case of a complex frequency 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. | f15958:c0:m18 |
@_noreal<EOL><INDENT>def to_timeseries(self, delta_t=None):<DEDENT> | from pycbc.fft import ifft<EOL>from pycbc.types import TimeSeries, real_same_precision_as<EOL>nat_delta_t = <NUM_LIT:1.0> / ((len(self)-<NUM_LIT:1>)*<NUM_LIT:2>) / self.delta_f<EOL>if not delta_t:<EOL><INDENT>delta_t = nat_delta_t<EOL><DEDENT>tlen = int(<NUM_LIT:1.0> / self.delta_f / delta_t + <NUM_LIT:0.5>)<EOL>flen = int(tlen / <NUM_LIT:2> + <NUM_LIT:1>)<EOL>if flen < len(self):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (delta_t, nat_delta_t))<EOL><DEDENT>if not delta_t:<EOL><INDENT>tmp = self<EOL><DEDENT>else:<EOL><INDENT>tmp = FrequencySeries(zeros(flen, dtype=self.dtype), <EOL>delta_f=self.delta_f, epoch=self.epoch)<EOL>tmp[:len(self)] = self[:]<EOL><DEDENT>f = TimeSeries(zeros(tlen, <EOL>dtype=real_same_precision_as(self)),<EOL>delta_t=delta_t)<EOL>ifft(tmp, f)<EOL>return f<EOL> | Return the Fourier transform of this time series.
Note that this assumes even length time series!
Parameters
----------
delta_t : {None, float}, optional
The time resolution of the returned series. By default the
resolution is determined by length and delta_f of this frequency
series.
Returns
-------
TimeSeries:
The inverse fourier transform of this frequency series. | f15958:c0:m19 |
@_noreal<EOL><INDENT>def cyclic_time_shift(self, dt):<DEDENT> | from pycbc.waveform import apply_fseries_time_shift<EOL>data = apply_fseries_time_shift(self, dt)<EOL>data.start_time = self.start_time - dt<EOL>return data<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.FrequencySeries
The time shifted frequency series. | f15958:c0:m20 |
def match(self, other, psd=None,<EOL>low_frequency_cutoff=None, high_frequency_cutoff=None): | from pycbc.types import TimeSeries<EOL>from pycbc.filter import match<EOL>if isinstance(other, TimeSeries):<EOL><INDENT>if other.duration != self.duration:<EOL><INDENT>other = other.copy()<EOL>other.resize(int(other.sample_rate * self.duration))<EOL><DEDENT>other = other.to_frequencyseries()<EOL><DEDENT>if len(other) != len(self):<EOL><INDENT>other = other.copy()<EOL>other.resize(len(self))<EOL><DEDENT>if psd is not None and len(psd) > len(self):<EOL><INDENT>psd = psd.copy()<EOL>psd.resize(len(self))<EOL><DEDENT>return match(self, 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. Beware, 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.
index: int
The number of samples to shift to get the match.
Returns
-------
match: float
index: int
The number of samples to shift to get the match. | f15958:c0:m21 |
def autochisq_from_precomputed(sn, corr_sn, hautocorr, indices,<EOL>stride=<NUM_LIT:1>, num_points=None, oneside=None,<EOL>twophase=True, maxvalued=False): | Nsnr = len(sn)<EOL>achisq = np.zeros(len(indices))<EOL>num_points_all = int(Nsnr/stride)<EOL>if num_points is None:<EOL><INDENT>num_points = num_points_all<EOL><DEDENT>if (num_points > num_points_all):<EOL><INDENT>num_points = num_points_all<EOL><DEDENT>snrabs = np.abs(sn[indices])<EOL>cphi_array = (sn[indices]).real / snrabs<EOL>sphi_array = (sn[indices]).imag / snrabs<EOL>start_point = - stride*num_points<EOL>end_point = stride*num_points+<NUM_LIT:1><EOL>if oneside == '<STR_LIT:left>':<EOL><INDENT>achisq_idx_list = np.arange(start_point, <NUM_LIT:0>, stride)<EOL><DEDENT>elif oneside == '<STR_LIT:right>':<EOL><INDENT>achisq_idx_list = np.arange(stride, end_point, stride)<EOL><DEDENT>else:<EOL><INDENT>achisq_idx_list_pt1 = np.arange(start_point, <NUM_LIT:0>, stride)<EOL>achisq_idx_list_pt2 = np.arange(stride, end_point, stride)<EOL>achisq_idx_list = np.append(achisq_idx_list_pt1,<EOL>achisq_idx_list_pt2)<EOL><DEDENT>hauto_corr_vec = hautocorr[achisq_idx_list]<EOL>hauto_norm = hauto_corr_vec.real*hauto_corr_vec.real<EOL>hauto_norm += hauto_corr_vec.imag*hauto_corr_vec.imag<EOL>chisq_norm = <NUM_LIT:1.0> - hauto_norm<EOL>for ip,ind in enumerate(indices):<EOL><INDENT>curr_achisq_idx_list = achisq_idx_list + ind<EOL>cphi = cphi_array[ip]<EOL>sphi = sphi_array[ip]<EOL>snr_ind = sn[ind].real*cphi + sn[ind].imag*sphi<EOL>if curr_achisq_idx_list[<NUM_LIT:0>] < <NUM_LIT:0>:<EOL><INDENT>curr_achisq_idx_list[curr_achisq_idx_list < <NUM_LIT:0>] += Nsnr<EOL><DEDENT>if curr_achisq_idx_list[-<NUM_LIT:1>] > (Nsnr - <NUM_LIT:1>):<EOL><INDENT>curr_achisq_idx_list[curr_achisq_idx_list > (Nsnr-<NUM_LIT:1>)] -= Nsnr<EOL><DEDENT>z = corr_sn[curr_achisq_idx_list].real*cphi +corr_sn[curr_achisq_idx_list].imag*sphi<EOL>dz = z - hauto_corr_vec.real*snr_ind<EOL>curr_achisq_list = dz*dz/chisq_norm<EOL>if twophase:<EOL><INDENT>chisq_norm = <NUM_LIT:1.0> - hauto_norm<EOL>z = -corr_sn[curr_achisq_idx_list].real*sphi +corr_sn[curr_achisq_idx_list].imag*cphi<EOL>dz = z - hauto_corr_vec.imag*snr_ind<EOL>curr_achisq_list += dz*dz/chisq_norm<EOL><DEDENT>if maxvalued:<EOL><INDENT>achisq[ip] = curr_achisq_list.max()<EOL><DEDENT>else:<EOL><INDENT>achisq[ip] = curr_achisq_list.sum()<EOL><DEDENT><DEDENT>dof = num_points<EOL>if oneside is None:<EOL><INDENT>dof = dof * <NUM_LIT:2><EOL><DEDENT>if twophase:<EOL><INDENT>dof = dof * <NUM_LIT:2><EOL><DEDENT>return dof, achisq, indices<EOL> | Compute correlation (two sided) between template and data
and compares with autocorrelation of the template: C(t) = IFFT(A*A/S(f))
Parameters
----------
sn: Array[complex]
normalized (!) array of complex snr for the template that produced the
trigger(s) being tested
corr_sn : Array[complex]
normalized (!) array of complex snr for the template that you want to
produce a correlation chisq test for. In the [common] case that sn and
corr_sn are the same, you are computing auto-correlation chisq.
hautocorr: Array[complex]
time domain autocorrelation for the template
indices: Array[int]
compute correlation chisquare at the points specified in this array,
num_points: [int, optional; default=None]
Number of points used for autochisq on each side, if None all points
are used.
stride: [int, optional; default = 1]
stride for points selection for autochisq
total length <= 2*num_points*stride
oneside: [str, optional; default=None]
whether to use one or two sided autochisquare. If None (or not
provided) twosided chi-squared will be used. If given, options are
'left' or 'right', to do one-sided chi-squared on the left or right.
twophase: Boolean, optional; default=True
If True calculate the auto-chisq using both phases of the filter.
If False only use the phase of the obtained trigger(s).
maxvalued: Boolean, optional; default=False
Return the largest auto-chisq at any of the points tested if True.
If False, return the sum of auto-chisq at all points tested.
Returns
-------
autochisq: [tuple]
returns autochisq values and snr corresponding to the instances
of time defined by indices | f15959:m0 |
def __init__(self, stride, num_points, onesided=None, twophase=False,<EOL>reverse_template=False, take_maximum_value=False,<EOL>maximal_value_dof=None): | if stride > <NUM_LIT:0>:<EOL><INDENT>self.do = True<EOL>self.column_name = "<STR_LIT>"<EOL>self.table_dof_name = "<STR_LIT>"<EOL>self.dof = num_points<EOL>self.num_points = num_points<EOL>self.stride = stride<EOL>self.one_sided = onesided<EOL>if (onesided is not None):<EOL><INDENT>self.dof = self.dof * <NUM_LIT:2><EOL><DEDENT>self.two_phase = twophase<EOL>if self.two_phase:<EOL><INDENT>self.dof = self.dof * <NUM_LIT:2><EOL><DEDENT>self.reverse_template = reverse_template<EOL>self.take_maximum_value=take_maximum_value<EOL>if self.take_maximum_value:<EOL><INDENT>if maximal_value_dof is None:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL><DEDENT>self.dof = maximal_value_dof<EOL><DEDENT>self._autocor = None<EOL>self._autocor_id = None<EOL><DEDENT>else:<EOL><INDENT>self.do = False<EOL><DEDENT> | Initialize autochisq calculation instance
Parameters
-----------
stride : int
Number of sample points between points at which auto-chisq is
calculated.
num_points : int
Number of sample points at which to calculate auto-chisq in each
direction from the trigger
onesided : optional, default=None, choices=['left','right']
If None (default), calculate auto-chisq in both directions from the
trigger. If left (backwards in time) or right (forwards in time)
calculate auto-chisq only in that direction.
twophase : optional, default=False
If False calculate auto-chisq using only the phase of the trigger.
If True, compare also against the orthogonal phase.
reverse_template : optional, default=False
If true, time-reverse the template before calculating auto-chisq.
In this case this is more of a cross-correlation chisq than auto.
take_maximum_value : optional, default=False
If provided, instead of adding the auto-chisq value at each sample
point tested, return only the maximum value.
maximal_value_dof : int, required if using take_maximum_value
If using take_maximum_value the expected value is not known. This
value specifies what to store in the cont_chisq_dof output. | f15959:c0:m0 |
def values(self, sn, indices, template, psd, norm, stilde=None,<EOL>low_frequency_cutoff=None, high_frequency_cutoff=None): | if self.do and (len(indices) > <NUM_LIT:0>):<EOL><INDENT>htilde = make_frequency_series(template)<EOL>key = (id(template), id(psd))<EOL>if key != self._autocor_id:<EOL><INDENT>logging.info("<STR_LIT>")<EOL>if not self.reverse_template:<EOL><INDENT>Pt, _, P_norm = matched_filter_core(htilde,<EOL>htilde, psd=psd,<EOL>low_frequency_cutoff=low_frequency_cutoff,<EOL>high_frequency_cutoff=high_frequency_cutoff)<EOL>Pt = Pt * (<NUM_LIT:1.>/ Pt[<NUM_LIT:0>])<EOL>self._autocor = Array(Pt, copy=True)<EOL><DEDENT>else:<EOL><INDENT>Pt, _, P_norm = matched_filter_core(htilde.conj(),<EOL>htilde, psd=psd,<EOL>low_frequency_cutoff=low_frequency_cutoff,<EOL>high_frequency_cutoff=high_frequency_cutoff)<EOL>norm_fac = P_norm / float(((template.sigmasq(psd))**<NUM_LIT:0.5>))<EOL>Pt *= norm_fac<EOL>self._autocor = Array(Pt, copy=True)<EOL><DEDENT>self._autocor_id = key<EOL><DEDENT>logging.info("<STR_LIT>")<EOL>sn = sn*norm<EOL>if self.reverse_template:<EOL><INDENT>assert(stilde is not None)<EOL>asn, _, ahnrm = matched_filter_core(htilde.conj(), stilde,<EOL>low_frequency_cutoff=low_frequency_cutoff,<EOL>high_frequency_cutoff=high_frequency_cutoff,<EOL>h_norm=template.sigmasq(psd))<EOL>correlation_snr = asn * ahnrm<EOL><DEDENT>else:<EOL><INDENT>correlation_snr = sn<EOL><DEDENT>achi_list = np.array([])<EOL>index_list = np.array(indices)<EOL>dof, achi_list, _ = autochisq_from_precomputed(sn, correlation_snr,<EOL>self._autocor, index_list, stride=self.stride,<EOL>num_points=self.num_points,<EOL>oneside=self.one_sided, twophase=self.two_phase,<EOL>maxvalued=self.take_maximum_value)<EOL>self.dof = dof<EOL>return achi_list<EOL><DEDENT> | Calculate the auto-chisq at the specified indices.
Parameters
-----------
sn : Array[complex]
SNR time series of the template for which auto-chisq is being
computed. Provided unnormalized.
indices : Array[int]
List of points at which to calculate auto-chisq
template : Pycbc template object
The template for which we are calculating auto-chisq
psd : Pycbc psd object
The PSD of the data being analysed
norm : float
The normalization factor to apply to sn
stilde : Pycbc data object, needed if using reverse-template
The data being analysed. Only needed if using reverse-template,
otherwise ignored
low_frequency_cutoff : float
The lower frequency to consider in matched-filters
high_frequency_cutoff : float
The upper frequency to consider in matched-filters | f15959:c0:m1 |
def power_chisq_bins_from_sigmasq_series(sigmasq_series, num_bins, kmin, kmax): | sigmasq = sigmasq_series[kmax - <NUM_LIT:1>]<EOL>edge_vec = numpy.arange(<NUM_LIT:0>, num_bins) * sigmasq / num_bins<EOL>bins = numpy.searchsorted(sigmasq_series[kmin:kmax], edge_vec, side='<STR_LIT:right>')<EOL>bins += kmin<EOL>return numpy.append(bins, kmax)<EOL> | Returns bins of equal power for use with the chisq functions
Parameters
----------
sigmasq_series: FrequencySeries
A frequency series containing the cumulative power of a filter template
preweighted by a psd.
num_bins: int
The number of chisq bins to calculate.
kmin: int
DOCUMENTME
kmax: int
DOCUMENTME
Returns
-------
bins: List of ints
A list of the edges of the chisq bins is returned. | f15960:m0 |
def power_chisq_bins(htilde, num_bins, psd, low_frequency_cutoff=None,<EOL>high_frequency_cutoff=None): | sigma_vec = sigmasq_series(htilde, psd, low_frequency_cutoff,<EOL>high_frequency_cutoff).numpy()<EOL>kmin, kmax = get_cutoff_indices(low_frequency_cutoff,<EOL>high_frequency_cutoff,<EOL>htilde.delta_f,<EOL>(len(htilde)-<NUM_LIT:1>)*<NUM_LIT:2>)<EOL>return power_chisq_bins_from_sigmasq_series(sigma_vec, num_bins, kmin, kmax)<EOL> | Returns bins of equal power for use with the chisq functions
Parameters
----------
htilde: FrequencySeries
A frequency series containing the template waveform
num_bins: int
The number of chisq bins to calculate.
psd: FrequencySeries
A frequency series containing the psd. Its length must be commensurate
with the template waveform.
low_frequency_cutoff: {None, float}, optional
The low frequency cutoff to apply
high_frequency_cutoff: {None, float}, optional
The high frequency cutoff to apply
Returns
-------
bins: List of ints
A list of the edges of the chisq bins is returned. | f15960:m1 |
@schemed(BACKEND_PREFIX)<EOL>def shift_sum(v1, shifts, bins): | err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL> | Calculate the time shifted sum of the FrequencySeries | f15960:m3 |
def power_chisq_at_points_from_precomputed(corr, snr, snr_norm, bins, indices): | num_bins = len(bins) - <NUM_LIT:1><EOL>chisq = shift_sum(corr, indices, bins) <EOL>return (chisq * num_bins - (snr.conj() * snr).real) * (snr_norm ** <NUM_LIT>)<EOL> | Calculate the chisq timeseries from precomputed values for only select points.
This function calculates the chisq at each point by explicitly time shifting
and summing each bin. No FFT is involved.
Parameters
----------
corr: FrequencySeries
The product of the template and data in the frequency domain.
snr: numpy.ndarray
The unnormalized array of snr values at only the selected points in `indices`.
snr_norm: float
The normalization of the snr (EXPLAINME : refer to Findchirp paper?)
bins: List of integers
The edges of the equal power bins
indices: Array
The indices where we will calculate the chisq. These must be relative
to the given `corr` series.
Returns
-------
chisq: Array
An array containing only the chisq at the selected points. | f15960:m4 |
def power_chisq_from_precomputed(corr, snr, snr_norm, bins, indices=None, return_bins=False): | <EOL>global _q_l, _qtilde_l, _chisq_l<EOL>bin_snrs = []<EOL>if _q_l is None or len(_q_l) != len(snr):<EOL><INDENT>q = zeros(len(snr), dtype=complex_same_precision_as(snr))<EOL>qtilde = zeros(len(snr), dtype=complex_same_precision_as(snr))<EOL>_q_l = q<EOL>_qtilde_l = qtilde<EOL><DEDENT>else:<EOL><INDENT>q = _q_l<EOL>qtilde = _qtilde_l<EOL><DEDENT>if indices is not None:<EOL><INDENT>snr = snr.take(indices)<EOL><DEDENT>if _chisq_l is None or len(_chisq_l) < len(snr):<EOL><INDENT>chisq = zeros(len(snr), dtype=real_same_precision_as(snr))<EOL>_chisq_l = chisq<EOL><DEDENT>else:<EOL><INDENT>chisq = _chisq_l[<NUM_LIT:0>:len(snr)]<EOL>chisq.clear()<EOL><DEDENT>num_bins = len(bins) - <NUM_LIT:1><EOL>for j in range(num_bins):<EOL><INDENT>k_min = int(bins[j])<EOL>k_max = int(bins[j+<NUM_LIT:1>])<EOL>qtilde[k_min:k_max] = corr[k_min:k_max]<EOL>pycbc.fft.ifft(qtilde, q)<EOL>qtilde[k_min:k_max].clear()<EOL>if return_bins:<EOL><INDENT>bin_snrs.append(TimeSeries(q * snr_norm * num_bins ** <NUM_LIT:0.5>,<EOL>delta_t=snr.delta_t,<EOL>epoch=snr.start_time))<EOL><DEDENT>if indices is not None:<EOL><INDENT>chisq_accum_bin(chisq, q.take(indices))<EOL><DEDENT>else:<EOL><INDENT>chisq_accum_bin(chisq, q)<EOL><DEDENT><DEDENT>chisq = (chisq * num_bins - snr.squared_norm()) * (snr_norm ** <NUM_LIT>)<EOL>if indices is None:<EOL><INDENT>chisq = TimeSeries(chisq, delta_t=snr.delta_t, epoch=snr.start_time, copy=False)<EOL><DEDENT>if return_bins:<EOL><INDENT>return chisq, bin_snrs<EOL><DEDENT>else:<EOL><INDENT>return chisq<EOL><DEDENT> | Calculate the chisq timeseries from precomputed values.
This function calculates the chisq at all times by performing an
inverse FFT of each bin.
Parameters
----------
corr: FrequencySeries
The produce of the template and data in the frequency domain.
snr: TimeSeries
The unnormalized snr time series.
snr_norm:
The snr normalization factor (true snr = snr * snr_norm) EXPLAINME - define 'true snr'?
bins: List of integers
The edges of the chisq bins.
indices: {Array, None}, optional
Index values into snr that indicate where to calculate
chisq values. If none, calculate chisq for all possible indices.
return_bins: {boolean, False}, optional
Return a list of the SNRs for each chisq bin.
Returns
-------
chisq: TimeSeries | f15960:m5 |
def power_chisq(template, data, num_bins, psd,<EOL>low_frequency_cutoff=None,<EOL>high_frequency_cutoff=None,<EOL>return_bins=False): | htilde = make_frequency_series(template)<EOL>stilde = make_frequency_series(data)<EOL>bins = power_chisq_bins(htilde, num_bins, psd, low_frequency_cutoff,<EOL>high_frequency_cutoff)<EOL>corra = zeros((len(htilde)-<NUM_LIT:1>)*<NUM_LIT:2>, dtype=htilde.dtype)<EOL>total_snr, corr, tnorm = matched_filter_core(htilde, stilde, psd,<EOL>low_frequency_cutoff, high_frequency_cutoff,<EOL>corr_out=corra)<EOL>return power_chisq_from_precomputed(corr, total_snr, tnorm, bins, return_bins=return_bins)<EOL> | Calculate the chisq timeseries
Parameters
----------
template: FrequencySeries or TimeSeries
A time or frequency series that contains the filter template.
data: FrequencySeries or TimeSeries
A time or frequency series that contains the data to filter. The length
must be commensurate with the template.
(EXPLAINME - does this mean 'the same as' or something else?)
num_bins: int
The number of bins in the chisq. Note that the dof goes as 2*num_bins-2.
psd: FrequencySeries
The psd of the data.
low_frequency_cutoff: {None, float}, optional
The low frequency cutoff for the filter
high_frequency_cutoff: {None, float}, optional
The high frequency cutoff for the filter
return_bins: {boolean, False}, optional
Return a list of the individual chisq bins
Returns
-------
chisq: TimeSeries
TimeSeries containing the chisq values for all times. | f15960:m7 |
def values(self, corr, snrv, snr_norm, psd, indices, template): | if self.do:<EOL><INDENT>num_above = len(indices)<EOL>if self.snr_threshold:<EOL><INDENT>above = abs(snrv * snr_norm) > self.snr_threshold<EOL>num_above = above.sum()<EOL>logging.info('<STR_LIT>' % num_above)<EOL>above_indices = indices[above]<EOL>above_snrv = snrv[above]<EOL>rchisq = numpy.zeros(len(indices), dtype=numpy.float32)<EOL>dof = -<NUM_LIT:100><EOL><DEDENT>else:<EOL><INDENT>above_indices = indices<EOL>above_snrv = snrv<EOL><DEDENT>if num_above > <NUM_LIT:0>:<EOL><INDENT>bins = self.cached_chisq_bins(template, psd)<EOL>dof = (len(bins) - <NUM_LIT:1>) * <NUM_LIT:2> - <NUM_LIT:2><EOL>chisq = power_chisq_at_points_from_precomputed(corr,<EOL>above_snrv, snr_norm, bins, above_indices)<EOL><DEDENT>if self.snr_threshold:<EOL><INDENT>if num_above > <NUM_LIT:0>:<EOL><INDENT>rchisq[above] = chisq<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rchisq = chisq<EOL><DEDENT>return rchisq, numpy.repeat(dof, len(indices))<EOL><DEDENT>else:<EOL><INDENT>return None, None<EOL><DEDENT> | Calculate the chisq at points given by indices.
Returns
-------
chisq: Array
Chisq values, one for each sample index
chisq_dof: Array
Number of statistical degrees of freedom for the chisq test
in the given template | f15960:c0:m3 |
def calculate_chisq_bins(self, template, psd): | num_bins = int(self.parse_option(template, self.num_bins))<EOL>if hasattr(psd, '<STR_LIT>') andtemplate.approximant in psd.sigmasq_vec:<EOL><INDENT>kmin = int(template.f_lower / psd.delta_f)<EOL>kmax = template.end_idx<EOL>bins = power_chisq_bins_from_sigmasq_series(<EOL>psd.sigmasq_vec[template.approximant], num_bins, kmin, kmax)<EOL><DEDENT>else:<EOL><INDENT>bins = power_chisq_bins(template, num_bins, psd, template.f_lower)<EOL><DEDENT>return bins<EOL> | Obtain the chisq bins for this template and PSD. | f15960:c1:m1 |
def values(self, corr_plus, corr_cross, snrv, psd,<EOL>indices, template_plus, template_cross, u_vals,<EOL>hplus_cross_corr, hpnorm, hcnorm): | if self.do:<EOL><INDENT>num_above = len(indices)<EOL>if self.snr_threshold:<EOL><INDENT>above = abs(snrv) > self.snr_threshold<EOL>num_above = above.sum()<EOL>logging.info('<STR_LIT>' % num_above)<EOL>above_indices = indices[above]<EOL>above_snrv = snrv[above]<EOL>rchisq = numpy.zeros(len(indices), dtype=numpy.float32)<EOL>dof = -<NUM_LIT:100><EOL><DEDENT>else:<EOL><INDENT>above_indices = indices<EOL>above_snrv = snrv<EOL><DEDENT>if num_above > <NUM_LIT:0>:<EOL><INDENT>chisq = []<EOL>curr_tmplt_mult_fac = <NUM_LIT:0.><EOL>curr_corr_mult_fac = <NUM_LIT:0.><EOL>if self.template_mem is None or(not len(self.template_mem) == len(template_plus)):<EOL><INDENT>self.template_mem = zeros(len(template_plus),<EOL>dtype=complex_same_precision_as(corr_plus))<EOL><DEDENT>if self.corr_mem is None or(not len(self.corr_mem) == len(corr_plus)):<EOL><INDENT>self.corr_mem = zeros(len(corr_plus),<EOL>dtype=complex_same_precision_as(corr_plus))<EOL><DEDENT>tmplt_data = template_cross.data<EOL>corr_data = corr_cross.data<EOL>numpy.copyto(self.template_mem.data, template_cross.data)<EOL>numpy.copyto(self.corr_mem.data, corr_cross.data)<EOL>template_cross._data = self.template_mem.data<EOL>corr_cross._data = self.corr_mem.data<EOL>for lidx, index in enumerate(above_indices):<EOL><INDENT>above_local_indices = numpy.array([index])<EOL>above_local_snr = numpy.array([above_snrv[lidx]])<EOL>local_u_val = u_vals[lidx]<EOL>template = template_cross.multiply_and_add(template_plus,<EOL>local_u_val-curr_tmplt_mult_fac)<EOL>curr_tmplt_mult_fac = local_u_val<EOL>template.f_lower = template_plus.f_lower<EOL>template.params = template_plus.params<EOL>norm_fac = local_u_val*local_u_val + <NUM_LIT:1><EOL>norm_fac += <NUM_LIT:2> * local_u_val * hplus_cross_corr<EOL>norm_fac = hcnorm / (norm_fac**<NUM_LIT:0.5>)<EOL>hp_fac = local_u_val * hpnorm / hcnorm<EOL>corr = corr_cross.multiply_and_add(corr_plus,<EOL>hp_fac - curr_corr_mult_fac)<EOL>curr_corr_mult_fac = hp_fac<EOL>bins = self.calculate_chisq_bins(template, psd)<EOL>dof = (len(bins) - <NUM_LIT:1>) * <NUM_LIT:2> - <NUM_LIT:2><EOL>curr_chisq = power_chisq_at_points_from_precomputed(corr,<EOL>above_local_snr/ norm_fac, norm_fac,<EOL>bins, above_local_indices)<EOL>chisq.append(curr_chisq[<NUM_LIT:0>])<EOL><DEDENT>chisq = numpy.array(chisq)<EOL>template_cross._data = tmplt_data<EOL>corr_cross._data = corr_data<EOL><DEDENT>if self.snr_threshold:<EOL><INDENT>if num_above > <NUM_LIT:0>:<EOL><INDENT>rchisq[above] = chisq<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rchisq = chisq<EOL><DEDENT>return rchisq, numpy.repeat(dof, len(indices))<EOL><DEDENT>else:<EOL><INDENT>return None, None<EOL><DEDENT> | Calculate the chisq at points given by indices.
Returns
-------
chisq: Array
Chisq values, one for each sample index
chisq_dof: Array
Number of statistical degrees of freedom for the chisq test
in the given template | f15960:c1:m2 |
def __init__(self, bank, num_bins=<NUM_LIT:0>,<EOL>snr_threshold=None,<EOL>chisq_locations=None): | if snr_threshold is not None:<EOL><INDENT>self.do = True<EOL>self.num_bins = num_bins<EOL>self.snr_threshold = snr_threshold<EOL>self.params = {}<EOL>for descr in chisq_locations:<EOL><INDENT>region, values = descr.split("<STR_LIT::>")<EOL>mask = bank.table.parse_boolargs([(<NUM_LIT:1>, region), (<NUM_LIT:0>, '<STR_LIT>')])[<NUM_LIT:0>]<EOL>hashes = bank.table['<STR_LIT>'][mask.astype(bool)]<EOL>for h in hashes:<EOL><INDENT>self.params[h] = values<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>self.do = False<EOL><DEDENT> | Create sine-Gaussian Chisq Calculator
Parameters
----------
bank: pycbc.waveform.TemplateBank
The template bank that will be processed.
num_bins: str
The string determining the number of power chisq bins
snr_threshold: float
The threshold to calculate the sine-Gaussian chisq
chisq_locations: list of strs
List of strings which detail where to place a sine-Gaussian.
The format is 'region-boolean:q1-offset1,q2-offset2'.
The offset is relative to the end frequency of the approximant.
The region is a boolean expression such as 'mtotal>40' indicating
which templates to apply this set of sine-Gaussians to. | f15961:c0:m0 |
def values(self, stilde, template, psd, snrv, snr_norm,<EOL>bchisq, bchisq_dof, indices): | if not self.do:<EOL><INDENT>return None<EOL><DEDENT>if template.params.template_hash not in self.params:<EOL><INDENT>return numpy.ones(len(snrv))<EOL><DEDENT>values = self.params[template.params.template_hash].split('<STR_LIT:U+002C>')<EOL>bins = self.cached_chisq_bins(template, psd)<EOL>chisq = numpy.ones(len(snrv))<EOL>for i, snrvi in enumerate(snrv):<EOL><INDENT>snr = abs(snrvi * snr_norm)<EOL>nsnr = ranking.newsnr(snr, bchisq[i] / bchisq_dof[i])<EOL>if nsnr < self.snr_threshold:<EOL><INDENT>continue<EOL><DEDENT>N = (len(template) - <NUM_LIT:1>) * <NUM_LIT:2><EOL>dt = <NUM_LIT:1.0> / (N * template.delta_f)<EOL>kmin = int(template.f_lower / psd.delta_f)<EOL>time = float(template.epoch) + dt * indices[i]<EOL>stilde_shift = apply_fseries_time_shift(stilde, -time)<EOL>qwindow = <NUM_LIT:50><EOL>chisq[i] = <NUM_LIT:0><EOL>fstep = (bins[-<NUM_LIT:2>] - bins[-<NUM_LIT:3>])<EOL>fpeak = (bins[-<NUM_LIT:2>] + fstep) * template.delta_f<EOL>fstop = len(stilde) * stilde.delta_f * <NUM_LIT><EOL>dof = <NUM_LIT:0><EOL>for descr in values:<EOL><INDENT>q, offset = descr.split('<STR_LIT:->')<EOL>q, offset = float(q), float(offset)<EOL>fcen = fpeak + offset<EOL>flow = max(kmin * template.delta_f, fcen - qwindow)<EOL>fhigh = fcen + qwindow<EOL>if fhigh > fstop:<EOL><INDENT>return numpy.ones(len(snrv))<EOL><DEDENT>kmin = int(flow / template.delta_f)<EOL>kmax = int(fhigh / template.delta_f)<EOL>gtem = sinegauss.fd_sine_gaussian(<NUM_LIT:1.0>, q, fcen, flow,<EOL>len(template) * template.delta_f,<EOL>template.delta_f).astype(numpy.complex64)<EOL>gsigma = sigma(gtem, psd=psd,<EOL>low_frequency_cutoff=flow,<EOL>high_frequency_cutoff=fhigh)<EOL>gsnr = (gtem[kmin:kmax] * stilde_shift[kmin:kmax]).sum()<EOL>gsnr *= <NUM_LIT> * gtem.delta_f / gsigma<EOL>chisq[i] += abs(gsnr)**<NUM_LIT><EOL>dof += <NUM_LIT:2><EOL><DEDENT>if dof == <NUM_LIT:0>:<EOL><INDENT>chisq[i] = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>chisq[i] /= dof<EOL><DEDENT><DEDENT>return chisq<EOL> | Calculate sine-Gaussian chisq
Parameters
----------
stilde: pycbc.types.Frequencyseries
The overwhitened strain
template: pycbc.types.Frequencyseries
The waveform template being analyzed
psd: pycbc.types.Frequencyseries
The power spectral density of the data
snrv: numpy.ndarray
The peak unnormalized complex SNR values
snr_norm: float
The normalization factor for the snr
bchisq: numpy.ndarray
The Bruce Allen power chisq values for these triggers
bchisq_dof: numpy.ndarray
The degrees of freedom of the Bruce chisq
indics: numpy.ndarray
The indices of the snr peaks.
Returns
-------
chisq: Array
Chisq values, one for each sample index | f15961:c0:m3 |
def segment_snrs(filters, stilde, psd, low_frequency_cutoff): | snrs = []<EOL>norms = []<EOL>for bank_template in filters:<EOL><INDENT>snr, _, norm = matched_filter_core(<EOL>bank_template, stilde, h_norm=bank_template.sigmasq(psd),<EOL>psd=None, low_frequency_cutoff=low_frequency_cutoff)<EOL>snrs.append(snr)<EOL>norms.append(norm)<EOL><DEDENT>return snrs, norms<EOL> | This functions calculates the snr of each bank veto template against
the segment
Parameters
----------
filters: list of FrequencySeries
The list of bank veto templates filters.
stilde: FrequencySeries
The current segment of data.
psd: FrequencySeries
low_frequency_cutoff: float
Returns
-------
snr (list): List of snr time series.
norm (list): List of normalizations factors for the snr time series. | f15964:m0 |
def template_overlaps(bank_filters, template, psd, low_frequency_cutoff): | overlaps = []<EOL>template_ow = template / psd<EOL>for bank_template in bank_filters:<EOL><INDENT>overlap = overlap_cplx(template_ow, bank_template,<EOL>low_frequency_cutoff=low_frequency_cutoff, normalized=False)<EOL>norm = sqrt(<NUM_LIT:1> / template.sigmasq(psd) / bank_template.sigmasq(psd))<EOL>overlaps.append(overlap * norm)<EOL>if (abs(overlaps[-<NUM_LIT:1>]) > <NUM_LIT>):<EOL><INDENT>errMsg = "<STR_LIT>"<EOL>errMsg += "<STR_LIT>"<EOL>errMsg += "<STR_LIT>"<EOL>errMsg += "<STR_LIT>"<EOL>errMsg += "<STR_LIT>"<EOL>errMsg += "<STR_LIT>"%(template.params.mass1, template.params.mass2)<EOL>errMsg += "<STR_LIT>"%(bank_template.params.mass1, bank_template.params.mass2)<EOL>errMsg += "<STR_LIT>" %(abs(overlaps[-<NUM_LIT:1>]))<EOL>logging.debug(errMsg)<EOL><DEDENT><DEDENT>return overlaps<EOL> | This functions calculates the overlaps between the template and the
bank veto templates.
Parameters
----------
bank_filters: List of FrequencySeries
template: FrequencySeries
psd: FrequencySeries
low_frequency_cutoff: float
Returns
-------
overlaps: List of complex overlap values. | f15964:m1 |
def bank_chisq_from_filters(tmplt_snr, tmplt_norm, bank_snrs, bank_norms,<EOL>tmplt_bank_matches, indices=None): | if indices is not None:<EOL><INDENT>tmplt_snr = Array(tmplt_snr, copy=False)<EOL>bank_snrs_tmp = []<EOL>for bank_snr in bank_snrs:<EOL><INDENT>bank_snrs_tmp.append(bank_snr.take(indices))<EOL><DEDENT>bank_snrs=bank_snrs_tmp<EOL><DEDENT>bank_chisq = zeros(len(tmplt_snr), dtype=real_same_precision_as(tmplt_snr))<EOL>for i in range(len(bank_snrs)):<EOL><INDENT>bank_match = tmplt_bank_matches[i]<EOL>if (abs(bank_match) > <NUM_LIT>):<EOL><INDENT>bank_chisq += <NUM_LIT><EOL>continue<EOL><DEDENT>bank_norm = sqrt((<NUM_LIT:1> - bank_match*bank_match.conj()).real)<EOL>bank_SNR = bank_snrs[i] * (bank_norms[i] / bank_norm)<EOL>tmplt_SNR = tmplt_snr * (bank_match.conj() * tmplt_norm / bank_norm)<EOL>bank_SNR = Array(bank_SNR, copy=False)<EOL>tmplt_SNR = Array(tmplt_SNR, copy=False)<EOL>bank_chisq += (bank_SNR - tmplt_SNR).squared_norm()<EOL><DEDENT>if indices is not None:<EOL><INDENT>return bank_chisq<EOL><DEDENT>else:<EOL><INDENT>return TimeSeries(bank_chisq, delta_t=tmplt_snr.delta_t,<EOL>epoch=tmplt_snr.start_time, copy=False)<EOL><DEDENT> | This function calculates and returns a TimeSeries object containing the
bank veto calculated over a segment.
Parameters
----------
tmplt_snr: TimeSeries
The SNR time series from filtering the segment against the current
search template
tmplt_norm: float
The normalization factor for the search template
bank_snrs: list of TimeSeries
The precomputed list of SNR time series between each of the bank veto
templates and the segment
bank_norms: list of floats
The normalization factors for the list of bank veto templates
(usually this will be the same for all bank veto templates)
tmplt_bank_matches: list of floats
The complex overlap between the search template and each
of the bank templates
indices: {None, Array}, optional
Array of indices into the snr time series. If given, the bank chisq
will only be calculated at these values.
Returns
-------
bank_chisq: TimeSeries of the bank vetos | f15964:m2 |
def values(self, template, psd, stilde, snrv, norm, indices): | if self.do:<EOL><INDENT>logging.info("<STR_LIT>")<EOL>overlaps = self.cache_overlaps(template, psd)<EOL>bank_veto_snrs, bank_veto_norms = self.cache_segment_snrs(stilde, psd)<EOL>chisq = bank_chisq_from_filters(snrv, norm, bank_veto_snrs,<EOL>bank_veto_norms, overlaps, indices)<EOL>dof = numpy.repeat(self.dof, len(chisq))<EOL>return chisq, dof<EOL><DEDENT>else:<EOL><INDENT>return None, None<EOL><DEDENT> | Returns
-------
bank_chisq_from_filters: TimeSeries of bank veto values - if indices
is None then evaluated at all time samples, if not then only at
requested sample indices
bank_chisq_dof: int, approx number of statistical degrees of freedom | f15964:c0:m3 |
def snr_series_to_xml(snr_series, document, sngl_inspiral_id): | snr_lal = snr_series.lal()<EOL>snr_lal.name = '<STR_LIT>'<EOL>snr_lal.sampleUnits = '<STR_LIT>'<EOL>snr_xml = _build_series(snr_lal, (u'<STR_LIT>', u'<STR_LIT>'), None,<EOL>'<STR_LIT>', '<STR_LIT:s>')<EOL>snr_node = document.childNodes[-<NUM_LIT:1>].appendChild(snr_xml)<EOL>eid_param = ligolw_param.Param.build(u'<STR_LIT>', u'<STR_LIT>',<EOL>sngl_inspiral_id)<EOL>snr_node.appendChild(eid_param)<EOL> | Save an SNR time series into an XML document, in a format compatible
with BAYESTAR. | f15965:m1 |
def make_psd_xmldoc(psddict, xmldoc=None): | xmldoc = ligolw.Document() if xmldoc is None else xmldoc.childNodes[<NUM_LIT:0>]<EOL>root_name = u"<STR_LIT>"<EOL>Attributes = ligolw.sax.xmlreader.AttributesImpl<EOL>lw = xmldoc.appendChild(<EOL>ligolw.LIGO_LW(Attributes({u"<STR_LIT:Name>": root_name})))<EOL>for instrument, psd in psddict.items():<EOL><INDENT>xmlseries = _build_series(psd, (u"<STR_LIT>", u"<STR_LIT>"),<EOL>None, '<STR_LIT>', '<STR_LIT>')<EOL>fs = lw.appendChild(xmlseries)<EOL>fs.appendChild(ligolw_param.Param.from_pyvalue(u"<STR_LIT>",<EOL>instrument))<EOL><DEDENT>return xmldoc<EOL> | Add a set of PSDs to a LIGOLW XML document. If the document is not
given, a new one is created first. | f15965:m2 |
def __init__(self, ifos, coinc_results, **kwargs): | self.template_id = coinc_results['<STR_LIT>' % ifos[<NUM_LIT:0>]]<EOL>self.coinc_results = coinc_results<EOL>self.ifos = ifos<EOL>self.is_hardware_injection = ('<STR_LIT>' in coinc_results<EOL>and coinc_results['<STR_LIT>'])<EOL>if '<STR_LIT>' in kwargs:<EOL><INDENT>fud = kwargs['<STR_LIT>']<EOL>assert len({fud[ifo]['<STR_LIT>'].delta_t for ifo in fud}) == <NUM_LIT:1>,"<STR_LIT>"<EOL>self.snr_series = {ifo: fud[ifo]['<STR_LIT>'] for ifo in fud}<EOL>usable_ifos = fud.keys()<EOL>followup_ifos = list(set(usable_ifos) - set(ifos))<EOL><DEDENT>else:<EOL><INDENT>self.snr_series = None<EOL>usable_ifos = ifos<EOL>followup_ifos = []<EOL><DEDENT>outdoc = ligolw.Document()<EOL>outdoc.appendChild(ligolw.LIGO_LW())<EOL>proc_id = ligolw_process.register_to_xmldoc(<EOL>outdoc, '<STR_LIT>', {}, ifos=usable_ifos, comment='<STR_LIT>',<EOL>version=pycbc_version.git_hash,<EOL>cvs_repository='<STR_LIT>'+pycbc_version.git_branch,<EOL>cvs_entry_time=pycbc_version.date).process_id<EOL>coinc_def_table = lsctables.New(lsctables.CoincDefTable)<EOL>coinc_def_id = lsctables.CoincDefID(<NUM_LIT:0>)<EOL>coinc_def_row = lsctables.CoincDef()<EOL>coinc_def_row.search = "<STR_LIT>"<EOL>coinc_def_row.description = "<STR_LIT>"<EOL>coinc_def_row.coinc_def_id = coinc_def_id<EOL>coinc_def_row.search_coinc_type = <NUM_LIT:0><EOL>coinc_def_table.append(coinc_def_row)<EOL>outdoc.childNodes[<NUM_LIT:0>].appendChild(coinc_def_table)<EOL>coinc_id = lsctables.CoincID(<NUM_LIT:0>)<EOL>coinc_event_table = lsctables.New(lsctables.CoincTable)<EOL>coinc_event_row = lsctables.Coinc()<EOL>coinc_event_row.coinc_def_id = coinc_def_id<EOL>coinc_event_row.nevents = len(usable_ifos)<EOL>coinc_event_row.instruments = '<STR_LIT:U+002C>'.join(usable_ifos)<EOL>coinc_event_row.time_slide_id = lsctables.TimeSlideID(<NUM_LIT:0>)<EOL>coinc_event_row.process_id = proc_id<EOL>coinc_event_row.coinc_event_id = coinc_id<EOL>coinc_event_row.likelihood = <NUM_LIT:0.><EOL>coinc_event_table.append(coinc_event_row)<EOL>outdoc.childNodes[<NUM_LIT:0>].appendChild(coinc_event_table)<EOL>sngl_inspiral_table = lsctables.New(lsctables.SnglInspiralTable)<EOL>coinc_event_map_table = lsctables.New(lsctables.CoincMapTable)<EOL>sngl_populated = None<EOL>network_snrsq = <NUM_LIT:0><EOL>for sngl_id, ifo in enumerate(usable_ifos):<EOL><INDENT>sngl = return_empty_sngl(nones=True)<EOL>sngl.event_id = lsctables.SnglInspiralID(sngl_id)<EOL>sngl.process_id = proc_id<EOL>sngl.ifo = ifo<EOL>names = [n.split('<STR_LIT:/>')[-<NUM_LIT:1>] for n in coinc_results<EOL>if '<STR_LIT>' % ifo in n]<EOL>for name in names:<EOL><INDENT>val = coinc_results['<STR_LIT>' % (ifo, name)]<EOL>if name == '<STR_LIT>':<EOL><INDENT>sngl.set_end(lal.LIGOTimeGPS(val))<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>setattr(sngl, name, val)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>if sngl.mass1 and sngl.mass2:<EOL><INDENT>sngl.mtotal, sngl.eta = pnutils.mass1_mass2_to_mtotal_eta(<EOL>sngl.mass1, sngl.mass2)<EOL>sngl.mchirp, _ = pnutils.mass1_mass2_to_mchirp_eta(<EOL>sngl.mass1, sngl.mass2)<EOL>sngl_populated = sngl<EOL><DEDENT>if sngl.snr:<EOL><INDENT>sngl.eff_distance = (sngl.sigmasq)**<NUM_LIT:0.5> / sngl.snr<EOL>network_snrsq += sngl.snr ** <NUM_LIT><EOL><DEDENT>if '<STR_LIT>' in kwargs and ifo in kwargs['<STR_LIT>']:<EOL><INDENT>sngl.channel = kwargs['<STR_LIT>'][ifo]<EOL><DEDENT>sngl_inspiral_table.append(sngl)<EOL>coinc_map_row = lsctables.CoincMap()<EOL>coinc_map_row.table_name = '<STR_LIT>'<EOL>coinc_map_row.coinc_event_id = coinc_id<EOL>coinc_map_row.event_id = sngl.event_id<EOL>coinc_event_map_table.append(coinc_map_row)<EOL>if self.snr_series is not None:<EOL><INDENT>snr_series_to_xml(self.snr_series[ifo], outdoc, sngl.event_id)<EOL><DEDENT><DEDENT>bayestar_check_fields = ('<STR_LIT>'<EOL>'<STR_LIT>').split()<EOL>subthreshold_sngl_time = numpy.mean(<EOL>[coinc_results['<STR_LIT>'.format(ifo)]<EOL>for ifo in ifos])<EOL>for sngl in sngl_inspiral_table:<EOL><INDENT>if sngl.ifo in followup_ifos:<EOL><INDENT>for bcf in bayestar_check_fields:<EOL><INDENT>setattr(sngl, bcf, getattr(sngl_populated, bcf))<EOL><DEDENT>sngl.set_end(lal.LIGOTimeGPS(subthreshold_sngl_time))<EOL><DEDENT><DEDENT>outdoc.childNodes[<NUM_LIT:0>].appendChild(coinc_event_map_table)<EOL>outdoc.childNodes[<NUM_LIT:0>].appendChild(sngl_inspiral_table)<EOL>coinc_inspiral_table = lsctables.New(lsctables.CoincInspiralTable)<EOL>coinc_inspiral_row = lsctables.CoincInspiral()<EOL>coinc_inspiral_row.false_alarm_rate = <NUM_LIT:0><EOL>coinc_inspiral_row.minimum_duration = <NUM_LIT:0.><EOL>coinc_inspiral_row.set_ifos(usable_ifos)<EOL>coinc_inspiral_row.coinc_event_id = coinc_id<EOL>coinc_inspiral_row.mchirp = sngl_populated.mchirp<EOL>coinc_inspiral_row.mass = sngl_populated.mtotal<EOL>coinc_inspiral_row.end_time = sngl_populated.end_time<EOL>coinc_inspiral_row.end_time_ns = sngl_populated.end_time_ns<EOL>coinc_inspiral_row.snr = network_snrsq ** <NUM_LIT:0.5><EOL>far = <NUM_LIT:1.0> / (lal.YRJUL_SI * coinc_results['<STR_LIT>'])<EOL>coinc_inspiral_row.combined_far = far<EOL>coinc_inspiral_table.append(coinc_inspiral_row)<EOL>outdoc.childNodes[<NUM_LIT:0>].appendChild(coinc_inspiral_table)<EOL>self.psds = kwargs['<STR_LIT>']<EOL>psds_lal = {}<EOL>for ifo in self.psds:<EOL><INDENT>psd = self.psds[ifo]<EOL>kmin = int(kwargs['<STR_LIT>'] / psd.delta_f)<EOL>fseries = lal.CreateREAL8FrequencySeries(<EOL>"<STR_LIT>", psd.epoch, kwargs['<STR_LIT>'], psd.delta_f,<EOL>lal.StrainUnit**<NUM_LIT:2> / lal.HertzUnit, len(psd) - kmin)<EOL>fseries.data.data = psd.numpy()[kmin:] / pycbc.DYN_RANGE_FAC ** <NUM_LIT><EOL>psds_lal[ifo] = fseries<EOL><DEDENT>make_psd_xmldoc(psds_lal, outdoc)<EOL>self.outdoc = outdoc<EOL>self.time = sngl_populated.get_end()<EOL> | Initialize a ligolw xml representation of a zerolag trigger
for upload from pycbc live to gracedb.
Parameters
----------
ifos: list of strs
A list of the ifos pariticipating in this trigger
coinc_results: dict of values
A dictionary of values. The format is defined in
pycbc/events/coinc.py and matches the on disk representation
in the hdf file for this time.
psds: dict of FrequencySeries
Dictionary providing PSD estimates for all involved detectors.
low_frequency_cutoff: float
Minimum valid frequency for the PSD estimates.
followup_data: dict of dicts, optional
Dictionary providing SNR time series for each detector,
to be used in sky localization with BAYESTAR. The format should
be `followup_data['H1']['snr_series']`. More detectors can be
present than given in `ifos`. If so, the extra detectors will only
be used for sky localization.
channel_names: dict of strings, optional
Strain channel names for each detector.
Will be recorded in the sngl_inspiral table. | f15965:c0:m0 |
def save(self, filename): | gz = filename.endswith('<STR_LIT>')<EOL>ligolw_utils.write_filename(self.outdoc, filename, gz=gz)<EOL> | Write this trigger to gracedb compatible xml format
Parameters
----------
filename: str
Name of file to write to disk. | f15965:c0:m1 |
def default_empty(shape, dtype): | default = numpy.zeros(shape, dtype=dtype)<EOL>set_default_empty(default)<EOL>return default<EOL> | Numpy's empty array can have random values in it. To prevent that, we
define here a default emtpy array. This default empty is a numpy.zeros
array, except that objects are set to None, and all ints to ID_NOT_SET. | f15966:m1 |
def lstring_as_obj(true_or_false=None): | if true_or_false is not None:<EOL><INDENT>_default_types_status['<STR_LIT>'] = true_or_false<EOL>numpy.typeDict[u'<STR_LIT>'] = numpy.object_if _default_types_status['<STR_LIT>']else '<STR_LIT>' % _default_types_status['<STR_LIT>']<EOL><DEDENT>return _default_types_status['<STR_LIT>']<EOL> | Toggles whether lstrings should be treated as strings or as objects.
When FieldArrays is first loaded, the default is True.
Parameters
----------
true_or_false : {None|bool}
Pass True to map lstrings to objects; False otherwise. If None
provided, just returns the current state.
Return
------
current_stat : bool
The current state of lstring_as_obj.
Examples
--------
>>> from pycbc.io import FieldArray
>>> FieldArray.lstring_as_obj()
True
>>> FieldArray.FieldArray.from_arrays([numpy.zeros(10)], dtype=[('foo', 'lstring')])
FieldArray([(0.0,), (0.0,), (0.0,), (0.0,), (0.0,), (0.0,), (0.0,), (0.0,),
(0.0,), (0.0,)],
dtype=[('foo', 'O')])
>>> FieldArray.lstring_as_obj(False)
False
>>> FieldArray.FieldArray.from_arrays([numpy.zeros(10)], dtype=[('foo', 'lstring')])
FieldArray([('0.0',), ('0.0',), ('0.0',), ('0.0',), ('0.0',), ('0.0',),
('0.0',), ('0.0',), ('0.0',), ('0.0',)],
dtype=[('foo', 'S50')]) | f15966:m2 |
def ilwd_as_int(true_or_false=None): | if true_or_false is not None:<EOL><INDENT>_default_types_status['<STR_LIT>'] = true_or_false<EOL>numpy.typeDict[u'<STR_LIT>'] = intif _default_types_status['<STR_LIT>']else '<STR_LIT>' % default_strlen<EOL><DEDENT>return _default_types_status['<STR_LIT>']<EOL> | Similar to lstring_as_obj, sets whether or not ilwd:chars should be
treated as strings or as ints. Default is True. | f15966:m3 |
def default_strlen(strlen=None): | if strlen is not None:<EOL><INDENT>_default_types_status['<STR_LIT>'] = strlen<EOL>lstring_as_obj(_default_types_status['<STR_LIT>'])<EOL>ilwd_as_int(_default_types_status['<STR_LIT>'])<EOL><DEDENT>return _default_types_status['<STR_LIT>']<EOL> | Sets the default string length for lstring and ilwd:char, if they are
treated as strings. Default is 50. | f15966:m4 |
def get_vars_from_arg(arg): | return set(_pyparser.findall(arg))<EOL> | Given a python string, gets the names of any identifiers use in it.
For example, if ``arg = '3*narf/foo.bar'``, this will return
``set(['narf', 'foo', 'bar'])``. | f15966:m5 |
def get_fields_from_arg(arg): | return set(_fieldparser.findall(arg))<EOL> | Given a python string, gets FieldArray field names used in it. This
differs from get_vars_from_arg in that any identifier with a '.' in it
will be treated as one identifier. For example, if
``arg = '3*narf/foo.bar'``, this will return ``set(['narf', 'foo.bar'])``. | f15966:m6 |
def get_instance_fields_from_arg(arg): | return set(_instfieldparser.findall(arg))<EOL> | Given a python string definining a method function on an instance of an
FieldArray, returns the field names used in it. This differs from
get_fields_from_arg in that it looks for variables that start with 'self'. | f15966:m7 |
def get_needed_fieldnames(arr, names): | fieldnames = set([])<EOL>cls = arr.__class__<EOL>if isinstance(names, string_types):<EOL><INDENT>names = [names]<EOL><DEDENT>parsed_names = set([])<EOL>for name in names:<EOL><INDENT>parsed_names.update(get_fields_from_arg(name))<EOL><DEDENT>names = list(parsed_names & (set(dir(arr)) | set(arr.fieldnames)))<EOL>for name in names:<EOL><INDENT>if name in arr.fieldnames:<EOL><INDENT>fieldnames.update([name])<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>func = getattr(cls, name).fget<EOL><DEDENT>except AttributeError:<EOL><INDENT>func = getattr(arr, name)<EOL><DEDENT>try:<EOL><INDENT>sourcecode = inspect.getsource(func)<EOL><DEDENT>except TypeError:<EOL><INDENT>continue<EOL><DEDENT>possible_fields = get_instance_fields_from_arg(sourcecode)<EOL>fieldnames.update(get_needed_fieldnames(arr, possible_fields))<EOL><DEDENT><DEDENT>return fieldnames<EOL> | Given a FieldArray-like array and a list of names, determines what
fields are needed from the array so that using the names does not result
in an error.
Parameters
----------
arr : instance of a FieldArray or similar
The array from which to determine what fields to get.
names : (list of) strings
A list of the names that are desired. The names may be either a field,
a virtualfield, a property, a method of ``arr``, or any function of
these. If a virtualfield/property or a method, the source code of that
property/method will be analyzed to pull out what fields are used in
it.
Returns
-------
set
The set of the fields needed to evaluate the names. | f15966:m8 |
def get_dtype_descr(dtype): | return [dt for dt in dtype.descr if not (dt[<NUM_LIT:0>] == '<STR_LIT>' and dt[<NUM_LIT:1>][<NUM_LIT:1>] == '<STR_LIT>')]<EOL> | Numpy's ``dtype.descr`` will return empty void fields if a dtype has
offsets specified. This function tries to fix that by not including
fields that have no names and are void types. | f15966:m9 |
def combine_fields(dtypes): | if not isinstance(dtypes, list):<EOL><INDENT>dtypes = [dtypes]<EOL><DEDENT>new_dt = numpy.dtype([dt for dtype in dtypesfor dt in get_dtype_descr(dtype)])<EOL>return new_dt<EOL> | Combines the fields in the list of given dtypes into a single dtype.
Parameters
----------
dtypes : (list of) numpy.dtype(s)
Either a numpy.dtype, or a list of numpy.dtypes.
Returns
-------
numpy.dtype
A new dtype combining the fields in the list of dtypes. | f15966:m10 |
def _ensure_array_list(arrays): | <EOL>return [numpy.array(arr, ndmin=<NUM_LIT:1>) if not isinstance(arr, numpy.ndarray)<EOL>else arr for arr in arrays]<EOL> | Ensures that every element in a list is an instance of a numpy array. | f15966:m11 |
def merge_arrays(merge_list, names=None, flatten=True, outtype=None): | <EOL>merge_list = _ensure_array_list(merge_list)<EOL>if not all(merge_list[<NUM_LIT:0>].shape == arr.shape for arr in merge_list):<EOL><INDENT>raise ValueError("<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>if flatten:<EOL><INDENT>new_dt = combine_fields([arr.dtype for arr in merge_list])<EOL><DEDENT>else:<EOL><INDENT>new_dt = numpy.dtype([('<STR_LIT>' %ii, arr.dtype.descr)for ii,arr in enumerate(merge_list)])<EOL><DEDENT>new_arr = merge_list[<NUM_LIT:0>].__class__(merge_list[<NUM_LIT:0>].shape, dtype=new_dt)<EOL>ii = <NUM_LIT:0><EOL>for arr in merge_list:<EOL><INDENT>if arr.dtype.names is None:<EOL><INDENT>new_arr[new_dt.names[ii]] = arr<EOL>ii += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>for field in arr.dtype.names:<EOL><INDENT>new_arr[field] = arr[field]<EOL>ii += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>if names is not None:<EOL><INDENT>new_arr.dtype.names = names<EOL><DEDENT>if outtype is not None:<EOL><INDENT>new_arr = new_arr.view(type=outtype)<EOL><DEDENT>return new_arr<EOL> | Merges the given arrays into a single array. The arrays must all have
the same shape. If one or more of the given arrays has multiple fields,
all of the fields will be included as separate fields in the new array.
Parameters
----------
merge_list : list of arrays
The list of arrays to merge.
names : {None | sequence of strings}
Optional, the names of the fields in the output array. If flatten is
True, must be the same length as the total number of fields in
merge_list. Otherise, must be the same length as the number of
arrays in merge_list. If None provided, and flatten is True, names
used will be the same as the name of the fields in the given arrays.
If the datatype has no name, or flatten is False, the new field will
be `fi` where i is the index of the array in arrays.
flatten : bool
Make all of the fields in the given arrays separate fields in the
new array. Otherwise, each array will be added as a field. If an
array has fields, they will be subfields in the output array. Default
is True.
outtype : {None | class}
Cast the new array to the given type. Default is to return a
numpy structured array.
Returns
-------
new array : {numpy.ndarray | outtype}
A new array with all of the fields in all of the arrays merged into
a single array. | f15966:m12 |
def add_fields(input_array, arrays, names=None, assubarray=False): | if not isinstance(arrays, list):<EOL><INDENT>arrays = [arrays]<EOL><DEDENT>arrays = _ensure_array_list(arrays)<EOL>if names is not None:<EOL><INDENT>if isinstance(names, string_types):<EOL><INDENT>names = [names]<EOL><DEDENT>subarray_names = [name for name in names if len(name.split('<STR_LIT:.>')) > <NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>subarray_names = []<EOL><DEDENT>if any(subarray_names):<EOL><INDENT>subarrays = [arrays[ii] for ii,name in enumerate(names)if name in subarray_names]<EOL>groups = {}<EOL>for name,arr in zip(subarray_names, subarrays):<EOL><INDENT>key = name.split('<STR_LIT:.>')[<NUM_LIT:0>]<EOL>subkey = '<STR_LIT:.>'.join(name.split('<STR_LIT:.>')[<NUM_LIT:1>:])<EOL>try:<EOL><INDENT>groups[key].append((subkey, arr))<EOL><DEDENT>except KeyError:<EOL><INDENT>groups[key] = [(subkey, arr)]<EOL><DEDENT><DEDENT>for group_name in groups:<EOL><INDENT>thisdict = dict(groups[group_name])<EOL>if group_name in input_array.fieldnames:<EOL><INDENT>new_subarray = input_array[group_name]<EOL>new_subarray = add_fields(new_subarray, thisdict.values(),<EOL>thisdict.keys())<EOL>input_array = input_array.without_fields(group_name)<EOL><DEDENT>else:<EOL><INDENT>new_subarray = thisdict.values()<EOL><DEDENT>input_array = add_fields(input_array, new_subarray,<EOL>names=group_name, assubarray=True)<EOL>input_array[group_name].dtype.names = thisdict.keys()<EOL><DEDENT>keep_idx = [ii for ii,name in enumerate(names)if name not in subarray_names]<EOL>names = [names[ii] for ii in keep_idx]<EOL>if names == []:<EOL><INDENT>return input_array<EOL><DEDENT>arrays = [arrays[ii] for ii in keep_idx]<EOL><DEDENT>if assubarray:<EOL><INDENT>if len(arrays) > <NUM_LIT:1>:<EOL><INDENT>arrays = [merge_arrays(arrays, flatten=True)]<EOL><DEDENT>merged_arr = numpy.empty(len(arrays[<NUM_LIT:0>]),<EOL>dtype=[('<STR_LIT>', arrays[<NUM_LIT:0>].dtype.descr)])<EOL>merged_arr['<STR_LIT>'] = arrays[<NUM_LIT:0>]<EOL>arrays = [merged_arr]<EOL><DEDENT>merge_list = [input_array] + arrays<EOL>if names is not None:<EOL><INDENT>names = list(input_array.dtype.names) + names<EOL><DEDENT>return merge_arrays(merge_list, names=names, flatten=True,<EOL>outtype=type(input_array))<EOL> | Adds the given array(s) as new field(s) to the given input array.
Returns a new instance of the input_array with the new fields added.
Parameters
----------
input_array : instance of a numpy.ndarray or numpy recarray
The array to to add the fields to.
arrays : (list of) numpy array(s)
The arrays to add. If adding multiple arrays, must be a list;
if adding a single array, can just be that array.
names : (list of) strings
Optional, the name(s) of the new fields in the output array. If
adding multiple fields, must be a list of strings with the same
length as the list of arrays. If None provided, names used will
be the same as the name of the datatype in the given arrays.
If the datatype has no name, the new field will be ``'fi'`` where
i is the index of the array in arrays.
assubarray : bool
Add the list of arrays as a single subarray field. If True, and names
provided, names should be a string or a length-1 sequence. Default is
False, in which case each array will be added as a separate field.
Returns
-------
new_array : new instance of `input_array`
A copy of the `input_array` with the desired fields added. | f15966:m13 |
def _isstring(dtype): | return dtype.type == numpy.unicode_ or dtype.type == numpy.string_<EOL> | Given a numpy dtype, determines whether it is a string. Returns True
if the dtype is string or unicode. | f15966:m14 |
def aliases_from_fields(fields): | return dict(c for c in fields if isinstance(c, tuple))<EOL> | Given a dictionary of fields, will return a dictionary mapping the
aliases to the names. | f15966:m15 |
def fields_from_names(fields, names=None): | if names is None:<EOL><INDENT>return fields<EOL><DEDENT>if isinstance(names, string_types):<EOL><INDENT>names = [names]<EOL><DEDENT>aliases_to_names = aliases_from_fields(fields)<EOL>names_to_aliases = dict(zip(aliases_to_names.values(),<EOL>aliases_to_names.keys()))<EOL>outfields = {}<EOL>for name in names:<EOL><INDENT>try:<EOL><INDENT>outfields[name] = fields[name]<EOL><DEDENT>except KeyError:<EOL><INDENT>if name in aliases_to_names:<EOL><INDENT>key = (name, aliases_to_names[name])<EOL><DEDENT>elif name in names_to_aliases:<EOL><INDENT>key = (names_to_aliases[name], name)<EOL><DEDENT>else:<EOL><INDENT>raise KeyError('<STR_LIT>' % name)<EOL><DEDENT>outfields[key] = fields[key]<EOL><DEDENT><DEDENT>return outfields<EOL> | Given a dictionary of fields and a list of names, will return a
dictionary consisting of the fields specified by names. Names can be
either the names of fields, or their aliases. | f15966:m16 |
def __new__(cls, shape, name=None, zero=True, **kwargs): | obj = super(FieldArray, cls).__new__(cls, shape, **kwargs).view(<EOL>type=cls)<EOL>obj.name = name<EOL>obj.__persistent_attributes__ = [a<EOL>for a in cls.__persistent_attributes__]<EOL>obj._functionlib = {f: func for f,func in cls._functionlib.items()}<EOL>obj._virtualfields = [f for f in cls._virtualfields]<EOL>if zero:<EOL><INDENT>default = default_empty(<NUM_LIT:1>, dtype=obj.dtype)<EOL>obj[:] = default<EOL><DEDENT>return obj<EOL> | Initializes a new empty array. | f15966:c0:m0 |
def __array_finalize__(self, obj): | if obj is None:<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>obj.__copy_attributes__(self)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>if self.dtype.names is not None andany(isinstance(name, unicode) for name in obj.dtype.names):<EOL><INDENT>self.dtype.names = map(str, self.dtype.names)<EOL><DEDENT> | Default values are set here.
See <https://docs.scipy.org/doc/numpy/user/basics.subclassing.html> for
details. | f15966:c0:m1 |
def __copy_attributes__(self, other, default=None): | [setattr(other, attr, copy.deepcopy(getattr(self, attr, default)))for attr in self.__persistent_attributes__]<EOL> | Copies the values of all of the attributes listed in
`self.__persistent_attributes__` to other. | f15966:c0:m2 |
def __getattribute__(self, attr): | <EOL>try:<EOL><INDENT>return numpy.ndarray.__getattribute__(self, attr)<EOL><DEDENT>except AttributeError as e:<EOL><INDENT>if attr in self.fields:<EOL><INDENT>return self.__getitem__(attr)<EOL><DEDENT>raise AttributeError(e)<EOL><DEDENT> | Allows fields to be accessed as attributes. | f15966:c0:m3 |
def __setitem__(self, item, values): | if type(item) is int and type(values) is numpy.ndarray:<EOL><INDENT>values = tuple(values)<EOL><DEDENT>try:<EOL><INDENT>return super(FieldArray, self).__setitem__(item, values)<EOL><DEDENT>except ValueError:<EOL><INDENT>fields = item.split('<STR_LIT:.>')<EOL>if len(fields) > <NUM_LIT:1>:<EOL><INDENT>for field in fields[:-<NUM_LIT:1>]:<EOL><INDENT>self = self[field]<EOL><DEDENT>item = fields[-<NUM_LIT:1>]<EOL><DEDENT>return super(FieldArray, self).__setitem__(item, values)<EOL><DEDENT> | Wrap's recarray's setitem to allow attribute-like indexing when
setting values. | f15966:c0:m4 |
def __getbaseitem__(self, item): | <EOL>out = self.view(numpy.ndarray)[item]<EOL>if out.dtype.fields is None:<EOL><INDENT>return out<EOL><DEDENT>elif out.ndim == <NUM_LIT:0>:<EOL><INDENT>return out.view(numpy.recarray)<EOL><DEDENT>else:<EOL><INDENT>return out.view(type(self))<EOL><DEDENT> | Gets an item assuming item is either an index or a fieldname. | f15966:c0:m5 |
def __getsubitem__(self, item): | try:<EOL><INDENT>return self.__getbaseitem__(item)<EOL><DEDENT>except ValueError as err:<EOL><INDENT>subitems = item.split('<STR_LIT:.>')<EOL>if len(subitems) > <NUM_LIT:1>:<EOL><INDENT>return self.__getbaseitem__(subitems[<NUM_LIT:0>]<EOL>).__getsubitem__('<STR_LIT:.>'.join(subitems[<NUM_LIT:1>:]))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(err)<EOL><DEDENT><DEDENT> | Gets a subfield using `field.subfield` notation. | f15966:c0:m6 |
def __getitem__(self, item): | try:<EOL><INDENT>return self.__getsubitem__(item)<EOL><DEDENT>except ValueError:<EOL><INDENT>item_dict = dict(_numpy_function_lib.items())<EOL>item_dict.update(self._functionlib)<EOL>itemvars = get_vars_from_arg(item)<EOL>itemvars = get_fields_from_arg(item)<EOL>d = {attr: getattr(self, attr)<EOL>for attr in set(dir(self)).intersection(itemvars)}<EOL>item_dict.update(d)<EOL>item_dict.update({fn: self.__getbaseitem__(fn)for fn in set(self.fieldnames).intersection(itemvars)})<EOL>item_dict.update({alias: item_dict[name]<EOL>for alias,name in self.aliases.items()<EOL>if name in item_dict})<EOL>return eval(item, {"<STR_LIT>": None}, item_dict)<EOL><DEDENT> | Wraps recarray's `__getitem__` so that math functions on fields and
attributes can be retrieved. Any function in numpy's library may be
used. | f15966:c0:m7 |
def __contains__(self, field): | return field in self.fields<EOL> | Returns True if the given field name is in self's fields. | f15966:c0:m8 |
def sort(self, axis=-<NUM_LIT:1>, kind='<STR_LIT>', order=None): | try:<EOL><INDENT>numpy.recarray.sort(self, axis=axis, kind=kind, order=order)<EOL><DEDENT>except ValueError:<EOL><INDENT>if isinstance(order, list):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self[:] = self[numpy.argsort(self[order])]<EOL><DEDENT> | Sort an array, in-place.
This function extends the standard numpy record array in-place sort
to allow the basic use of Field array virtual fields. Only a single
field is currently supported when referencing a virtual field.
Parameters
----------
axis : int, optional
Axis along which to sort. Default is -1, which means sort along the
last axis.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm. Default is 'quicksort'.
order : list, optional
When `a` is an array with fields defined, this argument specifies
which fields to compare first, second, etc. Not all fields need be
specified. | f15966:c0:m9 |
def addattr(self, attrname, value=None, persistent=True): | setattr(self, attrname, value)<EOL>if persistent and attrname not in self.__persistent_attributes__:<EOL><INDENT>self.__persistent_attributes__.append(attrname)<EOL><DEDENT> | Adds an attribute to self. If persistent is True, the attribute will
be made a persistent attribute. Persistent attributes are copied
whenever a view or copy of this array is created. Otherwise, new views
or copies of this will not have the attribute. | f15966:c0:m10 |
def add_methods(self, names, methods): | if isinstance(names, string_types):<EOL><INDENT>names = [names]<EOL>methods = [methods]<EOL><DEDENT>for name,method in zip(names, methods):<EOL><INDENT>setattr(self, name, types.MethodType(method, self))<EOL><DEDENT> | Adds the given method(s) as instance method(s) of self. The
method(s) must take `self` as a first argument. | f15966:c0:m11 |
def add_properties(self, names, methods): | cls = type(self)<EOL>cls = type(cls.__name__, (cls,), dict(cls.__dict__))<EOL>if isinstance(names, string_types):<EOL><INDENT>names = [names]<EOL>methods = [methods]<EOL><DEDENT>for name,method in zip(names, methods):<EOL><INDENT>setattr(cls, name, property(method))<EOL><DEDENT>return self.view(type=cls)<EOL> | Returns a view of self with the given methods added as properties.
From: <http://stackoverflow.com/a/2954373/1366472>. | f15966:c0:m12 |
def add_virtualfields(self, names, methods): | if isinstance(names, string_types):<EOL><INDENT>names = [names]<EOL>methods = [methods]<EOL><DEDENT>out = self.add_properties(names, methods)<EOL>if out._virtualfields is None:<EOL><INDENT>out._virtualfields = []<EOL><DEDENT>out._virtualfields.extend(names)<EOL>return out<EOL> | Returns a view of this array with the given methods added as virtual
fields. Specifically, the given methods are added using add_properties
and their names are added to the list of virtual fields. Virtual fields
are properties that are assumed to operate on one or more of self's
fields, thus returning an array of values. | f15966:c0:m13 |
def add_functions(self, names, functions): | if isinstance(names, string_types):<EOL><INDENT>names = [names]<EOL>functions = [functions]<EOL><DEDENT>if len(functions) != len(names):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>self._functionlib.update(dict(zip(names, functions)))<EOL> | Adds the given functions to the function library.
Functions are added to this instance of the array; all copies of
and slices of this array will also have the new functions included.
Parameters
----------
names : (list of) string(s)
Name or list of names of the functions.
functions : (list of) function(s)
The function(s) to call. | f15966:c0:m14 |
def del_functions(self, names): | if isinstance(names, string_types):<EOL><INDENT>names = [names]<EOL><DEDENT>for name in names:<EOL><INDENT>self._functionlib.pop(name)<EOL><DEDENT> | Removes the specified function names from the function library.
Functions are removed from this instance of the array; all copies
and slices of this array will also have the functions removed.
Parameters
----------
names : (list of) string(s)
Name or list of names of the functions to remove. | f15966:c0:m15 |
@classmethod<EOL><INDENT>def from_arrays(cls, arrays, name=None, **kwargs):<DEDENT> | obj = numpy.rec.fromarrays(arrays, **kwargs).view(type=cls)<EOL>obj.name = name<EOL>return obj<EOL> | Creates a new instance of self from the given (list of) array(s).
This is done by calling numpy.rec.fromarrays on the given arrays with
the given kwargs. The type of the returned array is cast to this
class, and the name (if provided) is set.
Parameters
----------
arrays : (list of) numpy array(s)
A list of the arrays to create the FieldArray from.
name : {None|str}
What the output array should be named.
For other keyword parameters, see the numpy.rec.fromarrays help.
Returns
-------
array : instance of this class
An array that is an instance of this class in which the field
data is from the given array(s). | f15966:c0:m16 |
@classmethod<EOL><INDENT>def from_records(cls, records, name=None, **kwargs):<DEDENT> | obj = numpy.rec.fromrecords(records, **kwargs).view(<EOL>type=cls)<EOL>obj.name = name<EOL>return obj<EOL> | Creates a new instance of self from the given (list of) record(s).
A "record" is a tuple in which each element is the value of one field
in the resulting record array. This is done by calling
`numpy.rec.fromrecords` on the given records with the given kwargs.
The type of the returned array is cast to this class, and the name
(if provided) is set.
Parameters
----------
records : (list of) tuple(s)
A list of the tuples to create the FieldArray from.
name : {None|str}
What the output array should be named.
Other Parameters
----------------
For other keyword parameters, see the `numpy.rec.fromrecords` help.
Returns
-------
array : instance of this class
An array that is an instance of this class in which the field
data is from the given record(s). | f15966:c0:m17 |
@classmethod<EOL><INDENT>def from_kwargs(cls, **kwargs):<DEDENT> | arrays = []<EOL>names = []<EOL>for p,vals in kwargs.items():<EOL><INDENT>if not isinstance(vals, numpy.ndarray):<EOL><INDENT>if not isinstance(vals, list):<EOL><INDENT>vals = [vals]<EOL><DEDENT>vals = numpy.array(vals)<EOL><DEDENT>arrays.append(vals)<EOL>names.append(p)<EOL><DEDENT>return cls.from_arrays(arrays, names=names)<EOL> | Creates a new instance of self from the given keyword arguments.
Each argument will correspond to a field in the returned array, with
the name of the field given by the keyword, and the value(s) whatever
the keyword was set to. Each keyword may be set to a single value or
a list of values. The number of values that each argument is set to
must be the same; this will be the size of the returned array.
Examples
--------
Create an array with fields 'mass1' and 'mass2':
>>> a = FieldArray.from_kwargs(mass1=[1.1, 3.], mass2=[2., 3.])
>>> a.fieldnames
('mass1', 'mass2')
>>> a.mass1, a.mass2
(array([ 1.1, 3. ]), array([ 2., 3.]))
Create an array with only a single element in it:
>>> a = FieldArray.from_kwargs(mass1=1.1, mass2=2.)
>>> a.mass1, a.mass2
(array([ 1.1]), array([ 2.])) | f15966:c0:m18 |
@classmethod<EOL><INDENT>def from_ligolw_table(cls, table, columns=None, cast_to_dtypes=None):<DEDENT> | name = table.tableName.split('<STR_LIT::>')[<NUM_LIT:0>]<EOL>if columns is None:<EOL><INDENT>columns = table.validcolumns<EOL><DEDENT>else:<EOL><INDENT>new_columns = {}<EOL>for col in columns:<EOL><INDENT>new_columns[col] = table.validcolumns[col]<EOL><DEDENT>columns = new_columns<EOL><DEDENT>if cast_to_dtypes is not None:<EOL><INDENT>dtype = [cast_to_dtypes[col] for col in columns]<EOL><DEDENT>else:<EOL><INDENT>dtype = columns.items()<EOL><DEDENT>if _default_types_status['<STR_LIT>']:<EOL><INDENT>input_array =[tuple(getattr(row, col) if dt != '<STR_LIT>'<EOL>else int(getattr(row, col))<EOL>for col,dt in columns.items())<EOL>for row in table]<EOL><DEDENT>else:<EOL><INDENT>input_array =[tuple(getattr(row, col) for col in columns) for row in table]<EOL><DEDENT>return cls.from_records(input_array, dtype=dtype,<EOL>name=name)<EOL> | Converts the given ligolw table into an FieldArray. The `tableName`
attribute is copied to the array's `name`.
Parameters
----------
table : LIGOLw table instance
The table to convert.
columns : {None|list}
Optionally specify a list of columns to retrieve. All of the
columns must be in the table's validcolumns attribute. If None
provided, all the columns in the table will be converted.
dtype : {None | dict}
Override the columns' dtypes using the given dictionary. The
dictionary should be keyed by the column names, with the values
a tuple that can be understood by numpy.dtype. For example, to
cast a ligolw column called "foo" to a field called "bar" with
type float, cast_to_dtypes would be: ``{"foo": ("bar", float)}``.
Returns
-------
array : FieldArray
The input table as an FieldArray. | f15966:c0:m19 |
def to_array(self, fields=None, axis=<NUM_LIT:0>): | if fields is None:<EOL><INDENT>fields = self.fieldnames<EOL><DEDENT>if isinstance(fields, string_types):<EOL><INDENT>fields = [fields]<EOL><DEDENT>return numpy.stack([self[f] for f in fields], axis=axis)<EOL> | Returns an `numpy.ndarray` of self in which the fields are included
as an extra dimension.
Parameters
----------
fields : {None, (list of) strings}
The fields to get. All of the fields must have the same datatype.
If None, will try to return all of the fields.
axis : {0, int}
Which dimension to put the fields in in the returned array. For
example, if `self` has shape `(l,m,n)` and `k` fields, the
returned array will have shape `(k,l,m,n)` if `axis=0`, `(l,k,m,n)`
if `axis=1`, etc. Setting `axis=-1` will put the fields in the
last dimension. Default is 0.
Returns
-------
numpy.ndarray
The desired fields as a numpy array. | f15966:c0:m20 |
@property<EOL><INDENT>def fieldnames(self):<DEDENT> | return self.dtype.names<EOL> | Returns a tuple listing the field names in self. Equivalent to
`array.dtype.names`, where `array` is self. | f15966:c0:m21 |
@property<EOL><INDENT>def virtualfields(self):<DEDENT> | if self._virtualfields is None:<EOL><INDENT>vfs = tuple()<EOL><DEDENT>else:<EOL><INDENT>vfs = tuple(self._virtualfields)<EOL><DEDENT>return vfs<EOL> | Returns a tuple listing the names of virtual fields in self. | f15966:c0:m22 |
@property<EOL><INDENT>def functionlib(self):<DEDENT> | return self._functionlib<EOL> | Returns the library of functions that are available when calling
items. | f15966:c0:m23 |
@property<EOL><INDENT>def fields(self):<DEDENT> | return tuple(list(self.fieldnames) + list(self.virtualfields))<EOL> | Returns a tuple listing the names of fields and virtual fields in
self. | f15966:c0:m24 |
@property<EOL><INDENT>def aliases(self):<DEDENT> | return dict(c[<NUM_LIT:0>] for c in self.dtype.descr if isinstance(c[<NUM_LIT:0>], tuple))<EOL> | Returns a dictionary of the aliases, or "titles", of the field names
in self. An alias can be specified by passing a tuple in the name
part of the dtype. For example, if an array is created with
``dtype=[(('foo', 'bar'), float)]``, the array will have a field
called `bar` that has alias `foo` that can be accessed using
either `arr['foo']` or `arr['bar']`. Note that the first string
in the dtype is the alias, the second the name. This function returns
a dictionary in which the aliases are the keys and the names are the
values. Only fields that have aliases are returned. | f15966:c0:m25 |
def add_fields(self, arrays, names=None, assubarray=False): | newself = add_fields(self, arrays, names=names, assubarray=assubarray)<EOL>self.__copy_attributes__(newself)<EOL>return newself<EOL> | Adds the given arrays as new fields to self. Returns a new instance
with the new fields added. Note: this array does not change; the
returned array is a new copy.
Parameters
----------
arrays : (list of) numpy array(s)
The arrays to add. If adding multiple arrays, must be a list;
if adding a single array, can just be that array.
names : (list of) strings
Optional, the name(s) of the new fields in the output array. If
adding multiple fields, must be a list of strings with the same
length as the list of arrays. If None provided, names used will
be the same as the name of the datatype in the given arrays.
If the datatype has no name, the new field will be ``'fi'`` where
i is the index of the array in arrays.
assubarray : bool
Add the list of arrays as a single subarray field. If True, and
names provided, names should be a string or a length-1 sequence.
Default is False, in which case each array will be added as a
separate field.
Returns
-------
new_array : new instance of this array
A copy of this array with the desired fields added. | f15966:c0:m26 |
def parse_boolargs(self, args): | if not isinstance(args, list):<EOL><INDENT>args = [args]<EOL><DEDENT>return_vals = []<EOL>bool_args = []<EOL>for arg in args:<EOL><INDENT>if not isinstance(arg, tuple):<EOL><INDENT>return_val = arg<EOL>bool_arg = None<EOL><DEDENT>elif len(arg) == <NUM_LIT:1>:<EOL><INDENT>return_val = arg[<NUM_LIT:0>]<EOL>bool_arg = None<EOL><DEDENT>elif len(arg) == <NUM_LIT:2>:<EOL><INDENT>return_val, bool_arg = arg<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return_vals.append(return_val)<EOL>bool_args.append(bool_arg)<EOL><DEDENT>outdtype = numpy.array(return_vals).dtype<EOL>out = numpy.zeros(self.size, dtype=outdtype)<EOL>mask = numpy.zeros(self.size, dtype=bool)<EOL>leftovers = numpy.ones(self.size, dtype=bool)<EOL>for ii,(boolarg,val) in enumerate(zip(bool_args, return_vals)):<EOL><INDENT>if boolarg is None or boolarg == '<STR_LIT>' or boolarg.lower() == '<STR_LIT>':<EOL><INDENT>if ii+<NUM_LIT:1> != len(bool_args):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>mask = leftovers<EOL><DEDENT>else:<EOL><INDENT>mask = leftovers & self[boolarg]<EOL><DEDENT>out[mask] = val<EOL>leftovers &= ~mask<EOL><DEDENT>return out, numpy.where(leftovers)[<NUM_LIT:0>]<EOL> | Returns an array populated by given values, with the indices of
those values dependent on given boolen tests on self.
The given `args` should be a list of tuples, with the first element the
return value and the second argument a string that evaluates to either
True or False for each element in self.
Each boolean argument is evaluated on elements for which every prior
boolean argument was False. For example, if array `foo` has a field
`bar`, and `args = [(1, 'bar < 10'), (2, 'bar < 20'), (3, 'bar < 30')]`,
then the returned array will have `1`s at the indices for
which `foo.bar < 10`, `2`s where `foo.bar < 20 and not foo.bar < 10`,
and `3`s where `foo.bar < 30 and not (foo.bar < 10 or foo.bar < 20)`.
The last argument in the list may have "else", an empty string, None,
or simply list a return value. In any of these cases, any element not
yet populated will be assigned the last return value.
Parameters
----------
args : {(list of) tuples, value}
One or more return values and boolean argument determining where
they should go.
Returns
-------
return_values : array
An array with length equal to self, with values populated with the
return values.
leftover_indices : array
An array of indices that evaluated to False for all arguments.
These indices will not have been popluated with any value,
defaulting to whatever numpy uses for a zero for the return
values' dtype. If there are no leftovers, an empty array is
returned.
Examples
--------
Given the following array:
>>> arr = FieldArray(5, dtype=[('mtotal', float)])
>>> arr['mtotal'] = numpy.array([3., 5., 2., 1., 4.])
Return `"TaylorF2"` for all elements with `mtotal < 4` (note that the
elements 1 and 4 are leftover):
>>> arr.parse_boolargs(('TaylorF2', 'mtotal<4'))
(array(['TaylorF2', '', 'TaylorF2', 'TaylorF2', ''],
dtype='|S8'),
array([1, 4]))
Return `"TaylorF2"` for all elements with `mtotal < 4`,
`"SEOBNR_ROM_DoubleSpin"` otherwise:
>>> arr.parse_boolargs([('TaylorF2', 'mtotal<4'), ('SEOBNRv2_ROM_DoubleSpin', 'else')])
(array(['TaylorF2', 'SEOBNRv2_ROM_DoubleSpin', 'TaylorF2', 'TaylorF2',
'SEOBNRv2_ROM_DoubleSpin'],
dtype='|S23'),
array([], dtype=int64))
The following will also return the same:
>>> arr.parse_boolargs([('TaylorF2', 'mtotal<4'), ('SEOBNRv2_ROM_DoubleSpin',)])
>>> arr.parse_boolargs([('TaylorF2', 'mtotal<4'), ('SEOBNRv2_ROM_DoubleSpin', '')])
>>> arr.parse_boolargs([('TaylorF2', 'mtotal<4'), 'SEOBNRv2_ROM_DoubleSpin'])
Return `"TaylorF2"` for all elements with `mtotal < 3`, `"IMRPhenomD"`
for all elements with `3 <= mtotal < 4`, `"SEOBNRv2_ROM_DoubleSpin"`
otherwise:
>>> arr.parse_boolargs([('TaylorF2', 'mtotal<3'), ('IMRPhenomD', 'mtotal<4'), 'SEOBNRv2_ROM_DoubleSpin'])
(array(['IMRPhenomD', 'SEOBNRv2_ROM_DoubleSpin', 'TaylorF2', 'TaylorF2',
'SEOBNRv2_ROM_DoubleSpin'],
dtype='|S23'),
array([], dtype=int64))
Just return `"TaylorF2"` for all elements:
>>> arr.parse_boolargs('TaylorF2')
(array(['TaylorF2', 'TaylorF2', 'TaylorF2', 'TaylorF2', 'TaylorF2'],
dtype='|S8'),
array([], dtype=int64)) | f15966:c0:m27 |
def append(self, other): | try:<EOL><INDENT>return numpy.append(self, other).view(type=self.__class__)<EOL><DEDENT>except TypeError:<EOL><INDENT>str_fields = [name for name in self.fieldnames<EOL>if _isstring(self.dtype[name])]<EOL>new_strlens = dict(<EOL>[[name,<EOL>max(self.dtype[name].itemsize, other.dtype[name].itemsize)]<EOL>for name in str_fields]<EOL>)<EOL>new_dt = []<EOL>for dt in self.dtype.descr:<EOL><INDENT>name = dt[<NUM_LIT:0>]<EOL>if name in new_strlens:<EOL><INDENT>dt = (name, self.dtype[name].type, new_strlens[name])<EOL><DEDENT>new_dt.append(dt)<EOL><DEDENT>new_dt = numpy.dtype(new_dt)<EOL>return numpy.append(<EOL>self.astype(new_dt),<EOL>other.astype(new_dt)<EOL>).view(type=self.__class__)<EOL><DEDENT> | Appends another array to this array.
The returned array will have all of the class methods and virutal
fields of this array, including any that were added using `add_method`
or `add_virtualfield`. If this array and other array have one or more
string fields, the dtype for those fields are updated to a string
length that can encompass the longest string in both arrays.
.. note::
Increasing the length of strings only works for fields, not
sub-fields.
Parameters
----------
other : array
The array to append values from. It must have the same fields and
dtype as this array, modulo the length of strings. If the other
array does not have the same dtype, a TypeError is raised.
Returns
-------
array
An array with others values appended to this array's values. The
returned array is an instance of the same class as this array,
including all methods and virtual fields. | f15966:c0:m28 |
@classmethod<EOL><INDENT>def parse_parameters(cls, parameters, possible_fields):<DEDENT> | if isinstance(possible_fields, string_types):<EOL><INDENT>possible_fields = [possible_fields]<EOL><DEDENT>possible_fields = map(str, possible_fields)<EOL>arr = cls(<NUM_LIT:1>, dtype=zip(possible_fields,<EOL>len(possible_fields)*[float]))<EOL>return list(get_needed_fieldnames(arr, parameters))<EOL> | Parses a list of parameters to get the list of fields needed in
order to evaluate those parameters.
Parameters
----------
parameters : (list of) string(s)
The list of desired parameters. These can be (functions of) fields
or virtual fields.
possible_fields : (list of) string(s)
The list of possible fields.
Returns
-------
list :
The list of names of the fields that are needed in order to
evaluate the given parameters. | f15966:c0:m29 |
@classmethod<EOL><INDENT>def default_fields(cls, include_virtual=True, **kwargs):<DEDENT> | output = cls._staticfields.copy()<EOL>if include_virtual:<EOL><INDENT>output.update({name: VIRTUALFIELD_DTYPE<EOL>for name in cls._virtualfields})<EOL><DEDENT>return output<EOL> | The default fields and their dtypes. By default, this returns
whatever the class's ``_staticfields`` and ``_virtualfields`` is set
to as a dictionary of fieldname, dtype (the dtype of virtualfields is
given by VIRTUALFIELD_DTYPE). This function should be overridden by
subclasses to add dynamic fields; i.e., fields that require some input
parameters at initialization. Keyword arguments can be passed to this
to set such dynamic fields. | f15966:c1:m0 |
def __new__(cls, shape, name=None, additional_fields=None,<EOL>field_kwargs=None, **kwargs): | if field_kwargs is None:<EOL><INDENT>field_kwargs = {}<EOL><DEDENT>if '<STR_LIT>' in kwargs and '<STR_LIT>' in kwargs:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>default_fields = cls.default_fields(include_virtual=False,<EOL>**field_kwargs)<EOL>if '<STR_LIT>' in kwargs:<EOL><INDENT>names = kwargs.pop('<STR_LIT>')<EOL>if isinstance(names, string_types):<EOL><INDENT>names = [names]<EOL><DEDENT>arr = cls(<NUM_LIT:1>, field_kwargs=field_kwargs)<EOL>sortdict = dict([[nm, ii] for ii,nm in enumerate(names)])<EOL>names = list(get_needed_fieldnames(arr, names))<EOL>names.sort(key=lambda x: sortdict[x] if x in sortdict<EOL>else len(names))<EOL>kwargs['<STR_LIT>'] = [(fld, default_fields[fld]) for fld in names]<EOL><DEDENT>if '<STR_LIT>' not in kwargs:<EOL><INDENT>kwargs['<STR_LIT>'] = default_fields.items()<EOL><DEDENT>if additional_fields is not None:<EOL><INDENT>if not isinstance(additional_fields, list):<EOL><INDENT>additional_fields = [additional_fields]<EOL><DEDENT>if not isinstance(kwargs['<STR_LIT>'], list):<EOL><INDENT>kwargs['<STR_LIT>'] = [kwargs['<STR_LIT>']]<EOL><DEDENT>kwargs['<STR_LIT>'] += additional_fields<EOL><DEDENT>return super(_FieldArrayWithDefaults, cls).__new__(cls, shape,<EOL>name=name, **kwargs)<EOL> | The ``additional_fields`` should be specified in the same way as
``dtype`` is normally given to FieldArray. The ``field_kwargs`` are
passed to the class's default_fields method as keyword arguments. | f15966:c1:m1 |
def add_default_fields(self, names, **kwargs): | if isinstance(names, string_types):<EOL><INDENT>names = [names]<EOL><DEDENT>default_fields = self.default_fields(include_virtual=False, **kwargs)<EOL>arr = self.__class__(<NUM_LIT:1>, field_kwargs=kwargs)<EOL>sortdict = dict([[nm, ii] for ii,nm in enumerate(names)])<EOL>names = list(get_needed_fieldnames(arr, names))<EOL>names.sort(key=lambda x: sortdict[x] if x in sortdict<EOL>else len(names))<EOL>fields = [(name, default_fields[name]) for name in names]<EOL>arrays = []<EOL>names = []<EOL>for name,dt in fields:<EOL><INDENT>arrays.append(default_empty(self.size, dtype=[(name, dt)]))<EOL>names.append(name)<EOL><DEDENT>return self.add_fields(arrays, names)<EOL> | Adds one or more empty default fields to self.
Parameters
----------
names : (list of) string(s)
The names of the fields to add. Must be a field in self's default
fields.
Other keyword args are any arguments passed to self's default fields.
Returns
-------
new array : instance of this array
A copy of this array with the field added. | f15966:c1:m2 |
@classmethod<EOL><INDENT>def parse_parameters(cls, parameters, possible_fields=None):<DEDENT> | if possible_fields is not None:<EOL><INDENT>possible_fields = dict([[f, dt]<EOL>for f,dt in possible_fields.items()])<EOL>class ModifiedArray(cls):<EOL><INDENT>_staticfields = possible_fields<EOL><DEDENT>cls = ModifiedArray<EOL><DEDENT>return cls(<NUM_LIT:1>, names=parameters).fieldnames<EOL> | Parses a list of parameters to get the list of fields needed in
order to evaluate those parameters.
Parameters
----------
parameters : (list of) strings
The list of desired parameters. These can be (functions of) fields
or virtual fields.
possible_fields : {None, dict}
Specify the list of possible fields. Must be a dictionary given
the names, and dtype of each possible field. If None, will use this
class's `_staticfields`.
Returns
-------
list :
The list of names of the fields that are needed in order to
evaluate the given parameters. | f15966:c1:m3 |
@property<EOL><INDENT>def primary_mass(self):<DEDENT> | return conversions.primary_mass(self.mass1, self.mass2)<EOL> | Returns the larger of self.mass1 and self.mass2. | f15966:c2:m0 |
@property<EOL><INDENT>def secondary_mass(self):<DEDENT> | return conversions.secondary_mass(self.mass1, self.mass)<EOL> | Returns the smaller of self.mass1 and self.mass2. | f15966:c2:m1 |
@property<EOL><INDENT>def mtotal(self):<DEDENT> | return conversions.mtotal_from_mass1_mass2(self.mass1, self.mass2)<EOL> | Returns the total mass. | f15966:c2:m2 |
@property<EOL><INDENT>def q(self):<DEDENT> | return conversions.q_from_mass1_mass2(self.mass1, self.mass2)<EOL> | Returns the mass ratio m1/m2, where m1 >= m2. | f15966:c2:m3 |
@property<EOL><INDENT>def eta(self):<DEDENT> | return conversions.eta_from_mass1_mass2(self.mass1, self.mass2)<EOL> | Returns the symmetric mass ratio. | f15966:c2:m4 |
@property<EOL><INDENT>def mchirp(self):<DEDENT> | return conversions.mchirp_from_mass1_mass2(self.mass1, self.mass2)<EOL> | Returns the chirp mass. | f15966:c2:m5 |
@property<EOL><INDENT>def chi_eff(self):<DEDENT> | return conversions.chi_eff(self.mass1, self.mass2, self.spin1z,<EOL>self.spin2z)<EOL> | Returns the effective spin. | f15966:c2:m6 |
@property<EOL><INDENT>def spin_px(self):<DEDENT> | return conversions.primary_spin(self.mass1, self.mass2, self.spin1x,<EOL>self.spin2x)<EOL> | Returns the x-component of the spin of the primary mass. | f15966:c2:m7 |
@property<EOL><INDENT>def spin_py(self):<DEDENT> | return conversions.primary_spin(self.mass1, self.mass2, self.spin1y,<EOL>self.spin2y)<EOL> | Returns the y-component of the spin of the primary mass. | f15966:c2:m8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.