id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
228,000
gwastro/pycbc
pycbc/population/rates_functions.py
_optm
def _optm(x, alpha, mu, sigma): '''Return probability density of skew-lognormal See scipy.optimize.curve_fit ''' return ss.skewnorm.pdf(x, alpha, mu, sigma)
python
def _optm(x, alpha, mu, sigma): '''Return probability density of skew-lognormal See scipy.optimize.curve_fit ''' return ss.skewnorm.pdf(x, alpha, mu, sigma)
[ "def", "_optm", "(", "x", ",", "alpha", ",", "mu", ",", "sigma", ")", ":", "return", "ss", ".", "skewnorm", ".", "pdf", "(", "x", ",", "alpha", ",", "mu", ",", "sigma", ")" ]
Return probability density of skew-lognormal See scipy.optimize.curve_fit
[ "Return", "probability", "density", "of", "skew", "-", "lognormal", "See", "scipy", ".", "optimize", ".", "curve_fit" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/population/rates_functions.py#L190-L194
228,001
gwastro/pycbc
pycbc/population/rates_functions.py
draw_imf_samples
def draw_imf_samples(**kwargs): ''' Draw samples for power-law model Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- array The first mass array The second mass ''' alpha_salpeter = kwargs.get('alpha', -2.35) nsamples = kwargs.get('nsamples', 1) min_mass = kwargs.get('min_mass', 5.) max_mass = kwargs.get('max_mass', 95.) max_mtotal = min_mass + max_mass a = (max_mass/min_mass)**(alpha_salpeter + 1.0) - 1.0 beta = 1.0 / (alpha_salpeter + 1.0) k = nsamples * int(1.5 + log(1 + 100./nsamples)) aa = min_mass * (1.0 + a * np.random.random(k))**beta bb = np.random.uniform(min_mass, aa, k) idx = np.where(aa + bb < max_mtotal) m1, m2 = (np.maximum(aa, bb))[idx], (np.minimum(aa, bb))[idx] return np.resize(m1, nsamples), np.resize(m2, nsamples)
python
def draw_imf_samples(**kwargs): ''' Draw samples for power-law model Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- array The first mass array The second mass ''' alpha_salpeter = kwargs.get('alpha', -2.35) nsamples = kwargs.get('nsamples', 1) min_mass = kwargs.get('min_mass', 5.) max_mass = kwargs.get('max_mass', 95.) max_mtotal = min_mass + max_mass a = (max_mass/min_mass)**(alpha_salpeter + 1.0) - 1.0 beta = 1.0 / (alpha_salpeter + 1.0) k = nsamples * int(1.5 + log(1 + 100./nsamples)) aa = min_mass * (1.0 + a * np.random.random(k))**beta bb = np.random.uniform(min_mass, aa, k) idx = np.where(aa + bb < max_mtotal) m1, m2 = (np.maximum(aa, bb))[idx], (np.minimum(aa, bb))[idx] return np.resize(m1, nsamples), np.resize(m2, nsamples)
[ "def", "draw_imf_samples", "(", "*", "*", "kwargs", ")", ":", "alpha_salpeter", "=", "kwargs", ".", "get", "(", "'alpha'", ",", "-", "2.35", ")", "nsamples", "=", "kwargs", ".", "get", "(", "'nsamples'", ",", "1", ")", "min_mass", "=", "kwargs", ".", ...
Draw samples for power-law model Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- array The first mass array The second mass
[ "Draw", "samples", "for", "power", "-", "law", "model" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/population/rates_functions.py#L379-L411
228,002
gwastro/pycbc
pycbc/population/rates_functions.py
draw_lnm_samples
def draw_lnm_samples(**kwargs): ''' Draw samples for uniform-in-log model Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- array The first mass array The second mass ''' #PDF doesnt match with sampler nsamples = kwargs.get('nsamples', 1) min_mass = kwargs.get('min_mass', 5.) max_mass = kwargs.get('max_mass', 95.) max_mtotal = min_mass + max_mass lnmmin = log(min_mass) lnmmax = log(max_mass) k = nsamples * int(1.5 + log(1 + 100./nsamples)) aa = np.exp(np.random.uniform(lnmmin, lnmmax, k)) bb = np.exp(np.random.uniform(lnmmin, lnmmax, k)) idx = np.where(aa + bb < max_mtotal) m1, m2 = (np.maximum(aa, bb))[idx], (np.minimum(aa, bb))[idx] return np.resize(m1, nsamples), np.resize(m2, nsamples)
python
def draw_lnm_samples(**kwargs): ''' Draw samples for uniform-in-log model Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- array The first mass array The second mass ''' #PDF doesnt match with sampler nsamples = kwargs.get('nsamples', 1) min_mass = kwargs.get('min_mass', 5.) max_mass = kwargs.get('max_mass', 95.) max_mtotal = min_mass + max_mass lnmmin = log(min_mass) lnmmax = log(max_mass) k = nsamples * int(1.5 + log(1 + 100./nsamples)) aa = np.exp(np.random.uniform(lnmmin, lnmmax, k)) bb = np.exp(np.random.uniform(lnmmin, lnmmax, k)) idx = np.where(aa + bb < max_mtotal) m1, m2 = (np.maximum(aa, bb))[idx], (np.minimum(aa, bb))[idx] return np.resize(m1, nsamples), np.resize(m2, nsamples)
[ "def", "draw_lnm_samples", "(", "*", "*", "kwargs", ")", ":", "#PDF doesnt match with sampler", "nsamples", "=", "kwargs", ".", "get", "(", "'nsamples'", ",", "1", ")", "min_mass", "=", "kwargs", ".", "get", "(", "'min_mass'", ",", "5.", ")", "max_mass", "...
Draw samples for uniform-in-log model Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- array The first mass array The second mass
[ "Draw", "samples", "for", "uniform", "-", "in", "-", "log", "model" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/population/rates_functions.py#L413-L444
228,003
gwastro/pycbc
pycbc/population/rates_functions.py
draw_flat_samples
def draw_flat_samples(**kwargs): ''' Draw samples for uniform in mass Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- array The first mass array The second mass ''' #PDF doesnt match with sampler nsamples = kwargs.get('nsamples', 1) min_mass = kwargs.get('min_mass', 1.) max_mass = kwargs.get('max_mass', 2.) m1 = np.random.uniform(min_mass, max_mass, nsamples) m2 = np.random.uniform(min_mass, max_mass, nsamples) return np.maximum(m1, m2), np.minimum(m1, m2)
python
def draw_flat_samples(**kwargs): ''' Draw samples for uniform in mass Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- array The first mass array The second mass ''' #PDF doesnt match with sampler nsamples = kwargs.get('nsamples', 1) min_mass = kwargs.get('min_mass', 1.) max_mass = kwargs.get('max_mass', 2.) m1 = np.random.uniform(min_mass, max_mass, nsamples) m2 = np.random.uniform(min_mass, max_mass, nsamples) return np.maximum(m1, m2), np.minimum(m1, m2)
[ "def", "draw_flat_samples", "(", "*", "*", "kwargs", ")", ":", "#PDF doesnt match with sampler", "nsamples", "=", "kwargs", ".", "get", "(", "'nsamples'", ",", "1", ")", "min_mass", "=", "kwargs", ".", "get", "(", "'min_mass'", ",", "1.", ")", "max_mass", ...
Draw samples for uniform in mass Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- array The first mass array The second mass
[ "Draw", "samples", "for", "uniform", "in", "mass" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/population/rates_functions.py#L446-L470
228,004
gwastro/pycbc
pycbc/population/rates_functions.py
mchirp_sampler_lnm
def mchirp_sampler_lnm(**kwargs): ''' Draw chirp mass samples for uniform-in-log model Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- mchirp-astro: array The chirp mass samples for the population ''' m1, m2 = draw_lnm_samples(**kwargs) mchirp_astro = mchirp_from_mass1_mass2(m1, m2) return mchirp_astro
python
def mchirp_sampler_lnm(**kwargs): ''' Draw chirp mass samples for uniform-in-log model Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- mchirp-astro: array The chirp mass samples for the population ''' m1, m2 = draw_lnm_samples(**kwargs) mchirp_astro = mchirp_from_mass1_mass2(m1, m2) return mchirp_astro
[ "def", "mchirp_sampler_lnm", "(", "*", "*", "kwargs", ")", ":", "m1", ",", "m2", "=", "draw_lnm_samples", "(", "*", "*", "kwargs", ")", "mchirp_astro", "=", "mchirp_from_mass1_mass2", "(", "m1", ",", "m2", ")", "return", "mchirp_astro" ]
Draw chirp mass samples for uniform-in-log model Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- mchirp-astro: array The chirp mass samples for the population
[ "Draw", "chirp", "mass", "samples", "for", "uniform", "-", "in", "-", "log", "model" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/population/rates_functions.py#L473-L489
228,005
gwastro/pycbc
pycbc/population/rates_functions.py
mchirp_sampler_imf
def mchirp_sampler_imf(**kwargs): ''' Draw chirp mass samples for power-law model Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- mchirp-astro: array The chirp mass samples for the population ''' m1, m2 = draw_imf_samples(**kwargs) mchirp_astro = mchirp_from_mass1_mass2(m1, m2) return mchirp_astro
python
def mchirp_sampler_imf(**kwargs): ''' Draw chirp mass samples for power-law model Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- mchirp-astro: array The chirp mass samples for the population ''' m1, m2 = draw_imf_samples(**kwargs) mchirp_astro = mchirp_from_mass1_mass2(m1, m2) return mchirp_astro
[ "def", "mchirp_sampler_imf", "(", "*", "*", "kwargs", ")", ":", "m1", ",", "m2", "=", "draw_imf_samples", "(", "*", "*", "kwargs", ")", "mchirp_astro", "=", "mchirp_from_mass1_mass2", "(", "m1", ",", "m2", ")", "return", "mchirp_astro" ]
Draw chirp mass samples for power-law model Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- mchirp-astro: array The chirp mass samples for the population
[ "Draw", "chirp", "mass", "samples", "for", "power", "-", "law", "model" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/population/rates_functions.py#L491-L507
228,006
gwastro/pycbc
pycbc/population/rates_functions.py
mchirp_sampler_flat
def mchirp_sampler_flat(**kwargs): ''' Draw chirp mass samples for flat in mass model Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- mchirp-astro: array The chirp mass samples for the population ''' m1, m2 = draw_flat_samples(**kwargs) mchirp_astro = mchirp_from_mass1_mass2(m1, m2) return mchirp_astro
python
def mchirp_sampler_flat(**kwargs): ''' Draw chirp mass samples for flat in mass model Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- mchirp-astro: array The chirp mass samples for the population ''' m1, m2 = draw_flat_samples(**kwargs) mchirp_astro = mchirp_from_mass1_mass2(m1, m2) return mchirp_astro
[ "def", "mchirp_sampler_flat", "(", "*", "*", "kwargs", ")", ":", "m1", ",", "m2", "=", "draw_flat_samples", "(", "*", "*", "kwargs", ")", "mchirp_astro", "=", "mchirp_from_mass1_mass2", "(", "m1", ",", "m2", ")", "return", "mchirp_astro" ]
Draw chirp mass samples for flat in mass model Parameters ---------- **kwargs: string Keyword arguments as model parameters and number of samples Returns ------- mchirp-astro: array The chirp mass samples for the population
[ "Draw", "chirp", "mass", "samples", "for", "flat", "in", "mass", "model" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/population/rates_functions.py#L509-L525
228,007
gwastro/pycbc
pycbc/types/array.py
load_array
def load_array(path, group=None): """ Load an Array from a .hdf, .txt or .npy file. The default data types will be double precision floating point. Parameters ---------- path : string source file path. Must end with either .npy or .txt. group: string Additional name for internal storage use. Ex. hdf storage uses this as the key value. Raises ------ ValueError If path does not end in .npy or .txt. """ ext = _os.path.splitext(path)[1] if ext == '.npy': data = _numpy.load(path) elif ext == '.txt': data = _numpy.loadtxt(path) elif ext == '.hdf': key = 'data' if group is None else group return Array(h5py.File(path)[key]) else: raise ValueError('Path must end with .npy, .hdf, or .txt') if data.ndim == 1: return Array(data) elif data.ndim == 2: return Array(data[:,0] + 1j*data[:,1]) else: raise ValueError('File has %s dimensions, cannot convert to Array, \ must be 1 (real) or 2 (complex)' % data.ndim)
python
def load_array(path, group=None): ext = _os.path.splitext(path)[1] if ext == '.npy': data = _numpy.load(path) elif ext == '.txt': data = _numpy.loadtxt(path) elif ext == '.hdf': key = 'data' if group is None else group return Array(h5py.File(path)[key]) else: raise ValueError('Path must end with .npy, .hdf, or .txt') if data.ndim == 1: return Array(data) elif data.ndim == 2: return Array(data[:,0] + 1j*data[:,1]) else: raise ValueError('File has %s dimensions, cannot convert to Array, \ must be 1 (real) or 2 (complex)' % data.ndim)
[ "def", "load_array", "(", "path", ",", "group", "=", "None", ")", ":", "ext", "=", "_os", ".", "path", ".", "splitext", "(", "path", ")", "[", "1", "]", "if", "ext", "==", "'.npy'", ":", "data", "=", "_numpy", ".", "load", "(", "path", ")", "el...
Load an Array from a .hdf, .txt or .npy file. The default data types will be double precision floating point. Parameters ---------- path : string source file path. Must end with either .npy or .txt. group: string Additional name for internal storage use. Ex. hdf storage uses this as the key value. Raises ------ ValueError If path does not end in .npy or .txt.
[ "Load", "an", "Array", "from", "a", ".", "hdf", ".", "txt", "or", ".", "npy", "file", ".", "The", "default", "data", "types", "will", "be", "double", "precision", "floating", "point", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/types/array.py#L1074-L1110
228,008
gwastro/pycbc
pycbc/types/array.py
Array._return
def _return(self, ary): """Wrap the ary to return an Array type """ if isinstance(ary, Array): return ary return Array(ary, copy=False)
python
def _return(self, ary): if isinstance(ary, Array): return ary return Array(ary, copy=False)
[ "def", "_return", "(", "self", ",", "ary", ")", ":", "if", "isinstance", "(", "ary", ",", "Array", ")", ":", "return", "ary", "return", "Array", "(", "ary", ",", "copy", "=", "False", ")" ]
Wrap the ary to return an Array type
[ "Wrap", "the", "ary", "to", "return", "an", "Array", "type" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/types/array.py#L238-L242
228,009
gwastro/pycbc
pycbc/types/array.py
Array._icheckother
def _icheckother(fn, self, other): """ Checks the input to in-place operations """ self._typecheck(other) if type(other) in _ALLOWED_SCALARS: if self.kind == 'real' and type(other) == complex: raise TypeError('dtypes are incompatible') other = force_precision_to_match(other, self.precision) elif isinstance(other, type(self)) or type(other) is Array: if len(other) != len(self): raise ValueError('lengths do not match') if self.kind == 'real' and other.kind == 'complex': raise TypeError('dtypes are incompatible') if other.precision == self.precision: _convert_to_scheme(other) other = other._data else: raise TypeError('precisions do not match') else: return NotImplemented return fn(self, other)
python
def _icheckother(fn, self, other): self._typecheck(other) if type(other) in _ALLOWED_SCALARS: if self.kind == 'real' and type(other) == complex: raise TypeError('dtypes are incompatible') other = force_precision_to_match(other, self.precision) elif isinstance(other, type(self)) or type(other) is Array: if len(other) != len(self): raise ValueError('lengths do not match') if self.kind == 'real' and other.kind == 'complex': raise TypeError('dtypes are incompatible') if other.precision == self.precision: _convert_to_scheme(other) other = other._data else: raise TypeError('precisions do not match') else: return NotImplemented return fn(self, other)
[ "def", "_icheckother", "(", "fn", ",", "self", ",", "other", ")", ":", "self", ".", "_typecheck", "(", "other", ")", "if", "type", "(", "other", ")", "in", "_ALLOWED_SCALARS", ":", "if", "self", ".", "kind", "==", "'real'", "and", "type", "(", "other...
Checks the input to in-place operations
[ "Checks", "the", "input", "to", "in", "-", "place", "operations" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/types/array.py#L301-L321
228,010
gwastro/pycbc
pycbc/types/array.py
Array.almost_equal_elem
def almost_equal_elem(self,other,tol,relative=True): """ Compare whether two array types are almost equal, element by element. If the 'relative' parameter is 'True' (the default) then the 'tol' parameter (which must be positive) is interpreted as a relative tolerance, and the comparison returns 'True' only if abs(self[i]-other[i]) <= tol*abs(self[i]) for all elements of the array. If 'relative' is 'False', then 'tol' is an absolute tolerance, and the comparison is true only if abs(self[i]-other[i]) <= tol for all elements of the array. Other meta-data (type, dtype, and length) must be exactly equal. If either object's memory lives on the GPU it will be copied to the CPU for the comparison, which may be slow. But the original object itself will not have its memory relocated nor scheme changed. Parameters ---------- other Another Python object, that should be tested for almost-equality with 'self', element-by-element. tol A non-negative number, the tolerance, which is interpreted as either a relative tolerance (the default) or an absolute tolerance. relative A boolean, indicating whether 'tol' should be interpreted as a relative tolerance (if True, the default if this argument is omitted) or as an absolute tolerance (if tol is False). Returns ------- boolean 'True' if the data agree within the tolerance, as interpreted by the 'relative' keyword, and if the types, lengths, and dtypes are exactly the same. """ # Check that the tolerance is non-negative and raise an # exception otherwise. if (tol<0): raise ValueError("Tolerance cannot be negative") # Check that the meta-data agree; the type check is written in # this way so that this method may be safely called from # subclasses as well. if type(other) != type(self): return False if self.dtype != other.dtype: return False if len(self) != len(other): return False # The numpy() method will move any GPU memory onto the CPU. # Slow, but the user was warned. diff = abs(self.numpy()-other.numpy()) if relative: cmpary = tol*abs(self.numpy()) else: cmpary = tol*ones(len(self),dtype=self.dtype) return (diff<=cmpary).all()
python
def almost_equal_elem(self,other,tol,relative=True): # Check that the tolerance is non-negative and raise an # exception otherwise. if (tol<0): raise ValueError("Tolerance cannot be negative") # Check that the meta-data agree; the type check is written in # this way so that this method may be safely called from # subclasses as well. if type(other) != type(self): return False if self.dtype != other.dtype: return False if len(self) != len(other): return False # The numpy() method will move any GPU memory onto the CPU. # Slow, but the user was warned. diff = abs(self.numpy()-other.numpy()) if relative: cmpary = tol*abs(self.numpy()) else: cmpary = tol*ones(len(self),dtype=self.dtype) return (diff<=cmpary).all()
[ "def", "almost_equal_elem", "(", "self", ",", "other", ",", "tol", ",", "relative", "=", "True", ")", ":", "# Check that the tolerance is non-negative and raise an", "# exception otherwise.", "if", "(", "tol", "<", "0", ")", ":", "raise", "ValueError", "(", "\"Tol...
Compare whether two array types are almost equal, element by element. If the 'relative' parameter is 'True' (the default) then the 'tol' parameter (which must be positive) is interpreted as a relative tolerance, and the comparison returns 'True' only if abs(self[i]-other[i]) <= tol*abs(self[i]) for all elements of the array. If 'relative' is 'False', then 'tol' is an absolute tolerance, and the comparison is true only if abs(self[i]-other[i]) <= tol for all elements of the array. Other meta-data (type, dtype, and length) must be exactly equal. If either object's memory lives on the GPU it will be copied to the CPU for the comparison, which may be slow. But the original object itself will not have its memory relocated nor scheme changed. Parameters ---------- other Another Python object, that should be tested for almost-equality with 'self', element-by-element. tol A non-negative number, the tolerance, which is interpreted as either a relative tolerance (the default) or an absolute tolerance. relative A boolean, indicating whether 'tol' should be interpreted as a relative tolerance (if True, the default if this argument is omitted) or as an absolute tolerance (if tol is False). Returns ------- boolean 'True' if the data agree within the tolerance, as interpreted by the 'relative' keyword, and if the types, lengths, and dtypes are exactly the same.
[ "Compare", "whether", "two", "array", "types", "are", "almost", "equal", "element", "by", "element", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/types/array.py#L492-L558
228,011
gwastro/pycbc
pycbc/types/array.py
Array.almost_equal_norm
def almost_equal_norm(self,other,tol,relative=True): """ Compare whether two array types are almost equal, normwise. If the 'relative' parameter is 'True' (the default) then the 'tol' parameter (which must be positive) is interpreted as a relative tolerance, and the comparison returns 'True' only if abs(norm(self-other)) <= tol*abs(norm(self)). If 'relative' is 'False', then 'tol' is an absolute tolerance, and the comparison is true only if abs(norm(self-other)) <= tol Other meta-data (type, dtype, and length) must be exactly equal. If either object's memory lives on the GPU it will be copied to the CPU for the comparison, which may be slow. But the original object itself will not have its memory relocated nor scheme changed. Parameters ---------- other another Python object, that should be tested for almost-equality with 'self', based on their norms. tol a non-negative number, the tolerance, which is interpreted as either a relative tolerance (the default) or an absolute tolerance. relative A boolean, indicating whether 'tol' should be interpreted as a relative tolerance (if True, the default if this argument is omitted) or as an absolute tolerance (if tol is False). Returns ------- boolean 'True' if the data agree within the tolerance, as interpreted by the 'relative' keyword, and if the types, lengths, and dtypes are exactly the same. """ # Check that the tolerance is non-negative and raise an # exception otherwise. if (tol<0): raise ValueError("Tolerance cannot be negative") # Check that the meta-data agree; the type check is written in # this way so that this method may be safely called from # subclasses as well. if type(other) != type(self): return False if self.dtype != other.dtype: return False if len(self) != len(other): return False # The numpy() method will move any GPU memory onto the CPU. # Slow, but the user was warned. diff = self.numpy()-other.numpy() dnorm = norm(diff) if relative: return (dnorm <= tol*norm(self)) else: return (dnorm <= tol)
python
def almost_equal_norm(self,other,tol,relative=True): # Check that the tolerance is non-negative and raise an # exception otherwise. if (tol<0): raise ValueError("Tolerance cannot be negative") # Check that the meta-data agree; the type check is written in # this way so that this method may be safely called from # subclasses as well. if type(other) != type(self): return False if self.dtype != other.dtype: return False if len(self) != len(other): return False # The numpy() method will move any GPU memory onto the CPU. # Slow, but the user was warned. diff = self.numpy()-other.numpy() dnorm = norm(diff) if relative: return (dnorm <= tol*norm(self)) else: return (dnorm <= tol)
[ "def", "almost_equal_norm", "(", "self", ",", "other", ",", "tol", ",", "relative", "=", "True", ")", ":", "# Check that the tolerance is non-negative and raise an", "# exception otherwise.", "if", "(", "tol", "<", "0", ")", ":", "raise", "ValueError", "(", "\"Tol...
Compare whether two array types are almost equal, normwise. If the 'relative' parameter is 'True' (the default) then the 'tol' parameter (which must be positive) is interpreted as a relative tolerance, and the comparison returns 'True' only if abs(norm(self-other)) <= tol*abs(norm(self)). If 'relative' is 'False', then 'tol' is an absolute tolerance, and the comparison is true only if abs(norm(self-other)) <= tol Other meta-data (type, dtype, and length) must be exactly equal. If either object's memory lives on the GPU it will be copied to the CPU for the comparison, which may be slow. But the original object itself will not have its memory relocated nor scheme changed. Parameters ---------- other another Python object, that should be tested for almost-equality with 'self', based on their norms. tol a non-negative number, the tolerance, which is interpreted as either a relative tolerance (the default) or an absolute tolerance. relative A boolean, indicating whether 'tol' should be interpreted as a relative tolerance (if True, the default if this argument is omitted) or as an absolute tolerance (if tol is False). Returns ------- boolean 'True' if the data agree within the tolerance, as interpreted by the 'relative' keyword, and if the types, lengths, and dtypes are exactly the same.
[ "Compare", "whether", "two", "array", "types", "are", "almost", "equal", "normwise", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/types/array.py#L560-L622
228,012
gwastro/pycbc
pycbc/types/array.py
Array.resize
def resize(self, new_size): """Resize self to new_size """ if new_size == len(self): return else: self._saved = LimitedSizeDict(size_limit=2**5) new_arr = zeros(new_size, dtype=self.dtype) if len(self) <= new_size: new_arr[0:len(self)] = self else: new_arr[:] = self[0:new_size] self._data = new_arr._data
python
def resize(self, new_size): if new_size == len(self): return else: self._saved = LimitedSizeDict(size_limit=2**5) new_arr = zeros(new_size, dtype=self.dtype) if len(self) <= new_size: new_arr[0:len(self)] = self else: new_arr[:] = self[0:new_size] self._data = new_arr._data
[ "def", "resize", "(", "self", ",", "new_size", ")", ":", "if", "new_size", "==", "len", "(", "self", ")", ":", "return", "else", ":", "self", ".", "_saved", "=", "LimitedSizeDict", "(", "size_limit", "=", "2", "**", "5", ")", "new_arr", "=", "zeros",...
Resize self to new_size
[ "Resize", "self", "to", "new_size" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/types/array.py#L804-L817
228,013
gwastro/pycbc
pycbc/types/array.py
Array.lal
def lal(self): """ Returns a LAL Object that contains this data """ lal_data = None if self._data.dtype == float32: lal_data = _lal.CreateREAL4Vector(len(self)) elif self._data.dtype == float64: lal_data = _lal.CreateREAL8Vector(len(self)) elif self._data.dtype == complex64: lal_data = _lal.CreateCOMPLEX8Vector(len(self)) elif self._data.dtype == complex128: lal_data = _lal.CreateCOMPLEX16Vector(len(self)) lal_data.data[:] = self.numpy() return lal_data
python
def lal(self): lal_data = None if self._data.dtype == float32: lal_data = _lal.CreateREAL4Vector(len(self)) elif self._data.dtype == float64: lal_data = _lal.CreateREAL8Vector(len(self)) elif self._data.dtype == complex64: lal_data = _lal.CreateCOMPLEX8Vector(len(self)) elif self._data.dtype == complex128: lal_data = _lal.CreateCOMPLEX16Vector(len(self)) lal_data.data[:] = self.numpy() return lal_data
[ "def", "lal", "(", "self", ")", ":", "lal_data", "=", "None", "if", "self", ".", "_data", ".", "dtype", "==", "float32", ":", "lal_data", "=", "_lal", ".", "CreateREAL4Vector", "(", "len", "(", "self", ")", ")", "elif", "self", ".", "_data", ".", "...
Returns a LAL Object that contains this data
[ "Returns", "a", "LAL", "Object", "that", "contains", "this", "data" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/types/array.py#L944-L959
228,014
gwastro/pycbc
pycbc/types/array.py
Array.save
def save(self, path, group=None): """ Save array to a Numpy .npy, hdf, or text file. When saving a complex array as text, the real and imaginary parts are saved as the first and second column respectively. When using hdf format, the data is stored as a single vector, along with relevant attributes. Parameters ---------- path: string Destination file path. Must end with either .hdf, .npy or .txt. group: string Additional name for internal storage use. Ex. hdf storage uses this as the key value. Raises ------ ValueError If path does not end in .npy or .txt. """ ext = _os.path.splitext(path)[1] if ext == '.npy': _numpy.save(path, self.numpy()) elif ext == '.txt': if self.kind == 'real': _numpy.savetxt(path, self.numpy()) elif self.kind == 'complex': output = _numpy.vstack((self.numpy().real, self.numpy().imag)).T _numpy.savetxt(path, output) elif ext == '.hdf': key = 'data' if group is None else group f = h5py.File(path) f.create_dataset(key, data=self.numpy(), compression='gzip', compression_opts=9, shuffle=True) else: raise ValueError('Path must end with .npy, .txt, or .hdf')
python
def save(self, path, group=None): ext = _os.path.splitext(path)[1] if ext == '.npy': _numpy.save(path, self.numpy()) elif ext == '.txt': if self.kind == 'real': _numpy.savetxt(path, self.numpy()) elif self.kind == 'complex': output = _numpy.vstack((self.numpy().real, self.numpy().imag)).T _numpy.savetxt(path, output) elif ext == '.hdf': key = 'data' if group is None else group f = h5py.File(path) f.create_dataset(key, data=self.numpy(), compression='gzip', compression_opts=9, shuffle=True) else: raise ValueError('Path must end with .npy, .txt, or .hdf')
[ "def", "save", "(", "self", ",", "path", ",", "group", "=", "None", ")", ":", "ext", "=", "_os", ".", "path", ".", "splitext", "(", "path", ")", "[", "1", "]", "if", "ext", "==", "'.npy'", ":", "_numpy", ".", "save", "(", "path", ",", "self", ...
Save array to a Numpy .npy, hdf, or text file. When saving a complex array as text, the real and imaginary parts are saved as the first and second column respectively. When using hdf format, the data is stored as a single vector, along with relevant attributes. Parameters ---------- path: string Destination file path. Must end with either .hdf, .npy or .txt. group: string Additional name for internal storage use. Ex. hdf storage uses this as the key value. Raises ------ ValueError If path does not end in .npy or .txt.
[ "Save", "array", "to", "a", "Numpy", ".", "npy", "hdf", "or", "text", "file", ".", "When", "saving", "a", "complex", "array", "as", "text", "the", "real", "and", "imaginary", "parts", "are", "saved", "as", "the", "first", "and", "second", "column", "re...
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/types/array.py#L965-L1003
228,015
gwastro/pycbc
pycbc/types/array.py
Array.trim_zeros
def trim_zeros(self): """Remove the leading and trailing zeros. """ tmp = self.numpy() f = len(self)-len(_numpy.trim_zeros(tmp, trim='f')) b = len(self)-len(_numpy.trim_zeros(tmp, trim='b')) return self[f:len(self)-b]
python
def trim_zeros(self): tmp = self.numpy() f = len(self)-len(_numpy.trim_zeros(tmp, trim='f')) b = len(self)-len(_numpy.trim_zeros(tmp, trim='b')) return self[f:len(self)-b]
[ "def", "trim_zeros", "(", "self", ")", ":", "tmp", "=", "self", ".", "numpy", "(", ")", "f", "=", "len", "(", "self", ")", "-", "len", "(", "_numpy", ".", "trim_zeros", "(", "tmp", ",", "trim", "=", "'f'", ")", ")", "b", "=", "len", "(", "sel...
Remove the leading and trailing zeros.
[ "Remove", "the", "leading", "and", "trailing", "zeros", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/types/array.py#L1006-L1012
228,016
gwastro/pycbc
pycbc/results/layout.py
two_column_layout
def two_column_layout(path, cols, **kwargs): """ Make a well layout in a two column format Parameters ---------- path: str Location to make the well html file cols: list of tuples The format of the items on the well result section. Each tuple contains the two files that are shown in the left and right hand side of a row in the well.html page. """ path = os.path.join(os.getcwd(), path, 'well.html') from pycbc.results.render import render_workflow_html_template render_workflow_html_template(path, 'two_column.html', cols, **kwargs)
python
def two_column_layout(path, cols, **kwargs): path = os.path.join(os.getcwd(), path, 'well.html') from pycbc.results.render import render_workflow_html_template render_workflow_html_template(path, 'two_column.html', cols, **kwargs)
[ "def", "two_column_layout", "(", "path", ",", "cols", ",", "*", "*", "kwargs", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "path", ",", "'well.html'", ")", "from", "pycbc", ".", "results", ".", ...
Make a well layout in a two column format Parameters ---------- path: str Location to make the well html file cols: list of tuples The format of the items on the well result section. Each tuple contains the two files that are shown in the left and right hand side of a row in the well.html page.
[ "Make", "a", "well", "layout", "in", "a", "two", "column", "format" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/results/layout.py#L21-L35
228,017
gwastro/pycbc
pycbc/results/layout.py
single_layout
def single_layout(path, files, **kwargs): """ Make a well layout in single column format path: str Location to make the well html file files: list of pycbc.workflow.core.Files This list of images to show in order within the well layout html file. """ two_column_layout(path, [(f,) for f in files], **kwargs)
python
def single_layout(path, files, **kwargs): two_column_layout(path, [(f,) for f in files], **kwargs)
[ "def", "single_layout", "(", "path", ",", "files", ",", "*", "*", "kwargs", ")", ":", "two_column_layout", "(", "path", ",", "[", "(", "f", ",", ")", "for", "f", "in", "files", "]", ",", "*", "*", "kwargs", ")" ]
Make a well layout in single column format path: str Location to make the well html file files: list of pycbc.workflow.core.Files This list of images to show in order within the well layout html file.
[ "Make", "a", "well", "layout", "in", "single", "column", "format" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/results/layout.py#L37-L45
228,018
gwastro/pycbc
pycbc/results/layout.py
group_layout
def group_layout(path, files, **kwargs): """ Make a well layout in chunks of two from a list of files path: str Location to make the well html file files: list of pycbc.workflow.core.Files This list of images to show in order within the well layout html file. Every two are placed on the same row. """ if len(files) > 0: two_column_layout(path, list(grouper(files, 2)), **kwargs)
python
def group_layout(path, files, **kwargs): if len(files) > 0: two_column_layout(path, list(grouper(files, 2)), **kwargs)
[ "def", "group_layout", "(", "path", ",", "files", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "files", ")", ">", "0", ":", "two_column_layout", "(", "path", ",", "list", "(", "grouper", "(", "files", ",", "2", ")", ")", ",", "*", "*", ...
Make a well layout in chunks of two from a list of files path: str Location to make the well html file files: list of pycbc.workflow.core.Files This list of images to show in order within the well layout html file. Every two are placed on the same row.
[ "Make", "a", "well", "layout", "in", "chunks", "of", "two", "from", "a", "list", "of", "files" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/results/layout.py#L53-L63
228,019
gwastro/pycbc
pycbc/workflow/plotting.py
make_seg_table
def make_seg_table(workflow, seg_files, seg_names, out_dir, tags=None, title_text=None, description=None): """ Creates a node in the workflow for writing the segment summary table. Returns a File instances for the output file. """ seg_files = list(seg_files) seg_names = list(seg_names) if tags is None: tags = [] makedir(out_dir) node = PlotExecutable(workflow.cp, 'page_segtable', ifos=workflow.ifos, out_dir=out_dir, tags=tags).create_node() node.add_input_list_opt('--segment-files', seg_files) quoted_seg_names = [] for s in seg_names: quoted_seg_names.append("'" + s + "'") node.add_opt('--segment-names', ' '.join(quoted_seg_names)) if description: node.add_opt('--description', "'" + description + "'") if title_text: node.add_opt('--title-text', "'" + title_text + "'") node.new_output_file_opt(workflow.analysis_time, '.html', '--output-file') workflow += node return node.output_files[0]
python
def make_seg_table(workflow, seg_files, seg_names, out_dir, tags=None, title_text=None, description=None): seg_files = list(seg_files) seg_names = list(seg_names) if tags is None: tags = [] makedir(out_dir) node = PlotExecutable(workflow.cp, 'page_segtable', ifos=workflow.ifos, out_dir=out_dir, tags=tags).create_node() node.add_input_list_opt('--segment-files', seg_files) quoted_seg_names = [] for s in seg_names: quoted_seg_names.append("'" + s + "'") node.add_opt('--segment-names', ' '.join(quoted_seg_names)) if description: node.add_opt('--description', "'" + description + "'") if title_text: node.add_opt('--title-text', "'" + title_text + "'") node.new_output_file_opt(workflow.analysis_time, '.html', '--output-file') workflow += node return node.output_files[0]
[ "def", "make_seg_table", "(", "workflow", ",", "seg_files", ",", "seg_names", ",", "out_dir", ",", "tags", "=", "None", ",", "title_text", "=", "None", ",", "description", "=", "None", ")", ":", "seg_files", "=", "list", "(", "seg_files", ")", "seg_names",...
Creates a node in the workflow for writing the segment summary table. Returns a File instances for the output file.
[ "Creates", "a", "node", "in", "the", "workflow", "for", "writing", "the", "segment", "summary", "table", ".", "Returns", "a", "File", "instances", "for", "the", "output", "file", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/plotting.py#L208-L230
228,020
gwastro/pycbc
pycbc/workflow/plotting.py
make_veto_table
def make_veto_table(workflow, out_dir, vetodef_file=None, tags=None): """ Creates a node in the workflow for writing the veto_definer table. Returns a File instances for the output file. """ if vetodef_file is None: vetodef_file = workflow.cp.get_opt_tags("workflow-segments", "segments-veto-definer-file", []) file_url = urlparse.urljoin('file:', urllib.pathname2url(vetodef_file)) vdf_file = File(workflow.ifos, 'VETO_DEFINER', workflow.analysis_time, file_url=file_url) vdf_file.PFN(file_url, site='local') else: vdf_file = vetodef_file if tags is None: tags = [] makedir(out_dir) node = PlotExecutable(workflow.cp, 'page_vetotable', ifos=workflow.ifos, out_dir=out_dir, tags=tags).create_node() node.add_input_opt('--veto-definer-file', vdf_file) node.new_output_file_opt(workflow.analysis_time, '.html', '--output-file') workflow += node return node.output_files[0]
python
def make_veto_table(workflow, out_dir, vetodef_file=None, tags=None): if vetodef_file is None: vetodef_file = workflow.cp.get_opt_tags("workflow-segments", "segments-veto-definer-file", []) file_url = urlparse.urljoin('file:', urllib.pathname2url(vetodef_file)) vdf_file = File(workflow.ifos, 'VETO_DEFINER', workflow.analysis_time, file_url=file_url) vdf_file.PFN(file_url, site='local') else: vdf_file = vetodef_file if tags is None: tags = [] makedir(out_dir) node = PlotExecutable(workflow.cp, 'page_vetotable', ifos=workflow.ifos, out_dir=out_dir, tags=tags).create_node() node.add_input_opt('--veto-definer-file', vdf_file) node.new_output_file_opt(workflow.analysis_time, '.html', '--output-file') workflow += node return node.output_files[0]
[ "def", "make_veto_table", "(", "workflow", ",", "out_dir", ",", "vetodef_file", "=", "None", ",", "tags", "=", "None", ")", ":", "if", "vetodef_file", "is", "None", ":", "vetodef_file", "=", "workflow", ".", "cp", ".", "get_opt_tags", "(", "\"workflow-segmen...
Creates a node in the workflow for writing the veto_definer table. Returns a File instances for the output file.
[ "Creates", "a", "node", "in", "the", "workflow", "for", "writing", "the", "veto_definer", "table", ".", "Returns", "a", "File", "instances", "for", "the", "output", "file", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/plotting.py#L232-L254
228,021
gwastro/pycbc
pycbc/workflow/plotting.py
make_ifar_plot
def make_ifar_plot(workflow, trigger_file, out_dir, tags=None, hierarchical_level=None): """ Creates a node in the workflow for plotting cumulative histogram of IFAR values. """ if hierarchical_level is not None and tags: tags = [("HIERARCHICAL_LEVEL_{:02d}".format( hierarchical_level))] + tags elif hierarchical_level is not None and not tags: tags = ["HIERARCHICAL_LEVEL_{:02d}".format(hierarchical_level)] elif hierarchical_level is None and not tags: tags = [] makedir(out_dir) node = PlotExecutable(workflow.cp, 'page_ifar', ifos=workflow.ifos, out_dir=out_dir, tags=tags).create_node() node.add_input_opt('--trigger-file', trigger_file) if hierarchical_level is not None: node.add_opt('--use-hierarchical-level', hierarchical_level) node.new_output_file_opt(workflow.analysis_time, '.png', '--output-file') workflow += node return node.output_files[0]
python
def make_ifar_plot(workflow, trigger_file, out_dir, tags=None, hierarchical_level=None): if hierarchical_level is not None and tags: tags = [("HIERARCHICAL_LEVEL_{:02d}".format( hierarchical_level))] + tags elif hierarchical_level is not None and not tags: tags = ["HIERARCHICAL_LEVEL_{:02d}".format(hierarchical_level)] elif hierarchical_level is None and not tags: tags = [] makedir(out_dir) node = PlotExecutable(workflow.cp, 'page_ifar', ifos=workflow.ifos, out_dir=out_dir, tags=tags).create_node() node.add_input_opt('--trigger-file', trigger_file) if hierarchical_level is not None: node.add_opt('--use-hierarchical-level', hierarchical_level) node.new_output_file_opt(workflow.analysis_time, '.png', '--output-file') workflow += node return node.output_files[0]
[ "def", "make_ifar_plot", "(", "workflow", ",", "trigger_file", ",", "out_dir", ",", "tags", "=", "None", ",", "hierarchical_level", "=", "None", ")", ":", "if", "hierarchical_level", "is", "not", "None", "and", "tags", ":", "tags", "=", "[", "(", "\"HIERAR...
Creates a node in the workflow for plotting cumulative histogram of IFAR values.
[ "Creates", "a", "node", "in", "the", "workflow", "for", "plotting", "cumulative", "histogram", "of", "IFAR", "values", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/plotting.py#L274-L296
228,022
gwastro/pycbc
pycbc/inference/io/base_multitemper.py
MultiTemperedMetadataIO.write_sampler_metadata
def write_sampler_metadata(self, sampler): """Adds writing ntemps to file. """ super(MultiTemperedMetadataIO, self).write_sampler_metadata(sampler) self[self.sampler_group].attrs["ntemps"] = sampler.ntemps
python
def write_sampler_metadata(self, sampler): super(MultiTemperedMetadataIO, self).write_sampler_metadata(sampler) self[self.sampler_group].attrs["ntemps"] = sampler.ntemps
[ "def", "write_sampler_metadata", "(", "self", ",", "sampler", ")", ":", "super", "(", "MultiTemperedMetadataIO", ",", "self", ")", ".", "write_sampler_metadata", "(", "sampler", ")", "self", "[", "self", ".", "sampler_group", "]", ".", "attrs", "[", "\"ntemps\...
Adds writing ntemps to file.
[ "Adds", "writing", "ntemps", "to", "file", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/io/base_multitemper.py#L77-L81
228,023
gwastro/pycbc
pycbc/inference/gelman_rubin.py
walk
def walk(chains, start, end, step): """ Calculates Gelman-Rubin conervergence statistic along chains of data. This function will advance along the chains and calculate the statistic for each step. Parameters ---------- chains : iterable An iterable of numpy.array instances that contain the samples for each chain. Each chain has shape (nparameters, niterations). start : float Start index of blocks to calculate all statistics. end : float Last index of blocks to calculate statistics. step : float Step size to take for next block. Returns ------- starts : numpy.array 1-D array of start indexes of calculations. ends : numpy.array 1-D array of end indexes of caluclations. stats : numpy.array Array with convergence statistic. It has shape (nparameters, ncalculations). """ # get number of chains, parameters, and iterations chains = numpy.array(chains) _, nparameters, _ = chains.shape # get end index of blocks ends = numpy.arange(start, end, step) stats = numpy.zeros((nparameters, len(ends))) # get start index of blocks starts = numpy.array(len(ends) * [start]) # loop over end indexes and calculate statistic for i, e in enumerate(ends): tmp = chains[:, :, 0:e] stats[:, i] = gelman_rubin(tmp) return starts, ends, stats
python
def walk(chains, start, end, step): # get number of chains, parameters, and iterations chains = numpy.array(chains) _, nparameters, _ = chains.shape # get end index of blocks ends = numpy.arange(start, end, step) stats = numpy.zeros((nparameters, len(ends))) # get start index of blocks starts = numpy.array(len(ends) * [start]) # loop over end indexes and calculate statistic for i, e in enumerate(ends): tmp = chains[:, :, 0:e] stats[:, i] = gelman_rubin(tmp) return starts, ends, stats
[ "def", "walk", "(", "chains", ",", "start", ",", "end", ",", "step", ")", ":", "# get number of chains, parameters, and iterations", "chains", "=", "numpy", ".", "array", "(", "chains", ")", "_", ",", "nparameters", ",", "_", "=", "chains", ".", "shape", "...
Calculates Gelman-Rubin conervergence statistic along chains of data. This function will advance along the chains and calculate the statistic for each step. Parameters ---------- chains : iterable An iterable of numpy.array instances that contain the samples for each chain. Each chain has shape (nparameters, niterations). start : float Start index of blocks to calculate all statistics. end : float Last index of blocks to calculate statistics. step : float Step size to take for next block. Returns ------- starts : numpy.array 1-D array of start indexes of calculations. ends : numpy.array 1-D array of end indexes of caluclations. stats : numpy.array Array with convergence statistic. It has shape (nparameters, ncalculations).
[ "Calculates", "Gelman", "-", "Rubin", "conervergence", "statistic", "along", "chains", "of", "data", ".", "This", "function", "will", "advance", "along", "the", "chains", "and", "calculate", "the", "statistic", "for", "each", "step", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/gelman_rubin.py#L22-L66
228,024
gwastro/pycbc
pycbc/distributions/arbitrary.py
Arbitrary.rvs
def rvs(self, size=1, param=None): """Gives a set of random values drawn from the kde. Parameters ---------- size : {1, int} The number of values to generate; default is 1. param : {None, string} If provided, will just return values for the given parameter. Otherwise, returns random values for each parameter. Returns ------- structured array The random values in a numpy structured array. If a param was specified, the array will only have an element corresponding to the given parameter. Otherwise, the array will have an element for each parameter in self's params. """ if param is not None: dtype = [(param, float)] else: dtype = [(p, float) for p in self.params] size = int(size) arr = numpy.zeros(size, dtype=dtype) draws = self._kde.resample(size) draws = {param: draws[ii,:] for ii,param in enumerate(self.params)} for (param,_) in dtype: try: # transform back to param space tparam = self._tparams[param] tdraws = {tparam: draws[param]} draws[param] = self._transforms[tparam].inverse_transform( tdraws)[param] except KeyError: pass arr[param] = draws[param] return arr
python
def rvs(self, size=1, param=None): if param is not None: dtype = [(param, float)] else: dtype = [(p, float) for p in self.params] size = int(size) arr = numpy.zeros(size, dtype=dtype) draws = self._kde.resample(size) draws = {param: draws[ii,:] for ii,param in enumerate(self.params)} for (param,_) in dtype: try: # transform back to param space tparam = self._tparams[param] tdraws = {tparam: draws[param]} draws[param] = self._transforms[tparam].inverse_transform( tdraws)[param] except KeyError: pass arr[param] = draws[param] return arr
[ "def", "rvs", "(", "self", ",", "size", "=", "1", ",", "param", "=", "None", ")", ":", "if", "param", "is", "not", "None", ":", "dtype", "=", "[", "(", "param", ",", "float", ")", "]", "else", ":", "dtype", "=", "[", "(", "p", ",", "float", ...
Gives a set of random values drawn from the kde. Parameters ---------- size : {1, int} The number of values to generate; default is 1. param : {None, string} If provided, will just return values for the given parameter. Otherwise, returns random values for each parameter. Returns ------- structured array The random values in a numpy structured array. If a param was specified, the array will only have an element corresponding to the given parameter. Otherwise, the array will have an element for each parameter in self's params.
[ "Gives", "a", "set", "of", "random", "values", "drawn", "from", "the", "kde", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/distributions/arbitrary.py#L137-L174
228,025
gwastro/pycbc
pycbc/distributions/arbitrary.py
FromFile.get_arrays_from_file
def get_arrays_from_file(params_file, params=None): """Reads the values of one or more parameters from an hdf file and returns as a dictionary. Parameters ---------- params_file : str The hdf file that contains the values of the parameters. params : {None, list} If provided, will just retrieve the given parameter names. Returns ------- dict A dictionary of the parameters mapping `param_name -> array`. """ try: f = h5py.File(params_file, 'r') except: raise ValueError('File not found.') if params is not None: if not isinstance(params, list): params = [params] for p in params: if p not in f.keys(): raise ValueError('Parameter {} is not in {}' .format(p, params_file)) else: params = [str(k) for k in f.keys()] params_values = {p:f[p][:] for p in params} try: bandwidth = f.attrs["bandwidth"] except KeyError: bandwidth = "scott" f.close() return params_values, bandwidth
python
def get_arrays_from_file(params_file, params=None): try: f = h5py.File(params_file, 'r') except: raise ValueError('File not found.') if params is not None: if not isinstance(params, list): params = [params] for p in params: if p not in f.keys(): raise ValueError('Parameter {} is not in {}' .format(p, params_file)) else: params = [str(k) for k in f.keys()] params_values = {p:f[p][:] for p in params} try: bandwidth = f.attrs["bandwidth"] except KeyError: bandwidth = "scott" f.close() return params_values, bandwidth
[ "def", "get_arrays_from_file", "(", "params_file", ",", "params", "=", "None", ")", ":", "try", ":", "f", "=", "h5py", ".", "File", "(", "params_file", ",", "'r'", ")", "except", ":", "raise", "ValueError", "(", "'File not found.'", ")", "if", "params", ...
Reads the values of one or more parameters from an hdf file and returns as a dictionary. Parameters ---------- params_file : str The hdf file that contains the values of the parameters. params : {None, list} If provided, will just retrieve the given parameter names. Returns ------- dict A dictionary of the parameters mapping `param_name -> array`.
[ "Reads", "the", "values", "of", "one", "or", "more", "parameters", "from", "an", "hdf", "file", "and", "returns", "as", "a", "dictionary", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/distributions/arbitrary.py#L250-L286
228,026
gwastro/pycbc
pycbc/noise/reproduceable.py
block
def block(seed): """ Return block of normal random numbers Parameters ---------- seed : {None, int} The seed to generate the noise.sd Returns -------- noise : numpy.ndarray Array of random numbers """ num = SAMPLE_RATE * BLOCK_SIZE rng = RandomState(seed % 2**32) variance = SAMPLE_RATE / 2 return rng.normal(size=num, scale=variance**0.5)
python
def block(seed): num = SAMPLE_RATE * BLOCK_SIZE rng = RandomState(seed % 2**32) variance = SAMPLE_RATE / 2 return rng.normal(size=num, scale=variance**0.5)
[ "def", "block", "(", "seed", ")", ":", "num", "=", "SAMPLE_RATE", "*", "BLOCK_SIZE", "rng", "=", "RandomState", "(", "seed", "%", "2", "**", "32", ")", "variance", "=", "SAMPLE_RATE", "/", "2", "return", "rng", ".", "normal", "(", "size", "=", "num",...
Return block of normal random numbers Parameters ---------- seed : {None, int} The seed to generate the noise.sd Returns -------- noise : numpy.ndarray Array of random numbers
[ "Return", "block", "of", "normal", "random", "numbers" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/noise/reproduceable.py#L34-L50
228,027
gwastro/pycbc
pycbc/noise/reproduceable.py
colored_noise
def colored_noise(psd, start_time, end_time, seed=0, low_frequency_cutoff=1.0): """ Create noise from a PSD Return noise from the chosen PSD. Note that if unique noise is desired a unique seed should be provided. Parameters ---------- psd : pycbc.types.FrequencySeries PSD to color the noise start_time : int Start time in GPS seconds to generate noise end_time : int End time in GPS seconds to generate nosie seed : {None, int} The seed to generate the noise. low_frequency_cutof : {1.0, float} The low frequency cutoff to pass to the PSD generation. Returns -------- noise : TimeSeries A TimeSeries containing gaussian noise colored by the given psd. """ psd = psd.copy() flen = int(SAMPLE_RATE / psd.delta_f) / 2 + 1 oldlen = len(psd) psd.resize(flen) # Want to avoid zeroes in PSD. max_val = psd.max() for i in xrange(len(psd)): if i >= (oldlen-1): psd.data[i] = psd[oldlen - 2] if psd[i] == 0: psd.data[i] = max_val wn_dur = int(end_time - start_time) + 2*FILTER_LENGTH if psd.delta_f >= 1. / (2.*FILTER_LENGTH): # If the PSD is short enough, this method is less memory intensive than # resizing and then calling inverse_spectrum_truncation psd = pycbc.psd.interpolate(psd, 1.0 / (2.*FILTER_LENGTH)) # inverse_spectrum_truncation truncates the inverted PSD. To truncate # the non-inverted PSD we give it the inverted PSD to truncate and then # invert the output. psd = 1. / pycbc.psd.inverse_spectrum_truncation(1./psd, FILTER_LENGTH * SAMPLE_RATE, low_frequency_cutoff=low_frequency_cutoff, trunc_method='hann') psd = psd.astype(complex_same_precision_as(psd)) # Zero-pad the time-domain PSD to desired length. Zeroes must be added # in the middle, so some rolling between a resize is used. psd = psd.to_timeseries() psd.roll(SAMPLE_RATE * FILTER_LENGTH) psd.resize(wn_dur * SAMPLE_RATE) psd.roll(-SAMPLE_RATE * FILTER_LENGTH) # As time series is still mirrored the complex frequency components are # 0. But convert to real by using abs as in inverse_spectrum_truncate psd = psd.to_frequencyseries() else: psd = pycbc.psd.interpolate(psd, 1.0 / wn_dur) psd = 1. / pycbc.psd.inverse_spectrum_truncation(1./psd, FILTER_LENGTH * SAMPLE_RATE, low_frequency_cutoff=low_frequency_cutoff, trunc_method='hann') kmin = int(low_frequency_cutoff / psd.delta_f) psd[:kmin].clear() asd = (psd.real())**0.5 del psd white_noise = normal(start_time - FILTER_LENGTH, end_time + FILTER_LENGTH, seed=seed) white_noise = white_noise.to_frequencyseries() # Here we color. Do not want to duplicate memory here though so use '*=' white_noise *= asd del asd colored = white_noise.to_timeseries() del white_noise return colored.time_slice(start_time, end_time)
python
def colored_noise(psd, start_time, end_time, seed=0, low_frequency_cutoff=1.0): psd = psd.copy() flen = int(SAMPLE_RATE / psd.delta_f) / 2 + 1 oldlen = len(psd) psd.resize(flen) # Want to avoid zeroes in PSD. max_val = psd.max() for i in xrange(len(psd)): if i >= (oldlen-1): psd.data[i] = psd[oldlen - 2] if psd[i] == 0: psd.data[i] = max_val wn_dur = int(end_time - start_time) + 2*FILTER_LENGTH if psd.delta_f >= 1. / (2.*FILTER_LENGTH): # If the PSD is short enough, this method is less memory intensive than # resizing and then calling inverse_spectrum_truncation psd = pycbc.psd.interpolate(psd, 1.0 / (2.*FILTER_LENGTH)) # inverse_spectrum_truncation truncates the inverted PSD. To truncate # the non-inverted PSD we give it the inverted PSD to truncate and then # invert the output. psd = 1. / pycbc.psd.inverse_spectrum_truncation(1./psd, FILTER_LENGTH * SAMPLE_RATE, low_frequency_cutoff=low_frequency_cutoff, trunc_method='hann') psd = psd.astype(complex_same_precision_as(psd)) # Zero-pad the time-domain PSD to desired length. Zeroes must be added # in the middle, so some rolling between a resize is used. psd = psd.to_timeseries() psd.roll(SAMPLE_RATE * FILTER_LENGTH) psd.resize(wn_dur * SAMPLE_RATE) psd.roll(-SAMPLE_RATE * FILTER_LENGTH) # As time series is still mirrored the complex frequency components are # 0. But convert to real by using abs as in inverse_spectrum_truncate psd = psd.to_frequencyseries() else: psd = pycbc.psd.interpolate(psd, 1.0 / wn_dur) psd = 1. / pycbc.psd.inverse_spectrum_truncation(1./psd, FILTER_LENGTH * SAMPLE_RATE, low_frequency_cutoff=low_frequency_cutoff, trunc_method='hann') kmin = int(low_frequency_cutoff / psd.delta_f) psd[:kmin].clear() asd = (psd.real())**0.5 del psd white_noise = normal(start_time - FILTER_LENGTH, end_time + FILTER_LENGTH, seed=seed) white_noise = white_noise.to_frequencyseries() # Here we color. Do not want to duplicate memory here though so use '*=' white_noise *= asd del asd colored = white_noise.to_timeseries() del white_noise return colored.time_slice(start_time, end_time)
[ "def", "colored_noise", "(", "psd", ",", "start_time", ",", "end_time", ",", "seed", "=", "0", ",", "low_frequency_cutoff", "=", "1.0", ")", ":", "psd", "=", "psd", ".", "copy", "(", ")", "flen", "=", "int", "(", "SAMPLE_RATE", "/", "psd", ".", "delt...
Create noise from a PSD Return noise from the chosen PSD. Note that if unique noise is desired a unique seed should be provided. Parameters ---------- psd : pycbc.types.FrequencySeries PSD to color the noise start_time : int Start time in GPS seconds to generate noise end_time : int End time in GPS seconds to generate nosie seed : {None, int} The seed to generate the noise. low_frequency_cutof : {1.0, float} The low frequency cutoff to pass to the PSD generation. Returns -------- noise : TimeSeries A TimeSeries containing gaussian noise colored by the given psd.
[ "Create", "noise", "from", "a", "PSD" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/noise/reproduceable.py#L82-L162
228,028
gwastro/pycbc
pycbc/inference/io/emcee_pt.py
EmceePTFile.write_sampler_metadata
def write_sampler_metadata(self, sampler): """Adds writing betas to MultiTemperedMCMCIO. """ super(EmceePTFile, self).write_sampler_metadata(sampler) self[self.sampler_group].attrs["betas"] = sampler.betas
python
def write_sampler_metadata(self, sampler): super(EmceePTFile, self).write_sampler_metadata(sampler) self[self.sampler_group].attrs["betas"] = sampler.betas
[ "def", "write_sampler_metadata", "(", "self", ",", "sampler", ")", ":", "super", "(", "EmceePTFile", ",", "self", ")", ".", "write_sampler_metadata", "(", "sampler", ")", "self", "[", "self", ".", "sampler_group", "]", ".", "attrs", "[", "\"betas\"", "]", ...
Adds writing betas to MultiTemperedMCMCIO.
[ "Adds", "writing", "betas", "to", "MultiTemperedMCMCIO", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/io/emcee_pt.py#L38-L42
228,029
gwastro/pycbc
pycbc/inference/io/emcee_pt.py
EmceePTFile.write_acceptance_fraction
def write_acceptance_fraction(self, acceptance_fraction): """Write acceptance_fraction data to file. Results are written to ``[sampler_group]/acceptance_fraction``; the resulting dataset has shape (ntemps, nwalkers). Parameters ----------- acceptance_fraction : numpy.ndarray Array of acceptance fractions to write. Must have shape ntemps x nwalkers. """ # check assert acceptance_fraction.shape == (self.ntemps, self.nwalkers), ( "acceptance fraction must have shape ntemps x nwalker") group = self.sampler_group + '/acceptance_fraction' try: self[group][:] = acceptance_fraction except KeyError: # dataset doesn't exist yet, create it self[group] = acceptance_fraction
python
def write_acceptance_fraction(self, acceptance_fraction): # check assert acceptance_fraction.shape == (self.ntemps, self.nwalkers), ( "acceptance fraction must have shape ntemps x nwalker") group = self.sampler_group + '/acceptance_fraction' try: self[group][:] = acceptance_fraction except KeyError: # dataset doesn't exist yet, create it self[group] = acceptance_fraction
[ "def", "write_acceptance_fraction", "(", "self", ",", "acceptance_fraction", ")", ":", "# check", "assert", "acceptance_fraction", ".", "shape", "==", "(", "self", ".", "ntemps", ",", "self", ".", "nwalkers", ")", ",", "(", "\"acceptance fraction must have shape nte...
Write acceptance_fraction data to file. Results are written to ``[sampler_group]/acceptance_fraction``; the resulting dataset has shape (ntemps, nwalkers). Parameters ----------- acceptance_fraction : numpy.ndarray Array of acceptance fractions to write. Must have shape ntemps x nwalkers.
[ "Write", "acceptance_fraction", "data", "to", "file", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/io/emcee_pt.py#L75-L95
228,030
gwastro/pycbc
pycbc/events/eventmgr.py
findchirp_cluster_over_window
def findchirp_cluster_over_window(times, values, window_length): """ Reduce the events by clustering over a window using the FindChirp clustering algorithm Parameters ----------- indices: Array The list of indices of the SNR values snr: Array The list of SNR value window_size: int The size of the window in integer samples. Must be positive. Returns ------- indices: Array The reduced list of indices of the SNR values """ assert window_length > 0, 'Clustering window length is not positive' from weave import inline indices = numpy.zeros(len(times), dtype=int) tlen = len(times) # pylint:disable=unused-variable k = numpy.zeros(1, dtype=int) absvalues = abs(values) # pylint:disable=unused-variable times = times.astype(int) code = """ int j = 0; int curr_ind = 0; for (int i=0; i < tlen; i++){ if ((times[i] - times[curr_ind]) > window_length){ j += 1; indices[j] = i; curr_ind = i; } else if (absvalues[i] > absvalues[curr_ind]){ indices[j] = i; curr_ind = i; } } k[0] = j; """ inline(code, ['times', 'absvalues', 'window_length', 'indices', 'tlen', 'k'], extra_compile_args=[WEAVE_FLAGS]) return indices[0:k[0]+1]
python
def findchirp_cluster_over_window(times, values, window_length): assert window_length > 0, 'Clustering window length is not positive' from weave import inline indices = numpy.zeros(len(times), dtype=int) tlen = len(times) # pylint:disable=unused-variable k = numpy.zeros(1, dtype=int) absvalues = abs(values) # pylint:disable=unused-variable times = times.astype(int) code = """ int j = 0; int curr_ind = 0; for (int i=0; i < tlen; i++){ if ((times[i] - times[curr_ind]) > window_length){ j += 1; indices[j] = i; curr_ind = i; } else if (absvalues[i] > absvalues[curr_ind]){ indices[j] = i; curr_ind = i; } } k[0] = j; """ inline(code, ['times', 'absvalues', 'window_length', 'indices', 'tlen', 'k'], extra_compile_args=[WEAVE_FLAGS]) return indices[0:k[0]+1]
[ "def", "findchirp_cluster_over_window", "(", "times", ",", "values", ",", "window_length", ")", ":", "assert", "window_length", ">", "0", ",", "'Clustering window length is not positive'", "from", "weave", "import", "inline", "indices", "=", "numpy", ".", "zeros", "...
Reduce the events by clustering over a window using the FindChirp clustering algorithm Parameters ----------- indices: Array The list of indices of the SNR values snr: Array The list of SNR value window_size: int The size of the window in integer samples. Must be positive. Returns ------- indices: Array The reduced list of indices of the SNR values
[ "Reduce", "the", "events", "by", "clustering", "over", "a", "window", "using", "the", "FindChirp", "clustering", "algorithm" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/eventmgr.py#L122-L166
228,031
gwastro/pycbc
pycbc/events/eventmgr.py
cluster_reduce
def cluster_reduce(idx, snr, window_size): """ Reduce the events by clustering over a window Parameters ----------- indices: Array The list of indices of the SNR values snr: Array The list of SNR value window_size: int The size of the window in integer samples. Returns ------- indices: Array The list of indices of the SNR values snr: Array The list of SNR values """ ind = findchirp_cluster_over_window(idx, snr, window_size) return idx.take(ind), snr.take(ind)
python
def cluster_reduce(idx, snr, window_size): ind = findchirp_cluster_over_window(idx, snr, window_size) return idx.take(ind), snr.take(ind)
[ "def", "cluster_reduce", "(", "idx", ",", "snr", ",", "window_size", ")", ":", "ind", "=", "findchirp_cluster_over_window", "(", "idx", ",", "snr", ",", "window_size", ")", "return", "idx", ".", "take", "(", "ind", ")", ",", "snr", ".", "take", "(", "i...
Reduce the events by clustering over a window Parameters ----------- indices: Array The list of indices of the SNR values snr: Array The list of SNR value window_size: int The size of the window in integer samples. Returns ------- indices: Array The list of indices of the SNR values snr: Array The list of SNR values
[ "Reduce", "the", "events", "by", "clustering", "over", "a", "window" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/eventmgr.py#L169-L189
228,032
gwastro/pycbc
pycbc/events/eventmgr.py
EventManager.from_multi_ifo_interface
def from_multi_ifo_interface(cls, opt, ifo, column, column_types, **kwds): """ To use this for a single ifo from the multi ifo interface requires some small fixing of the opt structure. This does that. As we edit the opt structure the process_params table will not be correct. """ opt = copy.deepcopy(opt) opt_dict = vars(opt) for arg, value in opt_dict.items(): if isinstance(value, dict): setattr(opt, arg, getattr(opt, arg)[ifo]) return cls(opt, column, column_types, **kwds)
python
def from_multi_ifo_interface(cls, opt, ifo, column, column_types, **kwds): opt = copy.deepcopy(opt) opt_dict = vars(opt) for arg, value in opt_dict.items(): if isinstance(value, dict): setattr(opt, arg, getattr(opt, arg)[ifo]) return cls(opt, column, column_types, **kwds)
[ "def", "from_multi_ifo_interface", "(", "cls", ",", "opt", ",", "ifo", ",", "column", ",", "column_types", ",", "*", "*", "kwds", ")", ":", "opt", "=", "copy", ".", "deepcopy", "(", "opt", ")", "opt_dict", "=", "vars", "(", "opt", ")", "for", "arg", ...
To use this for a single ifo from the multi ifo interface requires some small fixing of the opt structure. This does that. As we edit the opt structure the process_params table will not be correct.
[ "To", "use", "this", "for", "a", "single", "ifo", "from", "the", "multi", "ifo", "interface", "requires", "some", "small", "fixing", "of", "the", "opt", "structure", ".", "This", "does", "that", ".", "As", "we", "edit", "the", "opt", "structure", "the", ...
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/eventmgr.py#L209-L220
228,033
gwastro/pycbc
pycbc/events/eventmgr.py
EventManager.newsnr_threshold
def newsnr_threshold(self, threshold): """ Remove events with newsnr smaller than given threshold """ if not self.opt.chisq_bins: raise RuntimeError('Chi-square test must be enabled in order to ' 'use newsnr threshold') remove = [i for i, e in enumerate(self.events) if ranking.newsnr(abs(e['snr']), e['chisq'] / e['chisq_dof']) < threshold] self.events = numpy.delete(self.events, remove)
python
def newsnr_threshold(self, threshold): if not self.opt.chisq_bins: raise RuntimeError('Chi-square test must be enabled in order to ' 'use newsnr threshold') remove = [i for i, e in enumerate(self.events) if ranking.newsnr(abs(e['snr']), e['chisq'] / e['chisq_dof']) < threshold] self.events = numpy.delete(self.events, remove)
[ "def", "newsnr_threshold", "(", "self", ",", "threshold", ")", ":", "if", "not", "self", ".", "opt", ".", "chisq_bins", ":", "raise", "RuntimeError", "(", "'Chi-square test must be enabled in order to '", "'use newsnr threshold'", ")", "remove", "=", "[", "i", "fo...
Remove events with newsnr smaller than given threshold
[ "Remove", "events", "with", "newsnr", "smaller", "than", "given", "threshold" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/eventmgr.py#L231-L241
228,034
gwastro/pycbc
pycbc/events/eventmgr.py
EventManager.save_performance
def save_performance(self, ncores, nfilters, ntemplates, run_time, setup_time): """ Calls variables from pycbc_inspiral to be used in a timing calculation """ self.run_time = run_time self.setup_time = setup_time self.ncores = ncores self.nfilters = nfilters self.ntemplates = ntemplates self.write_performance = True
python
def save_performance(self, ncores, nfilters, ntemplates, run_time, setup_time): self.run_time = run_time self.setup_time = setup_time self.ncores = ncores self.nfilters = nfilters self.ntemplates = ntemplates self.write_performance = True
[ "def", "save_performance", "(", "self", ",", "ncores", ",", "nfilters", ",", "ntemplates", ",", "run_time", ",", "setup_time", ")", ":", "self", ".", "run_time", "=", "run_time", "self", ".", "setup_time", "=", "setup_time", "self", ".", "ncores", "=", "nc...
Calls variables from pycbc_inspiral to be used in a timing calculation
[ "Calls", "variables", "from", "pycbc_inspiral", "to", "be", "used", "in", "a", "timing", "calculation" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/eventmgr.py#L352-L362
228,035
gwastro/pycbc
pycbc/events/eventmgr.py
EventManager.write_events
def write_events(self, outname): """ Write the found events to a sngl inspiral table """ self.make_output_dir(outname) if '.hdf' in outname: self.write_to_hdf(outname) else: raise ValueError('Cannot write to this format')
python
def write_events(self, outname): self.make_output_dir(outname) if '.hdf' in outname: self.write_to_hdf(outname) else: raise ValueError('Cannot write to this format')
[ "def", "write_events", "(", "self", ",", "outname", ")", ":", "self", ".", "make_output_dir", "(", "outname", ")", "if", "'.hdf'", "in", "outname", ":", "self", ".", "write_to_hdf", "(", "outname", ")", "else", ":", "raise", "ValueError", "(", "'Cannot wri...
Write the found events to a sngl inspiral table
[ "Write", "the", "found", "events", "to", "a", "sngl", "inspiral", "table" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/eventmgr.py#L364-L372
228,036
gwastro/pycbc
pycbc/inference/sampler/emcee_pt.py
EmceePTSampler.model_stats
def model_stats(self): """Returns the log likelihood ratio and log prior as a dict of arrays. The returned array has shape ntemps x nwalkers x niterations. Unfortunately, because ``emcee_pt`` does not have blob support, this will only return the loglikelihood and logprior (with the logjacobian set to zero) regardless of what stats the model can return. .. warning:: Since the `logjacobian` is not saved by `emcee_pt`, the `logprior` returned here is the log of the prior pdf in the sampling coordinate frame rather than the variable params frame. This differs from the variable params frame by the log of the Jacobian of the transform from one frame to the other. If no sampling transforms were used, then the `logprior` is the same. """ # likelihood has shape ntemps x nwalkers x niterations logl = self._sampler.lnlikelihood # get prior from posterior logp = self._sampler.lnprobability - logl logjacobian = numpy.zeros(logp.shape) return {'loglikelihood': logl, 'logprior': logp, 'logjacobian': logjacobian}
python
def model_stats(self): # likelihood has shape ntemps x nwalkers x niterations logl = self._sampler.lnlikelihood # get prior from posterior logp = self._sampler.lnprobability - logl logjacobian = numpy.zeros(logp.shape) return {'loglikelihood': logl, 'logprior': logp, 'logjacobian': logjacobian}
[ "def", "model_stats", "(", "self", ")", ":", "# likelihood has shape ntemps x nwalkers x niterations", "logl", "=", "self", ".", "_sampler", ".", "lnlikelihood", "# get prior from posterior", "logp", "=", "self", ".", "_sampler", ".", "lnprobability", "-", "logl", "lo...
Returns the log likelihood ratio and log prior as a dict of arrays. The returned array has shape ntemps x nwalkers x niterations. Unfortunately, because ``emcee_pt`` does not have blob support, this will only return the loglikelihood and logprior (with the logjacobian set to zero) regardless of what stats the model can return. .. warning:: Since the `logjacobian` is not saved by `emcee_pt`, the `logprior` returned here is the log of the prior pdf in the sampling coordinate frame rather than the variable params frame. This differs from the variable params frame by the log of the Jacobian of the transform from one frame to the other. If no sampling transforms were used, then the `logprior` is the same.
[ "Returns", "the", "log", "likelihood", "ratio", "and", "log", "prior", "as", "a", "dict", "of", "arrays", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/sampler/emcee_pt.py#L187-L211
228,037
gwastro/pycbc
pycbc/inference/sampler/emcee_pt.py
EmceePTSampler.clear_samples
def clear_samples(self): """Clears the chain and blobs from memory. """ # store the iteration that the clear is occuring on self._lastclear = self.niterations self._itercounter = 0 # now clear the chain self._sampler.reset()
python
def clear_samples(self): # store the iteration that the clear is occuring on self._lastclear = self.niterations self._itercounter = 0 # now clear the chain self._sampler.reset()
[ "def", "clear_samples", "(", "self", ")", ":", "# store the iteration that the clear is occuring on", "self", ".", "_lastclear", "=", "self", ".", "niterations", "self", ".", "_itercounter", "=", "0", "# now clear the chain", "self", ".", "_sampler", ".", "reset", "...
Clears the chain and blobs from memory.
[ "Clears", "the", "chain", "and", "blobs", "from", "memory", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/sampler/emcee_pt.py#L213-L220
228,038
gwastro/pycbc
pycbc/inference/sampler/emcee_pt.py
EmceePTSampler.run_mcmc
def run_mcmc(self, niterations): """Advance the ensemble for a number of samples. Parameters ---------- niterations : int Number of samples to get from sampler. """ pos = self._pos if pos is None: pos = self._p0 res = self._sampler.run_mcmc(pos, niterations) p, _, _ = res[0], res[1], res[2] # update the positions self._pos = p
python
def run_mcmc(self, niterations): pos = self._pos if pos is None: pos = self._p0 res = self._sampler.run_mcmc(pos, niterations) p, _, _ = res[0], res[1], res[2] # update the positions self._pos = p
[ "def", "run_mcmc", "(", "self", ",", "niterations", ")", ":", "pos", "=", "self", ".", "_pos", "if", "pos", "is", "None", ":", "pos", "=", "self", ".", "_p0", "res", "=", "self", ".", "_sampler", ".", "run_mcmc", "(", "pos", ",", "niterations", ")"...
Advance the ensemble for a number of samples. Parameters ---------- niterations : int Number of samples to get from sampler.
[ "Advance", "the", "ensemble", "for", "a", "number", "of", "samples", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/sampler/emcee_pt.py#L230-L244
228,039
gwastro/pycbc
pycbc/inference/sampler/emcee_pt.py
EmceePTSampler.calculate_logevidence
def calculate_logevidence(cls, filename, thin_start=None, thin_end=None, thin_interval=None): """Calculates the log evidence from the given file using ``emcee_pt``'s thermodynamic integration. Parameters ---------- filename : str Name of the file to read the samples from. Should be an ``EmceePTFile``. thin_start : int Index of the sample to begin returning stats. Default is to read stats after burn in. To start from the beginning set thin_start to 0. thin_interval : int Interval to accept every i-th sample. Default is to use the `fp.acl`. If `fp.acl` is not set, then use all stats (set thin_interval to 1). thin_end : int Index of the last sample to read. If not given then `fp.niterations` is used. Returns ------- lnZ : float The estimate of log of the evidence. dlnZ : float The error on the estimate. """ with cls._io(filename, 'r') as fp: logls = fp.read_raw_samples(['loglikelihood'], thin_start=thin_start, thin_interval=thin_interval, thin_end=thin_end, temps='all', flatten=False) logls = logls['loglikelihood'] # we need the betas that were used betas = fp.betas # annoyingly, theromdynaimc integration in PTSampler is an instance # method, so we'll implement a dummy one ntemps = fp.ntemps nwalkers = fp.nwalkers ndim = len(fp.variable_params) dummy_sampler = emcee.PTSampler(ntemps, nwalkers, ndim, None, None, betas=betas) return dummy_sampler.thermodynamic_integration_log_evidence( logls=logls, fburnin=0.)
python
def calculate_logevidence(cls, filename, thin_start=None, thin_end=None, thin_interval=None): with cls._io(filename, 'r') as fp: logls = fp.read_raw_samples(['loglikelihood'], thin_start=thin_start, thin_interval=thin_interval, thin_end=thin_end, temps='all', flatten=False) logls = logls['loglikelihood'] # we need the betas that were used betas = fp.betas # annoyingly, theromdynaimc integration in PTSampler is an instance # method, so we'll implement a dummy one ntemps = fp.ntemps nwalkers = fp.nwalkers ndim = len(fp.variable_params) dummy_sampler = emcee.PTSampler(ntemps, nwalkers, ndim, None, None, betas=betas) return dummy_sampler.thermodynamic_integration_log_evidence( logls=logls, fburnin=0.)
[ "def", "calculate_logevidence", "(", "cls", ",", "filename", ",", "thin_start", "=", "None", ",", "thin_end", "=", "None", ",", "thin_interval", "=", "None", ")", ":", "with", "cls", ".", "_io", "(", "filename", ",", "'r'", ")", "as", "fp", ":", "logls...
Calculates the log evidence from the given file using ``emcee_pt``'s thermodynamic integration. Parameters ---------- filename : str Name of the file to read the samples from. Should be an ``EmceePTFile``. thin_start : int Index of the sample to begin returning stats. Default is to read stats after burn in. To start from the beginning set thin_start to 0. thin_interval : int Interval to accept every i-th sample. Default is to use the `fp.acl`. If `fp.acl` is not set, then use all stats (set thin_interval to 1). thin_end : int Index of the last sample to read. If not given then `fp.niterations` is used. Returns ------- lnZ : float The estimate of log of the evidence. dlnZ : float The error on the estimate.
[ "Calculates", "the", "log", "evidence", "from", "the", "given", "file", "using", "emcee_pt", "s", "thermodynamic", "integration", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/sampler/emcee_pt.py#L268-L314
228,040
gwastro/pycbc
pycbc/inference/sampler/emcee_pt.py
EmceePTSampler.finalize
def finalize(self): """Calculates the log evidence and writes to the checkpoint file. The thin start/interval/end for calculating the log evidence are retrieved from the checkpoint file's thinning attributes. """ logging.info("Calculating log evidence") # get the thinning settings with self.io(self.checkpoint_file, 'r') as fp: thin_start = fp.thin_start thin_interval = fp.thin_interval thin_end = fp.thin_end # calculate logz, dlogz = self.calculate_logevidence( self.checkpoint_file, thin_start=thin_start, thin_end=thin_end, thin_interval=thin_interval) logging.info("log Z, dlog Z: {}, {}".format(logz, dlogz)) # write to both the checkpoint and backup for fn in [self.checkpoint_file, self.backup_file]: with self.io(fn, "a") as fp: fp.write_logevidence(logz, dlogz)
python
def finalize(self): logging.info("Calculating log evidence") # get the thinning settings with self.io(self.checkpoint_file, 'r') as fp: thin_start = fp.thin_start thin_interval = fp.thin_interval thin_end = fp.thin_end # calculate logz, dlogz = self.calculate_logevidence( self.checkpoint_file, thin_start=thin_start, thin_end=thin_end, thin_interval=thin_interval) logging.info("log Z, dlog Z: {}, {}".format(logz, dlogz)) # write to both the checkpoint and backup for fn in [self.checkpoint_file, self.backup_file]: with self.io(fn, "a") as fp: fp.write_logevidence(logz, dlogz)
[ "def", "finalize", "(", "self", ")", ":", "logging", ".", "info", "(", "\"Calculating log evidence\"", ")", "# get the thinning settings", "with", "self", ".", "io", "(", "self", ".", "checkpoint_file", ",", "'r'", ")", "as", "fp", ":", "thin_start", "=", "f...
Calculates the log evidence and writes to the checkpoint file. The thin start/interval/end for calculating the log evidence are retrieved from the checkpoint file's thinning attributes.
[ "Calculates", "the", "log", "evidence", "and", "writes", "to", "the", "checkpoint", "file", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/sampler/emcee_pt.py#L316-L336
228,041
gwastro/pycbc
pycbc/frame/losc.py
losc_frame_json
def losc_frame_json(ifo, start_time, end_time): """ Get the information about the public data files in a duration of time Parameters ---------- ifo: str The name of the IFO to find the information about. start_time: int The gps time in GPS seconds end_time: int The end time in GPS seconds Returns ------- info: dict A dictionary containing information about the files that span the requested times. """ import urllib, json run = get_run(start_time) run2 = get_run(end_time) if run != run2: raise ValueError('Spanning multiple runs is not currently supported.' 'You have requested data that uses ' 'both %s and %s' % (run, run2)) url = _losc_url % (run, ifo, int(start_time), int(end_time)) try: return json.loads(urllib.urlopen(url).read()) except Exception as e: print(e) raise ValueError('Failed to find gwf files for ' 'ifo=%s, run=%s, between %s-%s' % (ifo, run, start_time, end_time))
python
def losc_frame_json(ifo, start_time, end_time): import urllib, json run = get_run(start_time) run2 = get_run(end_time) if run != run2: raise ValueError('Spanning multiple runs is not currently supported.' 'You have requested data that uses ' 'both %s and %s' % (run, run2)) url = _losc_url % (run, ifo, int(start_time), int(end_time)) try: return json.loads(urllib.urlopen(url).read()) except Exception as e: print(e) raise ValueError('Failed to find gwf files for ' 'ifo=%s, run=%s, between %s-%s' % (ifo, run, start_time, end_time))
[ "def", "losc_frame_json", "(", "ifo", ",", "start_time", ",", "end_time", ")", ":", "import", "urllib", ",", "json", "run", "=", "get_run", "(", "start_time", ")", "run2", "=", "get_run", "(", "end_time", ")", "if", "run", "!=", "run2", ":", "raise", "...
Get the information about the public data files in a duration of time Parameters ---------- ifo: str The name of the IFO to find the information about. start_time: int The gps time in GPS seconds end_time: int The end time in GPS seconds Returns ------- info: dict A dictionary containing information about the files that span the requested times.
[ "Get", "the", "information", "about", "the", "public", "data", "files", "in", "a", "duration", "of", "time" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/frame/losc.py#L41-L74
228,042
gwastro/pycbc
pycbc/frame/losc.py
losc_frame_urls
def losc_frame_urls(ifo, start_time, end_time): """ Get a list of urls to losc frame files Parameters ---------- ifo: str The name of the IFO to find the information about. start_time: int The gps time in GPS seconds end_time: int The end time in GPS seconds Returns ------- frame_files: list A dictionary containing information about the files that span the requested times. """ data = losc_frame_json(ifo, start_time, end_time)['strain'] return [d['url'] for d in data if d['format'] == 'gwf']
python
def losc_frame_urls(ifo, start_time, end_time): data = losc_frame_json(ifo, start_time, end_time)['strain'] return [d['url'] for d in data if d['format'] == 'gwf']
[ "def", "losc_frame_urls", "(", "ifo", ",", "start_time", ",", "end_time", ")", ":", "data", "=", "losc_frame_json", "(", "ifo", ",", "start_time", ",", "end_time", ")", "[", "'strain'", "]", "return", "[", "d", "[", "'url'", "]", "for", "d", "in", "dat...
Get a list of urls to losc frame files Parameters ---------- ifo: str The name of the IFO to find the information about. start_time: int The gps time in GPS seconds end_time: int The end time in GPS seconds Returns ------- frame_files: list A dictionary containing information about the files that span the requested times.
[ "Get", "a", "list", "of", "urls", "to", "losc", "frame", "files" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/frame/losc.py#L76-L95
228,043
gwastro/pycbc
pycbc/frame/losc.py
read_frame_losc
def read_frame_losc(channels, start_time, end_time): """ Read channels from losc data Parameters ---------- channels: str or list The channel name to read or list of channel names. start_time: int The gps time in GPS seconds end_time: int The end time in GPS seconds Returns ------- ts: TimeSeries Returns a timeseries or list of timeseries with the requested data. """ from pycbc.frame import read_frame if not isinstance(channels, list): channels = [channels] ifos = [c[0:2] for c in channels] urls = {} for ifo in ifos: urls[ifo] = losc_frame_urls(ifo, start_time, end_time) if len(urls[ifo]) == 0: raise ValueError("No data found for %s so we " "can't produce a time series" % ifo) fnames = {ifo:[] for ifo in ifos} for ifo in ifos: for url in urls[ifo]: fname = download_file(url, cache=True) fnames[ifo].append(fname) ts = [read_frame(fnames[channel[0:2]], channel, start_time=start_time, end_time=end_time) for channel in channels] if len(ts) == 1: return ts[0] else: return ts
python
def read_frame_losc(channels, start_time, end_time): from pycbc.frame import read_frame if not isinstance(channels, list): channels = [channels] ifos = [c[0:2] for c in channels] urls = {} for ifo in ifos: urls[ifo] = losc_frame_urls(ifo, start_time, end_time) if len(urls[ifo]) == 0: raise ValueError("No data found for %s so we " "can't produce a time series" % ifo) fnames = {ifo:[] for ifo in ifos} for ifo in ifos: for url in urls[ifo]: fname = download_file(url, cache=True) fnames[ifo].append(fname) ts = [read_frame(fnames[channel[0:2]], channel, start_time=start_time, end_time=end_time) for channel in channels] if len(ts) == 1: return ts[0] else: return ts
[ "def", "read_frame_losc", "(", "channels", ",", "start_time", ",", "end_time", ")", ":", "from", "pycbc", ".", "frame", "import", "read_frame", "if", "not", "isinstance", "(", "channels", ",", "list", ")", ":", "channels", "=", "[", "channels", "]", "ifos"...
Read channels from losc data Parameters ---------- channels: str or list The channel name to read or list of channel names. start_time: int The gps time in GPS seconds end_time: int The end time in GPS seconds Returns ------- ts: TimeSeries Returns a timeseries or list of timeseries with the requested data.
[ "Read", "channels", "from", "losc", "data" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/frame/losc.py#L97-L136
228,044
gwastro/pycbc
pycbc/frame/losc.py
read_strain_losc
def read_strain_losc(ifo, start_time, end_time): """ Get the strain data from the LOSC data Parameters ---------- ifo: str The name of the IFO to read data for. Ex. 'H1', 'L1', 'V1' start_time: int The gps time in GPS seconds end_time: int The end time in GPS seconds Returns ------- ts: TimeSeries Returns a timeseries with the strain data. """ channel = _get_channel(start_time) return read_frame_losc('%s:%s' % (ifo, channel), start_time, end_time)
python
def read_strain_losc(ifo, start_time, end_time): channel = _get_channel(start_time) return read_frame_losc('%s:%s' % (ifo, channel), start_time, end_time)
[ "def", "read_strain_losc", "(", "ifo", ",", "start_time", ",", "end_time", ")", ":", "channel", "=", "_get_channel", "(", "start_time", ")", "return", "read_frame_losc", "(", "'%s:%s'", "%", "(", "ifo", ",", "channel", ")", ",", "start_time", ",", "end_time"...
Get the strain data from the LOSC data Parameters ---------- ifo: str The name of the IFO to read data for. Ex. 'H1', 'L1', 'V1' start_time: int The gps time in GPS seconds end_time: int The end time in GPS seconds Returns ------- ts: TimeSeries Returns a timeseries with the strain data.
[ "Get", "the", "strain", "data", "from", "the", "LOSC", "data" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/frame/losc.py#L138-L156
228,045
gwastro/pycbc
pycbc/events/coinc.py
background_bin_from_string
def background_bin_from_string(background_bins, data): """ Return template ids for each bin as defined by the format string Parameters ---------- bins: list of strings List of strings which define how a background bin is taken from the list of templates. data: dict of numpy.ndarrays Dict with parameter key values and numpy.ndarray values which define the parameters of the template bank to bin up. Returns ------- bins: dict Dictionary of location indices indexed by a bin name """ used = numpy.array([], dtype=numpy.uint32) bins = {} for mbin in background_bins: name, bin_type, boundary = tuple(mbin.split(':')) if boundary[0:2] == 'lt': member_func = lambda vals, bd=boundary : vals < float(bd[2:]) elif boundary[0:2] == 'gt': member_func = lambda vals, bd=boundary : vals > float(bd[2:]) else: raise RuntimeError("Can't parse boundary condition! Must begin " "with 'lt' or 'gt'") if bin_type == 'component' and boundary[0:2] == 'lt': # maximum component mass is less than boundary value vals = numpy.maximum(data['mass1'], data['mass2']) if bin_type == 'component' and boundary[0:2] == 'gt': # minimum component mass is greater than bdary vals = numpy.minimum(data['mass1'], data['mass2']) elif bin_type == 'total': vals = data['mass1'] + data['mass2'] elif bin_type == 'chirp': vals = pycbc.pnutils.mass1_mass2_to_mchirp_eta( data['mass1'], data['mass2'])[0] elif bin_type == 'SEOBNRv2Peak': vals = pycbc.pnutils.get_freq('fSEOBNRv2Peak', data['mass1'], data['mass2'], data['spin1z'], data['spin2z']) elif bin_type == 'SEOBNRv4Peak': vals = pycbc.pnutils.get_freq('fSEOBNRv4Peak', data['mass1'], data['mass2'], data['spin1z'], data['spin2z']) elif bin_type == 'SEOBNRv2duration': vals = pycbc.pnutils.get_imr_duration(data['mass1'], data['mass2'], data['spin1z'], data['spin2z'], data['f_lower'], approximant='SEOBNRv2') else: raise ValueError('Invalid bin type %s' % bin_type) locs = member_func(vals) del vals # make sure we don't reuse anything from an earlier bin locs = numpy.where(locs)[0] locs = numpy.delete(locs, numpy.where(numpy.in1d(locs, used))[0]) used = numpy.concatenate([used, locs]) bins[name] = locs return bins
python
def background_bin_from_string(background_bins, data): used = numpy.array([], dtype=numpy.uint32) bins = {} for mbin in background_bins: name, bin_type, boundary = tuple(mbin.split(':')) if boundary[0:2] == 'lt': member_func = lambda vals, bd=boundary : vals < float(bd[2:]) elif boundary[0:2] == 'gt': member_func = lambda vals, bd=boundary : vals > float(bd[2:]) else: raise RuntimeError("Can't parse boundary condition! Must begin " "with 'lt' or 'gt'") if bin_type == 'component' and boundary[0:2] == 'lt': # maximum component mass is less than boundary value vals = numpy.maximum(data['mass1'], data['mass2']) if bin_type == 'component' and boundary[0:2] == 'gt': # minimum component mass is greater than bdary vals = numpy.minimum(data['mass1'], data['mass2']) elif bin_type == 'total': vals = data['mass1'] + data['mass2'] elif bin_type == 'chirp': vals = pycbc.pnutils.mass1_mass2_to_mchirp_eta( data['mass1'], data['mass2'])[0] elif bin_type == 'SEOBNRv2Peak': vals = pycbc.pnutils.get_freq('fSEOBNRv2Peak', data['mass1'], data['mass2'], data['spin1z'], data['spin2z']) elif bin_type == 'SEOBNRv4Peak': vals = pycbc.pnutils.get_freq('fSEOBNRv4Peak', data['mass1'], data['mass2'], data['spin1z'], data['spin2z']) elif bin_type == 'SEOBNRv2duration': vals = pycbc.pnutils.get_imr_duration(data['mass1'], data['mass2'], data['spin1z'], data['spin2z'], data['f_lower'], approximant='SEOBNRv2') else: raise ValueError('Invalid bin type %s' % bin_type) locs = member_func(vals) del vals # make sure we don't reuse anything from an earlier bin locs = numpy.where(locs)[0] locs = numpy.delete(locs, numpy.where(numpy.in1d(locs, used))[0]) used = numpy.concatenate([used, locs]) bins[name] = locs return bins
[ "def", "background_bin_from_string", "(", "background_bins", ",", "data", ")", ":", "used", "=", "numpy", ".", "array", "(", "[", "]", ",", "dtype", "=", "numpy", ".", "uint32", ")", "bins", "=", "{", "}", "for", "mbin", "in", "background_bins", ":", "...
Return template ids for each bin as defined by the format string Parameters ---------- bins: list of strings List of strings which define how a background bin is taken from the list of templates. data: dict of numpy.ndarrays Dict with parameter key values and numpy.ndarray values which define the parameters of the template bank to bin up. Returns ------- bins: dict Dictionary of location indices indexed by a bin name
[ "Return", "template", "ids", "for", "each", "bin", "as", "defined", "by", "the", "format", "string" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc.py#L32-L96
228,046
gwastro/pycbc
pycbc/events/coinc.py
calculate_n_louder
def calculate_n_louder(bstat, fstat, dec, skip_background=False): """ Calculate for each foreground event the number of background events that are louder than it. Parameters ---------- bstat: numpy.ndarray Array of the background statistic values fstat: numpy.ndarray Array of the foreground statitsic values dec: numpy.ndarray Array of the decimation factors for the background statistics skip_background: optional, {boolean, False} Skip calculating cumulative numbers for background triggers Returns ------- cum_back_num: numpy.ndarray The cumulative array of background triggers. Does not return this argument if skip_background == True fore_n_louder: numpy.ndarray The number of background triggers above each foreground trigger """ sort = bstat.argsort() bstat = bstat[sort] dec = dec[sort] # calculate cumulative number of triggers louder than the trigger in # a given index. We need to subtract the decimation factor, as the cumsum # includes itself in the first sum (it is inclusive of the first value) n_louder = dec[::-1].cumsum()[::-1] - dec # Determine how many values are louder than the foreground ones # We need to subtract one from the index, to be consistent with the definition # of n_louder, as here we do want to include the background value at the # found index idx = numpy.searchsorted(bstat, fstat, side='left') - 1 # If the foreground are *quieter* than the background or at the same value # then the search sorted alorithm will choose position -1, which does not exist # We force it back to zero. if isinstance(idx, numpy.ndarray): # Handle the case where our input is an array idx[idx < 0] = 0 else: # Handle the case where we are simply given a scalar value if idx < 0: idx = 0 fore_n_louder = n_louder[idx] if not skip_background: unsort = sort.argsort() back_cum_num = n_louder[unsort] return back_cum_num, fore_n_louder else: return fore_n_louder
python
def calculate_n_louder(bstat, fstat, dec, skip_background=False): sort = bstat.argsort() bstat = bstat[sort] dec = dec[sort] # calculate cumulative number of triggers louder than the trigger in # a given index. We need to subtract the decimation factor, as the cumsum # includes itself in the first sum (it is inclusive of the first value) n_louder = dec[::-1].cumsum()[::-1] - dec # Determine how many values are louder than the foreground ones # We need to subtract one from the index, to be consistent with the definition # of n_louder, as here we do want to include the background value at the # found index idx = numpy.searchsorted(bstat, fstat, side='left') - 1 # If the foreground are *quieter* than the background or at the same value # then the search sorted alorithm will choose position -1, which does not exist # We force it back to zero. if isinstance(idx, numpy.ndarray): # Handle the case where our input is an array idx[idx < 0] = 0 else: # Handle the case where we are simply given a scalar value if idx < 0: idx = 0 fore_n_louder = n_louder[idx] if not skip_background: unsort = sort.argsort() back_cum_num = n_louder[unsort] return back_cum_num, fore_n_louder else: return fore_n_louder
[ "def", "calculate_n_louder", "(", "bstat", ",", "fstat", ",", "dec", ",", "skip_background", "=", "False", ")", ":", "sort", "=", "bstat", ".", "argsort", "(", ")", "bstat", "=", "bstat", "[", "sort", "]", "dec", "=", "dec", "[", "sort", "]", "# calc...
Calculate for each foreground event the number of background events that are louder than it. Parameters ---------- bstat: numpy.ndarray Array of the background statistic values fstat: numpy.ndarray Array of the foreground statitsic values dec: numpy.ndarray Array of the decimation factors for the background statistics skip_background: optional, {boolean, False} Skip calculating cumulative numbers for background triggers Returns ------- cum_back_num: numpy.ndarray The cumulative array of background triggers. Does not return this argument if skip_background == True fore_n_louder: numpy.ndarray The number of background triggers above each foreground trigger
[ "Calculate", "for", "each", "foreground", "event", "the", "number", "of", "background", "events", "that", "are", "louder", "than", "it", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc.py#L98-L152
228,047
gwastro/pycbc
pycbc/events/coinc.py
timeslide_durations
def timeslide_durations(start1, start2, end1, end2, timeslide_offsets): """ Find the coincident time for each timeslide. Find the coincident time for each timeslide, where the first time vector is slid to the right by the offset in the given timeslide_offsets vector. Parameters ---------- start1: numpy.ndarray Array of the start of valid analyzed times for detector 1 start2: numpy.ndarray Array of the start of valid analyzed times for detector 2 end1: numpy.ndarray Array of the end of valid analyzed times for detector 1 end2: numpy.ndarray Array of the end of valid analyzed times for detector 2 timseslide_offset: numpy.ndarray Array of offsets (in seconds) for each timeslide Returns -------- durations: numpy.ndarray Array of coincident time for each timeslide in the offset array """ from . import veto durations = [] seg2 = veto.start_end_to_segments(start2, end2) for offset in timeslide_offsets: seg1 = veto.start_end_to_segments(start1 + offset, end1 + offset) durations.append(abs((seg1 & seg2).coalesce())) return numpy.array(durations)
python
def timeslide_durations(start1, start2, end1, end2, timeslide_offsets): from . import veto durations = [] seg2 = veto.start_end_to_segments(start2, end2) for offset in timeslide_offsets: seg1 = veto.start_end_to_segments(start1 + offset, end1 + offset) durations.append(abs((seg1 & seg2).coalesce())) return numpy.array(durations)
[ "def", "timeslide_durations", "(", "start1", ",", "start2", ",", "end1", ",", "end2", ",", "timeslide_offsets", ")", ":", "from", ".", "import", "veto", "durations", "=", "[", "]", "seg2", "=", "veto", ".", "start_end_to_segments", "(", "start2", ",", "end...
Find the coincident time for each timeslide. Find the coincident time for each timeslide, where the first time vector is slid to the right by the offset in the given timeslide_offsets vector. Parameters ---------- start1: numpy.ndarray Array of the start of valid analyzed times for detector 1 start2: numpy.ndarray Array of the start of valid analyzed times for detector 2 end1: numpy.ndarray Array of the end of valid analyzed times for detector 1 end2: numpy.ndarray Array of the end of valid analyzed times for detector 2 timseslide_offset: numpy.ndarray Array of offsets (in seconds) for each timeslide Returns -------- durations: numpy.ndarray Array of coincident time for each timeslide in the offset array
[ "Find", "the", "coincident", "time", "for", "each", "timeslide", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc.py#L154-L184
228,048
gwastro/pycbc
pycbc/events/coinc.py
time_coincidence
def time_coincidence(t1, t2, window, slide_step=0): """ Find coincidences by time window Parameters ---------- t1 : numpy.ndarray Array of trigger times from the first detector t2 : numpy.ndarray Array of trigger times from the second detector window : float The coincidence window in seconds slide_step : optional, {None, float} If calculating background coincidences, the interval between background slides in seconds. Returns ------- idx1 : numpy.ndarray Array of indices into the t1 array. idx2 : numpy.ndarray Array of indices into the t2 array. slide : numpy.ndarray Array of slide ids """ if slide_step: fold1 = t1 % slide_step fold2 = t2 % slide_step else: fold1 = t1 fold2 = t2 sort1 = fold1.argsort() sort2 = fold2.argsort() fold1 = fold1[sort1] fold2 = fold2[sort2] if slide_step: fold2 = numpy.concatenate([fold2 - slide_step, fold2, fold2 + slide_step]) sort2 = numpy.concatenate([sort2, sort2, sort2]) left = numpy.searchsorted(fold2, fold1 - window) right = numpy.searchsorted(fold2, fold1 + window) idx1 = numpy.repeat(sort1, right-left) idx2 = [sort2[l:r] for l,r in zip(left, right)] if len(idx2) > 0: idx2 = numpy.concatenate(idx2) else: idx2 = numpy.array([], dtype=numpy.int64) if slide_step: diff = ((t1 / slide_step)[idx1] - (t2 / slide_step)[idx2]) slide = numpy.rint(diff) else: slide = numpy.zeros(len(idx1)) return idx1.astype(numpy.uint32), idx2.astype(numpy.uint32), slide.astype(numpy.int32)
python
def time_coincidence(t1, t2, window, slide_step=0): if slide_step: fold1 = t1 % slide_step fold2 = t2 % slide_step else: fold1 = t1 fold2 = t2 sort1 = fold1.argsort() sort2 = fold2.argsort() fold1 = fold1[sort1] fold2 = fold2[sort2] if slide_step: fold2 = numpy.concatenate([fold2 - slide_step, fold2, fold2 + slide_step]) sort2 = numpy.concatenate([sort2, sort2, sort2]) left = numpy.searchsorted(fold2, fold1 - window) right = numpy.searchsorted(fold2, fold1 + window) idx1 = numpy.repeat(sort1, right-left) idx2 = [sort2[l:r] for l,r in zip(left, right)] if len(idx2) > 0: idx2 = numpy.concatenate(idx2) else: idx2 = numpy.array([], dtype=numpy.int64) if slide_step: diff = ((t1 / slide_step)[idx1] - (t2 / slide_step)[idx2]) slide = numpy.rint(diff) else: slide = numpy.zeros(len(idx1)) return idx1.astype(numpy.uint32), idx2.astype(numpy.uint32), slide.astype(numpy.int32)
[ "def", "time_coincidence", "(", "t1", ",", "t2", ",", "window", ",", "slide_step", "=", "0", ")", ":", "if", "slide_step", ":", "fold1", "=", "t1", "%", "slide_step", "fold2", "=", "t2", "%", "slide_step", "else", ":", "fold1", "=", "t1", "fold2", "=...
Find coincidences by time window Parameters ---------- t1 : numpy.ndarray Array of trigger times from the first detector t2 : numpy.ndarray Array of trigger times from the second detector window : float The coincidence window in seconds slide_step : optional, {None, float} If calculating background coincidences, the interval between background slides in seconds. Returns ------- idx1 : numpy.ndarray Array of indices into the t1 array. idx2 : numpy.ndarray Array of indices into the t2 array. slide : numpy.ndarray Array of slide ids
[ "Find", "coincidences", "by", "time", "window" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc.py#L186-L243
228,049
gwastro/pycbc
pycbc/events/coinc.py
time_multi_coincidence
def time_multi_coincidence(times, slide_step=0, slop=.003, pivot='H1', fixed='L1'): """ Find multi detector concidences. Parameters ---------- times: dict of numpy.ndarrays Dictionary keyed by ifo of the times of each single detector trigger. slide_step: float The interval between time slides slop: float The amount of time to add to the TOF between detectors for coincidence pivot: str ifo used to test coincidence against in first stage fixed: str the other ifo used in the first stage coincidence which we'll use as a fixed time reference for coincident triggers. All other detectors are time slid by being fixed to this detector. """ # pivots are used to determine standard coincidence triggers, we then # pair off additional detectors to those. def win(ifo1, ifo2): d1 = Detector(ifo1) d2 = Detector(ifo2) return d1.light_travel_time_to_detector(d2) + slop # Find coincs first between the two fully time-slid detectors pivot_id, fix_id, slide = time_coincidence(times[pivot], times[fixed], win(pivot, fixed), slide_step=slide_step) # additional detectors do not slide independently of the fixed one # Each trigger in an additional detector must be concident with an # existing coincident one. All times moved to 'fixed' relative time fixed_time = times[fixed][fix_id] pivot_time = times[pivot][pivot_id] - slide_step * slide ctimes = {fixed: fixed_time, pivot:pivot_time} ids = {fixed:fix_id, pivot:pivot_id} dep_ifos = [ifo for ifo in times.keys() if ifo != fixed and ifo != pivot] for ifo1 in dep_ifos: otime = times[ifo1] sort = times[ifo1].argsort() time = otime[sort] # Find coincidences between dependent ifo triggers and existing coinc. for ifo2 in ids.keys(): # Currently assumes that additional detectors do not slide # independently of the 'fixed one' # # To modify that assumption, the code here would be modified # by adding a function that remaps the coinc time frame and unmaps # it and the end of this loop. # This remapping must ensure # * function of the standard slide number # * ensure all times remain within coincident segment # * unbiased distribution of triggers after mapping. w = win(ifo1, ifo2) left = numpy.searchsorted(time, ctimes[ifo2] - w) right = numpy.searchsorted(time, ctimes[ifo2] + w) # remove elements that will not form a coinc # There is only at most one trigger for an existing coinc # (assumes triggers spaced > slide step) nz = (right - left).nonzero() dep_ids = left[nz] # The property that only one trigger can be within the window is ensured # by the peak finding algorithm we use for each template. # If that is modifed, this function may need to be # extended. if len(left) > 0 and (right - left).max() > 1: raise ValueError('Somehow triggers are closer than time-delay window') slide = slide[nz] for ifo in ctimes: ctimes[ifo] = ctimes[ifo][nz] ids[ifo] = ids[ifo][nz] # Add this detector now to the cumulative set and proceed to the next # ifo coincidence test ids[ifo1] = sort[dep_ids] ctimes[ifo1] = otime[ids[ifo1]] return ids, slide
python
def time_multi_coincidence(times, slide_step=0, slop=.003, pivot='H1', fixed='L1'): # pivots are used to determine standard coincidence triggers, we then # pair off additional detectors to those. def win(ifo1, ifo2): d1 = Detector(ifo1) d2 = Detector(ifo2) return d1.light_travel_time_to_detector(d2) + slop # Find coincs first between the two fully time-slid detectors pivot_id, fix_id, slide = time_coincidence(times[pivot], times[fixed], win(pivot, fixed), slide_step=slide_step) # additional detectors do not slide independently of the fixed one # Each trigger in an additional detector must be concident with an # existing coincident one. All times moved to 'fixed' relative time fixed_time = times[fixed][fix_id] pivot_time = times[pivot][pivot_id] - slide_step * slide ctimes = {fixed: fixed_time, pivot:pivot_time} ids = {fixed:fix_id, pivot:pivot_id} dep_ifos = [ifo for ifo in times.keys() if ifo != fixed and ifo != pivot] for ifo1 in dep_ifos: otime = times[ifo1] sort = times[ifo1].argsort() time = otime[sort] # Find coincidences between dependent ifo triggers and existing coinc. for ifo2 in ids.keys(): # Currently assumes that additional detectors do not slide # independently of the 'fixed one' # # To modify that assumption, the code here would be modified # by adding a function that remaps the coinc time frame and unmaps # it and the end of this loop. # This remapping must ensure # * function of the standard slide number # * ensure all times remain within coincident segment # * unbiased distribution of triggers after mapping. w = win(ifo1, ifo2) left = numpy.searchsorted(time, ctimes[ifo2] - w) right = numpy.searchsorted(time, ctimes[ifo2] + w) # remove elements that will not form a coinc # There is only at most one trigger for an existing coinc # (assumes triggers spaced > slide step) nz = (right - left).nonzero() dep_ids = left[nz] # The property that only one trigger can be within the window is ensured # by the peak finding algorithm we use for each template. # If that is modifed, this function may need to be # extended. if len(left) > 0 and (right - left).max() > 1: raise ValueError('Somehow triggers are closer than time-delay window') slide = slide[nz] for ifo in ctimes: ctimes[ifo] = ctimes[ifo][nz] ids[ifo] = ids[ifo][nz] # Add this detector now to the cumulative set and proceed to the next # ifo coincidence test ids[ifo1] = sort[dep_ids] ctimes[ifo1] = otime[ids[ifo1]] return ids, slide
[ "def", "time_multi_coincidence", "(", "times", ",", "slide_step", "=", "0", ",", "slop", "=", ".003", ",", "pivot", "=", "'H1'", ",", "fixed", "=", "'L1'", ")", ":", "# pivots are used to determine standard coincidence triggers, we then", "# pair off additional detector...
Find multi detector concidences. Parameters ---------- times: dict of numpy.ndarrays Dictionary keyed by ifo of the times of each single detector trigger. slide_step: float The interval between time slides slop: float The amount of time to add to the TOF between detectors for coincidence pivot: str ifo used to test coincidence against in first stage fixed: str the other ifo used in the first stage coincidence which we'll use as a fixed time reference for coincident triggers. All other detectors are time slid by being fixed to this detector.
[ "Find", "multi", "detector", "concidences", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc.py#L246-L332
228,050
gwastro/pycbc
pycbc/events/coinc.py
mean_if_greater_than_zero
def mean_if_greater_than_zero(vals): """ Calculate mean over numerical values, ignoring values less than zero. E.g. used for mean time over coincident triggers when timestamps are set to -1 for ifos not included in the coincidence. Parameters ---------- vals: iterator of numerical values values to be mean averaged Returns ------- mean: float The mean of the values in the original vector which are greater than zero num_above_zero: int The number of entries in the vector which are above zero """ vals = numpy.array(vals) above_zero = vals > 0 return vals[above_zero].mean(), above_zero.sum()
python
def mean_if_greater_than_zero(vals): vals = numpy.array(vals) above_zero = vals > 0 return vals[above_zero].mean(), above_zero.sum()
[ "def", "mean_if_greater_than_zero", "(", "vals", ")", ":", "vals", "=", "numpy", ".", "array", "(", "vals", ")", "above_zero", "=", "vals", ">", "0", "return", "vals", "[", "above_zero", "]", ".", "mean", "(", ")", ",", "above_zero", ".", "sum", "(", ...
Calculate mean over numerical values, ignoring values less than zero. E.g. used for mean time over coincident triggers when timestamps are set to -1 for ifos not included in the coincidence. Parameters ---------- vals: iterator of numerical values values to be mean averaged Returns ------- mean: float The mean of the values in the original vector which are greater than zero num_above_zero: int The number of entries in the vector which are above zero
[ "Calculate", "mean", "over", "numerical", "values", "ignoring", "values", "less", "than", "zero", ".", "E", ".", "g", ".", "used", "for", "mean", "time", "over", "coincident", "triggers", "when", "timestamps", "are", "set", "to", "-", "1", "for", "ifos", ...
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc.py#L432-L452
228,051
gwastro/pycbc
pycbc/events/coinc.py
cluster_over_time
def cluster_over_time(stat, time, window, argmax=numpy.argmax): """Cluster generalized transient events over time via maximum stat over a symmetric sliding window Parameters ---------- stat: numpy.ndarray vector of ranking values to maximize time: numpy.ndarray time to use for clustering window: float length to cluster over argmax: function the function used to calculate the maximum value Returns ------- cindex: numpy.ndarray The set of indices corresponding to the surviving coincidences. """ logging.info('Clustering events over %s s window', window) indices = [] time_sorting = time.argsort() stat = stat[time_sorting] time = time[time_sorting] left = numpy.searchsorted(time, time - window) right = numpy.searchsorted(time, time + window) indices = numpy.zeros(len(left), dtype=numpy.uint32) # i is the index we are inspecting, j is the next one to save i = 0 j = 0 while i < len(left): l = left[i] r = right[i] # If there are no other points to compare it is obviously the max if (r - l) == 1: indices[j] = i j += 1 i += 1 continue # Find the location of the maximum within the time interval around i max_loc = argmax(stat[l:r]) + l # If this point is the max, we can skip to the right boundary if max_loc == i: indices[j] = i i = r j += 1 # If the max is later than i, we can skip to it elif max_loc > i: i = max_loc elif max_loc < i: i += 1 indices = indices[:j] logging.info('%d triggers remaining', len(indices)) return time_sorting[indices]
python
def cluster_over_time(stat, time, window, argmax=numpy.argmax): logging.info('Clustering events over %s s window', window) indices = [] time_sorting = time.argsort() stat = stat[time_sorting] time = time[time_sorting] left = numpy.searchsorted(time, time - window) right = numpy.searchsorted(time, time + window) indices = numpy.zeros(len(left), dtype=numpy.uint32) # i is the index we are inspecting, j is the next one to save i = 0 j = 0 while i < len(left): l = left[i] r = right[i] # If there are no other points to compare it is obviously the max if (r - l) == 1: indices[j] = i j += 1 i += 1 continue # Find the location of the maximum within the time interval around i max_loc = argmax(stat[l:r]) + l # If this point is the max, we can skip to the right boundary if max_loc == i: indices[j] = i i = r j += 1 # If the max is later than i, we can skip to it elif max_loc > i: i = max_loc elif max_loc < i: i += 1 indices = indices[:j] logging.info('%d triggers remaining', len(indices)) return time_sorting[indices]
[ "def", "cluster_over_time", "(", "stat", ",", "time", ",", "window", ",", "argmax", "=", "numpy", ".", "argmax", ")", ":", "logging", ".", "info", "(", "'Clustering events over %s s window'", ",", "window", ")", "indices", "=", "[", "]", "time_sorting", "=",...
Cluster generalized transient events over time via maximum stat over a symmetric sliding window Parameters ---------- stat: numpy.ndarray vector of ranking values to maximize time: numpy.ndarray time to use for clustering window: float length to cluster over argmax: function the function used to calculate the maximum value Returns ------- cindex: numpy.ndarray The set of indices corresponding to the surviving coincidences.
[ "Cluster", "generalized", "transient", "events", "over", "time", "via", "maximum", "stat", "over", "a", "symmetric", "sliding", "window" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc.py#L454-L518
228,052
gwastro/pycbc
pycbc/events/coinc.py
MultiRingBuffer.discard_last
def discard_last(self, indices): """Discard the triggers added in the latest update""" for i in indices: self.buffer_expire[i] = self.buffer_expire[i][:-1] self.buffer[i] = self.buffer[i][:-1]
python
def discard_last(self, indices): for i in indices: self.buffer_expire[i] = self.buffer_expire[i][:-1] self.buffer[i] = self.buffer[i][:-1]
[ "def", "discard_last", "(", "self", ",", "indices", ")", ":", "for", "i", "in", "indices", ":", "self", ".", "buffer_expire", "[", "i", "]", "=", "self", ".", "buffer_expire", "[", "i", "]", "[", ":", "-", "1", "]", "self", ".", "buffer", "[", "i...
Discard the triggers added in the latest update
[ "Discard", "the", "triggers", "added", "in", "the", "latest", "update" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc.py#L555-L559
228,053
gwastro/pycbc
pycbc/events/coinc.py
MultiRingBuffer.add
def add(self, indices, values): """Add triggers in 'values' to the buffers indicated by the indices """ for i, v in zip(indices, values): self.buffer[i] = numpy.append(self.buffer[i], v) self.buffer_expire[i] = numpy.append(self.buffer_expire[i], self.time) self.advance_time()
python
def add(self, indices, values): for i, v in zip(indices, values): self.buffer[i] = numpy.append(self.buffer[i], v) self.buffer_expire[i] = numpy.append(self.buffer_expire[i], self.time) self.advance_time()
[ "def", "add", "(", "self", ",", "indices", ",", "values", ")", ":", "for", "i", ",", "v", "in", "zip", "(", "indices", ",", "values", ")", ":", "self", ".", "buffer", "[", "i", "]", "=", "numpy", ".", "append", "(", "self", ".", "buffer", "[", ...
Add triggers in 'values' to the buffers indicated by the indices
[ "Add", "triggers", "in", "values", "to", "the", "buffers", "indicated", "by", "the", "indices" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc.py#L567-L573
228,054
gwastro/pycbc
pycbc/events/coinc.py
MultiRingBuffer.data
def data(self, buffer_index): """Return the data vector for a given ring buffer""" # Check for expired elements and discard if they exist expired = self.time - self.max_time exp = self.buffer_expire[buffer_index] j = 0 while j < len(exp): # Everything before this j must be expired if exp[j] >= expired: self.buffer_expire[buffer_index] = exp[j:].copy() self.buffer[buffer_index] = self.buffer[buffer_index][j:].copy() break j += 1 return self.buffer[buffer_index]
python
def data(self, buffer_index): # Check for expired elements and discard if they exist expired = self.time - self.max_time exp = self.buffer_expire[buffer_index] j = 0 while j < len(exp): # Everything before this j must be expired if exp[j] >= expired: self.buffer_expire[buffer_index] = exp[j:].copy() self.buffer[buffer_index] = self.buffer[buffer_index][j:].copy() break j += 1 return self.buffer[buffer_index]
[ "def", "data", "(", "self", ",", "buffer_index", ")", ":", "# Check for expired elements and discard if they exist", "expired", "=", "self", ".", "time", "-", "self", ".", "max_time", "exp", "=", "self", ".", "buffer_expire", "[", "buffer_index", "]", "j", "=", ...
Return the data vector for a given ring buffer
[ "Return", "the", "data", "vector", "for", "a", "given", "ring", "buffer" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc.py#L579-L593
228,055
gwastro/pycbc
pycbc/events/coinc.py
CoincExpireBuffer.add
def add(self, values, times, ifos): """Add values to the internal buffer Parameters ---------- values: numpy.ndarray Array of elements to add to the internal buffer. times: dict of arrays The current time to use for each element being added. ifos: list of strs The set of timers to be incremented. """ for ifo in ifos: self.time[ifo] += 1 # Resize the internal buffer if we need more space if self.index + len(values) >= len(self.buffer): newlen = len(self.buffer) * 2 for ifo in self.ifos: self.timer[ifo].resize(newlen) self.buffer.resize(newlen) self.buffer[self.index:self.index+len(values)] = values if len(values) > 0: for ifo in self.ifos: self.timer[ifo][self.index:self.index+len(values)] = times[ifo] self.index += len(values) # Remove the expired old elements keep = None for ifo in ifos: kt = self.timer[ifo][:self.index] >= self.time[ifo] - self.expiration keep = numpy.logical_and(keep, kt) if keep is not None else kt self.buffer[:keep.sum()] = self.buffer[:self.index][keep] for ifo in self.ifos: self.timer[ifo][:keep.sum()] = self.timer[ifo][:self.index][keep] self.index = keep.sum()
python
def add(self, values, times, ifos): for ifo in ifos: self.time[ifo] += 1 # Resize the internal buffer if we need more space if self.index + len(values) >= len(self.buffer): newlen = len(self.buffer) * 2 for ifo in self.ifos: self.timer[ifo].resize(newlen) self.buffer.resize(newlen) self.buffer[self.index:self.index+len(values)] = values if len(values) > 0: for ifo in self.ifos: self.timer[ifo][self.index:self.index+len(values)] = times[ifo] self.index += len(values) # Remove the expired old elements keep = None for ifo in ifos: kt = self.timer[ifo][:self.index] >= self.time[ifo] - self.expiration keep = numpy.logical_and(keep, kt) if keep is not None else kt self.buffer[:keep.sum()] = self.buffer[:self.index][keep] for ifo in self.ifos: self.timer[ifo][:keep.sum()] = self.timer[ifo][:self.index][keep] self.index = keep.sum()
[ "def", "add", "(", "self", ",", "values", ",", "times", ",", "ifos", ")", ":", "for", "ifo", "in", "ifos", ":", "self", ".", "time", "[", "ifo", "]", "+=", "1", "# Resize the internal buffer if we need more space", "if", "self", ".", "index", "+", "len",...
Add values to the internal buffer Parameters ---------- values: numpy.ndarray Array of elements to add to the internal buffer. times: dict of arrays The current time to use for each element being added. ifos: list of strs The set of timers to be incremented.
[ "Add", "values", "to", "the", "internal", "buffer" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc.py#L642-L681
228,056
gwastro/pycbc
pycbc/events/coinc.py
LiveCoincTimeslideBackgroundEstimator.pick_best_coinc
def pick_best_coinc(cls, coinc_results): """Choose the best two-ifo coinc by ifar first, then statistic if needed. This function picks which of the available double-ifo coincs to use. It chooses the best (highest) ifar. The ranking statistic is used as a tie-breaker. A trials factor is applied if multiple types of coincs are possible at this time given the active ifos. Parameters ---------- coinc_results: list of coinc result dicts Dictionary by detector pair of coinc result dicts. Returns ------- best: coinc results dict If there is a coinc, this will contain the 'best' one. Otherwise it will return the provided dict. """ mstat = 0 mifar = 0 mresult = None # record the trials factor from the possible coincs we could # maximize over trials = 0 for result in coinc_results: # Check that a coinc was possible. See the 'add_singles' method # to see where this flag was added into the results dict if 'coinc_possible' in result: trials += 1 # Check that a coinc exists if 'foreground/ifar' in result: ifar = result['foreground/ifar'] stat = result['foreground/stat'] if ifar > mifar or (ifar == mifar and stat > mstat): mifar = ifar mstat = stat mresult = result # apply trials factor for the best coinc if mresult: mresult['foreground/ifar'] = mifar / float(trials) logging.info('Found %s coinc with ifar %s', mresult['foreground/type'], mresult['foreground/ifar']) return mresult # If no coinc, just return one of the results dictionaries. They will # all contain the same results (i.e. single triggers) in this case. else: return coinc_results[0]
python
def pick_best_coinc(cls, coinc_results): mstat = 0 mifar = 0 mresult = None # record the trials factor from the possible coincs we could # maximize over trials = 0 for result in coinc_results: # Check that a coinc was possible. See the 'add_singles' method # to see where this flag was added into the results dict if 'coinc_possible' in result: trials += 1 # Check that a coinc exists if 'foreground/ifar' in result: ifar = result['foreground/ifar'] stat = result['foreground/stat'] if ifar > mifar or (ifar == mifar and stat > mstat): mifar = ifar mstat = stat mresult = result # apply trials factor for the best coinc if mresult: mresult['foreground/ifar'] = mifar / float(trials) logging.info('Found %s coinc with ifar %s', mresult['foreground/type'], mresult['foreground/ifar']) return mresult # If no coinc, just return one of the results dictionaries. They will # all contain the same results (i.e. single triggers) in this case. else: return coinc_results[0]
[ "def", "pick_best_coinc", "(", "cls", ",", "coinc_results", ")", ":", "mstat", "=", "0", "mifar", "=", "0", "mresult", "=", "None", "# record the trials factor from the possible coincs we could", "# maximize over", "trials", "=", "0", "for", "result", "in", "coinc_r...
Choose the best two-ifo coinc by ifar first, then statistic if needed. This function picks which of the available double-ifo coincs to use. It chooses the best (highest) ifar. The ranking statistic is used as a tie-breaker. A trials factor is applied if multiple types of coincs are possible at this time given the active ifos. Parameters ---------- coinc_results: list of coinc result dicts Dictionary by detector pair of coinc result dicts. Returns ------- best: coinc results dict If there is a coinc, this will contain the 'best' one. Otherwise it will return the provided dict.
[ "Choose", "the", "best", "two", "-", "ifo", "coinc", "by", "ifar", "first", "then", "statistic", "if", "needed", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc.py#L761-L813
228,057
gwastro/pycbc
pycbc/events/coinc.py
LiveCoincTimeslideBackgroundEstimator.background_time
def background_time(self): """Return the amount of background time that the buffers contain""" time = 1.0 / self.timeslide_interval for ifo in self.singles: time *= self.singles[ifo].filled_time * self.analysis_block return time
python
def background_time(self): time = 1.0 / self.timeslide_interval for ifo in self.singles: time *= self.singles[ifo].filled_time * self.analysis_block return time
[ "def", "background_time", "(", "self", ")", ":", "time", "=", "1.0", "/", "self", ".", "timeslide_interval", "for", "ifo", "in", "self", ".", "singles", ":", "time", "*=", "self", ".", "singles", "[", "ifo", "]", ".", "filled_time", "*", "self", ".", ...
Return the amount of background time that the buffers contain
[ "Return", "the", "amount", "of", "background", "time", "that", "the", "buffers", "contain" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc.py#L847-L852
228,058
gwastro/pycbc
pycbc/events/coinc.py
LiveCoincTimeslideBackgroundEstimator.ifar
def ifar(self, coinc_stat): """Return the far that would be associated with the coincident given. """ n = self.coincs.num_greater(coinc_stat) return self.background_time / lal.YRJUL_SI / (n + 1)
python
def ifar(self, coinc_stat): n = self.coincs.num_greater(coinc_stat) return self.background_time / lal.YRJUL_SI / (n + 1)
[ "def", "ifar", "(", "self", ",", "coinc_stat", ")", ":", "n", "=", "self", ".", "coincs", ".", "num_greater", "(", "coinc_stat", ")", "return", "self", ".", "background_time", "/", "lal", ".", "YRJUL_SI", "/", "(", "n", "+", "1", ")" ]
Return the far that would be associated with the coincident given.
[ "Return", "the", "far", "that", "would", "be", "associated", "with", "the", "coincident", "given", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc.py#L865-L869
228,059
gwastro/pycbc
pycbc/events/coinc.py
LiveCoincTimeslideBackgroundEstimator.set_singles_buffer
def set_singles_buffer(self, results): """Create the singles buffer This creates the singles buffer for each ifo. The dtype is determined by a representative sample of the single triggers in the results. Parameters ---------- restuls: dict of dict Dict indexed by ifo and then trigger column. """ # Determine the dtype from a sample of the data. self.singles_dtype = [] data = False for ifo in self.ifos: if ifo in results and results[ifo] is not False: data = results[ifo] break if data is False: return for key in data: self.singles_dtype.append((key, data[key].dtype)) if 'stat' not in data: self.singles_dtype.append(('stat', self.stat_calculator.single_dtype)) # Create a ring buffer for each template ifo combination for ifo in self.ifos: self.singles[ifo] = MultiRingBuffer(self.num_templates, self.buffer_size, self.singles_dtype)
python
def set_singles_buffer(self, results): # Determine the dtype from a sample of the data. self.singles_dtype = [] data = False for ifo in self.ifos: if ifo in results and results[ifo] is not False: data = results[ifo] break if data is False: return for key in data: self.singles_dtype.append((key, data[key].dtype)) if 'stat' not in data: self.singles_dtype.append(('stat', self.stat_calculator.single_dtype)) # Create a ring buffer for each template ifo combination for ifo in self.ifos: self.singles[ifo] = MultiRingBuffer(self.num_templates, self.buffer_size, self.singles_dtype)
[ "def", "set_singles_buffer", "(", "self", ",", "results", ")", ":", "# Determine the dtype from a sample of the data.", "self", ".", "singles_dtype", "=", "[", "]", "data", "=", "False", "for", "ifo", "in", "self", ".", "ifos", ":", "if", "ifo", "in", "results...
Create the singles buffer This creates the singles buffer for each ifo. The dtype is determined by a representative sample of the single triggers in the results. Parameters ---------- restuls: dict of dict Dict indexed by ifo and then trigger column.
[ "Create", "the", "singles", "buffer" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc.py#L871-L903
228,060
gwastro/pycbc
pycbc/events/coinc.py
LiveCoincTimeslideBackgroundEstimator._add_singles_to_buffer
def _add_singles_to_buffer(self, results, ifos): """Add single detector triggers to the internal buffer Parameters ---------- results: dict of arrays Dictionary of dictionaries indexed by ifo and keys such as 'snr', 'chisq', etc. The specific format it determined by the LiveBatchMatchedFilter class. Returns ------- updated_singles: dict of numpy.ndarrays Array of indices that have been just updated in the internal buffers of single detector triggers. """ if len(self.singles.keys()) == 0: self.set_singles_buffer(results) # convert to single detector trigger values # FIXME Currently configured to use pycbc live output # where chisq is the reduced chisq and chisq_dof is the actual DOF logging.info("adding singles to the background estimate...") updated_indices = {} for ifo in ifos: trigs = results[ifo] if len(trigs['snr'] > 0): trigsc = copy.copy(trigs) trigsc['chisq'] = trigs['chisq'] * trigs['chisq_dof'] trigsc['chisq_dof'] = (trigs['chisq_dof'] + 2) / 2 single_stat = self.stat_calculator.single(trigsc) else: single_stat = numpy.array([], ndmin=1, dtype=self.stat_calculator.single_dtype) trigs['stat'] = single_stat # add each single detector trigger to the and advance the buffer data = numpy.zeros(len(single_stat), dtype=self.singles_dtype) for key, value in trigs.items(): data[key] = value self.singles[ifo].add(trigs['template_id'], data) updated_indices[ifo] = trigs['template_id'] return updated_indices
python
def _add_singles_to_buffer(self, results, ifos): if len(self.singles.keys()) == 0: self.set_singles_buffer(results) # convert to single detector trigger values # FIXME Currently configured to use pycbc live output # where chisq is the reduced chisq and chisq_dof is the actual DOF logging.info("adding singles to the background estimate...") updated_indices = {} for ifo in ifos: trigs = results[ifo] if len(trigs['snr'] > 0): trigsc = copy.copy(trigs) trigsc['chisq'] = trigs['chisq'] * trigs['chisq_dof'] trigsc['chisq_dof'] = (trigs['chisq_dof'] + 2) / 2 single_stat = self.stat_calculator.single(trigsc) else: single_stat = numpy.array([], ndmin=1, dtype=self.stat_calculator.single_dtype) trigs['stat'] = single_stat # add each single detector trigger to the and advance the buffer data = numpy.zeros(len(single_stat), dtype=self.singles_dtype) for key, value in trigs.items(): data[key] = value self.singles[ifo].add(trigs['template_id'], data) updated_indices[ifo] = trigs['template_id'] return updated_indices
[ "def", "_add_singles_to_buffer", "(", "self", ",", "results", ",", "ifos", ")", ":", "if", "len", "(", "self", ".", "singles", ".", "keys", "(", ")", ")", "==", "0", ":", "self", ".", "set_singles_buffer", "(", "results", ")", "# convert to single detector...
Add single detector triggers to the internal buffer Parameters ---------- results: dict of arrays Dictionary of dictionaries indexed by ifo and keys such as 'snr', 'chisq', etc. The specific format it determined by the LiveBatchMatchedFilter class. Returns ------- updated_singles: dict of numpy.ndarrays Array of indices that have been just updated in the internal buffers of single detector triggers.
[ "Add", "single", "detector", "triggers", "to", "the", "internal", "buffer" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc.py#L905-L949
228,061
gwastro/pycbc
pycbc/events/coinc.py
LiveCoincTimeslideBackgroundEstimator.backout_last
def backout_last(self, updated_singles, num_coincs): """Remove the recently added singles and coincs Parameters ---------- updated_singles: dict of numpy.ndarrays Array of indices that have been just updated in the internal buffers of single detector triggers. num_coincs: int The number of coincs that were just added to the internal buffer of coincident triggers """ for ifo in updated_singles: self.singles[ifo].discard_last(updated_singles[ifo]) self.coincs.remove(num_coincs)
python
def backout_last(self, updated_singles, num_coincs): for ifo in updated_singles: self.singles[ifo].discard_last(updated_singles[ifo]) self.coincs.remove(num_coincs)
[ "def", "backout_last", "(", "self", ",", "updated_singles", ",", "num_coincs", ")", ":", "for", "ifo", "in", "updated_singles", ":", "self", ".", "singles", "[", "ifo", "]", ".", "discard_last", "(", "updated_singles", "[", "ifo", "]", ")", "self", ".", ...
Remove the recently added singles and coincs Parameters ---------- updated_singles: dict of numpy.ndarrays Array of indices that have been just updated in the internal buffers of single detector triggers. num_coincs: int The number of coincs that were just added to the internal buffer of coincident triggers
[ "Remove", "the", "recently", "added", "singles", "and", "coincs" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc.py#L1081-L1095
228,062
gwastro/pycbc
pycbc/events/coinc.py
LiveCoincTimeslideBackgroundEstimator.add_singles
def add_singles(self, results): """Add singles to the bacckground estimate and find candidates Parameters ---------- results: dict of arrays Dictionary of dictionaries indexed by ifo and keys such as 'snr', 'chisq', etc. The specific format it determined by the LiveBatchMatchedFilter class. Returns ------- coinc_results: dict of arrays A dictionary of arrays containing the coincident results. """ # Let's see how large everything is logging.info('BKG Coincs %s stored %s bytes', len(self.coincs), self.coincs.nbytes) # If there are no results just return valid_ifos = [k for k in results.keys() if results[k] and k in self.ifos] if len(valid_ifos) == 0: return {} # Add single triggers to the internal buffer self._add_singles_to_buffer(results, ifos=valid_ifos) # Calculate zerolag and background coincidences _, coinc_results = self._find_coincs(results, ifos=valid_ifos) # record if a coinc is possible in this chunk if len(valid_ifos) == 2: coinc_results['coinc_possible'] = True return coinc_results
python
def add_singles(self, results): # Let's see how large everything is logging.info('BKG Coincs %s stored %s bytes', len(self.coincs), self.coincs.nbytes) # If there are no results just return valid_ifos = [k for k in results.keys() if results[k] and k in self.ifos] if len(valid_ifos) == 0: return {} # Add single triggers to the internal buffer self._add_singles_to_buffer(results, ifos=valid_ifos) # Calculate zerolag and background coincidences _, coinc_results = self._find_coincs(results, ifos=valid_ifos) # record if a coinc is possible in this chunk if len(valid_ifos) == 2: coinc_results['coinc_possible'] = True return coinc_results
[ "def", "add_singles", "(", "self", ",", "results", ")", ":", "# Let's see how large everything is", "logging", ".", "info", "(", "'BKG Coincs %s stored %s bytes'", ",", "len", "(", "self", ".", "coincs", ")", ",", "self", ".", "coincs", ".", "nbytes", ")", "# ...
Add singles to the bacckground estimate and find candidates Parameters ---------- results: dict of arrays Dictionary of dictionaries indexed by ifo and keys such as 'snr', 'chisq', etc. The specific format it determined by the LiveBatchMatchedFilter class. Returns ------- coinc_results: dict of arrays A dictionary of arrays containing the coincident results.
[ "Add", "singles", "to", "the", "bacckground", "estimate", "and", "find", "candidates" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc.py#L1097-L1130
228,063
gwastro/pycbc
pycbc/distributions/spins.py
IndependentChiPChiEff._constraints
def _constraints(self, values): """Applies physical constraints to the given parameter values. Parameters ---------- values : {arr or dict} A dictionary or structured array giving the values. Returns ------- bool Whether or not the values satisfy physical """ mass1, mass2, phi_a, phi_s, chi_eff, chi_a, xi1, xi2, _ = \ conversions.ensurearray(values['mass1'], values['mass2'], values['phi_a'], values['phi_s'], values['chi_eff'], values['chi_a'], values['xi1'], values['xi2']) s1x = conversions.spin1x_from_xi1_phi_a_phi_s(xi1, phi_a, phi_s) s2x = conversions.spin2x_from_mass1_mass2_xi2_phi_a_phi_s(mass1, mass2, xi2, phi_a, phi_s) s1y = conversions.spin1y_from_xi1_phi_a_phi_s(xi1, phi_a, phi_s) s2y = conversions.spin2y_from_mass1_mass2_xi2_phi_a_phi_s(mass1, mass2, xi2, phi_a, phi_s) s1z = conversions.spin1z_from_mass1_mass2_chi_eff_chi_a(mass1, mass2, chi_eff, chi_a) s2z = conversions.spin2z_from_mass1_mass2_chi_eff_chi_a(mass1, mass2, chi_eff, chi_a) test = ((s1x**2. + s1y**2. + s1z**2.) < 1.) & \ ((s2x**2. + s2y**2. + s2z**2.) < 1.) return test
python
def _constraints(self, values): mass1, mass2, phi_a, phi_s, chi_eff, chi_a, xi1, xi2, _ = \ conversions.ensurearray(values['mass1'], values['mass2'], values['phi_a'], values['phi_s'], values['chi_eff'], values['chi_a'], values['xi1'], values['xi2']) s1x = conversions.spin1x_from_xi1_phi_a_phi_s(xi1, phi_a, phi_s) s2x = conversions.spin2x_from_mass1_mass2_xi2_phi_a_phi_s(mass1, mass2, xi2, phi_a, phi_s) s1y = conversions.spin1y_from_xi1_phi_a_phi_s(xi1, phi_a, phi_s) s2y = conversions.spin2y_from_mass1_mass2_xi2_phi_a_phi_s(mass1, mass2, xi2, phi_a, phi_s) s1z = conversions.spin1z_from_mass1_mass2_chi_eff_chi_a(mass1, mass2, chi_eff, chi_a) s2z = conversions.spin2z_from_mass1_mass2_chi_eff_chi_a(mass1, mass2, chi_eff, chi_a) test = ((s1x**2. + s1y**2. + s1z**2.) < 1.) & \ ((s2x**2. + s2y**2. + s2z**2.) < 1.) return test
[ "def", "_constraints", "(", "self", ",", "values", ")", ":", "mass1", ",", "mass2", ",", "phi_a", ",", "phi_s", ",", "chi_eff", ",", "chi_a", ",", "xi1", ",", "xi2", ",", "_", "=", "conversions", ".", "ensurearray", "(", "values", "[", "'mass1'", "]"...
Applies physical constraints to the given parameter values. Parameters ---------- values : {arr or dict} A dictionary or structured array giving the values. Returns ------- bool Whether or not the values satisfy physical
[ "Applies", "physical", "constraints", "to", "the", "given", "parameter", "values", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/distributions/spins.py#L134-L164
228,064
gwastro/pycbc
pycbc/distributions/spins.py
IndependentChiPChiEff._draw
def _draw(self, size=1, **kwargs): """Draws random samples without applying physical constrains. """ # draw masses try: mass1 = kwargs['mass1'] except KeyError: mass1 = self.mass1_distr.rvs(size=size)['mass1'] try: mass2 = kwargs['mass2'] except KeyError: mass2 = self.mass2_distr.rvs(size=size)['mass2'] # draw angles try: phi_a = kwargs['phi_a'] except KeyError: phi_a = self.phia_distr.rvs(size=size)['phi_a'] try: phi_s = kwargs['phi_s'] except KeyError: phi_s = self.phis_distr.rvs(size=size)['phi_s'] # draw chi_eff, chi_a try: chi_eff = kwargs['chi_eff'] except KeyError: chi_eff = self.chieff_distr.rvs(size=size)['chi_eff'] try: chi_a = kwargs['chi_a'] except KeyError: chi_a = self.chia_distr.rvs(size=size)['chi_a'] # draw xis try: xi1 = kwargs['xi1'] except KeyError: xi1 = self.xi1_distr.rvs(size=size)['xi1'] try: xi2 = kwargs['xi2'] except KeyError: xi2 = self.xi2_distr.rvs(size=size)['xi2'] dtype = [(p, float) for p in self.params] arr = numpy.zeros(size, dtype=dtype) arr['mass1'] = mass1 arr['mass2'] = mass2 arr['phi_a'] = phi_a arr['phi_s'] = phi_s arr['chi_eff'] = chi_eff arr['chi_a'] = chi_a arr['xi1'] = xi1 arr['xi2'] = xi2 return arr
python
def _draw(self, size=1, **kwargs): # draw masses try: mass1 = kwargs['mass1'] except KeyError: mass1 = self.mass1_distr.rvs(size=size)['mass1'] try: mass2 = kwargs['mass2'] except KeyError: mass2 = self.mass2_distr.rvs(size=size)['mass2'] # draw angles try: phi_a = kwargs['phi_a'] except KeyError: phi_a = self.phia_distr.rvs(size=size)['phi_a'] try: phi_s = kwargs['phi_s'] except KeyError: phi_s = self.phis_distr.rvs(size=size)['phi_s'] # draw chi_eff, chi_a try: chi_eff = kwargs['chi_eff'] except KeyError: chi_eff = self.chieff_distr.rvs(size=size)['chi_eff'] try: chi_a = kwargs['chi_a'] except KeyError: chi_a = self.chia_distr.rvs(size=size)['chi_a'] # draw xis try: xi1 = kwargs['xi1'] except KeyError: xi1 = self.xi1_distr.rvs(size=size)['xi1'] try: xi2 = kwargs['xi2'] except KeyError: xi2 = self.xi2_distr.rvs(size=size)['xi2'] dtype = [(p, float) for p in self.params] arr = numpy.zeros(size, dtype=dtype) arr['mass1'] = mass1 arr['mass2'] = mass2 arr['phi_a'] = phi_a arr['phi_s'] = phi_s arr['chi_eff'] = chi_eff arr['chi_a'] = chi_a arr['xi1'] = xi1 arr['xi2'] = xi2 return arr
[ "def", "_draw", "(", "self", ",", "size", "=", "1", ",", "*", "*", "kwargs", ")", ":", "# draw masses", "try", ":", "mass1", "=", "kwargs", "[", "'mass1'", "]", "except", "KeyError", ":", "mass1", "=", "self", ".", "mass1_distr", ".", "rvs", "(", "...
Draws random samples without applying physical constrains.
[ "Draws", "random", "samples", "without", "applying", "physical", "constrains", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/distributions/spins.py#L176-L225
228,065
gwastro/pycbc
pycbc/distributions/spins.py
IndependentChiPChiEff.rvs
def rvs(self, size=1, **kwargs): """Returns random values for all of the parameters. """ size = int(size) dtype = [(p, float) for p in self.params] arr = numpy.zeros(size, dtype=dtype) remaining = size keepidx = 0 while remaining: draws = self._draw(size=remaining, **kwargs) mask = self._constraints(draws) addpts = mask.sum() arr[keepidx:keepidx+addpts] = draws[mask] keepidx += addpts remaining = size - keepidx return arr
python
def rvs(self, size=1, **kwargs): size = int(size) dtype = [(p, float) for p in self.params] arr = numpy.zeros(size, dtype=dtype) remaining = size keepidx = 0 while remaining: draws = self._draw(size=remaining, **kwargs) mask = self._constraints(draws) addpts = mask.sum() arr[keepidx:keepidx+addpts] = draws[mask] keepidx += addpts remaining = size - keepidx return arr
[ "def", "rvs", "(", "self", ",", "size", "=", "1", ",", "*", "*", "kwargs", ")", ":", "size", "=", "int", "(", "size", ")", "dtype", "=", "[", "(", "p", ",", "float", ")", "for", "p", "in", "self", ".", "params", "]", "arr", "=", "numpy", "....
Returns random values for all of the parameters.
[ "Returns", "random", "values", "for", "all", "of", "the", "parameters", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/distributions/spins.py#L231-L246
228,066
gwastro/pycbc
pycbc/catalog/catalog.py
get_source
def get_source(source): """Get the source data for a particular GW catalog """ if source == 'gwtc-1': fname = download_file(gwtc1_url, cache=True) data = json.load(open(fname, 'r')) else: raise ValueError('Unkown catalog source {}'.format(source)) return data['data']
python
def get_source(source): if source == 'gwtc-1': fname = download_file(gwtc1_url, cache=True) data = json.load(open(fname, 'r')) else: raise ValueError('Unkown catalog source {}'.format(source)) return data['data']
[ "def", "get_source", "(", "source", ")", ":", "if", "source", "==", "'gwtc-1'", ":", "fname", "=", "download_file", "(", "gwtc1_url", ",", "cache", "=", "True", ")", "data", "=", "json", ".", "load", "(", "open", "(", "fname", ",", "'r'", ")", ")", ...
Get the source data for a particular GW catalog
[ "Get", "the", "source", "data", "for", "a", "particular", "GW", "catalog" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/catalog/catalog.py#L38-L46
228,067
gwastro/pycbc
pycbc/__init__.py
init_logging
def init_logging(verbose=False, format='%(asctime)s %(message)s'): """ Common utility for setting up logging in PyCBC. Installs a signal handler such that verbosity can be activated at run-time by sending a SIGUSR1 to the process. """ def sig_handler(signum, frame): logger = logging.getLogger() log_level = logger.level if log_level == logging.DEBUG: log_level = logging.WARN else: log_level = logging.DEBUG logging.warn('Got signal %d, setting log level to %d', signum, log_level) logger.setLevel(log_level) signal.signal(signal.SIGUSR1, sig_handler) if verbose: initial_level = logging.DEBUG else: initial_level = logging.WARN logging.getLogger().setLevel(initial_level) logging.basicConfig(format=format, level=initial_level)
python
def init_logging(verbose=False, format='%(asctime)s %(message)s'): def sig_handler(signum, frame): logger = logging.getLogger() log_level = logger.level if log_level == logging.DEBUG: log_level = logging.WARN else: log_level = logging.DEBUG logging.warn('Got signal %d, setting log level to %d', signum, log_level) logger.setLevel(log_level) signal.signal(signal.SIGUSR1, sig_handler) if verbose: initial_level = logging.DEBUG else: initial_level = logging.WARN logging.getLogger().setLevel(initial_level) logging.basicConfig(format=format, level=initial_level)
[ "def", "init_logging", "(", "verbose", "=", "False", ",", "format", "=", "'%(asctime)s %(message)s'", ")", ":", "def", "sig_handler", "(", "signum", ",", "frame", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", ")", "log_level", "=", "logger", "...
Common utility for setting up logging in PyCBC. Installs a signal handler such that verbosity can be activated at run-time by sending a SIGUSR1 to the process.
[ "Common", "utility", "for", "setting", "up", "logging", "in", "PyCBC", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/__init__.py#L47-L71
228,068
gwastro/pycbc
pycbc/__init__.py
makedir
def makedir(path): """ Make the analysis directory path and any parent directories that don't already exist. Will do nothing if path already exists. """ if path is not None and not os.path.exists(path): os.makedirs(path)
python
def makedir(path): if path is not None and not os.path.exists(path): os.makedirs(path)
[ "def", "makedir", "(", "path", ")", ":", "if", "path", "is", "not", "None", "and", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "makedirs", "(", "path", ")" ]
Make the analysis directory path and any parent directories that don't already exist. Will do nothing if path already exists.
[ "Make", "the", "analysis", "directory", "path", "and", "any", "parent", "directories", "that", "don", "t", "already", "exist", ".", "Will", "do", "nothing", "if", "path", "already", "exists", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/__init__.py#L73-L79
228,069
gwastro/pycbc
pycbc/workflow/core.py
check_output_error_and_retcode
def check_output_error_and_retcode(*popenargs, **kwargs): """ This function is used to obtain the stdout of a command. It is only used internally, recommend using the make_external_call command if you want to call external executables. """ if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') process = subprocess.Popen(stdout=subprocess.PIPE, stderr=subprocess.PIPE, *popenargs, **kwargs) output, error = process.communicate() retcode = process.poll() return output, error, retcode
python
def check_output_error_and_retcode(*popenargs, **kwargs): if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') process = subprocess.Popen(stdout=subprocess.PIPE, stderr=subprocess.PIPE, *popenargs, **kwargs) output, error = process.communicate() retcode = process.poll() return output, error, retcode
[ "def", "check_output_error_and_retcode", "(", "*", "popenargs", ",", "*", "*", "kwargs", ")", ":", "if", "'stdout'", "in", "kwargs", ":", "raise", "ValueError", "(", "'stdout argument not allowed, it will be overridden.'", ")", "process", "=", "subprocess", ".", "Po...
This function is used to obtain the stdout of a command. It is only used internally, recommend using the make_external_call command if you want to call external executables.
[ "This", "function", "is", "used", "to", "obtain", "the", "stdout", "of", "a", "command", ".", "It", "is", "only", "used", "internally", "recommend", "using", "the", "make_external_call", "command", "if", "you", "want", "to", "call", "external", "executables", ...
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L54-L67
228,070
gwastro/pycbc
pycbc/workflow/core.py
get_full_analysis_chunk
def get_full_analysis_chunk(science_segs): """ Function to find the first and last time point contained in the science segments and return a single segment spanning that full time. Parameters ----------- science_segs : ifo-keyed dictionary of ligo.segments.segmentlist instances The list of times that are being analysed in this workflow. Returns -------- fullSegment : ligo.segments.segment The segment spanning the first and last time point contained in science_segs. """ extents = [science_segs[ifo].extent() for ifo in science_segs.keys()] min, max = extents[0] for lo, hi in extents: if min > lo: min = lo if max < hi: max = hi fullSegment = segments.segment(min, max) return fullSegment
python
def get_full_analysis_chunk(science_segs): extents = [science_segs[ifo].extent() for ifo in science_segs.keys()] min, max = extents[0] for lo, hi in extents: if min > lo: min = lo if max < hi: max = hi fullSegment = segments.segment(min, max) return fullSegment
[ "def", "get_full_analysis_chunk", "(", "science_segs", ")", ":", "extents", "=", "[", "science_segs", "[", "ifo", "]", ".", "extent", "(", ")", "for", "ifo", "in", "science_segs", ".", "keys", "(", ")", "]", "min", ",", "max", "=", "extents", "[", "0",...
Function to find the first and last time point contained in the science segments and return a single segment spanning that full time. Parameters ----------- science_segs : ifo-keyed dictionary of ligo.segments.segmentlist instances The list of times that are being analysed in this workflow. Returns -------- fullSegment : ligo.segments.segment The segment spanning the first and last time point contained in science_segs.
[ "Function", "to", "find", "the", "first", "and", "last", "time", "point", "contained", "in", "the", "science", "segments", "and", "return", "a", "single", "segment", "spanning", "that", "full", "time", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1955-L1978
228,071
gwastro/pycbc
pycbc/workflow/core.py
get_random_label
def get_random_label(): """ Get a random label string to use when clustering jobs. """ return ''.join(random.choice(string.ascii_uppercase + string.digits) \ for _ in range(15))
python
def get_random_label(): return ''.join(random.choice(string.ascii_uppercase + string.digits) \ for _ in range(15))
[ "def", "get_random_label", "(", ")", ":", "return", "''", ".", "join", "(", "random", ".", "choice", "(", "string", ".", "ascii_uppercase", "+", "string", ".", "digits", ")", "for", "_", "in", "range", "(", "15", ")", ")" ]
Get a random label string to use when clustering jobs.
[ "Get", "a", "random", "label", "string", "to", "use", "when", "clustering", "jobs", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1980-L1985
228,072
gwastro/pycbc
pycbc/workflow/core.py
Executable.ifo
def ifo(self): """Return the ifo. If only one ifo in the ifo list this will be that ifo. Otherwise an error is raised. """ if self.ifo_list and len(self.ifo_list) == 1: return self.ifo_list[0] else: errMsg = "self.ifoList must contain only one ifo to access the " errMsg += "ifo property. %s." %(str(self.ifo_list),) raise TypeError(errMsg)
python
def ifo(self): if self.ifo_list and len(self.ifo_list) == 1: return self.ifo_list[0] else: errMsg = "self.ifoList must contain only one ifo to access the " errMsg += "ifo property. %s." %(str(self.ifo_list),) raise TypeError(errMsg)
[ "def", "ifo", "(", "self", ")", ":", "if", "self", ".", "ifo_list", "and", "len", "(", "self", ".", "ifo_list", ")", "==", "1", ":", "return", "self", ".", "ifo_list", "[", "0", "]", "else", ":", "errMsg", "=", "\"self.ifoList must contain only one ifo t...
Return the ifo. If only one ifo in the ifo list this will be that ifo. Otherwise an error is raised.
[ "Return", "the", "ifo", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L268-L279
228,073
gwastro/pycbc
pycbc/workflow/core.py
Executable.add_ini_profile
def add_ini_profile(self, cp, sec): """Add profile from configuration file. Parameters ----------- cp : ConfigParser object The ConfigParser object holding the workflow configuration settings sec : string The section containing options for this job. """ for opt in cp.options(sec): namespace = opt.split('|')[0] if namespace == 'pycbc' or namespace == 'container': continue value = string.strip(cp.get(sec, opt)) key = opt.split('|')[1] self.add_profile(namespace, key, value, force=True) # Remove if Pegasus can apply this hint in the TC if namespace == 'hints' and key == 'execution.site': self.execution_site = value
python
def add_ini_profile(self, cp, sec): for opt in cp.options(sec): namespace = opt.split('|')[0] if namespace == 'pycbc' or namespace == 'container': continue value = string.strip(cp.get(sec, opt)) key = opt.split('|')[1] self.add_profile(namespace, key, value, force=True) # Remove if Pegasus can apply this hint in the TC if namespace == 'hints' and key == 'execution.site': self.execution_site = value
[ "def", "add_ini_profile", "(", "self", ",", "cp", ",", "sec", ")", ":", "for", "opt", "in", "cp", ".", "options", "(", "sec", ")", ":", "namespace", "=", "opt", ".", "split", "(", "'|'", ")", "[", "0", "]", "if", "namespace", "==", "'pycbc'", "or...
Add profile from configuration file. Parameters ----------- cp : ConfigParser object The ConfigParser object holding the workflow configuration settings sec : string The section containing options for this job.
[ "Add", "profile", "from", "configuration", "file", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L281-L302
228,074
gwastro/pycbc
pycbc/workflow/core.py
Executable.add_ini_opts
def add_ini_opts(self, cp, sec): """Add job-specific options from configuration file. Parameters ----------- cp : ConfigParser object The ConfigParser object holding the workflow configuration settings sec : string The section containing options for this job. """ for opt in cp.options(sec): value = string.strip(cp.get(sec, opt)) opt = '--%s' %(opt,) if opt in self.file_input_options: # This now expects the option to be a file # Check is we have a list of files values = [path for path in value.split(' ') if path] self.common_raw_options.append(opt) self.common_raw_options.append(' ') # Get LFN and PFN for path in values: # Here I decide if the path is URL or # IFO:/path/to/file or IFO:url://path/to/file # That's somewhat tricksy as we used : as delimiter split_path = path.split(':', 1) if len(split_path) == 1: ifo = None path = path else: # Have I split a URL or not? if split_path[1].startswith('//'): # URL ifo = None path = path else: #IFO:path or IFO:URL ifo = split_path[0] path = split_path[1] curr_lfn = os.path.basename(path) # If the file exists make sure to use the # fill path as a file:// URL if os.path.isfile(path): curr_pfn = urlparse.urljoin('file:', urllib.pathname2url( os.path.abspath(path))) else: curr_pfn = path if curr_lfn in file_input_from_config_dict.keys(): file_pfn = file_input_from_config_dict[curr_lfn][2] assert(file_pfn == curr_pfn) curr_file = file_input_from_config_dict[curr_lfn][1] else: local_file_path = resolve_url(curr_pfn) curr_file = File.from_path(local_file_path) tuple_val = (local_file_path, curr_file, curr_pfn) file_input_from_config_dict[curr_lfn] = tuple_val self.common_input_files.append(curr_file) if ifo: self.common_raw_options.append(ifo + ':') self.common_raw_options.append(curr_file.dax_repr) else: self.common_raw_options.append(curr_file.dax_repr) self.common_raw_options.append(' ') else: self.common_options += [opt, value]
python
def add_ini_opts(self, cp, sec): for opt in cp.options(sec): value = string.strip(cp.get(sec, opt)) opt = '--%s' %(opt,) if opt in self.file_input_options: # This now expects the option to be a file # Check is we have a list of files values = [path for path in value.split(' ') if path] self.common_raw_options.append(opt) self.common_raw_options.append(' ') # Get LFN and PFN for path in values: # Here I decide if the path is URL or # IFO:/path/to/file or IFO:url://path/to/file # That's somewhat tricksy as we used : as delimiter split_path = path.split(':', 1) if len(split_path) == 1: ifo = None path = path else: # Have I split a URL or not? if split_path[1].startswith('//'): # URL ifo = None path = path else: #IFO:path or IFO:URL ifo = split_path[0] path = split_path[1] curr_lfn = os.path.basename(path) # If the file exists make sure to use the # fill path as a file:// URL if os.path.isfile(path): curr_pfn = urlparse.urljoin('file:', urllib.pathname2url( os.path.abspath(path))) else: curr_pfn = path if curr_lfn in file_input_from_config_dict.keys(): file_pfn = file_input_from_config_dict[curr_lfn][2] assert(file_pfn == curr_pfn) curr_file = file_input_from_config_dict[curr_lfn][1] else: local_file_path = resolve_url(curr_pfn) curr_file = File.from_path(local_file_path) tuple_val = (local_file_path, curr_file, curr_pfn) file_input_from_config_dict[curr_lfn] = tuple_val self.common_input_files.append(curr_file) if ifo: self.common_raw_options.append(ifo + ':') self.common_raw_options.append(curr_file.dax_repr) else: self.common_raw_options.append(curr_file.dax_repr) self.common_raw_options.append(' ') else: self.common_options += [opt, value]
[ "def", "add_ini_opts", "(", "self", ",", "cp", ",", "sec", ")", ":", "for", "opt", "in", "cp", ".", "options", "(", "sec", ")", ":", "value", "=", "string", ".", "strip", "(", "cp", ".", "get", "(", "sec", ",", "opt", ")", ")", "opt", "=", "'...
Add job-specific options from configuration file. Parameters ----------- cp : ConfigParser object The ConfigParser object holding the workflow configuration settings sec : string The section containing options for this job.
[ "Add", "job", "-", "specific", "options", "from", "configuration", "file", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L304-L373
228,075
gwastro/pycbc
pycbc/workflow/core.py
Executable.add_opt
def add_opt(self, opt, value=None): """Add option to job. Parameters ----------- opt : string Name of option (e.g. --output-file-format) value : string, (default=None) The value for the option (no value if set to None). """ if value is None: self.common_options += [opt] else: self.common_options += [opt, value]
python
def add_opt(self, opt, value=None): if value is None: self.common_options += [opt] else: self.common_options += [opt, value]
[ "def", "add_opt", "(", "self", ",", "opt", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "self", ".", "common_options", "+=", "[", "opt", "]", "else", ":", "self", ".", "common_options", "+=", "[", "opt", ",", "value", "]" ...
Add option to job. Parameters ----------- opt : string Name of option (e.g. --output-file-format) value : string, (default=None) The value for the option (no value if set to None).
[ "Add", "option", "to", "job", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L375-L388
228,076
gwastro/pycbc
pycbc/workflow/core.py
Executable.get_opt
def get_opt(self, opt): """Get value of option from configuration file Parameters ----------- opt : string Name of option (e.g. output-file-format) Returns -------- value : string The value for the option. Returns None if option not present. """ for sec in self.sections: try: key = self.cp.get(sec, opt) if key: return key except ConfigParser.NoOptionError: pass return None
python
def get_opt(self, opt): for sec in self.sections: try: key = self.cp.get(sec, opt) if key: return key except ConfigParser.NoOptionError: pass return None
[ "def", "get_opt", "(", "self", ",", "opt", ")", ":", "for", "sec", "in", "self", ".", "sections", ":", "try", ":", "key", "=", "self", ".", "cp", ".", "get", "(", "sec", ",", "opt", ")", "if", "key", ":", "return", "key", "except", "ConfigParser"...
Get value of option from configuration file Parameters ----------- opt : string Name of option (e.g. output-file-format) Returns -------- value : string The value for the option. Returns None if option not present.
[ "Get", "value", "of", "option", "from", "configuration", "file" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L390-L411
228,077
gwastro/pycbc
pycbc/workflow/core.py
Executable.has_opt
def has_opt(self, opt): """Check if option is present in configuration file Parameters ----------- opt : string Name of option (e.g. output-file-format) """ for sec in self.sections: val = self.cp.has_option(sec, opt) if val: return val return False
python
def has_opt(self, opt): for sec in self.sections: val = self.cp.has_option(sec, opt) if val: return val return False
[ "def", "has_opt", "(", "self", ",", "opt", ")", ":", "for", "sec", "in", "self", ".", "sections", ":", "val", "=", "self", ".", "cp", ".", "has_option", "(", "sec", ",", "opt", ")", "if", "val", ":", "return", "val", "return", "False" ]
Check if option is present in configuration file Parameters ----------- opt : string Name of option (e.g. output-file-format)
[ "Check", "if", "option", "is", "present", "in", "configuration", "file" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L413-L426
228,078
gwastro/pycbc
pycbc/workflow/core.py
Executable.update_current_retention_level
def update_current_retention_level(self, value): """Set a new value for the current retention level. This updates the value of self.retain_files for an updated value of the retention level. Parameters ----------- value : int The new value to use for the retention level. """ # Determine the level at which output files should be kept self.current_retention_level = value try: global_retention_level = \ self.cp.get_opt_tags("workflow", "file-retention-level", self.tags+[self.name]) except ConfigParser.Error: msg="Cannot find file-retention-level in [workflow] section " msg+="of the configuration file. Setting a default value of " msg+="retain all files." logging.warn(msg) self.retain_files = True self.global_retention_threshold = 1 self.cp.set("workflow", "file-retention-level", "all_files") else: # FIXME: Are these names suitably descriptive? retention_choices = { 'all_files' : 1, 'all_triggers' : 2, 'merged_triggers' : 3, 'results' : 4 } try: self.global_retention_threshold = \ retention_choices[global_retention_level] except KeyError: err_msg = "Cannot recognize the file-retention-level in the " err_msg += "[workflow] section of the ini file. " err_msg += "Got : {0}.".format(global_retention_level) err_msg += "Valid options are: 'all_files', 'all_triggers'," err_msg += "'merged_triggers' or 'results' " raise ValueError(err_msg) if self.current_retention_level == 5: self.retain_files = True if type(self).__name__ in Executable._warned_classes_list: pass else: warn_msg = "Attribute current_retention_level has not " warn_msg += "been set in class {0}. ".format(type(self)) warn_msg += "This value should be set explicitly. " warn_msg += "All output from this class will be stored." logging.warn(warn_msg) Executable._warned_classes_list.append(type(self).__name__) elif self.global_retention_threshold > self.current_retention_level: self.retain_files = False else: self.retain_files = True
python
def update_current_retention_level(self, value): # Determine the level at which output files should be kept self.current_retention_level = value try: global_retention_level = \ self.cp.get_opt_tags("workflow", "file-retention-level", self.tags+[self.name]) except ConfigParser.Error: msg="Cannot find file-retention-level in [workflow] section " msg+="of the configuration file. Setting a default value of " msg+="retain all files." logging.warn(msg) self.retain_files = True self.global_retention_threshold = 1 self.cp.set("workflow", "file-retention-level", "all_files") else: # FIXME: Are these names suitably descriptive? retention_choices = { 'all_files' : 1, 'all_triggers' : 2, 'merged_triggers' : 3, 'results' : 4 } try: self.global_retention_threshold = \ retention_choices[global_retention_level] except KeyError: err_msg = "Cannot recognize the file-retention-level in the " err_msg += "[workflow] section of the ini file. " err_msg += "Got : {0}.".format(global_retention_level) err_msg += "Valid options are: 'all_files', 'all_triggers'," err_msg += "'merged_triggers' or 'results' " raise ValueError(err_msg) if self.current_retention_level == 5: self.retain_files = True if type(self).__name__ in Executable._warned_classes_list: pass else: warn_msg = "Attribute current_retention_level has not " warn_msg += "been set in class {0}. ".format(type(self)) warn_msg += "This value should be set explicitly. " warn_msg += "All output from this class will be stored." logging.warn(warn_msg) Executable._warned_classes_list.append(type(self).__name__) elif self.global_retention_threshold > self.current_retention_level: self.retain_files = False else: self.retain_files = True
[ "def", "update_current_retention_level", "(", "self", ",", "value", ")", ":", "# Determine the level at which output files should be kept", "self", ".", "current_retention_level", "=", "value", "try", ":", "global_retention_level", "=", "self", ".", "cp", ".", "get_opt_ta...
Set a new value for the current retention level. This updates the value of self.retain_files for an updated value of the retention level. Parameters ----------- value : int The new value to use for the retention level.
[ "Set", "a", "new", "value", "for", "the", "current", "retention", "level", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L435-L492
228,079
gwastro/pycbc
pycbc/workflow/core.py
Executable.update_current_tags
def update_current_tags(self, tags): """Set a new set of tags for this executable. Update the set of tags that this job will use. This updated default file naming and shared options. It will *not* update the pegasus profile, which belong to the executable and cannot be different for different nodes. Parameters ----------- tags : list The new list of tags to consider. """ if tags is None: tags = [] tags = [tag.upper() for tag in tags] self.tags = tags if len(tags) > 6: warn_msg = "This job has way too many tags. " warn_msg += "Current tags are {}. ".format(' '.join(tags)) warn_msg += "Current executable {}.".format(self.name) logging.info(warn_msg) if len(tags) != 0: self.tagged_name = "{0}-{1}".format(self.name, '_'.join(tags)) else: self.tagged_name = self.name if self.ifo_string is not None: self.tagged_name = "{0}-{1}".format(self.tagged_name, self.ifo_string) # Determine the sections from the ini file that will configure # this executable sections = [self.name] if self.ifo_list is not None: if len(self.ifo_list) > 1: sec_tags = tags + self.ifo_list + [self.ifo_string] else: sec_tags = tags + self.ifo_list else: sec_tags = tags for sec_len in range(1, len(sec_tags)+1): for tag_permutation in permutations(sec_tags, sec_len): joined_name = '-'.join(tag_permutation) section = '{0}-{1}'.format(self.name, joined_name.lower()) if self.cp.has_section(section): sections.append(section) self.sections = sections # Do some basic sanity checking on the options for sec1, sec2 in combinations(sections, 2): self.cp.check_duplicate_options(sec1, sec2, raise_error=True) # collect the options and profile information # from the ini file section(s) self.common_options = [] self.common_raw_options = [] self.common_input_files = [] for sec in sections: if self.cp.has_section(sec): self.add_ini_opts(self.cp, sec) else: warn_string = "warning: config file is missing section " warn_string += "[{0}]".format(sec) logging.warn(warn_string)
python
def update_current_tags(self, tags): if tags is None: tags = [] tags = [tag.upper() for tag in tags] self.tags = tags if len(tags) > 6: warn_msg = "This job has way too many tags. " warn_msg += "Current tags are {}. ".format(' '.join(tags)) warn_msg += "Current executable {}.".format(self.name) logging.info(warn_msg) if len(tags) != 0: self.tagged_name = "{0}-{1}".format(self.name, '_'.join(tags)) else: self.tagged_name = self.name if self.ifo_string is not None: self.tagged_name = "{0}-{1}".format(self.tagged_name, self.ifo_string) # Determine the sections from the ini file that will configure # this executable sections = [self.name] if self.ifo_list is not None: if len(self.ifo_list) > 1: sec_tags = tags + self.ifo_list + [self.ifo_string] else: sec_tags = tags + self.ifo_list else: sec_tags = tags for sec_len in range(1, len(sec_tags)+1): for tag_permutation in permutations(sec_tags, sec_len): joined_name = '-'.join(tag_permutation) section = '{0}-{1}'.format(self.name, joined_name.lower()) if self.cp.has_section(section): sections.append(section) self.sections = sections # Do some basic sanity checking on the options for sec1, sec2 in combinations(sections, 2): self.cp.check_duplicate_options(sec1, sec2, raise_error=True) # collect the options and profile information # from the ini file section(s) self.common_options = [] self.common_raw_options = [] self.common_input_files = [] for sec in sections: if self.cp.has_section(sec): self.add_ini_opts(self.cp, sec) else: warn_string = "warning: config file is missing section " warn_string += "[{0}]".format(sec) logging.warn(warn_string)
[ "def", "update_current_tags", "(", "self", ",", "tags", ")", ":", "if", "tags", "is", "None", ":", "tags", "=", "[", "]", "tags", "=", "[", "tag", ".", "upper", "(", ")", "for", "tag", "in", "tags", "]", "self", ".", "tags", "=", "tags", "if", ...
Set a new set of tags for this executable. Update the set of tags that this job will use. This updated default file naming and shared options. It will *not* update the pegasus profile, which belong to the executable and cannot be different for different nodes. Parameters ----------- tags : list The new list of tags to consider.
[ "Set", "a", "new", "set", "of", "tags", "for", "this", "executable", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L494-L561
228,080
gwastro/pycbc
pycbc/workflow/core.py
Executable.update_output_directory
def update_output_directory(self, out_dir=None): """Update the default output directory for output files. Parameters ----------- out_dir : string (optional, default=None) If provided use this as the output directory. Else choose this automatically from the tags. """ # Determine the output directory if out_dir is not None: self.out_dir = out_dir elif len(self.tags) == 0: self.out_dir = self.name else: self.out_dir = self.tagged_name if not os.path.isabs(self.out_dir): self.out_dir = os.path.join(os.getcwd(), self.out_dir)
python
def update_output_directory(self, out_dir=None): # Determine the output directory if out_dir is not None: self.out_dir = out_dir elif len(self.tags) == 0: self.out_dir = self.name else: self.out_dir = self.tagged_name if not os.path.isabs(self.out_dir): self.out_dir = os.path.join(os.getcwd(), self.out_dir)
[ "def", "update_output_directory", "(", "self", ",", "out_dir", "=", "None", ")", ":", "# Determine the output directory", "if", "out_dir", "is", "not", "None", ":", "self", ".", "out_dir", "=", "out_dir", "elif", "len", "(", "self", ".", "tags", ")", "==", ...
Update the default output directory for output files. Parameters ----------- out_dir : string (optional, default=None) If provided use this as the output directory. Else choose this automatically from the tags.
[ "Update", "the", "default", "output", "directory", "for", "output", "files", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L563-L580
228,081
gwastro/pycbc
pycbc/workflow/core.py
Executable._set_pegasus_profile_options
def _set_pegasus_profile_options(self): """Set the pegasus-profile settings for this Executable. These are a property of the Executable and not of nodes that it will spawn. Therefore it *cannot* be updated without also changing values for nodes that might already have been created. Therefore this is only called once in __init__. Second calls to this will fail. """ # Add executable non-specific profile information if self.cp.has_section('pegasus_profile'): self.add_ini_profile(self.cp, 'pegasus_profile') # Executable- and tag-specific profile information for sec in self.sections: if self.cp.has_section('pegasus_profile-{0}'.format(sec)): self.add_ini_profile(self.cp, 'pegasus_profile-{0}'.format(sec))
python
def _set_pegasus_profile_options(self): # Add executable non-specific profile information if self.cp.has_section('pegasus_profile'): self.add_ini_profile(self.cp, 'pegasus_profile') # Executable- and tag-specific profile information for sec in self.sections: if self.cp.has_section('pegasus_profile-{0}'.format(sec)): self.add_ini_profile(self.cp, 'pegasus_profile-{0}'.format(sec))
[ "def", "_set_pegasus_profile_options", "(", "self", ")", ":", "# Add executable non-specific profile information", "if", "self", ".", "cp", ".", "has_section", "(", "'pegasus_profile'", ")", ":", "self", ".", "add_ini_profile", "(", "self", ".", "cp", ",", "'pegasus...
Set the pegasus-profile settings for this Executable. These are a property of the Executable and not of nodes that it will spawn. Therefore it *cannot* be updated without also changing values for nodes that might already have been created. Therefore this is only called once in __init__. Second calls to this will fail.
[ "Set", "the", "pegasus", "-", "profile", "settings", "for", "this", "Executable", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L582-L598
228,082
gwastro/pycbc
pycbc/workflow/core.py
Workflow.execute_node
def execute_node(self, node, verbatim_exe = False): """ Execute this node immediately on the local machine """ node.executed = True # Check that the PFN is for a file or path if node.executable.needs_fetching: try: # The pfn may have been marked local... pfn = node.executable.get_pfn() except: # or it may have been marked nonlocal. That's # fine, we'll resolve the URL and make a local # entry. pfn = node.executable.get_pfn('nonlocal') resolved = resolve_url(pfn, permissions=stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) node.executable.clear_pfns() node.executable.add_pfn(urlparse.urljoin('file:', urllib.pathname2url( resolved)), site='local') cmd_list = node.get_command_line() # Must execute in output directory. curr_dir = os.getcwd() out_dir = node.executable.out_dir os.chdir(out_dir) # Make call make_external_call(cmd_list, out_dir=os.path.join(out_dir, 'logs'), out_basename=node.executable.name) # Change back os.chdir(curr_dir) for fil in node._outputs: fil.node = None fil.PFN(urlparse.urljoin('file:', urllib.pathname2url(fil.storage_path)), site='local')
python
def execute_node(self, node, verbatim_exe = False): node.executed = True # Check that the PFN is for a file or path if node.executable.needs_fetching: try: # The pfn may have been marked local... pfn = node.executable.get_pfn() except: # or it may have been marked nonlocal. That's # fine, we'll resolve the URL and make a local # entry. pfn = node.executable.get_pfn('nonlocal') resolved = resolve_url(pfn, permissions=stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) node.executable.clear_pfns() node.executable.add_pfn(urlparse.urljoin('file:', urllib.pathname2url( resolved)), site='local') cmd_list = node.get_command_line() # Must execute in output directory. curr_dir = os.getcwd() out_dir = node.executable.out_dir os.chdir(out_dir) # Make call make_external_call(cmd_list, out_dir=os.path.join(out_dir, 'logs'), out_basename=node.executable.name) # Change back os.chdir(curr_dir) for fil in node._outputs: fil.node = None fil.PFN(urlparse.urljoin('file:', urllib.pathname2url(fil.storage_path)), site='local')
[ "def", "execute_node", "(", "self", ",", "node", ",", "verbatim_exe", "=", "False", ")", ":", "node", ".", "executed", "=", "True", "# Check that the PFN is for a file or path", "if", "node", ".", "executable", ".", "needs_fetching", ":", "try", ":", "# The pfn ...
Execute this node immediately on the local machine
[ "Execute", "this", "node", "immediately", "on", "the", "local", "machine" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L667-L706
228,083
gwastro/pycbc
pycbc/workflow/core.py
Workflow.save_config
def save_config(self, fname, output_dir, cp=None): """ Writes configuration file to disk and returns a pycbc.workflow.File instance for the configuration file. Parameters ----------- fname : string The filename of the configuration file written to disk. output_dir : string The directory where the file is written to disk. cp : ConfigParser object The ConfigParser object to write. If None then uses self.cp. Returns ------- FileList The FileList object with the configuration file. """ cp = self.cp if cp is None else cp ini_file_path = os.path.join(output_dir, fname) with open(ini_file_path, "wb") as fp: cp.write(fp) ini_file = FileList([File(self.ifos, "", self.analysis_time, file_url="file://" + ini_file_path)]) return ini_file
python
def save_config(self, fname, output_dir, cp=None): cp = self.cp if cp is None else cp ini_file_path = os.path.join(output_dir, fname) with open(ini_file_path, "wb") as fp: cp.write(fp) ini_file = FileList([File(self.ifos, "", self.analysis_time, file_url="file://" + ini_file_path)]) return ini_file
[ "def", "save_config", "(", "self", ",", "fname", ",", "output_dir", ",", "cp", "=", "None", ")", ":", "cp", "=", "self", ".", "cp", "if", "cp", "is", "None", "else", "cp", "ini_file_path", "=", "os", ".", "path", ".", "join", "(", "output_dir", ","...
Writes configuration file to disk and returns a pycbc.workflow.File instance for the configuration file. Parameters ----------- fname : string The filename of the configuration file written to disk. output_dir : string The directory where the file is written to disk. cp : ConfigParser object The ConfigParser object to write. If None then uses self.cp. Returns ------- FileList The FileList object with the configuration file.
[ "Writes", "configuration", "file", "to", "disk", "and", "returns", "a", "pycbc", ".", "workflow", ".", "File", "instance", "for", "the", "configuration", "file", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L800-L825
228,084
gwastro/pycbc
pycbc/workflow/core.py
Node.new_output_file_opt
def new_output_file_opt(self, valid_seg, extension, option_name, tags=None, store_file=None, use_tmp_subdirs=False): """ This function will create a workflow.File object corresponding to the given information and then add that file as output of this node. Parameters ----------- valid_seg : ligo.segments.segment The time span over which the job is valid for. extension : string The extension to be used at the end of the filename. E.g. '.xml' or '.sqlite'. option_name : string The option that is used when setting this job as output. For e.g. 'output-name' or 'output-file', whatever is appropriate for the current executable. tags : list of strings, (optional, default=[]) These tags will be added to the list of tags already associated with the job. They can be used to uniquely identify this output file. store_file : Boolean, (optional, default=True) This file is to be added to the output mapper and will be stored in the specified output location if True. If false file will be removed when no longer needed in the workflow. """ if tags is None: tags = [] # Changing this from set(tags) to enforce order. It might make sense # for all jobs to have file names with tags in the same order. all_tags = copy.deepcopy(self.executable.tags) for tag in tags: if tag not in all_tags: all_tags.append(tag) store_file = store_file if store_file is not None else self.executable.retain_files fil = File(self.executable.ifo_list, self.executable.name, valid_seg, extension=extension, store_file=store_file, directory=self.executable.out_dir, tags=all_tags, use_tmp_subdirs=use_tmp_subdirs) self.add_output_opt(option_name, fil) return fil
python
def new_output_file_opt(self, valid_seg, extension, option_name, tags=None, store_file=None, use_tmp_subdirs=False): if tags is None: tags = [] # Changing this from set(tags) to enforce order. It might make sense # for all jobs to have file names with tags in the same order. all_tags = copy.deepcopy(self.executable.tags) for tag in tags: if tag not in all_tags: all_tags.append(tag) store_file = store_file if store_file is not None else self.executable.retain_files fil = File(self.executable.ifo_list, self.executable.name, valid_seg, extension=extension, store_file=store_file, directory=self.executable.out_dir, tags=all_tags, use_tmp_subdirs=use_tmp_subdirs) self.add_output_opt(option_name, fil) return fil
[ "def", "new_output_file_opt", "(", "self", ",", "valid_seg", ",", "extension", ",", "option_name", ",", "tags", "=", "None", ",", "store_file", "=", "None", ",", "use_tmp_subdirs", "=", "False", ")", ":", "if", "tags", "is", "None", ":", "tags", "=", "["...
This function will create a workflow.File object corresponding to the given information and then add that file as output of this node. Parameters ----------- valid_seg : ligo.segments.segment The time span over which the job is valid for. extension : string The extension to be used at the end of the filename. E.g. '.xml' or '.sqlite'. option_name : string The option that is used when setting this job as output. For e.g. 'output-name' or 'output-file', whatever is appropriate for the current executable. tags : list of strings, (optional, default=[]) These tags will be added to the list of tags already associated with the job. They can be used to uniquely identify this output file. store_file : Boolean, (optional, default=True) This file is to be added to the output mapper and will be stored in the specified output location if True. If false file will be removed when no longer needed in the workflow.
[ "This", "function", "will", "create", "a", "workflow", ".", "File", "object", "corresponding", "to", "the", "given", "information", "and", "then", "add", "that", "file", "as", "output", "of", "this", "node", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L866-L908
228,085
gwastro/pycbc
pycbc/workflow/core.py
Node.output_file
def output_file(self): """ If only one output file return it. Otherwise raise an exception. """ out_files = self.output_files if len(out_files) != 1: err_msg = "output_file property is only valid if there is a single" err_msg += " output file. Here there are " err_msg += "%d output files." %(len(out_files)) raise ValueError(err_msg) return out_files[0]
python
def output_file(self): out_files = self.output_files if len(out_files) != 1: err_msg = "output_file property is only valid if there is a single" err_msg += " output file. Here there are " err_msg += "%d output files." %(len(out_files)) raise ValueError(err_msg) return out_files[0]
[ "def", "output_file", "(", "self", ")", ":", "out_files", "=", "self", ".", "output_files", "if", "len", "(", "out_files", ")", "!=", "1", ":", "err_msg", "=", "\"output_file property is only valid if there is a single\"", "err_msg", "+=", "\" output file. Here there ...
If only one output file return it. Otherwise raise an exception.
[ "If", "only", "one", "output", "file", "return", "it", ".", "Otherwise", "raise", "an", "exception", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L976-L986
228,086
gwastro/pycbc
pycbc/workflow/core.py
File.ifo
def ifo(self): """ If only one ifo in the ifo_list this will be that ifo. Otherwise an error is raised. """ if len(self.ifo_list) == 1: return self.ifo_list[0] else: err = "self.ifo_list must contain only one ifo to access the " err += "ifo property. %s." %(str(self.ifo_list),) raise TypeError(err)
python
def ifo(self): if len(self.ifo_list) == 1: return self.ifo_list[0] else: err = "self.ifo_list must contain only one ifo to access the " err += "ifo property. %s." %(str(self.ifo_list),) raise TypeError(err)
[ "def", "ifo", "(", "self", ")", ":", "if", "len", "(", "self", ".", "ifo_list", ")", "==", "1", ":", "return", "self", ".", "ifo_list", "[", "0", "]", "else", ":", "err", "=", "\"self.ifo_list must contain only one ifo to access the \"", "err", "+=", "\"if...
If only one ifo in the ifo_list this will be that ifo. Otherwise an error is raised.
[ "If", "only", "one", "ifo", "in", "the", "ifo_list", "this", "will", "be", "that", "ifo", ".", "Otherwise", "an", "error", "is", "raised", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1129-L1139
228,087
gwastro/pycbc
pycbc/workflow/core.py
File.segment
def segment(self): """ If only one segment in the segmentlist this will be that segment. Otherwise an error is raised. """ if len(self.segment_list) == 1: return self.segment_list[0] else: err = "self.segment_list must only contain one segment to access" err += " the segment property. %s." %(str(self.segment_list),) raise TypeError(err)
python
def segment(self): if len(self.segment_list) == 1: return self.segment_list[0] else: err = "self.segment_list must only contain one segment to access" err += " the segment property. %s." %(str(self.segment_list),) raise TypeError(err)
[ "def", "segment", "(", "self", ")", ":", "if", "len", "(", "self", ".", "segment_list", ")", "==", "1", ":", "return", "self", ".", "segment_list", "[", "0", "]", "else", ":", "err", "=", "\"self.segment_list must only contain one segment to access\"", "err", ...
If only one segment in the segmentlist this will be that segment. Otherwise an error is raised.
[ "If", "only", "one", "segment", "in", "the", "segmentlist", "this", "will", "be", "that", "segment", ".", "Otherwise", "an", "error", "is", "raised", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1142-L1152
228,088
gwastro/pycbc
pycbc/workflow/core.py
File.cache_entry
def cache_entry(self): """ Returns a CacheEntry instance for File. """ if self.storage_path is None: raise ValueError('This file is temporary and so a lal ' 'cache entry cannot be made') file_url = urlparse.urlunparse(['file', 'localhost', self.storage_path, None, None, None]) cache_entry = lal.utils.CacheEntry(self.ifo_string, self.tagged_description, self.segment_list.extent(), file_url) cache_entry.workflow_file = self return cache_entry
python
def cache_entry(self): if self.storage_path is None: raise ValueError('This file is temporary and so a lal ' 'cache entry cannot be made') file_url = urlparse.urlunparse(['file', 'localhost', self.storage_path, None, None, None]) cache_entry = lal.utils.CacheEntry(self.ifo_string, self.tagged_description, self.segment_list.extent(), file_url) cache_entry.workflow_file = self return cache_entry
[ "def", "cache_entry", "(", "self", ")", ":", "if", "self", ".", "storage_path", "is", "None", ":", "raise", "ValueError", "(", "'This file is temporary and so a lal '", "'cache entry cannot be made'", ")", "file_url", "=", "urlparse", ".", "urlunparse", "(", "[", ...
Returns a CacheEntry instance for File.
[ "Returns", "a", "CacheEntry", "instance", "for", "File", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1155-L1168
228,089
gwastro/pycbc
pycbc/workflow/core.py
File._filename
def _filename(self, ifo, description, extension, segment): """ Construct the standard output filename. Should only be used internally of the File class. """ if extension.startswith('.'): extension = extension[1:] # Follow the frame convention of using integer filenames, # but stretching to cover partially covered seconds. start = int(segment[0]) end = int(math.ceil(segment[1])) duration = str(end-start) start = str(start) return "%s-%s-%s-%s.%s" % (ifo, description.upper(), start, duration, extension)
python
def _filename(self, ifo, description, extension, segment): if extension.startswith('.'): extension = extension[1:] # Follow the frame convention of using integer filenames, # but stretching to cover partially covered seconds. start = int(segment[0]) end = int(math.ceil(segment[1])) duration = str(end-start) start = str(start) return "%s-%s-%s-%s.%s" % (ifo, description.upper(), start, duration, extension)
[ "def", "_filename", "(", "self", ",", "ifo", ",", "description", ",", "extension", ",", "segment", ")", ":", "if", "extension", ".", "startswith", "(", "'.'", ")", ":", "extension", "=", "extension", "[", "1", ":", "]", "# Follow the frame convention of usin...
Construct the standard output filename. Should only be used internally of the File class.
[ "Construct", "the", "standard", "output", "filename", ".", "Should", "only", "be", "used", "internally", "of", "the", "File", "class", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1170-L1186
228,090
gwastro/pycbc
pycbc/workflow/core.py
FileList.find_output_at_time
def find_output_at_time(self, ifo, time): ''' Return File that covers the given time. Parameters ----------- ifo : string Name of the ifo (or ifos) that the File should correspond to time : int/float/LIGOGPStime Return the Files that covers the supplied time. If no File covers the time this will return None. Returns -------- list of File classes The Files that corresponds to the time. ''' # Get list of Files that overlap time, for given ifo outFiles = [i for i in self if ifo in i.ifo_list and time in i.segment_list] if len(outFiles) == 0: # No OutFile at this time return None elif len(outFiles) == 1: # 1 OutFile at this time (good!) return outFiles else: # Multiple output files. Currently this is valid, but we may want # to demand exclusivity later, or in certain cases. Hence the # separation. return outFiles
python
def find_output_at_time(self, ifo, time): ''' Return File that covers the given time. Parameters ----------- ifo : string Name of the ifo (or ifos) that the File should correspond to time : int/float/LIGOGPStime Return the Files that covers the supplied time. If no File covers the time this will return None. Returns -------- list of File classes The Files that corresponds to the time. ''' # Get list of Files that overlap time, for given ifo outFiles = [i for i in self if ifo in i.ifo_list and time in i.segment_list] if len(outFiles) == 0: # No OutFile at this time return None elif len(outFiles) == 1: # 1 OutFile at this time (good!) return outFiles else: # Multiple output files. Currently this is valid, but we may want # to demand exclusivity later, or in certain cases. Hence the # separation. return outFiles
[ "def", "find_output_at_time", "(", "self", ",", "ifo", ",", "time", ")", ":", "# Get list of Files that overlap time, for given ifo", "outFiles", "=", "[", "i", "for", "i", "in", "self", "if", "ifo", "in", "i", ".", "ifo_list", "and", "time", "in", "i", ".",...
Return File that covers the given time. Parameters ----------- ifo : string Name of the ifo (or ifos) that the File should correspond to time : int/float/LIGOGPStime Return the Files that covers the supplied time. If no File covers the time this will return None. Returns -------- list of File classes The Files that corresponds to the time.
[ "Return", "File", "that", "covers", "the", "given", "time", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1267-L1296
228,091
gwastro/pycbc
pycbc/workflow/core.py
FileList.find_outputs_in_range
def find_outputs_in_range(self, ifo, current_segment, useSplitLists=False): """ Return the list of Files that is most appropriate for the supplied time range. That is, the Files whose coverage time has the largest overlap with the supplied time range. Parameters ----------- ifo : string Name of the ifo (or ifos) that the File should correspond to current_segment : glue.segment.segment The segment of time that files must intersect. Returns -------- FileList class The list of Files that are most appropriate for the time range """ currsegment_list = segments.segmentlist([current_segment]) # Get all files overlapping the window overlap_files = self.find_all_output_in_range(ifo, current_segment, useSplitLists=useSplitLists) # By how much do they overlap? overlap_windows = [abs(i.segment_list & currsegment_list) for i in overlap_files] if not overlap_windows: return [] # Return the File with the biggest overlap # Note if two File have identical overlap, the first is used # to define the valid segment overlap_windows = numpy.array(overlap_windows, dtype = int) segmentLst = overlap_files[overlap_windows.argmax()].segment_list # Get all output files with the exact same segment definition output_files = [f for f in overlap_files if f.segment_list==segmentLst] return output_files
python
def find_outputs_in_range(self, ifo, current_segment, useSplitLists=False): currsegment_list = segments.segmentlist([current_segment]) # Get all files overlapping the window overlap_files = self.find_all_output_in_range(ifo, current_segment, useSplitLists=useSplitLists) # By how much do they overlap? overlap_windows = [abs(i.segment_list & currsegment_list) for i in overlap_files] if not overlap_windows: return [] # Return the File with the biggest overlap # Note if two File have identical overlap, the first is used # to define the valid segment overlap_windows = numpy.array(overlap_windows, dtype = int) segmentLst = overlap_files[overlap_windows.argmax()].segment_list # Get all output files with the exact same segment definition output_files = [f for f in overlap_files if f.segment_list==segmentLst] return output_files
[ "def", "find_outputs_in_range", "(", "self", ",", "ifo", ",", "current_segment", ",", "useSplitLists", "=", "False", ")", ":", "currsegment_list", "=", "segments", ".", "segmentlist", "(", "[", "current_segment", "]", ")", "# Get all files overlapping the window", "...
Return the list of Files that is most appropriate for the supplied time range. That is, the Files whose coverage time has the largest overlap with the supplied time range. Parameters ----------- ifo : string Name of the ifo (or ifos) that the File should correspond to current_segment : glue.segment.segment The segment of time that files must intersect. Returns -------- FileList class The list of Files that are most appropriate for the time range
[ "Return", "the", "list", "of", "Files", "that", "is", "most", "appropriate", "for", "the", "supplied", "time", "range", ".", "That", "is", "the", "Files", "whose", "coverage", "time", "has", "the", "largest", "overlap", "with", "the", "supplied", "time", "...
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1298-L1336
228,092
gwastro/pycbc
pycbc/workflow/core.py
FileList.find_output_in_range
def find_output_in_range(self, ifo, start, end): ''' Return the File that is most appropriate for the supplied time range. That is, the File whose coverage time has the largest overlap with the supplied time range. If no Files overlap the supplied time window, will return None. Parameters ----------- ifo : string Name of the ifo (or ifos) that the File should correspond to start : int/float/LIGOGPStime The start of the time range of interest. end : int/float/LIGOGPStime The end of the time range of interest Returns -------- File class The File that is most appropriate for the time range ''' currsegment_list = segments.segmentlist([segments.segment(start, end)]) # First filter Files corresponding to ifo outFiles = [i for i in self if ifo in i.ifo_list] if len(outFiles) == 0: # No OutFiles correspond to that ifo return None # Filter OutFiles to those overlapping the given window currSeg = segments.segment([start,end]) outFiles = [i for i in outFiles \ if i.segment_list.intersects_segment(currSeg)] if len(outFiles) == 0: # No OutFile overlap that time period return None elif len(outFiles) == 1: # One OutFile overlaps that period return outFiles[0] else: overlap_windows = [abs(i.segment_list & currsegment_list) \ for i in outFiles] # Return the File with the biggest overlap # Note if two File have identical overlap, this will return # the first File in the list overlap_windows = numpy.array(overlap_windows, dtype = int) return outFiles[overlap_windows.argmax()]
python
def find_output_in_range(self, ifo, start, end): ''' Return the File that is most appropriate for the supplied time range. That is, the File whose coverage time has the largest overlap with the supplied time range. If no Files overlap the supplied time window, will return None. Parameters ----------- ifo : string Name of the ifo (or ifos) that the File should correspond to start : int/float/LIGOGPStime The start of the time range of interest. end : int/float/LIGOGPStime The end of the time range of interest Returns -------- File class The File that is most appropriate for the time range ''' currsegment_list = segments.segmentlist([segments.segment(start, end)]) # First filter Files corresponding to ifo outFiles = [i for i in self if ifo in i.ifo_list] if len(outFiles) == 0: # No OutFiles correspond to that ifo return None # Filter OutFiles to those overlapping the given window currSeg = segments.segment([start,end]) outFiles = [i for i in outFiles \ if i.segment_list.intersects_segment(currSeg)] if len(outFiles) == 0: # No OutFile overlap that time period return None elif len(outFiles) == 1: # One OutFile overlaps that period return outFiles[0] else: overlap_windows = [abs(i.segment_list & currsegment_list) \ for i in outFiles] # Return the File with the biggest overlap # Note if two File have identical overlap, this will return # the first File in the list overlap_windows = numpy.array(overlap_windows, dtype = int) return outFiles[overlap_windows.argmax()]
[ "def", "find_output_in_range", "(", "self", ",", "ifo", ",", "start", ",", "end", ")", ":", "currsegment_list", "=", "segments", ".", "segmentlist", "(", "[", "segments", ".", "segment", "(", "start", ",", "end", ")", "]", ")", "# First filter Files correspo...
Return the File that is most appropriate for the supplied time range. That is, the File whose coverage time has the largest overlap with the supplied time range. If no Files overlap the supplied time window, will return None. Parameters ----------- ifo : string Name of the ifo (or ifos) that the File should correspond to start : int/float/LIGOGPStime The start of the time range of interest. end : int/float/LIGOGPStime The end of the time range of interest Returns -------- File class The File that is most appropriate for the time range
[ "Return", "the", "File", "that", "is", "most", "appropriate", "for", "the", "supplied", "time", "range", ".", "That", "is", "the", "File", "whose", "coverage", "time", "has", "the", "largest", "overlap", "with", "the", "supplied", "time", "range", ".", "If...
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1338-L1385
228,093
gwastro/pycbc
pycbc/workflow/core.py
FileList.find_all_output_in_range
def find_all_output_in_range(self, ifo, currSeg, useSplitLists=False): """ Return all files that overlap the specified segment. """ if not useSplitLists: # Slower, but simpler method outFiles = [i for i in self if ifo in i.ifo_list] outFiles = [i for i in outFiles \ if i.segment_list.intersects_segment(currSeg)] else: # Faster, but more complicated # Basically only check if a subset of files intersects_segment by # using a presorted list. Sorting only happens once. if not self._check_split_list_validity(): # FIXME: DO NOT hard code this. self._temporal_split_list(100) startIdx = int( (currSeg[0] - self._splitListsStart) / \ self._splitListsStep ) # Add some small rounding here endIdx = (currSeg[1] - self._splitListsStart) / self._splitListsStep endIdx = int(endIdx - 0.000001) outFiles = [] for idx in range(startIdx, endIdx + 1): if idx < 0 or idx >= self._splitListsNum: continue outFilesTemp = [i for i in self._splitLists[idx] \ if ifo in i.ifo_list] outFiles.extend([i for i in outFilesTemp \ if i.segment_list.intersects_segment(currSeg)]) # Remove duplicates outFiles = list(set(outFiles)) return self.__class__(outFiles)
python
def find_all_output_in_range(self, ifo, currSeg, useSplitLists=False): if not useSplitLists: # Slower, but simpler method outFiles = [i for i in self if ifo in i.ifo_list] outFiles = [i for i in outFiles \ if i.segment_list.intersects_segment(currSeg)] else: # Faster, but more complicated # Basically only check if a subset of files intersects_segment by # using a presorted list. Sorting only happens once. if not self._check_split_list_validity(): # FIXME: DO NOT hard code this. self._temporal_split_list(100) startIdx = int( (currSeg[0] - self._splitListsStart) / \ self._splitListsStep ) # Add some small rounding here endIdx = (currSeg[1] - self._splitListsStart) / self._splitListsStep endIdx = int(endIdx - 0.000001) outFiles = [] for idx in range(startIdx, endIdx + 1): if idx < 0 or idx >= self._splitListsNum: continue outFilesTemp = [i for i in self._splitLists[idx] \ if ifo in i.ifo_list] outFiles.extend([i for i in outFilesTemp \ if i.segment_list.intersects_segment(currSeg)]) # Remove duplicates outFiles = list(set(outFiles)) return self.__class__(outFiles)
[ "def", "find_all_output_in_range", "(", "self", ",", "ifo", ",", "currSeg", ",", "useSplitLists", "=", "False", ")", ":", "if", "not", "useSplitLists", ":", "# Slower, but simpler method", "outFiles", "=", "[", "i", "for", "i", "in", "self", "if", "ifo", "in...
Return all files that overlap the specified segment.
[ "Return", "all", "files", "that", "overlap", "the", "specified", "segment", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1387-L1420
228,094
gwastro/pycbc
pycbc/workflow/core.py
FileList.find_output_with_tag
def find_output_with_tag(self, tag): """ Find all files who have tag in self.tags """ # Enforce upper case tag = tag.upper() return FileList([i for i in self if tag in i.tags])
python
def find_output_with_tag(self, tag): # Enforce upper case tag = tag.upper() return FileList([i for i in self if tag in i.tags])
[ "def", "find_output_with_tag", "(", "self", ",", "tag", ")", ":", "# Enforce upper case", "tag", "=", "tag", ".", "upper", "(", ")", "return", "FileList", "(", "[", "i", "for", "i", "in", "self", "if", "tag", "in", "i", ".", "tags", "]", ")" ]
Find all files who have tag in self.tags
[ "Find", "all", "files", "who", "have", "tag", "in", "self", ".", "tags" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1422-L1428
228,095
gwastro/pycbc
pycbc/workflow/core.py
FileList.find_output_without_tag
def find_output_without_tag(self, tag): """ Find all files who do not have tag in self.tags """ # Enforce upper case tag = tag.upper() return FileList([i for i in self if tag not in i.tags])
python
def find_output_without_tag(self, tag): # Enforce upper case tag = tag.upper() return FileList([i for i in self if tag not in i.tags])
[ "def", "find_output_without_tag", "(", "self", ",", "tag", ")", ":", "# Enforce upper case", "tag", "=", "tag", ".", "upper", "(", ")", "return", "FileList", "(", "[", "i", "for", "i", "in", "self", "if", "tag", "not", "in", "i", ".", "tags", "]", ")...
Find all files who do not have tag in self.tags
[ "Find", "all", "files", "who", "do", "not", "have", "tag", "in", "self", ".", "tags" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1430-L1436
228,096
gwastro/pycbc
pycbc/workflow/core.py
FileList.find_output_with_ifo
def find_output_with_ifo(self, ifo): """ Find all files who have ifo = ifo """ # Enforce upper case ifo = ifo.upper() return FileList([i for i in self if ifo in i.ifo_list])
python
def find_output_with_ifo(self, ifo): # Enforce upper case ifo = ifo.upper() return FileList([i for i in self if ifo in i.ifo_list])
[ "def", "find_output_with_ifo", "(", "self", ",", "ifo", ")", ":", "# Enforce upper case", "ifo", "=", "ifo", ".", "upper", "(", ")", "return", "FileList", "(", "[", "i", "for", "i", "in", "self", "if", "ifo", "in", "i", ".", "ifo_list", "]", ")" ]
Find all files who have ifo = ifo
[ "Find", "all", "files", "who", "have", "ifo", "=", "ifo" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1438-L1444
228,097
gwastro/pycbc
pycbc/workflow/core.py
FileList.get_times_covered_by_files
def get_times_covered_by_files(self): """ Find the coalesced intersection of the segments of all files in the list. """ times = segments.segmentlist([]) for entry in self: times.extend(entry.segment_list) times.coalesce() return times
python
def get_times_covered_by_files(self): times = segments.segmentlist([]) for entry in self: times.extend(entry.segment_list) times.coalesce() return times
[ "def", "get_times_covered_by_files", "(", "self", ")", ":", "times", "=", "segments", ".", "segmentlist", "(", "[", "]", ")", "for", "entry", "in", "self", ":", "times", ".", "extend", "(", "entry", ".", "segment_list", ")", "times", ".", "coalesce", "("...
Find the coalesced intersection of the segments of all files in the list.
[ "Find", "the", "coalesced", "intersection", "of", "the", "segments", "of", "all", "files", "in", "the", "list", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1446-L1455
228,098
gwastro/pycbc
pycbc/workflow/core.py
FileList.convert_to_lal_cache
def convert_to_lal_cache(self): """ Return all files in this object as a glue.lal.Cache object """ lal_cache = gluelal.Cache([]) for entry in self: try: lal_cache.append(entry.cache_entry) except ValueError: pass return lal_cache
python
def convert_to_lal_cache(self): lal_cache = gluelal.Cache([]) for entry in self: try: lal_cache.append(entry.cache_entry) except ValueError: pass return lal_cache
[ "def", "convert_to_lal_cache", "(", "self", ")", ":", "lal_cache", "=", "gluelal", ".", "Cache", "(", "[", "]", ")", "for", "entry", "in", "self", ":", "try", ":", "lal_cache", ".", "append", "(", "entry", ".", "cache_entry", ")", "except", "ValueError",...
Return all files in this object as a glue.lal.Cache object
[ "Return", "all", "files", "in", "this", "object", "as", "a", "glue", ".", "lal", ".", "Cache", "object" ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1457-L1467
228,099
gwastro/pycbc
pycbc/workflow/core.py
FileList._check_split_list_validity
def _check_split_list_validity(self): """ See _temporal_split_list above. This function checks if the current split lists are still valid. """ # FIXME: Currently very primitive, but needs to be fast if not (hasattr(self,"_splitListsSet") and (self._splitListsSet)): return False elif len(self) != self._splitListsLength: return False else: return True
python
def _check_split_list_validity(self): # FIXME: Currently very primitive, but needs to be fast if not (hasattr(self,"_splitListsSet") and (self._splitListsSet)): return False elif len(self) != self._splitListsLength: return False else: return True
[ "def", "_check_split_list_validity", "(", "self", ")", ":", "# FIXME: Currently very primitive, but needs to be fast", "if", "not", "(", "hasattr", "(", "self", ",", "\"_splitListsSet\"", ")", "and", "(", "self", ".", "_splitListsSet", ")", ")", ":", "return", "Fals...
See _temporal_split_list above. This function checks if the current split lists are still valid.
[ "See", "_temporal_split_list", "above", ".", "This", "function", "checks", "if", "the", "current", "split", "lists", "are", "still", "valid", "." ]
7a64cdd104d263f1b6ea0b01e6841837d05a4cb3
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1521-L1532