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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
227,800 | gwastro/pycbc | pycbc/waveform/bank.py | TemplateBank.write_to_hdf | def write_to_hdf(self, filename, start_index=None, stop_index=None,
force=False, skip_fields=None,
write_compressed_waveforms=True):
"""Writes self to the given hdf file.
Parameters
----------
filename : str
The name of the file to write to. Must end in '.hdf'.
start_index : If a specific slice of the template bank is to be
written to the hdf file, this would specify the index of the
first template in the slice
stop_index : If a specific slice of the template bank is to be
written to the hdf file, this would specify the index of the
last template in the slice
force : {False, bool}
If the file already exists, it will be overwritten if True.
Otherwise, an OSError is raised if the file exists.
skip_fields : {None, (list of) strings}
Do not write the given fields to the hdf file. Default is None,
in which case all fields in self.table.fieldnames are written.
write_compressed_waveforms : {True, bool}
Write compressed waveforms to the output (hdf) file if this is
True, which is the default setting. If False, do not write the
compressed waveforms group, but only the template parameters to
the output file.
Returns
-------
h5py.File
The file handler to the output hdf file (left open).
"""
if not filename.endswith('.hdf'):
raise ValueError("Unrecoginized file extension")
if os.path.exists(filename) and not force:
raise IOError("File %s already exists" %(filename))
f = h5py.File(filename, 'w')
parameters = self.parameters
if skip_fields is not None:
if not isinstance(skip_fields, list):
skip_fields = [skip_fields]
parameters = [p for p in parameters if p not in skip_fields]
# save the parameters
f.attrs['parameters'] = parameters
write_tbl = self.table[start_index:stop_index]
for p in parameters:
f[p] = write_tbl[p]
if write_compressed_waveforms and self.has_compressed_waveforms:
for tmplt_hash in write_tbl.template_hash:
compressed_waveform = pycbc.waveform.compress.CompressedWaveform.from_hdf(
self.filehandler, tmplt_hash,
load_now=True)
compressed_waveform.write_to_hdf(f, tmplt_hash)
return f | python | def write_to_hdf(self, filename, start_index=None, stop_index=None,
force=False, skip_fields=None,
write_compressed_waveforms=True):
if not filename.endswith('.hdf'):
raise ValueError("Unrecoginized file extension")
if os.path.exists(filename) and not force:
raise IOError("File %s already exists" %(filename))
f = h5py.File(filename, 'w')
parameters = self.parameters
if skip_fields is not None:
if not isinstance(skip_fields, list):
skip_fields = [skip_fields]
parameters = [p for p in parameters if p not in skip_fields]
# save the parameters
f.attrs['parameters'] = parameters
write_tbl = self.table[start_index:stop_index]
for p in parameters:
f[p] = write_tbl[p]
if write_compressed_waveforms and self.has_compressed_waveforms:
for tmplt_hash in write_tbl.template_hash:
compressed_waveform = pycbc.waveform.compress.CompressedWaveform.from_hdf(
self.filehandler, tmplt_hash,
load_now=True)
compressed_waveform.write_to_hdf(f, tmplt_hash)
return f | [
"def",
"write_to_hdf",
"(",
"self",
",",
"filename",
",",
"start_index",
"=",
"None",
",",
"stop_index",
"=",
"None",
",",
"force",
"=",
"False",
",",
"skip_fields",
"=",
"None",
",",
"write_compressed_waveforms",
"=",
"True",
")",
":",
"if",
"not",
"filen... | Writes self to the given hdf file.
Parameters
----------
filename : str
The name of the file to write to. Must end in '.hdf'.
start_index : If a specific slice of the template bank is to be
written to the hdf file, this would specify the index of the
first template in the slice
stop_index : If a specific slice of the template bank is to be
written to the hdf file, this would specify the index of the
last template in the slice
force : {False, bool}
If the file already exists, it will be overwritten if True.
Otherwise, an OSError is raised if the file exists.
skip_fields : {None, (list of) strings}
Do not write the given fields to the hdf file. Default is None,
in which case all fields in self.table.fieldnames are written.
write_compressed_waveforms : {True, bool}
Write compressed waveforms to the output (hdf) file if this is
True, which is the default setting. If False, do not write the
compressed waveforms group, but only the template parameters to
the output file.
Returns
-------
h5py.File
The file handler to the output hdf file (left open). | [
"Writes",
"self",
"to",
"the",
"given",
"hdf",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/bank.py#L332-L385 |
227,801 | gwastro/pycbc | pycbc/waveform/bank.py | TemplateBank.end_frequency | def end_frequency(self, index):
""" Return the end frequency of the waveform at the given index value
"""
from pycbc.waveform.waveform import props
return pycbc.waveform.get_waveform_end_frequency(
self.table[index],
approximant=self.approximant(index),
**self.extra_args) | python | def end_frequency(self, index):
from pycbc.waveform.waveform import props
return pycbc.waveform.get_waveform_end_frequency(
self.table[index],
approximant=self.approximant(index),
**self.extra_args) | [
"def",
"end_frequency",
"(",
"self",
",",
"index",
")",
":",
"from",
"pycbc",
".",
"waveform",
".",
"waveform",
"import",
"props",
"return",
"pycbc",
".",
"waveform",
".",
"get_waveform_end_frequency",
"(",
"self",
".",
"table",
"[",
"index",
"]",
",",
"ap... | Return the end frequency of the waveform at the given index value | [
"Return",
"the",
"end",
"frequency",
"of",
"the",
"waveform",
"at",
"the",
"given",
"index",
"value"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/bank.py#L387-L395 |
227,802 | gwastro/pycbc | pycbc/waveform/bank.py | TemplateBank.approximant | def approximant(self, index):
""" Return the name of the approximant ot use at the given index
"""
if 'approximant' not in self.table.fieldnames:
raise ValueError("approximant not found in input file and no "
"approximant was specified on initialization")
return self.table["approximant"][index] | python | def approximant(self, index):
if 'approximant' not in self.table.fieldnames:
raise ValueError("approximant not found in input file and no "
"approximant was specified on initialization")
return self.table["approximant"][index] | [
"def",
"approximant",
"(",
"self",
",",
"index",
")",
":",
"if",
"'approximant'",
"not",
"in",
"self",
".",
"table",
".",
"fieldnames",
":",
"raise",
"ValueError",
"(",
"\"approximant not found in input file and no \"",
"\"approximant was specified on initialization\"",
... | Return the name of the approximant ot use at the given index | [
"Return",
"the",
"name",
"of",
"the",
"approximant",
"ot",
"use",
"at",
"the",
"given",
"index"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/bank.py#L404-L410 |
227,803 | gwastro/pycbc | pycbc/waveform/bank.py | TemplateBank.template_thinning | def template_thinning(self, inj_filter_rejector):
"""Remove templates from bank that are far from all injections."""
if not inj_filter_rejector.enabled or \
inj_filter_rejector.chirp_time_window is None:
# Do nothing!
return
injection_parameters = inj_filter_rejector.injection_params.table
fref = inj_filter_rejector.f_lower
threshold = inj_filter_rejector.chirp_time_window
m1= self.table['mass1']
m2= self.table['mass2']
tau0_temp, _ = pycbc.pnutils.mass1_mass2_to_tau0_tau3(m1, m2, fref)
indices = []
for inj in injection_parameters:
tau0_inj, _ = \
pycbc.pnutils.mass1_mass2_to_tau0_tau3(inj.mass1, inj.mass2,
fref)
inj_indices = np.where(abs(tau0_temp - tau0_inj) <= threshold)[0]
indices.append(inj_indices)
indices_combined = np.concatenate(indices)
indices_unique= np.unique(indices_combined)
self.table = self.table[indices_unique] | python | def template_thinning(self, inj_filter_rejector):
if not inj_filter_rejector.enabled or \
inj_filter_rejector.chirp_time_window is None:
# Do nothing!
return
injection_parameters = inj_filter_rejector.injection_params.table
fref = inj_filter_rejector.f_lower
threshold = inj_filter_rejector.chirp_time_window
m1= self.table['mass1']
m2= self.table['mass2']
tau0_temp, _ = pycbc.pnutils.mass1_mass2_to_tau0_tau3(m1, m2, fref)
indices = []
for inj in injection_parameters:
tau0_inj, _ = \
pycbc.pnutils.mass1_mass2_to_tau0_tau3(inj.mass1, inj.mass2,
fref)
inj_indices = np.where(abs(tau0_temp - tau0_inj) <= threshold)[0]
indices.append(inj_indices)
indices_combined = np.concatenate(indices)
indices_unique= np.unique(indices_combined)
self.table = self.table[indices_unique] | [
"def",
"template_thinning",
"(",
"self",
",",
"inj_filter_rejector",
")",
":",
"if",
"not",
"inj_filter_rejector",
".",
"enabled",
"or",
"inj_filter_rejector",
".",
"chirp_time_window",
"is",
"None",
":",
"# Do nothing!",
"return",
"injection_parameters",
"=",
"inj_fi... | Remove templates from bank that are far from all injections. | [
"Remove",
"templates",
"from",
"bank",
"that",
"are",
"far",
"from",
"all",
"injections",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/bank.py#L415-L439 |
227,804 | gwastro/pycbc | pycbc/waveform/bank.py | TemplateBank.ensure_standard_filter_columns | def ensure_standard_filter_columns(self, low_frequency_cutoff=None):
""" Initialize FilterBank common fields
Parameters
----------
low_frequency_cutoff: {float, None}, Optional
A low frequency cutoff which overrides any given within the
template bank file.
"""
# Make sure we have a template duration field
if not hasattr(self.table, 'template_duration'):
self.table = self.table.add_fields(np.zeros(len(self.table),
dtype=np.float32), 'template_duration')
# Make sure we have a f_lower field
if low_frequency_cutoff is not None:
if not hasattr(self.table, 'f_lower'):
vec = np.zeros(len(self.table), dtype=np.float32)
self.table = self.table.add_fields(vec, 'f_lower')
self.table['f_lower'][:] = low_frequency_cutoff
self.min_f_lower = min(self.table['f_lower'])
if self.f_lower is None and self.min_f_lower == 0.:
raise ValueError('Invalid low-frequency cutoff settings') | python | def ensure_standard_filter_columns(self, low_frequency_cutoff=None):
# Make sure we have a template duration field
if not hasattr(self.table, 'template_duration'):
self.table = self.table.add_fields(np.zeros(len(self.table),
dtype=np.float32), 'template_duration')
# Make sure we have a f_lower field
if low_frequency_cutoff is not None:
if not hasattr(self.table, 'f_lower'):
vec = np.zeros(len(self.table), dtype=np.float32)
self.table = self.table.add_fields(vec, 'f_lower')
self.table['f_lower'][:] = low_frequency_cutoff
self.min_f_lower = min(self.table['f_lower'])
if self.f_lower is None and self.min_f_lower == 0.:
raise ValueError('Invalid low-frequency cutoff settings') | [
"def",
"ensure_standard_filter_columns",
"(",
"self",
",",
"low_frequency_cutoff",
"=",
"None",
")",
":",
"# Make sure we have a template duration field",
"if",
"not",
"hasattr",
"(",
"self",
".",
"table",
",",
"'template_duration'",
")",
":",
"self",
".",
"table",
... | Initialize FilterBank common fields
Parameters
----------
low_frequency_cutoff: {float, None}, Optional
A low frequency cutoff which overrides any given within the
template bank file. | [
"Initialize",
"FilterBank",
"common",
"fields"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/bank.py#L442-L466 |
227,805 | gwastro/pycbc | pycbc/waveform/bank.py | LiveFilterBank.round_up | def round_up(self, num):
"""Determine the length to use for this waveform by rounding.
Parameters
----------
num : int
Proposed size of waveform in seconds
Returns
-------
size: int
The rounded size to use for the waveform buffer in seconds. This
is calculaed using an internal `increment` attribute, which determines
the discreteness of the rounding.
"""
inc = self.increment
size = np.ceil(num / self.sample_rate / inc) * self.sample_rate * inc
return size | python | def round_up(self, num):
inc = self.increment
size = np.ceil(num / self.sample_rate / inc) * self.sample_rate * inc
return size | [
"def",
"round_up",
"(",
"self",
",",
"num",
")",
":",
"inc",
"=",
"self",
".",
"increment",
"size",
"=",
"np",
".",
"ceil",
"(",
"num",
"/",
"self",
".",
"sample_rate",
"/",
"inc",
")",
"*",
"self",
".",
"sample_rate",
"*",
"inc",
"return",
"size"
... | Determine the length to use for this waveform by rounding.
Parameters
----------
num : int
Proposed size of waveform in seconds
Returns
-------
size: int
The rounded size to use for the waveform buffer in seconds. This
is calculaed using an internal `increment` attribute, which determines
the discreteness of the rounding. | [
"Determine",
"the",
"length",
"to",
"use",
"for",
"this",
"waveform",
"by",
"rounding",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/bank.py#L488-L505 |
227,806 | gwastro/pycbc | pycbc/waveform/bank.py | FilterBank.get_decompressed_waveform | def get_decompressed_waveform(self, tempout, index, f_lower=None,
approximant=None, df=None):
"""Returns a frequency domain decompressed waveform for the template
in the bank corresponding to the index taken in as an argument. The
decompressed waveform is obtained by interpolating in frequency space,
the amplitude and phase points for the compressed template that are
read in from the bank."""
from pycbc.waveform.waveform import props
from pycbc.waveform import get_waveform_filter_length_in_time
# Get the template hash corresponding to the template index taken in as argument
tmplt_hash = self.table.template_hash[index]
# Read the compressed waveform from the bank file
compressed_waveform = pycbc.waveform.compress.CompressedWaveform.from_hdf(
self.filehandler, tmplt_hash,
load_now=True)
# Get the interpolation method to be used to decompress the waveform
if self.waveform_decompression_method is not None :
decompression_method = self.waveform_decompression_method
else :
decompression_method = compressed_waveform.interpolation
logging.info("Decompressing waveform using %s", decompression_method)
if df is not None :
delta_f = df
else :
delta_f = self.delta_f
# Create memory space for writing the decompressed waveform
decomp_scratch = FrequencySeries(tempout[0:self.filter_length], delta_f=delta_f, copy=False)
# Get the decompressed waveform
hdecomp = compressed_waveform.decompress(out=decomp_scratch, f_lower=f_lower, interpolation=decompression_method)
p = props(self.table[index])
p.pop('approximant')
try:
tmpltdur = self.table[index].template_duration
except AttributeError:
tmpltdur = None
if tmpltdur is None or tmpltdur==0.0 :
tmpltdur = get_waveform_filter_length_in_time(approximant, **p)
hdecomp.chirp_length = tmpltdur
hdecomp.length_in_time = hdecomp.chirp_length
return hdecomp | python | def get_decompressed_waveform(self, tempout, index, f_lower=None,
approximant=None, df=None):
from pycbc.waveform.waveform import props
from pycbc.waveform import get_waveform_filter_length_in_time
# Get the template hash corresponding to the template index taken in as argument
tmplt_hash = self.table.template_hash[index]
# Read the compressed waveform from the bank file
compressed_waveform = pycbc.waveform.compress.CompressedWaveform.from_hdf(
self.filehandler, tmplt_hash,
load_now=True)
# Get the interpolation method to be used to decompress the waveform
if self.waveform_decompression_method is not None :
decompression_method = self.waveform_decompression_method
else :
decompression_method = compressed_waveform.interpolation
logging.info("Decompressing waveform using %s", decompression_method)
if df is not None :
delta_f = df
else :
delta_f = self.delta_f
# Create memory space for writing the decompressed waveform
decomp_scratch = FrequencySeries(tempout[0:self.filter_length], delta_f=delta_f, copy=False)
# Get the decompressed waveform
hdecomp = compressed_waveform.decompress(out=decomp_scratch, f_lower=f_lower, interpolation=decompression_method)
p = props(self.table[index])
p.pop('approximant')
try:
tmpltdur = self.table[index].template_duration
except AttributeError:
tmpltdur = None
if tmpltdur is None or tmpltdur==0.0 :
tmpltdur = get_waveform_filter_length_in_time(approximant, **p)
hdecomp.chirp_length = tmpltdur
hdecomp.length_in_time = hdecomp.chirp_length
return hdecomp | [
"def",
"get_decompressed_waveform",
"(",
"self",
",",
"tempout",
",",
"index",
",",
"f_lower",
"=",
"None",
",",
"approximant",
"=",
"None",
",",
"df",
"=",
"None",
")",
":",
"from",
"pycbc",
".",
"waveform",
".",
"waveform",
"import",
"props",
"from",
"... | Returns a frequency domain decompressed waveform for the template
in the bank corresponding to the index taken in as an argument. The
decompressed waveform is obtained by interpolating in frequency space,
the amplitude and phase points for the compressed template that are
read in from the bank. | [
"Returns",
"a",
"frequency",
"domain",
"decompressed",
"waveform",
"for",
"the",
"template",
"in",
"the",
"bank",
"corresponding",
"to",
"the",
"index",
"taken",
"in",
"as",
"an",
"argument",
".",
"The",
"decompressed",
"waveform",
"is",
"obtained",
"by",
"int... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/bank.py#L624-L670 |
227,807 | gwastro/pycbc | pycbc/waveform/bank.py | FilterBank.generate_with_delta_f_and_max_freq | def generate_with_delta_f_and_max_freq(self, t_num, max_freq, delta_f,
low_frequency_cutoff=None,
cached_mem=None):
"""Generate the template with index t_num using custom length."""
approximant = self.approximant(t_num)
# Don't want to use INTERP waveforms in here
if approximant.endswith('_INTERP'):
approximant = approximant.replace('_INTERP', '')
# Using SPAtmplt here is bad as the stored cbrt and logv get
# recalculated as we change delta_f values. Fall back to TaylorF2
# in lalsimulation.
if approximant == 'SPAtmplt':
approximant = 'TaylorF2'
if cached_mem is None:
wav_len = int(max_freq / delta_f) + 1
cached_mem = zeros(wav_len, dtype=np.complex64)
if self.has_compressed_waveforms and self.enable_compressed_waveforms:
htilde = self.get_decompressed_waveform(cached_mem, t_num,
f_lower=low_frequency_cutoff,
approximant=approximant,
df=delta_f)
else :
htilde = pycbc.waveform.get_waveform_filter(
cached_mem, self.table[t_num], approximant=approximant,
f_lower=low_frequency_cutoff, f_final=max_freq, delta_f=delta_f,
distance=1./DYN_RANGE_FAC, delta_t=1./(2.*max_freq))
return htilde | python | def generate_with_delta_f_and_max_freq(self, t_num, max_freq, delta_f,
low_frequency_cutoff=None,
cached_mem=None):
approximant = self.approximant(t_num)
# Don't want to use INTERP waveforms in here
if approximant.endswith('_INTERP'):
approximant = approximant.replace('_INTERP', '')
# Using SPAtmplt here is bad as the stored cbrt and logv get
# recalculated as we change delta_f values. Fall back to TaylorF2
# in lalsimulation.
if approximant == 'SPAtmplt':
approximant = 'TaylorF2'
if cached_mem is None:
wav_len = int(max_freq / delta_f) + 1
cached_mem = zeros(wav_len, dtype=np.complex64)
if self.has_compressed_waveforms and self.enable_compressed_waveforms:
htilde = self.get_decompressed_waveform(cached_mem, t_num,
f_lower=low_frequency_cutoff,
approximant=approximant,
df=delta_f)
else :
htilde = pycbc.waveform.get_waveform_filter(
cached_mem, self.table[t_num], approximant=approximant,
f_lower=low_frequency_cutoff, f_final=max_freq, delta_f=delta_f,
distance=1./DYN_RANGE_FAC, delta_t=1./(2.*max_freq))
return htilde | [
"def",
"generate_with_delta_f_and_max_freq",
"(",
"self",
",",
"t_num",
",",
"max_freq",
",",
"delta_f",
",",
"low_frequency_cutoff",
"=",
"None",
",",
"cached_mem",
"=",
"None",
")",
":",
"approximant",
"=",
"self",
".",
"approximant",
"(",
"t_num",
")",
"# D... | Generate the template with index t_num using custom length. | [
"Generate",
"the",
"template",
"with",
"index",
"t_num",
"using",
"custom",
"length",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/bank.py#L672-L698 |
227,808 | gwastro/pycbc | pycbc/waveform/generator.py | select_waveform_generator | def select_waveform_generator(approximant):
"""Returns the single-IFO generator for the approximant.
Parameters
----------
approximant : str
Name of waveform approximant. Valid names can be found using
``pycbc.waveform`` methods.
Returns
-------
generator : (PyCBC generator instance)
A waveform generator object.
Examples
--------
Get a list of available approximants:
>>> from pycbc import waveform
>>> waveform.fd_approximants()
>>> waveform.td_approximants()
>>> from pycbc.waveform import ringdown
>>> ringdown.ringdown_fd_approximants.keys()
Get generator object:
>>> from pycbc.waveform.generator import select_waveform_generator
>>> select_waveform_generator(waveform.fd_approximants()[0])
"""
# check if frequency-domain CBC waveform
if approximant in waveform.fd_approximants():
return FDomainCBCGenerator
# check if time-domain CBC waveform
elif approximant in waveform.td_approximants():
return TDomainCBCGenerator
# check if frequency-domain ringdown waveform
elif approximant in ringdown.ringdown_fd_approximants:
if approximant == 'FdQNMfromFinalMassSpin':
return FDomainMassSpinRingdownGenerator
elif approximant == 'FdQNMfromFreqTau':
return FDomainFreqTauRingdownGenerator
elif approximant in ringdown.ringdown_td_approximants:
if approximant == 'TdQNMfromFinalMassSpin':
return TDomainMassSpinRingdownGenerator
elif approximant == 'TdQNMfromFreqTau':
return TDomainFreqTauRingdownGenerator
# otherwise waveform approximant is not supported
else:
raise ValueError("%s is not a valid approximant." % approximant) | python | def select_waveform_generator(approximant):
# check if frequency-domain CBC waveform
if approximant in waveform.fd_approximants():
return FDomainCBCGenerator
# check if time-domain CBC waveform
elif approximant in waveform.td_approximants():
return TDomainCBCGenerator
# check if frequency-domain ringdown waveform
elif approximant in ringdown.ringdown_fd_approximants:
if approximant == 'FdQNMfromFinalMassSpin':
return FDomainMassSpinRingdownGenerator
elif approximant == 'FdQNMfromFreqTau':
return FDomainFreqTauRingdownGenerator
elif approximant in ringdown.ringdown_td_approximants:
if approximant == 'TdQNMfromFinalMassSpin':
return TDomainMassSpinRingdownGenerator
elif approximant == 'TdQNMfromFreqTau':
return TDomainFreqTauRingdownGenerator
# otherwise waveform approximant is not supported
else:
raise ValueError("%s is not a valid approximant." % approximant) | [
"def",
"select_waveform_generator",
"(",
"approximant",
")",
":",
"# check if frequency-domain CBC waveform",
"if",
"approximant",
"in",
"waveform",
".",
"fd_approximants",
"(",
")",
":",
"return",
"FDomainCBCGenerator",
"# check if time-domain CBC waveform",
"elif",
"approxi... | Returns the single-IFO generator for the approximant.
Parameters
----------
approximant : str
Name of waveform approximant. Valid names can be found using
``pycbc.waveform`` methods.
Returns
-------
generator : (PyCBC generator instance)
A waveform generator object.
Examples
--------
Get a list of available approximants:
>>> from pycbc import waveform
>>> waveform.fd_approximants()
>>> waveform.td_approximants()
>>> from pycbc.waveform import ringdown
>>> ringdown.ringdown_fd_approximants.keys()
Get generator object:
>>> from pycbc.waveform.generator import select_waveform_generator
>>> select_waveform_generator(waveform.fd_approximants()[0]) | [
"Returns",
"the",
"single",
"-",
"IFO",
"generator",
"for",
"the",
"approximant",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/generator.py#L597-L648 |
227,809 | gwastro/pycbc | pycbc/waveform/generator.py | BaseGenerator.generate_from_args | def generate_from_args(self, *args):
"""Generates a waveform. The list of arguments must be in the same
order as self's variable_args attribute.
"""
if len(args) != len(self.variable_args):
raise ValueError("variable argument length mismatch")
return self.generate(**dict(zip(self.variable_args, args))) | python | def generate_from_args(self, *args):
if len(args) != len(self.variable_args):
raise ValueError("variable argument length mismatch")
return self.generate(**dict(zip(self.variable_args, args))) | [
"def",
"generate_from_args",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"!=",
"len",
"(",
"self",
".",
"variable_args",
")",
":",
"raise",
"ValueError",
"(",
"\"variable argument length mismatch\"",
")",
"return",
"self",
".",
... | Generates a waveform. The list of arguments must be in the same
order as self's variable_args attribute. | [
"Generates",
"a",
"waveform",
".",
"The",
"list",
"of",
"arguments",
"must",
"be",
"in",
"the",
"same",
"order",
"as",
"self",
"s",
"variable_args",
"attribute",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/generator.py#L104-L110 |
227,810 | gwastro/pycbc | pycbc/waveform/generator.py | TDomainCBCGenerator._postgenerate | def _postgenerate(self, res):
"""Applies a taper if it is in current params.
"""
hp, hc = res
try:
hp = taper_timeseries(hp, tapermethod=self.current_params['taper'])
hc = taper_timeseries(hc, tapermethod=self.current_params['taper'])
except KeyError:
pass
return hp, hc | python | def _postgenerate(self, res):
hp, hc = res
try:
hp = taper_timeseries(hp, tapermethod=self.current_params['taper'])
hc = taper_timeseries(hc, tapermethod=self.current_params['taper'])
except KeyError:
pass
return hp, hc | [
"def",
"_postgenerate",
"(",
"self",
",",
"res",
")",
":",
"hp",
",",
"hc",
"=",
"res",
"try",
":",
"hp",
"=",
"taper_timeseries",
"(",
"hp",
",",
"tapermethod",
"=",
"self",
".",
"current_params",
"[",
"'taper'",
"]",
")",
"hc",
"=",
"taper_timeseries... | Applies a taper if it is in current params. | [
"Applies",
"a",
"taper",
"if",
"it",
"is",
"in",
"current",
"params",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/generator.py#L281-L290 |
227,811 | gwastro/pycbc | pycbc/waveform/generator.py | FDomainDetFrameGenerator.generate_from_args | def generate_from_args(self, *args):
"""Generates a waveform, applies a time shift and the detector response
function from the given args.
The args are assumed to be in the same order as the variable args.
"""
return self.generate(**dict(zip(self.variable_args, args))) | python | def generate_from_args(self, *args):
return self.generate(**dict(zip(self.variable_args, args))) | [
"def",
"generate_from_args",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"self",
".",
"generate",
"(",
"*",
"*",
"dict",
"(",
"zip",
"(",
"self",
".",
"variable_args",
",",
"args",
")",
")",
")"
] | Generates a waveform, applies a time shift and the detector response
function from the given args.
The args are assumed to be in the same order as the variable args. | [
"Generates",
"a",
"waveform",
"applies",
"a",
"time",
"shift",
"and",
"the",
"detector",
"response",
"function",
"from",
"the",
"given",
"args",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/generator.py#L537-L543 |
227,812 | gwastro/pycbc | pycbc/waveform/generator.py | FDomainDetFrameGenerator.generate | def generate(self, **kwargs):
"""Generates a waveform, applies a time shift and the detector response
function from the given kwargs.
"""
self.current_params.update(kwargs)
rfparams = {param: self.current_params[param]
for param in kwargs if param not in self.location_args}
hp, hc = self.rframe_generator.generate(**rfparams)
if isinstance(hp, TimeSeries):
df = self.current_params['delta_f']
hp = hp.to_frequencyseries(delta_f=df)
hc = hc.to_frequencyseries(delta_f=df)
# time-domain waveforms will not be shifted so that the peak amp
# happens at the end of the time series (as they are for f-domain),
# so we add an additional shift to account for it
tshift = 1./df - abs(hp._epoch)
else:
tshift = 0.
hp._epoch = hc._epoch = self._epoch
h = {}
if self.detector_names != ['RF']:
for detname, det in self.detectors.items():
# apply detector response function
fp, fc = det.antenna_pattern(self.current_params['ra'],
self.current_params['dec'],
self.current_params['polarization'],
self.current_params['tc'])
thish = fp*hp + fc*hc
# apply the time shift
tc = self.current_params['tc'] + \
det.time_delay_from_earth_center(self.current_params['ra'],
self.current_params['dec'], self.current_params['tc'])
h[detname] = apply_fd_time_shift(thish, tc+tshift, copy=False)
if self.recalib:
# recalibrate with given calibration model
h[detname] = \
self.recalib[detname].map_to_adjust(h[detname],
**self.current_params)
else:
# no detector response, just use the + polarization
if 'tc' in self.current_params:
hp = apply_fd_time_shift(hp, self.current_params['tc']+tshift,
copy=False)
h['RF'] = hp
if self.gates is not None:
# resize all to nearest power of 2
for d in h.values():
d.resize(ceilpow2(len(d)-1) + 1)
h = strain.apply_gates_to_fd(h, self.gates)
return h | python | def generate(self, **kwargs):
self.current_params.update(kwargs)
rfparams = {param: self.current_params[param]
for param in kwargs if param not in self.location_args}
hp, hc = self.rframe_generator.generate(**rfparams)
if isinstance(hp, TimeSeries):
df = self.current_params['delta_f']
hp = hp.to_frequencyseries(delta_f=df)
hc = hc.to_frequencyseries(delta_f=df)
# time-domain waveforms will not be shifted so that the peak amp
# happens at the end of the time series (as they are for f-domain),
# so we add an additional shift to account for it
tshift = 1./df - abs(hp._epoch)
else:
tshift = 0.
hp._epoch = hc._epoch = self._epoch
h = {}
if self.detector_names != ['RF']:
for detname, det in self.detectors.items():
# apply detector response function
fp, fc = det.antenna_pattern(self.current_params['ra'],
self.current_params['dec'],
self.current_params['polarization'],
self.current_params['tc'])
thish = fp*hp + fc*hc
# apply the time shift
tc = self.current_params['tc'] + \
det.time_delay_from_earth_center(self.current_params['ra'],
self.current_params['dec'], self.current_params['tc'])
h[detname] = apply_fd_time_shift(thish, tc+tshift, copy=False)
if self.recalib:
# recalibrate with given calibration model
h[detname] = \
self.recalib[detname].map_to_adjust(h[detname],
**self.current_params)
else:
# no detector response, just use the + polarization
if 'tc' in self.current_params:
hp = apply_fd_time_shift(hp, self.current_params['tc']+tshift,
copy=False)
h['RF'] = hp
if self.gates is not None:
# resize all to nearest power of 2
for d in h.values():
d.resize(ceilpow2(len(d)-1) + 1)
h = strain.apply_gates_to_fd(h, self.gates)
return h | [
"def",
"generate",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"current_params",
".",
"update",
"(",
"kwargs",
")",
"rfparams",
"=",
"{",
"param",
":",
"self",
".",
"current_params",
"[",
"param",
"]",
"for",
"param",
"in",
"kwargs",
... | Generates a waveform, applies a time shift and the detector response
function from the given kwargs. | [
"Generates",
"a",
"waveform",
"applies",
"a",
"time",
"shift",
"and",
"the",
"detector",
"response",
"function",
"from",
"the",
"given",
"kwargs",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/generator.py#L545-L594 |
227,813 | gwastro/pycbc | pycbc/types/optparse.py | positive_float | def positive_float(s):
"""
Ensure argument is a positive real number and return it as float.
To be used as type in argparse arguments.
"""
err_msg = "must be a positive number, not %r" % s
try:
value = float(s)
except ValueError:
raise argparse.ArgumentTypeError(err_msg)
if value <= 0:
raise argparse.ArgumentTypeError(err_msg)
return value | python | def positive_float(s):
err_msg = "must be a positive number, not %r" % s
try:
value = float(s)
except ValueError:
raise argparse.ArgumentTypeError(err_msg)
if value <= 0:
raise argparse.ArgumentTypeError(err_msg)
return value | [
"def",
"positive_float",
"(",
"s",
")",
":",
"err_msg",
"=",
"\"must be a positive number, not %r\"",
"%",
"s",
"try",
":",
"value",
"=",
"float",
"(",
"s",
")",
"except",
"ValueError",
":",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"err_msg",
")",
... | Ensure argument is a positive real number and return it as float.
To be used as type in argparse arguments. | [
"Ensure",
"argument",
"is",
"a",
"positive",
"real",
"number",
"and",
"return",
"it",
"as",
"float",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/types/optparse.py#L326-L339 |
227,814 | gwastro/pycbc | pycbc/types/optparse.py | nonnegative_float | def nonnegative_float(s):
"""
Ensure argument is a positive real number or zero and return it as float.
To be used as type in argparse arguments.
"""
err_msg = "must be either positive or zero, not %r" % s
try:
value = float(s)
except ValueError:
raise argparse.ArgumentTypeError(err_msg)
if value < 0:
raise argparse.ArgumentTypeError(err_msg)
return value | python | def nonnegative_float(s):
err_msg = "must be either positive or zero, not %r" % s
try:
value = float(s)
except ValueError:
raise argparse.ArgumentTypeError(err_msg)
if value < 0:
raise argparse.ArgumentTypeError(err_msg)
return value | [
"def",
"nonnegative_float",
"(",
"s",
")",
":",
"err_msg",
"=",
"\"must be either positive or zero, not %r\"",
"%",
"s",
"try",
":",
"value",
"=",
"float",
"(",
"s",
")",
"except",
"ValueError",
":",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"err_msg",... | Ensure argument is a positive real number or zero and return it as float.
To be used as type in argparse arguments. | [
"Ensure",
"argument",
"is",
"a",
"positive",
"real",
"number",
"or",
"zero",
"and",
"return",
"it",
"as",
"float",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/types/optparse.py#L341-L354 |
227,815 | gwastro/pycbc | pycbc/psd/__init__.py | from_cli | def from_cli(opt, length, delta_f, low_frequency_cutoff,
strain=None, dyn_range_factor=1, precision=None):
"""Parses the CLI options related to the noise PSD and returns a
FrequencySeries with the corresponding PSD. If necessary, the PSD is
linearly interpolated to achieve the resolution specified in the CLI.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes (psd_model, psd_file, asd_file, psd_estimation,
psd_segment_length, psd_segment_stride, psd_inverse_length,
psd_output).
length : int
The length in samples of the output PSD.
delta_f : float
The frequency step of the output PSD.
low_frequency_cutoff: float
The low frequncy cutoff to use when calculating the PSD.
strain : {None, TimeSeries}
Time series containing the data from which the PSD should be measured,
when psd_estimation is in use.
dyn_range_factor : {1, float}
For PSDs taken from models or text files, if `dyn_range_factor` is
not None, then the PSD is multiplied by `dyn_range_factor` ** 2.
precision : str, choices (None,'single','double')
If not specified, or specified as None, the precision of the returned
PSD will match the precision of the data, if measuring a PSD, or will
match the default precision of the model if using an analytical PSD.
If 'single' the PSD will be converted to float32, if not already in
that precision. If 'double' the PSD will be converted to float64, if
not already in that precision.
Returns
-------
psd : FrequencySeries
The frequency series containing the PSD.
"""
f_low = low_frequency_cutoff
sample_rate = int((length -1) * 2 * delta_f)
try:
psd_estimation = opt.psd_estimation is not None
except AttributeError:
psd_estimation = False
exclusive_opts = [opt.psd_model, opt.psd_file, opt.asd_file,
psd_estimation]
if sum(map(bool, exclusive_opts)) != 1:
err_msg = "You must specify exactly one of '--psd-file', "
err_msg += "'--psd-model', '--asd-file', '--psd-estimation'"
raise ValueError(err_msg)
if (opt.psd_model or opt.psd_file or opt.asd_file):
# PSD from lalsimulation or file
if opt.psd_model:
psd = from_string(opt.psd_model, length, delta_f, f_low)
elif opt.psd_file or opt.asd_file:
if opt.asd_file:
psd_file_name = opt.asd_file
else:
psd_file_name = opt.psd_file
if psd_file_name.endswith(('.dat', '.txt')):
is_asd_file = bool(opt.asd_file)
psd = from_txt(psd_file_name, length,
delta_f, f_low, is_asd_file=is_asd_file)
elif opt.asd_file:
err_msg = "ASD files are only valid as ASCII files (.dat or "
err_msg += ".txt). Supplied {}.".format(psd_file_name)
elif psd_file_name.endswith(('.xml', '.xml.gz')):
psd = from_xml(psd_file_name, length, delta_f, f_low,
ifo_string=opt.psd_file_xml_ifo_string,
root_name=opt.psd_file_xml_root_name)
# Set values < flow to the value at flow
kmin = int(low_frequency_cutoff / psd.delta_f)
psd[0:kmin] = psd[kmin]
psd *= dyn_range_factor ** 2
elif psd_estimation:
# estimate PSD from data
psd = welch(strain, avg_method=opt.psd_estimation,
seg_len=int(opt.psd_segment_length * sample_rate),
seg_stride=int(opt.psd_segment_stride * sample_rate),
num_segments=opt.psd_num_segments,
require_exact_data_fit=False)
if delta_f != psd.delta_f:
psd = interpolate(psd, delta_f)
else:
# Shouldn't be possible to get here
raise ValueError("Shouldn't be possible to raise this!")
if opt.psd_inverse_length:
psd = inverse_spectrum_truncation(psd,
int(opt.psd_inverse_length * sample_rate),
low_frequency_cutoff=f_low)
if hasattr(opt, 'psd_output') and opt.psd_output:
(psd.astype(float64) / (dyn_range_factor ** 2)).save(opt.psd_output)
if precision is None:
return psd
elif precision == 'single':
return psd.astype(float32)
elif precision == 'double':
return psd.astype(float64)
else:
err_msg = "If provided the precision kwarg must be either 'single' "
err_msg += "or 'double'. You provided %s." %(precision)
raise ValueError(err_msg) | python | def from_cli(opt, length, delta_f, low_frequency_cutoff,
strain=None, dyn_range_factor=1, precision=None):
f_low = low_frequency_cutoff
sample_rate = int((length -1) * 2 * delta_f)
try:
psd_estimation = opt.psd_estimation is not None
except AttributeError:
psd_estimation = False
exclusive_opts = [opt.psd_model, opt.psd_file, opt.asd_file,
psd_estimation]
if sum(map(bool, exclusive_opts)) != 1:
err_msg = "You must specify exactly one of '--psd-file', "
err_msg += "'--psd-model', '--asd-file', '--psd-estimation'"
raise ValueError(err_msg)
if (opt.psd_model or opt.psd_file or opt.asd_file):
# PSD from lalsimulation or file
if opt.psd_model:
psd = from_string(opt.psd_model, length, delta_f, f_low)
elif opt.psd_file or opt.asd_file:
if opt.asd_file:
psd_file_name = opt.asd_file
else:
psd_file_name = opt.psd_file
if psd_file_name.endswith(('.dat', '.txt')):
is_asd_file = bool(opt.asd_file)
psd = from_txt(psd_file_name, length,
delta_f, f_low, is_asd_file=is_asd_file)
elif opt.asd_file:
err_msg = "ASD files are only valid as ASCII files (.dat or "
err_msg += ".txt). Supplied {}.".format(psd_file_name)
elif psd_file_name.endswith(('.xml', '.xml.gz')):
psd = from_xml(psd_file_name, length, delta_f, f_low,
ifo_string=opt.psd_file_xml_ifo_string,
root_name=opt.psd_file_xml_root_name)
# Set values < flow to the value at flow
kmin = int(low_frequency_cutoff / psd.delta_f)
psd[0:kmin] = psd[kmin]
psd *= dyn_range_factor ** 2
elif psd_estimation:
# estimate PSD from data
psd = welch(strain, avg_method=opt.psd_estimation,
seg_len=int(opt.psd_segment_length * sample_rate),
seg_stride=int(opt.psd_segment_stride * sample_rate),
num_segments=opt.psd_num_segments,
require_exact_data_fit=False)
if delta_f != psd.delta_f:
psd = interpolate(psd, delta_f)
else:
# Shouldn't be possible to get here
raise ValueError("Shouldn't be possible to raise this!")
if opt.psd_inverse_length:
psd = inverse_spectrum_truncation(psd,
int(opt.psd_inverse_length * sample_rate),
low_frequency_cutoff=f_low)
if hasattr(opt, 'psd_output') and opt.psd_output:
(psd.astype(float64) / (dyn_range_factor ** 2)).save(opt.psd_output)
if precision is None:
return psd
elif precision == 'single':
return psd.astype(float32)
elif precision == 'double':
return psd.astype(float64)
else:
err_msg = "If provided the precision kwarg must be either 'single' "
err_msg += "or 'double'. You provided %s." %(precision)
raise ValueError(err_msg) | [
"def",
"from_cli",
"(",
"opt",
",",
"length",
",",
"delta_f",
",",
"low_frequency_cutoff",
",",
"strain",
"=",
"None",
",",
"dyn_range_factor",
"=",
"1",
",",
"precision",
"=",
"None",
")",
":",
"f_low",
"=",
"low_frequency_cutoff",
"sample_rate",
"=",
"int"... | Parses the CLI options related to the noise PSD and returns a
FrequencySeries with the corresponding PSD. If necessary, the PSD is
linearly interpolated to achieve the resolution specified in the CLI.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes (psd_model, psd_file, asd_file, psd_estimation,
psd_segment_length, psd_segment_stride, psd_inverse_length,
psd_output).
length : int
The length in samples of the output PSD.
delta_f : float
The frequency step of the output PSD.
low_frequency_cutoff: float
The low frequncy cutoff to use when calculating the PSD.
strain : {None, TimeSeries}
Time series containing the data from which the PSD should be measured,
when psd_estimation is in use.
dyn_range_factor : {1, float}
For PSDs taken from models or text files, if `dyn_range_factor` is
not None, then the PSD is multiplied by `dyn_range_factor` ** 2.
precision : str, choices (None,'single','double')
If not specified, or specified as None, the precision of the returned
PSD will match the precision of the data, if measuring a PSD, or will
match the default precision of the model if using an analytical PSD.
If 'single' the PSD will be converted to float32, if not already in
that precision. If 'double' the PSD will be converted to float64, if
not already in that precision.
Returns
-------
psd : FrequencySeries
The frequency series containing the PSD. | [
"Parses",
"the",
"CLI",
"options",
"related",
"to",
"the",
"noise",
"PSD",
"and",
"returns",
"a",
"FrequencySeries",
"with",
"the",
"corresponding",
"PSD",
".",
"If",
"necessary",
"the",
"PSD",
"is",
"linearly",
"interpolated",
"to",
"achieve",
"the",
"resolut... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/psd/__init__.py#L29-L139 |
227,816 | gwastro/pycbc | pycbc/psd/__init__.py | from_cli_single_ifo | def from_cli_single_ifo(opt, length, delta_f, low_frequency_cutoff, ifo,
**kwargs):
"""
Get the PSD for a single ifo when using the multi-detector CLI
"""
single_det_opt = copy_opts_for_single_ifo(opt, ifo)
return from_cli(single_det_opt, length, delta_f, low_frequency_cutoff,
**kwargs) | python | def from_cli_single_ifo(opt, length, delta_f, low_frequency_cutoff, ifo,
**kwargs):
single_det_opt = copy_opts_for_single_ifo(opt, ifo)
return from_cli(single_det_opt, length, delta_f, low_frequency_cutoff,
**kwargs) | [
"def",
"from_cli_single_ifo",
"(",
"opt",
",",
"length",
",",
"delta_f",
",",
"low_frequency_cutoff",
",",
"ifo",
",",
"*",
"*",
"kwargs",
")",
":",
"single_det_opt",
"=",
"copy_opts_for_single_ifo",
"(",
"opt",
",",
"ifo",
")",
"return",
"from_cli",
"(",
"s... | Get the PSD for a single ifo when using the multi-detector CLI | [
"Get",
"the",
"PSD",
"for",
"a",
"single",
"ifo",
"when",
"using",
"the",
"multi",
"-",
"detector",
"CLI"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/psd/__init__.py#L141-L148 |
227,817 | gwastro/pycbc | pycbc/psd/__init__.py | from_cli_multi_ifos | def from_cli_multi_ifos(opt, length_dict, delta_f_dict,
low_frequency_cutoff_dict, ifos, strain_dict=None,
**kwargs):
"""
Get the PSD for all ifos when using the multi-detector CLI
"""
psd = {}
for ifo in ifos:
if strain_dict is not None:
strain = strain_dict[ifo]
else:
strain = None
psd[ifo] = from_cli_single_ifo(opt, length_dict[ifo], delta_f_dict[ifo],
low_frequency_cutoff_dict[ifo], ifo,
strain=strain, **kwargs)
return psd | python | def from_cli_multi_ifos(opt, length_dict, delta_f_dict,
low_frequency_cutoff_dict, ifos, strain_dict=None,
**kwargs):
psd = {}
for ifo in ifos:
if strain_dict is not None:
strain = strain_dict[ifo]
else:
strain = None
psd[ifo] = from_cli_single_ifo(opt, length_dict[ifo], delta_f_dict[ifo],
low_frequency_cutoff_dict[ifo], ifo,
strain=strain, **kwargs)
return psd | [
"def",
"from_cli_multi_ifos",
"(",
"opt",
",",
"length_dict",
",",
"delta_f_dict",
",",
"low_frequency_cutoff_dict",
",",
"ifos",
",",
"strain_dict",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"psd",
"=",
"{",
"}",
"for",
"ifo",
"in",
"ifos",
":",
"... | Get the PSD for all ifos when using the multi-detector CLI | [
"Get",
"the",
"PSD",
"for",
"all",
"ifos",
"when",
"using",
"the",
"multi",
"-",
"detector",
"CLI"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/psd/__init__.py#L150-L165 |
227,818 | gwastro/pycbc | pycbc/psd/__init__.py | generate_overlapping_psds | def generate_overlapping_psds(opt, gwstrain, flen, delta_f, flow,
dyn_range_factor=1., precision=None):
"""Generate a set of overlapping PSDs to cover a stretch of data. This
allows one to analyse a long stretch of data with PSD measurements that
change with time.
Parameters
-----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes (psd_model, psd_file, asd_file, psd_estimation,
psd_segment_length, psd_segment_stride, psd_inverse_length, psd_output).
gwstrain : Strain object
The timeseries of raw data on which to estimate PSDs.
flen : int
The length in samples of the output PSDs.
delta_f : float
The frequency step of the output PSDs.
flow: float
The low frequncy cutoff to use when calculating the PSD.
dyn_range_factor : {1, float}
For PSDs taken from models or text files, if `dyn_range_factor` is
not None, then the PSD is multiplied by `dyn_range_factor` ** 2.
precision : str, choices (None,'single','double')
If not specified, or specified as None, the precision of the returned
PSD will match the precision of the data, if measuring a PSD, or will
match the default precision of the model if using an analytical PSD.
If 'single' the PSD will be converted to float32, if not already in
that precision. If 'double' the PSD will be converted to float64, if
not already in that precision.
Returns
--------
psd_and_times : list of (start, end, PSD) tuples
This is a list of tuples containing one entry for each PSD. The first
and second entries (start, end) in each tuple represent the index
range of the gwstrain data that was used to estimate that PSD. The
third entry (psd) contains the PSD estimate between that interval.
"""
if not opt.psd_estimation:
psd = from_cli(opt, flen, delta_f, flow, strain=gwstrain,
dyn_range_factor=dyn_range_factor, precision=precision)
psds_and_times = [ (0, len(gwstrain), psd) ]
return psds_and_times
# Figure out the data length used for PSD generation
seg_stride = int(opt.psd_segment_stride * gwstrain.sample_rate)
seg_len = int(opt.psd_segment_length * gwstrain.sample_rate)
input_data_len = len(gwstrain)
if opt.psd_num_segments is None:
# FIXME: Should we make --psd-num-segments mandatory?
# err_msg = "You must supply --num-segments."
# raise ValueError(err_msg)
num_segments = int(input_data_len // seg_stride) - 1
else:
num_segments = int(opt.psd_num_segments)
psd_data_len = (num_segments - 1) * seg_stride + seg_len
# How many unique PSD measurements is this?
psds_and_times = []
if input_data_len < psd_data_len:
err_msg = "Input data length must be longer than data length needed "
err_msg += "to estimate a PSD. You specified that a PSD should be "
err_msg += "estimated with %d seconds. " %(psd_data_len)
err_msg += "Input data length is %d seconds. " %(input_data_len)
raise ValueError(err_msg)
elif input_data_len == psd_data_len:
num_psd_measurements = 1
psd_stride = 0
else:
num_psd_measurements = int(2 * (input_data_len-1) / psd_data_len)
psd_stride = int((input_data_len - psd_data_len) / num_psd_measurements)
for idx in range(num_psd_measurements):
if idx == (num_psd_measurements - 1):
start_idx = input_data_len - psd_data_len
end_idx = input_data_len
else:
start_idx = psd_stride * idx
end_idx = psd_data_len + psd_stride * idx
strain_part = gwstrain[start_idx:end_idx]
psd = from_cli(opt, flen, delta_f, flow, strain=strain_part,
dyn_range_factor=dyn_range_factor, precision=precision)
psds_and_times.append( (start_idx, end_idx, psd) )
return psds_and_times | python | def generate_overlapping_psds(opt, gwstrain, flen, delta_f, flow,
dyn_range_factor=1., precision=None):
if not opt.psd_estimation:
psd = from_cli(opt, flen, delta_f, flow, strain=gwstrain,
dyn_range_factor=dyn_range_factor, precision=precision)
psds_and_times = [ (0, len(gwstrain), psd) ]
return psds_and_times
# Figure out the data length used for PSD generation
seg_stride = int(opt.psd_segment_stride * gwstrain.sample_rate)
seg_len = int(opt.psd_segment_length * gwstrain.sample_rate)
input_data_len = len(gwstrain)
if opt.psd_num_segments is None:
# FIXME: Should we make --psd-num-segments mandatory?
# err_msg = "You must supply --num-segments."
# raise ValueError(err_msg)
num_segments = int(input_data_len // seg_stride) - 1
else:
num_segments = int(opt.psd_num_segments)
psd_data_len = (num_segments - 1) * seg_stride + seg_len
# How many unique PSD measurements is this?
psds_and_times = []
if input_data_len < psd_data_len:
err_msg = "Input data length must be longer than data length needed "
err_msg += "to estimate a PSD. You specified that a PSD should be "
err_msg += "estimated with %d seconds. " %(psd_data_len)
err_msg += "Input data length is %d seconds. " %(input_data_len)
raise ValueError(err_msg)
elif input_data_len == psd_data_len:
num_psd_measurements = 1
psd_stride = 0
else:
num_psd_measurements = int(2 * (input_data_len-1) / psd_data_len)
psd_stride = int((input_data_len - psd_data_len) / num_psd_measurements)
for idx in range(num_psd_measurements):
if idx == (num_psd_measurements - 1):
start_idx = input_data_len - psd_data_len
end_idx = input_data_len
else:
start_idx = psd_stride * idx
end_idx = psd_data_len + psd_stride * idx
strain_part = gwstrain[start_idx:end_idx]
psd = from_cli(opt, flen, delta_f, flow, strain=strain_part,
dyn_range_factor=dyn_range_factor, precision=precision)
psds_and_times.append( (start_idx, end_idx, psd) )
return psds_and_times | [
"def",
"generate_overlapping_psds",
"(",
"opt",
",",
"gwstrain",
",",
"flen",
",",
"delta_f",
",",
"flow",
",",
"dyn_range_factor",
"=",
"1.",
",",
"precision",
"=",
"None",
")",
":",
"if",
"not",
"opt",
".",
"psd_estimation",
":",
"psd",
"=",
"from_cli",
... | Generate a set of overlapping PSDs to cover a stretch of data. This
allows one to analyse a long stretch of data with PSD measurements that
change with time.
Parameters
-----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes (psd_model, psd_file, asd_file, psd_estimation,
psd_segment_length, psd_segment_stride, psd_inverse_length, psd_output).
gwstrain : Strain object
The timeseries of raw data on which to estimate PSDs.
flen : int
The length in samples of the output PSDs.
delta_f : float
The frequency step of the output PSDs.
flow: float
The low frequncy cutoff to use when calculating the PSD.
dyn_range_factor : {1, float}
For PSDs taken from models or text files, if `dyn_range_factor` is
not None, then the PSD is multiplied by `dyn_range_factor` ** 2.
precision : str, choices (None,'single','double')
If not specified, or specified as None, the precision of the returned
PSD will match the precision of the data, if measuring a PSD, or will
match the default precision of the model if using an analytical PSD.
If 'single' the PSD will be converted to float32, if not already in
that precision. If 'double' the PSD will be converted to float64, if
not already in that precision.
Returns
--------
psd_and_times : list of (start, end, PSD) tuples
This is a list of tuples containing one entry for each PSD. The first
and second entries (start, end) in each tuple represent the index
range of the gwstrain data that was used to estimate that PSD. The
third entry (psd) contains the PSD estimate between that interval. | [
"Generate",
"a",
"set",
"of",
"overlapping",
"PSDs",
"to",
"cover",
"a",
"stretch",
"of",
"data",
".",
"This",
"allows",
"one",
"to",
"analyse",
"a",
"long",
"stretch",
"of",
"data",
"with",
"PSD",
"measurements",
"that",
"change",
"with",
"time",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/psd/__init__.py#L383-L469 |
227,819 | gwastro/pycbc | pycbc/psd/__init__.py | associate_psds_to_segments | def associate_psds_to_segments(opt, fd_segments, gwstrain, flen, delta_f, flow,
dyn_range_factor=1., precision=None):
"""Generate a set of overlapping PSDs covering the data in GWstrain.
Then associate these PSDs with the appropriate segment in strain_segments.
Parameters
-----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes (psd_model, psd_file, asd_file, psd_estimation,
psd_segment_length, psd_segment_stride, psd_inverse_length, psd_output).
fd_segments : StrainSegments.fourier_segments() object
The fourier transforms of the various analysis segments. The psd
attribute of each segment is updated to point to the appropriate PSD.
gwstrain : Strain object
The timeseries of raw data on which to estimate PSDs.
flen : int
The length in samples of the output PSDs.
delta_f : float
The frequency step of the output PSDs.
flow: float
The low frequncy cutoff to use when calculating the PSD.
dyn_range_factor : {1, float}
For PSDs taken from models or text files, if `dyn_range_factor` is
not None, then the PSD is multiplied by `dyn_range_factor` ** 2.
precision : str, choices (None,'single','double')
If not specified, or specified as None, the precision of the returned
PSD will match the precision of the data, if measuring a PSD, or will
match the default precision of the model if using an analytical PSD.
If 'single' the PSD will be converted to float32, if not already in
that precision. If 'double' the PSD will be converted to float64, if
not already in that precision.
"""
psds_and_times = generate_overlapping_psds(opt, gwstrain, flen, delta_f,
flow, dyn_range_factor=dyn_range_factor,
precision=precision)
for fd_segment in fd_segments:
best_psd = None
psd_overlap = 0
inp_seg = segments.segment(fd_segment.seg_slice.start,
fd_segment.seg_slice.stop)
for start_idx, end_idx, psd in psds_and_times:
psd_seg = segments.segment(start_idx, end_idx)
if psd_seg.intersects(inp_seg):
curr_overlap = abs(inp_seg & psd_seg)
if curr_overlap > psd_overlap:
psd_overlap = curr_overlap
best_psd = psd
if best_psd is None:
err_msg = "No PSDs found intersecting segment!"
raise ValueError(err_msg)
fd_segment.psd = best_psd | python | def associate_psds_to_segments(opt, fd_segments, gwstrain, flen, delta_f, flow,
dyn_range_factor=1., precision=None):
psds_and_times = generate_overlapping_psds(opt, gwstrain, flen, delta_f,
flow, dyn_range_factor=dyn_range_factor,
precision=precision)
for fd_segment in fd_segments:
best_psd = None
psd_overlap = 0
inp_seg = segments.segment(fd_segment.seg_slice.start,
fd_segment.seg_slice.stop)
for start_idx, end_idx, psd in psds_and_times:
psd_seg = segments.segment(start_idx, end_idx)
if psd_seg.intersects(inp_seg):
curr_overlap = abs(inp_seg & psd_seg)
if curr_overlap > psd_overlap:
psd_overlap = curr_overlap
best_psd = psd
if best_psd is None:
err_msg = "No PSDs found intersecting segment!"
raise ValueError(err_msg)
fd_segment.psd = best_psd | [
"def",
"associate_psds_to_segments",
"(",
"opt",
",",
"fd_segments",
",",
"gwstrain",
",",
"flen",
",",
"delta_f",
",",
"flow",
",",
"dyn_range_factor",
"=",
"1.",
",",
"precision",
"=",
"None",
")",
":",
"psds_and_times",
"=",
"generate_overlapping_psds",
"(",
... | Generate a set of overlapping PSDs covering the data in GWstrain.
Then associate these PSDs with the appropriate segment in strain_segments.
Parameters
-----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes (psd_model, psd_file, asd_file, psd_estimation,
psd_segment_length, psd_segment_stride, psd_inverse_length, psd_output).
fd_segments : StrainSegments.fourier_segments() object
The fourier transforms of the various analysis segments. The psd
attribute of each segment is updated to point to the appropriate PSD.
gwstrain : Strain object
The timeseries of raw data on which to estimate PSDs.
flen : int
The length in samples of the output PSDs.
delta_f : float
The frequency step of the output PSDs.
flow: float
The low frequncy cutoff to use when calculating the PSD.
dyn_range_factor : {1, float}
For PSDs taken from models or text files, if `dyn_range_factor` is
not None, then the PSD is multiplied by `dyn_range_factor` ** 2.
precision : str, choices (None,'single','double')
If not specified, or specified as None, the precision of the returned
PSD will match the precision of the data, if measuring a PSD, or will
match the default precision of the model if using an analytical PSD.
If 'single' the PSD will be converted to float32, if not already in
that precision. If 'double' the PSD will be converted to float64, if
not already in that precision. | [
"Generate",
"a",
"set",
"of",
"overlapping",
"PSDs",
"covering",
"the",
"data",
"in",
"GWstrain",
".",
"Then",
"associate",
"these",
"PSDs",
"with",
"the",
"appropriate",
"segment",
"in",
"strain_segments",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/psd/__init__.py#L471-L523 |
227,820 | gwastro/pycbc | pycbc/psd/__init__.py | associate_psds_to_single_ifo_segments | def associate_psds_to_single_ifo_segments(opt, fd_segments, gwstrain, flen,
delta_f, flow, ifo,
dyn_range_factor=1., precision=None):
"""
Associate PSDs to segments for a single ifo when using the multi-detector
CLI
"""
single_det_opt = copy_opts_for_single_ifo(opt, ifo)
associate_psds_to_segments(single_det_opt, fd_segments, gwstrain, flen,
delta_f, flow, dyn_range_factor=dyn_range_factor,
precision=precision) | python | def associate_psds_to_single_ifo_segments(opt, fd_segments, gwstrain, flen,
delta_f, flow, ifo,
dyn_range_factor=1., precision=None):
single_det_opt = copy_opts_for_single_ifo(opt, ifo)
associate_psds_to_segments(single_det_opt, fd_segments, gwstrain, flen,
delta_f, flow, dyn_range_factor=dyn_range_factor,
precision=precision) | [
"def",
"associate_psds_to_single_ifo_segments",
"(",
"opt",
",",
"fd_segments",
",",
"gwstrain",
",",
"flen",
",",
"delta_f",
",",
"flow",
",",
"ifo",
",",
"dyn_range_factor",
"=",
"1.",
",",
"precision",
"=",
"None",
")",
":",
"single_det_opt",
"=",
"copy_opt... | Associate PSDs to segments for a single ifo when using the multi-detector
CLI | [
"Associate",
"PSDs",
"to",
"segments",
"for",
"a",
"single",
"ifo",
"when",
"using",
"the",
"multi",
"-",
"detector",
"CLI"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/psd/__init__.py#L525-L535 |
227,821 | gwastro/pycbc | pycbc/psd/__init__.py | associate_psds_to_multi_ifo_segments | def associate_psds_to_multi_ifo_segments(opt, fd_segments, gwstrain, flen,
delta_f, flow, ifos,
dyn_range_factor=1., precision=None):
"""
Associate PSDs to segments for all ifos when using the multi-detector CLI
"""
for ifo in ifos:
if gwstrain is not None:
strain = gwstrain[ifo]
else:
strain = None
if fd_segments is not None:
segments = fd_segments[ifo]
else:
segments = None
associate_psds_to_single_ifo_segments(opt, segments, strain, flen,
delta_f, flow, ifo, dyn_range_factor=dyn_range_factor,
precision=precision) | python | def associate_psds_to_multi_ifo_segments(opt, fd_segments, gwstrain, flen,
delta_f, flow, ifos,
dyn_range_factor=1., precision=None):
for ifo in ifos:
if gwstrain is not None:
strain = gwstrain[ifo]
else:
strain = None
if fd_segments is not None:
segments = fd_segments[ifo]
else:
segments = None
associate_psds_to_single_ifo_segments(opt, segments, strain, flen,
delta_f, flow, ifo, dyn_range_factor=dyn_range_factor,
precision=precision) | [
"def",
"associate_psds_to_multi_ifo_segments",
"(",
"opt",
",",
"fd_segments",
",",
"gwstrain",
",",
"flen",
",",
"delta_f",
",",
"flow",
",",
"ifos",
",",
"dyn_range_factor",
"=",
"1.",
",",
"precision",
"=",
"None",
")",
":",
"for",
"ifo",
"in",
"ifos",
... | Associate PSDs to segments for all ifos when using the multi-detector CLI | [
"Associate",
"PSDs",
"to",
"segments",
"for",
"all",
"ifos",
"when",
"using",
"the",
"multi",
"-",
"detector",
"CLI"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/psd/__init__.py#L537-L556 |
227,822 | gwastro/pycbc | pycbc/strain/recalibrate.py | CubicSpline.apply_calibration | def apply_calibration(self, strain):
"""Apply calibration model
This applies cubic spline calibration to the strain.
Parameters
----------
strain : FrequencySeries
The strain to be recalibrated.
Return
------
strain_adjusted : FrequencySeries
The recalibrated strain.
"""
amplitude_parameters =\
[self.params['amplitude_{}_{}'.format(self.ifo_name, ii)]
for ii in range(self.n_points)]
amplitude_spline = UnivariateSpline(self.spline_points,
amplitude_parameters)
delta_amplitude = amplitude_spline(strain.sample_frequencies.numpy())
phase_parameters =\
[self.params['phase_{}_{}'.format(self.ifo_name, ii)]
for ii in range(self.n_points)]
phase_spline = UnivariateSpline(self.spline_points, phase_parameters)
delta_phase = phase_spline(strain.sample_frequencies.numpy())
strain_adjusted = strain * (1.0 + delta_amplitude)\
* (2.0 + 1j * delta_phase) / (2.0 - 1j * delta_phase)
return strain_adjusted | python | def apply_calibration(self, strain):
amplitude_parameters =\
[self.params['amplitude_{}_{}'.format(self.ifo_name, ii)]
for ii in range(self.n_points)]
amplitude_spline = UnivariateSpline(self.spline_points,
amplitude_parameters)
delta_amplitude = amplitude_spline(strain.sample_frequencies.numpy())
phase_parameters =\
[self.params['phase_{}_{}'.format(self.ifo_name, ii)]
for ii in range(self.n_points)]
phase_spline = UnivariateSpline(self.spline_points, phase_parameters)
delta_phase = phase_spline(strain.sample_frequencies.numpy())
strain_adjusted = strain * (1.0 + delta_amplitude)\
* (2.0 + 1j * delta_phase) / (2.0 - 1j * delta_phase)
return strain_adjusted | [
"def",
"apply_calibration",
"(",
"self",
",",
"strain",
")",
":",
"amplitude_parameters",
"=",
"[",
"self",
".",
"params",
"[",
"'amplitude_{}_{}'",
".",
"format",
"(",
"self",
".",
"ifo_name",
",",
"ii",
")",
"]",
"for",
"ii",
"in",
"range",
"(",
"self"... | Apply calibration model
This applies cubic spline calibration to the strain.
Parameters
----------
strain : FrequencySeries
The strain to be recalibrated.
Return
------
strain_adjusted : FrequencySeries
The recalibrated strain. | [
"Apply",
"calibration",
"model"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/strain/recalibrate.py#L145-L176 |
227,823 | gwastro/pycbc | pycbc/results/metadata.py | save_html_with_metadata | def save_html_with_metadata(fig, filename, fig_kwds, kwds):
""" Save a html output to file with metadata """
if isinstance(fig, str):
text = fig
else:
from mpld3 import fig_to_html
text = fig_to_html(fig, **fig_kwds)
f = open(filename, 'w')
for key, value in kwds.items():
value = escape(value, escape_table)
line = "<div class=pycbc-meta key=\"%s\" value=\"%s\"></div>" % (str(key), value)
f.write(line)
f.write(text) | python | def save_html_with_metadata(fig, filename, fig_kwds, kwds):
if isinstance(fig, str):
text = fig
else:
from mpld3 import fig_to_html
text = fig_to_html(fig, **fig_kwds)
f = open(filename, 'w')
for key, value in kwds.items():
value = escape(value, escape_table)
line = "<div class=pycbc-meta key=\"%s\" value=\"%s\"></div>" % (str(key), value)
f.write(line)
f.write(text) | [
"def",
"save_html_with_metadata",
"(",
"fig",
",",
"filename",
",",
"fig_kwds",
",",
"kwds",
")",
":",
"if",
"isinstance",
"(",
"fig",
",",
"str",
")",
":",
"text",
"=",
"fig",
"else",
":",
"from",
"mpld3",
"import",
"fig_to_html",
"text",
"=",
"fig_to_h... | Save a html output to file with metadata | [
"Save",
"a",
"html",
"output",
"to",
"file",
"with",
"metadata"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/results/metadata.py#L41-L55 |
227,824 | gwastro/pycbc | pycbc/results/metadata.py | load_html_metadata | def load_html_metadata(filename):
""" Get metadata from html file """
parser = MetaParser()
data = open(filename, 'r').read()
if 'pycbc-meta' in data:
print("LOADING HTML FILE %s" % filename)
parser.feed(data)
cp = ConfigParser.ConfigParser(parser.metadata)
cp.add_section(os.path.basename(filename))
return cp | python | def load_html_metadata(filename):
parser = MetaParser()
data = open(filename, 'r').read()
if 'pycbc-meta' in data:
print("LOADING HTML FILE %s" % filename)
parser.feed(data)
cp = ConfigParser.ConfigParser(parser.metadata)
cp.add_section(os.path.basename(filename))
return cp | [
"def",
"load_html_metadata",
"(",
"filename",
")",
":",
"parser",
"=",
"MetaParser",
"(",
")",
"data",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
".",
"read",
"(",
")",
"if",
"'pycbc-meta'",
"in",
"data",
":",
"print",
"(",
"\"LOADING HTML FILE %s\"",
... | Get metadata from html file | [
"Get",
"metadata",
"from",
"html",
"file"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/results/metadata.py#L57-L67 |
227,825 | gwastro/pycbc | pycbc/results/metadata.py | save_png_with_metadata | def save_png_with_metadata(fig, filename, fig_kwds, kwds):
""" Save a matplotlib figure to a png with metadata
"""
from PIL import Image, PngImagePlugin
fig.savefig(filename, **fig_kwds)
im = Image.open(filename)
meta = PngImagePlugin.PngInfo()
for key in kwds:
meta.add_text(str(key), str(kwds[key]))
im.save(filename, "png", pnginfo=meta) | python | def save_png_with_metadata(fig, filename, fig_kwds, kwds):
from PIL import Image, PngImagePlugin
fig.savefig(filename, **fig_kwds)
im = Image.open(filename)
meta = PngImagePlugin.PngInfo()
for key in kwds:
meta.add_text(str(key), str(kwds[key]))
im.save(filename, "png", pnginfo=meta) | [
"def",
"save_png_with_metadata",
"(",
"fig",
",",
"filename",
",",
"fig_kwds",
",",
"kwds",
")",
":",
"from",
"PIL",
"import",
"Image",
",",
"PngImagePlugin",
"fig",
".",
"savefig",
"(",
"filename",
",",
"*",
"*",
"fig_kwds",
")",
"im",
"=",
"Image",
"."... | Save a matplotlib figure to a png with metadata | [
"Save",
"a",
"matplotlib",
"figure",
"to",
"a",
"png",
"with",
"metadata"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/results/metadata.py#L69-L81 |
227,826 | gwastro/pycbc | pycbc/results/metadata.py | save_fig_with_metadata | def save_fig_with_metadata(fig, filename, fig_kwds=None, **kwds):
""" Save plot to file with metadata included. Kewords translate to metadata
that is stored directly in the plot file. Limited format types available.
Parameters
----------
fig: matplotlib figure
The matplotlib figure to save to the file
filename: str
Name of file to store the plot.
"""
if fig_kwds is None:
fig_kwds = {}
try:
extension = os.path.splitext(filename)[1]
kwds['version'] = pycbc.version.git_verbose_msg
_metadata_saver[extension](fig, filename, fig_kwds, kwds)
except KeyError:
raise TypeError('Cannot save file %s with metadata, extension %s not '
'supported at this time' % (filename, extension)) | python | def save_fig_with_metadata(fig, filename, fig_kwds=None, **kwds):
if fig_kwds is None:
fig_kwds = {}
try:
extension = os.path.splitext(filename)[1]
kwds['version'] = pycbc.version.git_verbose_msg
_metadata_saver[extension](fig, filename, fig_kwds, kwds)
except KeyError:
raise TypeError('Cannot save file %s with metadata, extension %s not '
'supported at this time' % (filename, extension)) | [
"def",
"save_fig_with_metadata",
"(",
"fig",
",",
"filename",
",",
"fig_kwds",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"fig_kwds",
"is",
"None",
":",
"fig_kwds",
"=",
"{",
"}",
"try",
":",
"extension",
"=",
"os",
".",
"path",
".",
"splite... | Save plot to file with metadata included. Kewords translate to metadata
that is stored directly in the plot file. Limited format types available.
Parameters
----------
fig: matplotlib figure
The matplotlib figure to save to the file
filename: str
Name of file to store the plot. | [
"Save",
"plot",
"to",
"file",
"with",
"metadata",
"included",
".",
"Kewords",
"translate",
"to",
"metadata",
"that",
"is",
"stored",
"directly",
"in",
"the",
"plot",
"file",
".",
"Limited",
"format",
"types",
"available",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/results/metadata.py#L97-L116 |
227,827 | gwastro/pycbc | pycbc/results/metadata.py | load_metadata_from_file | def load_metadata_from_file(filename):
""" Load the plot related metadata saved in a file
Parameters
----------
filename: str
Name of file load metadata from.
Returns
-------
cp: ConfigParser
A configparser object containing the metadata
"""
try:
extension = os.path.splitext(filename)[1]
return _metadata_loader[extension](filename)
except KeyError:
raise TypeError('Cannot read metadata from file %s, extension %s not '
'supported at this time' % (filename, extension)) | python | def load_metadata_from_file(filename):
try:
extension = os.path.splitext(filename)[1]
return _metadata_loader[extension](filename)
except KeyError:
raise TypeError('Cannot read metadata from file %s, extension %s not '
'supported at this time' % (filename, extension)) | [
"def",
"load_metadata_from_file",
"(",
"filename",
")",
":",
"try",
":",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"1",
"]",
"return",
"_metadata_loader",
"[",
"extension",
"]",
"(",
"filename",
")",
"except",
"KeyErr... | Load the plot related metadata saved in a file
Parameters
----------
filename: str
Name of file load metadata from.
Returns
-------
cp: ConfigParser
A configparser object containing the metadata | [
"Load",
"the",
"plot",
"related",
"metadata",
"saved",
"in",
"a",
"file"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/results/metadata.py#L118-L136 |
227,828 | gwastro/pycbc | pycbc/results/versioning.py | get_code_version_numbers | def get_code_version_numbers(cp):
"""Will extract the version information from the executables listed in
the executable section of the supplied ConfigParser object.
Returns
--------
dict
A dictionary keyed by the executable name with values giving the
version string for each executable.
"""
code_version_dict = {}
for _, value in cp.items('executables'):
_, exe_name = os.path.split(value)
version_string = None
if value.startswith('gsiftp://') or value.startswith('http://'):
code_version_dict[exe_name] = "Using bundle downloaded from %s" % value
else:
try:
if value.startswith('file://'):
value = value[7:]
version_string = subprocess.check_output([value, '--version'],
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
version_string = "Executable fails on %s --version" % (value)
except OSError:
version_string = "Executable doesn't seem to exist(!)"
code_version_dict[exe_name] = version_string
return code_version_dict | python | def get_code_version_numbers(cp):
code_version_dict = {}
for _, value in cp.items('executables'):
_, exe_name = os.path.split(value)
version_string = None
if value.startswith('gsiftp://') or value.startswith('http://'):
code_version_dict[exe_name] = "Using bundle downloaded from %s" % value
else:
try:
if value.startswith('file://'):
value = value[7:]
version_string = subprocess.check_output([value, '--version'],
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
version_string = "Executable fails on %s --version" % (value)
except OSError:
version_string = "Executable doesn't seem to exist(!)"
code_version_dict[exe_name] = version_string
return code_version_dict | [
"def",
"get_code_version_numbers",
"(",
"cp",
")",
":",
"code_version_dict",
"=",
"{",
"}",
"for",
"_",
",",
"value",
"in",
"cp",
".",
"items",
"(",
"'executables'",
")",
":",
"_",
",",
"exe_name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"value",
... | Will extract the version information from the executables listed in
the executable section of the supplied ConfigParser object.
Returns
--------
dict
A dictionary keyed by the executable name with values giving the
version string for each executable. | [
"Will",
"extract",
"the",
"version",
"information",
"from",
"the",
"executables",
"listed",
"in",
"the",
"executable",
"section",
"of",
"the",
"supplied",
"ConfigParser",
"object",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/results/versioning.py#L131-L158 |
227,829 | gwastro/pycbc | pycbc/results/legacy_grb.py | initialize_page | def initialize_page(title, style, script, header=None):
"""
A function that returns a markup.py page object with the required html
header.
"""
page = markup.page(mode="strict_html")
page._escape = False
page.init(title=title, css=style, script=script, header=header)
return page | python | def initialize_page(title, style, script, header=None):
page = markup.page(mode="strict_html")
page._escape = False
page.init(title=title, css=style, script=script, header=header)
return page | [
"def",
"initialize_page",
"(",
"title",
",",
"style",
",",
"script",
",",
"header",
"=",
"None",
")",
":",
"page",
"=",
"markup",
".",
"page",
"(",
"mode",
"=",
"\"strict_html\"",
")",
"page",
".",
"_escape",
"=",
"False",
"page",
".",
"init",
"(",
"... | A function that returns a markup.py page object with the required html
header. | [
"A",
"function",
"that",
"returns",
"a",
"markup",
".",
"py",
"page",
"object",
"with",
"the",
"required",
"html",
"header",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/results/legacy_grb.py#L31-L41 |
227,830 | gwastro/pycbc | pycbc/results/legacy_grb.py | write_table | def write_table(page, headers, data, cl=''):
"""
Write table in html
"""
page.table(class_=cl)
# list
if cl=='list':
for i in range(len(headers)):
page.tr()
page.th()
page.add('%s' % headers[i])
page.th.close()
page.td()
page.add('%s' % data[i])
page.td.close()
page.tr.close()
else:
page.tr()
for n in headers:
page.th()
page.add('%s' % n)
page.th.close()
page.tr.close()
if data and not re.search('list',str(type(data[0]))):
data = [data]
for row in data:
page.tr()
for item in row:
page.td()
page.add('%s' % item)
page.td.close()
page.tr.close()
page.table.close()
return page | python | def write_table(page, headers, data, cl=''):
page.table(class_=cl)
# list
if cl=='list':
for i in range(len(headers)):
page.tr()
page.th()
page.add('%s' % headers[i])
page.th.close()
page.td()
page.add('%s' % data[i])
page.td.close()
page.tr.close()
else:
page.tr()
for n in headers:
page.th()
page.add('%s' % n)
page.th.close()
page.tr.close()
if data and not re.search('list',str(type(data[0]))):
data = [data]
for row in data:
page.tr()
for item in row:
page.td()
page.add('%s' % item)
page.td.close()
page.tr.close()
page.table.close()
return page | [
"def",
"write_table",
"(",
"page",
",",
"headers",
",",
"data",
",",
"cl",
"=",
"''",
")",
":",
"page",
".",
"table",
"(",
"class_",
"=",
"cl",
")",
"# list",
"if",
"cl",
"==",
"'list'",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"headers",... | Write table in html | [
"Write",
"table",
"in",
"html"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/results/legacy_grb.py#L70-L112 |
227,831 | gwastro/pycbc | pycbc/results/legacy_grb.py | write_offsource | def write_offsource(page, args, grbtag, onsource=False):
"""
Write offsource SNR versus time plots to markup.page object page
"""
th = ['Re-weighted SNR', 'Coherent SNR']
if args.time_slides:
if onsource:
out_dir = 'ZEROLAG_ALL'
else:
out_dir = 'ZEROLAG_OFF'
else:
if onsource:
out_dir = 'ALL_TIMES'
else:
out_dir = 'OFFSOURCE'
plot = markup.page()
p = "%s/plots_clustered/GRB%s_bestnr_vs_time_noinj.png" % (out_dir, grbtag)
plot.a(href=p, title="Detection statistic versus time")
plot.img(src=p)
plot.a.close()
td = [ plot() ]
plot = markup.page()
p = "%s/plots_clustered/GRB%s_triggers_vs_time_noinj.png" % (out_dir, grbtag)
plot.a(href=p, title="Coherent SNR versus time")
plot.img(src=p)
plot.a.close()
td.append(plot())
ifos = [args.ifo_tag[i:i+2] for i in range(0, len(args.ifo_tag), 2)]
for ifo in ifos:
th.append('%s SNR' % ifo)
plot = markup.page()
p = "%s/plots_clustered/GRB%s_%s_triggers_vs_time_noinj.png"\
% (out_dir, grbtag, ifo)
plot.a(href=p, title="%s SNR versus time" % ifo)
plot.img(src=p)
plot.a.close()
td.append(plot())
page = write_table(page, th, td)
return page | python | def write_offsource(page, args, grbtag, onsource=False):
th = ['Re-weighted SNR', 'Coherent SNR']
if args.time_slides:
if onsource:
out_dir = 'ZEROLAG_ALL'
else:
out_dir = 'ZEROLAG_OFF'
else:
if onsource:
out_dir = 'ALL_TIMES'
else:
out_dir = 'OFFSOURCE'
plot = markup.page()
p = "%s/plots_clustered/GRB%s_bestnr_vs_time_noinj.png" % (out_dir, grbtag)
plot.a(href=p, title="Detection statistic versus time")
plot.img(src=p)
plot.a.close()
td = [ plot() ]
plot = markup.page()
p = "%s/plots_clustered/GRB%s_triggers_vs_time_noinj.png" % (out_dir, grbtag)
plot.a(href=p, title="Coherent SNR versus time")
plot.img(src=p)
plot.a.close()
td.append(plot())
ifos = [args.ifo_tag[i:i+2] for i in range(0, len(args.ifo_tag), 2)]
for ifo in ifos:
th.append('%s SNR' % ifo)
plot = markup.page()
p = "%s/plots_clustered/GRB%s_%s_triggers_vs_time_noinj.png"\
% (out_dir, grbtag, ifo)
plot.a(href=p, title="%s SNR versus time" % ifo)
plot.img(src=p)
plot.a.close()
td.append(plot())
page = write_table(page, th, td)
return page | [
"def",
"write_offsource",
"(",
"page",
",",
"args",
",",
"grbtag",
",",
"onsource",
"=",
"False",
")",
":",
"th",
"=",
"[",
"'Re-weighted SNR'",
",",
"'Coherent SNR'",
"]",
"if",
"args",
".",
"time_slides",
":",
"if",
"onsource",
":",
"out_dir",
"=",
"'Z... | Write offsource SNR versus time plots to markup.page object page | [
"Write",
"offsource",
"SNR",
"versus",
"time",
"plots",
"to",
"markup",
".",
"page",
"object",
"page"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/results/legacy_grb.py#L311-L357 |
227,832 | gwastro/pycbc | pycbc/results/legacy_grb.py | write_recovery | def write_recovery(page, injList):
"""
Write injection recovery plots to markup.page object page
"""
th = ['']+injList
td = []
plots = ['sky_error_time','sky_error_mchirp','sky_error_distance']
text = { 'sky_error_time':'Sky error vs time',\
'sky_error_mchirp':'Sky error vs mchirp',\
'sky_error_distance':'Sky error vs distance' }
for row in plots:
pTag = text[row]
d = [pTag]
for inj in injList:
plot = markup.page()
plot = markup.page()
p = "%s/efficiency_OFFTRIAL_1/found_%s.png" % (inj, row)
plot.a(href=p, title=pTag)
plot.img(src=p)
plot.a.close()
d.append(plot())
td.append(d)
page = write_table(page, th, td)
return page | python | def write_recovery(page, injList):
th = ['']+injList
td = []
plots = ['sky_error_time','sky_error_mchirp','sky_error_distance']
text = { 'sky_error_time':'Sky error vs time',\
'sky_error_mchirp':'Sky error vs mchirp',\
'sky_error_distance':'Sky error vs distance' }
for row in plots:
pTag = text[row]
d = [pTag]
for inj in injList:
plot = markup.page()
plot = markup.page()
p = "%s/efficiency_OFFTRIAL_1/found_%s.png" % (inj, row)
plot.a(href=p, title=pTag)
plot.img(src=p)
plot.a.close()
d.append(plot())
td.append(d)
page = write_table(page, th, td)
return page | [
"def",
"write_recovery",
"(",
"page",
",",
"injList",
")",
":",
"th",
"=",
"[",
"''",
"]",
"+",
"injList",
"td",
"=",
"[",
"]",
"plots",
"=",
"[",
"'sky_error_time'",
",",
"'sky_error_mchirp'",
",",
"'sky_error_distance'",
"]",
"text",
"=",
"{",
"'sky_er... | Write injection recovery plots to markup.page object page | [
"Write",
"injection",
"recovery",
"plots",
"to",
"markup",
".",
"page",
"object",
"page"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/results/legacy_grb.py#L483-L512 |
227,833 | gwastro/pycbc | pycbc/tmpltbank/lattice_utils.py | generate_hexagonal_lattice | def generate_hexagonal_lattice(maxv1, minv1, maxv2, minv2, mindist):
"""
This function generates a 2-dimensional lattice of points using a hexagonal
lattice.
Parameters
-----------
maxv1 : float
Largest value in the 1st dimension to cover
minv1 : float
Smallest value in the 1st dimension to cover
maxv2 : float
Largest value in the 2nd dimension to cover
minv2 : float
Smallest value in the 2nd dimension to cover
mindist : float
Maximum allowed mismatch between a point in the parameter space and the
generated bank of points.
Returns
--------
v1s : numpy.array
Array of positions in the first dimension
v2s : numpy.array
Array of positions in the second dimension
"""
if minv1 > maxv1:
raise ValueError("Invalid input to function.")
if minv2 > maxv2:
raise ValueError("Invalid input to function.")
# Place first point
v1s = [minv1]
v2s = [minv2]
initPoint = [minv1,minv2]
# Place first line
initLine = [initPoint]
tmpv1 = minv1
while (tmpv1 < maxv1):
tmpv1 = tmpv1 + (3 * mindist)**(0.5)
initLine.append([tmpv1,minv2])
v1s.append(tmpv1)
v2s.append(minv2)
initLine = numpy.array(initLine)
initLine2 = copy.deepcopy(initLine)
initLine2[:,0] += 0.5 * (3*mindist)**0.5
initLine2[:,1] += 1.5 * (mindist)**0.5
for i in xrange(len(initLine2)):
v1s.append(initLine2[i,0])
v2s.append(initLine2[i,1])
tmpv2_1 = initLine[0,1]
tmpv2_2 = initLine2[0,1]
while tmpv2_1 < maxv2 and tmpv2_2 < maxv2:
tmpv2_1 = tmpv2_1 + 3.0 * (mindist)**0.5
tmpv2_2 = tmpv2_2 + 3.0 * (mindist)**0.5
initLine[:,1] = tmpv2_1
initLine2[:,1] = tmpv2_2
for i in xrange(len(initLine)):
v1s.append(initLine[i,0])
v2s.append(initLine[i,1])
for i in xrange(len(initLine2)):
v1s.append(initLine2[i,0])
v2s.append(initLine2[i,1])
v1s = numpy.array(v1s)
v2s = numpy.array(v2s)
return v1s, v2s | python | def generate_hexagonal_lattice(maxv1, minv1, maxv2, minv2, mindist):
if minv1 > maxv1:
raise ValueError("Invalid input to function.")
if minv2 > maxv2:
raise ValueError("Invalid input to function.")
# Place first point
v1s = [minv1]
v2s = [minv2]
initPoint = [minv1,minv2]
# Place first line
initLine = [initPoint]
tmpv1 = minv1
while (tmpv1 < maxv1):
tmpv1 = tmpv1 + (3 * mindist)**(0.5)
initLine.append([tmpv1,minv2])
v1s.append(tmpv1)
v2s.append(minv2)
initLine = numpy.array(initLine)
initLine2 = copy.deepcopy(initLine)
initLine2[:,0] += 0.5 * (3*mindist)**0.5
initLine2[:,1] += 1.5 * (mindist)**0.5
for i in xrange(len(initLine2)):
v1s.append(initLine2[i,0])
v2s.append(initLine2[i,1])
tmpv2_1 = initLine[0,1]
tmpv2_2 = initLine2[0,1]
while tmpv2_1 < maxv2 and tmpv2_2 < maxv2:
tmpv2_1 = tmpv2_1 + 3.0 * (mindist)**0.5
tmpv2_2 = tmpv2_2 + 3.0 * (mindist)**0.5
initLine[:,1] = tmpv2_1
initLine2[:,1] = tmpv2_2
for i in xrange(len(initLine)):
v1s.append(initLine[i,0])
v2s.append(initLine[i,1])
for i in xrange(len(initLine2)):
v1s.append(initLine2[i,0])
v2s.append(initLine2[i,1])
v1s = numpy.array(v1s)
v2s = numpy.array(v2s)
return v1s, v2s | [
"def",
"generate_hexagonal_lattice",
"(",
"maxv1",
",",
"minv1",
",",
"maxv2",
",",
"minv2",
",",
"mindist",
")",
":",
"if",
"minv1",
">",
"maxv1",
":",
"raise",
"ValueError",
"(",
"\"Invalid input to function.\"",
")",
"if",
"minv2",
">",
"maxv2",
":",
"rai... | This function generates a 2-dimensional lattice of points using a hexagonal
lattice.
Parameters
-----------
maxv1 : float
Largest value in the 1st dimension to cover
minv1 : float
Smallest value in the 1st dimension to cover
maxv2 : float
Largest value in the 2nd dimension to cover
minv2 : float
Smallest value in the 2nd dimension to cover
mindist : float
Maximum allowed mismatch between a point in the parameter space and the
generated bank of points.
Returns
--------
v1s : numpy.array
Array of positions in the first dimension
v2s : numpy.array
Array of positions in the second dimension | [
"This",
"function",
"generates",
"a",
"2",
"-",
"dimensional",
"lattice",
"of",
"points",
"using",
"a",
"hexagonal",
"lattice",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/lattice_utils.py#L22-L86 |
227,834 | gwastro/pycbc | pycbc/events/ranking.py | newsnr_sgveto | def newsnr_sgveto(snr, bchisq, sgchisq):
""" Combined SNR derived from NewSNR and Sine-Gaussian Chisq"""
nsnr = numpy.array(newsnr(snr, bchisq), ndmin=1)
sgchisq = numpy.array(sgchisq, ndmin=1)
t = numpy.array(sgchisq > 4, ndmin=1)
if len(t):
nsnr[t] = nsnr[t] / (sgchisq[t] / 4.0) ** 0.5
# If snr input is float, return a float. Otherwise return numpy array.
if hasattr(snr, '__len__'):
return nsnr
else:
return nsnr[0] | python | def newsnr_sgveto(snr, bchisq, sgchisq):
nsnr = numpy.array(newsnr(snr, bchisq), ndmin=1)
sgchisq = numpy.array(sgchisq, ndmin=1)
t = numpy.array(sgchisq > 4, ndmin=1)
if len(t):
nsnr[t] = nsnr[t] / (sgchisq[t] / 4.0) ** 0.5
# If snr input is float, return a float. Otherwise return numpy array.
if hasattr(snr, '__len__'):
return nsnr
else:
return nsnr[0] | [
"def",
"newsnr_sgveto",
"(",
"snr",
",",
"bchisq",
",",
"sgchisq",
")",
":",
"nsnr",
"=",
"numpy",
".",
"array",
"(",
"newsnr",
"(",
"snr",
",",
"bchisq",
")",
",",
"ndmin",
"=",
"1",
")",
"sgchisq",
"=",
"numpy",
".",
"array",
"(",
"sgchisq",
",",... | Combined SNR derived from NewSNR and Sine-Gaussian Chisq | [
"Combined",
"SNR",
"derived",
"from",
"NewSNR",
"and",
"Sine",
"-",
"Gaussian",
"Chisq"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/ranking.py#L40-L52 |
227,835 | gwastro/pycbc | pycbc/events/ranking.py | newsnr_sgveto_psdvar | def newsnr_sgveto_psdvar(snr, bchisq, sgchisq, psd_var_val):
""" Combined SNR derived from NewSNR, Sine-Gaussian Chisq and PSD
variation statistic """
nsnr = numpy.array(newsnr_sgveto(snr, bchisq, sgchisq), ndmin=1)
psd_var_val = numpy.array(psd_var_val, ndmin=1)
lgc = psd_var_val >= 1.8
nsnr[lgc] = nsnr[lgc] / numpy.sqrt(psd_var_val[lgc])
# If snr input is float, return a float. Otherwise return numpy array.
if hasattr(snr, '__len__'):
return nsnr
else:
return nsnr[0] | python | def newsnr_sgveto_psdvar(snr, bchisq, sgchisq, psd_var_val):
nsnr = numpy.array(newsnr_sgveto(snr, bchisq, sgchisq), ndmin=1)
psd_var_val = numpy.array(psd_var_val, ndmin=1)
lgc = psd_var_val >= 1.8
nsnr[lgc] = nsnr[lgc] / numpy.sqrt(psd_var_val[lgc])
# If snr input is float, return a float. Otherwise return numpy array.
if hasattr(snr, '__len__'):
return nsnr
else:
return nsnr[0] | [
"def",
"newsnr_sgveto_psdvar",
"(",
"snr",
",",
"bchisq",
",",
"sgchisq",
",",
"psd_var_val",
")",
":",
"nsnr",
"=",
"numpy",
".",
"array",
"(",
"newsnr_sgveto",
"(",
"snr",
",",
"bchisq",
",",
"sgchisq",
")",
",",
"ndmin",
"=",
"1",
")",
"psd_var_val",
... | Combined SNR derived from NewSNR, Sine-Gaussian Chisq and PSD
variation statistic | [
"Combined",
"SNR",
"derived",
"from",
"NewSNR",
"Sine",
"-",
"Gaussian",
"Chisq",
"and",
"PSD",
"variation",
"statistic"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/ranking.py#L55-L67 |
227,836 | gwastro/pycbc | pycbc/events/ranking.py | get_newsnr_sgveto | def get_newsnr_sgveto(trigs):
"""
Calculate newsnr re-weigthed by the sine-gaussian veto
Parameters
----------
trigs: dict of numpy.ndarrays, h5py group (or similar dict-like object)
Dictionary-like object holding single detector trigger information.
'chisq_dof', 'snr', 'sg_chisq' and 'chisq' are required keys
Returns
-------
numpy.ndarray
Array of newsnr values
"""
dof = 2. * trigs['chisq_dof'][:] - 2.
nsnr_sg = newsnr_sgveto(trigs['snr'][:],
trigs['chisq'][:] / dof,
trigs['sg_chisq'][:])
return numpy.array(nsnr_sg, ndmin=1, dtype=numpy.float32) | python | def get_newsnr_sgveto(trigs):
dof = 2. * trigs['chisq_dof'][:] - 2.
nsnr_sg = newsnr_sgveto(trigs['snr'][:],
trigs['chisq'][:] / dof,
trigs['sg_chisq'][:])
return numpy.array(nsnr_sg, ndmin=1, dtype=numpy.float32) | [
"def",
"get_newsnr_sgveto",
"(",
"trigs",
")",
":",
"dof",
"=",
"2.",
"*",
"trigs",
"[",
"'chisq_dof'",
"]",
"[",
":",
"]",
"-",
"2.",
"nsnr_sg",
"=",
"newsnr_sgveto",
"(",
"trigs",
"[",
"'snr'",
"]",
"[",
":",
"]",
",",
"trigs",
"[",
"'chisq'",
"]... | Calculate newsnr re-weigthed by the sine-gaussian veto
Parameters
----------
trigs: dict of numpy.ndarrays, h5py group (or similar dict-like object)
Dictionary-like object holding single detector trigger information.
'chisq_dof', 'snr', 'sg_chisq' and 'chisq' are required keys
Returns
-------
numpy.ndarray
Array of newsnr values | [
"Calculate",
"newsnr",
"re",
"-",
"weigthed",
"by",
"the",
"sine",
"-",
"gaussian",
"veto"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/ranking.py#L90-L109 |
227,837 | gwastro/pycbc | pycbc/events/ranking.py | get_newsnr_sgveto_psdvar | def get_newsnr_sgveto_psdvar(trigs):
"""
Calculate newsnr re-weighted by the sine-gaussian veto and psd variation
statistic
Parameters
----------
trigs: dict of numpy.ndarrays
Dictionary holding single detector trigger information.
'chisq_dof', 'snr', 'chisq' and 'psd_var_val' are required keys
Returns
-------
numpy.ndarray
Array of newsnr values
"""
dof = 2. * trigs['chisq_dof'][:] - 2.
nsnr_sg_psd = \
newsnr_sgveto_psdvar(trigs['snr'][:], trigs['chisq'][:] / dof,
trigs['sg_chisq'][:],
trigs['psd_var_val'][:])
return numpy.array(nsnr_sg_psd, ndmin=1, dtype=numpy.float32) | python | def get_newsnr_sgveto_psdvar(trigs):
dof = 2. * trigs['chisq_dof'][:] - 2.
nsnr_sg_psd = \
newsnr_sgveto_psdvar(trigs['snr'][:], trigs['chisq'][:] / dof,
trigs['sg_chisq'][:],
trigs['psd_var_val'][:])
return numpy.array(nsnr_sg_psd, ndmin=1, dtype=numpy.float32) | [
"def",
"get_newsnr_sgveto_psdvar",
"(",
"trigs",
")",
":",
"dof",
"=",
"2.",
"*",
"trigs",
"[",
"'chisq_dof'",
"]",
"[",
":",
"]",
"-",
"2.",
"nsnr_sg_psd",
"=",
"newsnr_sgveto_psdvar",
"(",
"trigs",
"[",
"'snr'",
"]",
"[",
":",
"]",
",",
"trigs",
"[",... | Calculate newsnr re-weighted by the sine-gaussian veto and psd variation
statistic
Parameters
----------
trigs: dict of numpy.ndarrays
Dictionary holding single detector trigger information.
'chisq_dof', 'snr', 'chisq' and 'psd_var_val' are required keys
Returns
-------
numpy.ndarray
Array of newsnr values | [
"Calculate",
"newsnr",
"re",
"-",
"weighted",
"by",
"the",
"sine",
"-",
"gaussian",
"veto",
"and",
"psd",
"variation",
"statistic"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/ranking.py#L112-L133 |
227,838 | gwastro/pycbc | pycbc/results/str_utils.py | drop_trailing_zeros | def drop_trailing_zeros(num):
"""
Drops the trailing zeros in a float that is printed.
"""
txt = '%f' %(num)
txt = txt.rstrip('0')
if txt.endswith('.'):
txt = txt[:-1]
return txt | python | def drop_trailing_zeros(num):
txt = '%f' %(num)
txt = txt.rstrip('0')
if txt.endswith('.'):
txt = txt[:-1]
return txt | [
"def",
"drop_trailing_zeros",
"(",
"num",
")",
":",
"txt",
"=",
"'%f'",
"%",
"(",
"num",
")",
"txt",
"=",
"txt",
".",
"rstrip",
"(",
"'0'",
")",
"if",
"txt",
".",
"endswith",
"(",
"'.'",
")",
":",
"txt",
"=",
"txt",
"[",
":",
"-",
"1",
"]",
"... | Drops the trailing zeros in a float that is printed. | [
"Drops",
"the",
"trailing",
"zeros",
"in",
"a",
"float",
"that",
"is",
"printed",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/results/str_utils.py#L50-L58 |
227,839 | gwastro/pycbc | pycbc/results/str_utils.py | get_signum | def get_signum(val, err, max_sig=numpy.inf):
"""
Given an error, returns a string for val formated to the appropriate
number of significant figures.
"""
coeff, pwr = ('%e' % err).split('e')
if pwr.startswith('-'):
pwr = int(pwr[1:])
if round(float(coeff)) == 10.:
pwr -= 1
pwr = min(pwr, max_sig)
tmplt = '%.' + str(pwr+1) + 'f'
return tmplt % val
else:
pwr = int(pwr[1:])
if round(float(coeff)) == 10.:
pwr += 1
# if the error is large, we can sometimes get 0;
# adjust the round until we don't get 0 (assuming the actual
# value isn't 0)
return_val = round(val, -pwr+1)
if val != 0.:
loop_count = 0
max_recursion = 100
while return_val == 0.:
pwr -= 1
return_val = round(val, -pwr+1)
loop_count += 1
if loop_count > max_recursion:
raise ValueError("Maximum recursion depth hit! Input " +\
"values are: val = %f, err = %f" %(val, err))
return drop_trailing_zeros(return_val) | python | def get_signum(val, err, max_sig=numpy.inf):
coeff, pwr = ('%e' % err).split('e')
if pwr.startswith('-'):
pwr = int(pwr[1:])
if round(float(coeff)) == 10.:
pwr -= 1
pwr = min(pwr, max_sig)
tmplt = '%.' + str(pwr+1) + 'f'
return tmplt % val
else:
pwr = int(pwr[1:])
if round(float(coeff)) == 10.:
pwr += 1
# if the error is large, we can sometimes get 0;
# adjust the round until we don't get 0 (assuming the actual
# value isn't 0)
return_val = round(val, -pwr+1)
if val != 0.:
loop_count = 0
max_recursion = 100
while return_val == 0.:
pwr -= 1
return_val = round(val, -pwr+1)
loop_count += 1
if loop_count > max_recursion:
raise ValueError("Maximum recursion depth hit! Input " +\
"values are: val = %f, err = %f" %(val, err))
return drop_trailing_zeros(return_val) | [
"def",
"get_signum",
"(",
"val",
",",
"err",
",",
"max_sig",
"=",
"numpy",
".",
"inf",
")",
":",
"coeff",
",",
"pwr",
"=",
"(",
"'%e'",
"%",
"err",
")",
".",
"split",
"(",
"'e'",
")",
"if",
"pwr",
".",
"startswith",
"(",
"'-'",
")",
":",
"pwr",... | Given an error, returns a string for val formated to the appropriate
number of significant figures. | [
"Given",
"an",
"error",
"returns",
"a",
"string",
"for",
"val",
"formated",
"to",
"the",
"appropriate",
"number",
"of",
"significant",
"figures",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/results/str_utils.py#L60-L91 |
227,840 | gwastro/pycbc | pycbc/strain/strain.py | from_cli_single_ifo | def from_cli_single_ifo(opt, ifo, **kwargs):
"""
Get the strain for a single ifo when using the multi-detector CLI
"""
single_det_opt = copy_opts_for_single_ifo(opt, ifo)
return from_cli(single_det_opt, **kwargs) | python | def from_cli_single_ifo(opt, ifo, **kwargs):
single_det_opt = copy_opts_for_single_ifo(opt, ifo)
return from_cli(single_det_opt, **kwargs) | [
"def",
"from_cli_single_ifo",
"(",
"opt",
",",
"ifo",
",",
"*",
"*",
"kwargs",
")",
":",
"single_det_opt",
"=",
"copy_opts_for_single_ifo",
"(",
"opt",
",",
"ifo",
")",
"return",
"from_cli",
"(",
"single_det_opt",
",",
"*",
"*",
"kwargs",
")"
] | Get the strain for a single ifo when using the multi-detector CLI | [
"Get",
"the",
"strain",
"for",
"a",
"single",
"ifo",
"when",
"using",
"the",
"multi",
"-",
"detector",
"CLI"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/strain/strain.py#L420-L425 |
227,841 | gwastro/pycbc | pycbc/strain/strain.py | from_cli_multi_ifos | def from_cli_multi_ifos(opt, ifos, **kwargs):
"""
Get the strain for all ifos when using the multi-detector CLI
"""
strain = {}
for ifo in ifos:
strain[ifo] = from_cli_single_ifo(opt, ifo, **kwargs)
return strain | python | def from_cli_multi_ifos(opt, ifos, **kwargs):
strain = {}
for ifo in ifos:
strain[ifo] = from_cli_single_ifo(opt, ifo, **kwargs)
return strain | [
"def",
"from_cli_multi_ifos",
"(",
"opt",
",",
"ifos",
",",
"*",
"*",
"kwargs",
")",
":",
"strain",
"=",
"{",
"}",
"for",
"ifo",
"in",
"ifos",
":",
"strain",
"[",
"ifo",
"]",
"=",
"from_cli_single_ifo",
"(",
"opt",
",",
"ifo",
",",
"*",
"*",
"kwarg... | Get the strain for all ifos when using the multi-detector CLI | [
"Get",
"the",
"strain",
"for",
"all",
"ifos",
"when",
"using",
"the",
"multi",
"-",
"detector",
"CLI"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/strain/strain.py#L427-L434 |
227,842 | gwastro/pycbc | pycbc/strain/strain.py | gate_data | def gate_data(data, gate_params):
"""Apply a set of gating windows to a time series.
Each gating window is
defined by a central time, a given duration (centered on the given
time) to zero out, and a given duration of smooth tapering on each side of
the window. The window function used for tapering is a Tukey window.
Parameters
----------
data : TimeSeries
The time series to be gated.
gate_params : list
List of parameters for the gating windows. Each element should be a
list or tuple with 3 elements: the central time of the gating window,
the half-duration of the portion to zero out, and the duration of the
Tukey tapering on each side. All times in seconds. The total duration
of the data affected by one gating window is thus twice the second
parameter plus twice the third parameter.
Returns
-------
data: TimeSeries
The gated time series.
"""
def inverted_tukey(M, n_pad):
midlen = M - 2*n_pad
if midlen < 0:
raise ValueError("No zeros left after applying padding.")
padarr = 0.5*(1.+numpy.cos(numpy.pi*numpy.arange(n_pad)/n_pad))
return numpy.concatenate((padarr,numpy.zeros(midlen),padarr[::-1]))
sample_rate = 1./data.delta_t
temp = data.data
for glitch_time, glitch_width, pad_width in gate_params:
t_start = glitch_time - glitch_width - pad_width - data.start_time
t_end = glitch_time + glitch_width + pad_width - data.start_time
if t_start > data.duration or t_end < 0.:
continue # Skip gate segments that don't overlap
win_samples = int(2*sample_rate*(glitch_width+pad_width))
pad_samples = int(sample_rate*pad_width)
window = inverted_tukey(win_samples, pad_samples)
offset = int(t_start * sample_rate)
idx1 = max(0, -offset)
idx2 = min(len(window), len(data)-offset)
temp[idx1+offset:idx2+offset] *= window[idx1:idx2]
return data | python | def gate_data(data, gate_params):
def inverted_tukey(M, n_pad):
midlen = M - 2*n_pad
if midlen < 0:
raise ValueError("No zeros left after applying padding.")
padarr = 0.5*(1.+numpy.cos(numpy.pi*numpy.arange(n_pad)/n_pad))
return numpy.concatenate((padarr,numpy.zeros(midlen),padarr[::-1]))
sample_rate = 1./data.delta_t
temp = data.data
for glitch_time, glitch_width, pad_width in gate_params:
t_start = glitch_time - glitch_width - pad_width - data.start_time
t_end = glitch_time + glitch_width + pad_width - data.start_time
if t_start > data.duration or t_end < 0.:
continue # Skip gate segments that don't overlap
win_samples = int(2*sample_rate*(glitch_width+pad_width))
pad_samples = int(sample_rate*pad_width)
window = inverted_tukey(win_samples, pad_samples)
offset = int(t_start * sample_rate)
idx1 = max(0, -offset)
idx2 = min(len(window), len(data)-offset)
temp[idx1+offset:idx2+offset] *= window[idx1:idx2]
return data | [
"def",
"gate_data",
"(",
"data",
",",
"gate_params",
")",
":",
"def",
"inverted_tukey",
"(",
"M",
",",
"n_pad",
")",
":",
"midlen",
"=",
"M",
"-",
"2",
"*",
"n_pad",
"if",
"midlen",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"No zeros left after applyi... | Apply a set of gating windows to a time series.
Each gating window is
defined by a central time, a given duration (centered on the given
time) to zero out, and a given duration of smooth tapering on each side of
the window. The window function used for tapering is a Tukey window.
Parameters
----------
data : TimeSeries
The time series to be gated.
gate_params : list
List of parameters for the gating windows. Each element should be a
list or tuple with 3 elements: the central time of the gating window,
the half-duration of the portion to zero out, and the duration of the
Tukey tapering on each side. All times in seconds. The total duration
of the data affected by one gating window is thus twice the second
parameter plus twice the third parameter.
Returns
-------
data: TimeSeries
The gated time series. | [
"Apply",
"a",
"set",
"of",
"gating",
"windows",
"to",
"a",
"time",
"series",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/strain/strain.py#L811-L859 |
227,843 | gwastro/pycbc | pycbc/strain/strain.py | StrainSegments.fourier_segments | def fourier_segments(self):
""" Return a list of the FFT'd segments.
Return the list of FrequencySeries. Additional properties are
added that describe the strain segment. The property 'analyze'
is a slice corresponding to the portion of the time domain equivelant
of the segment to analyze for triggers. The value 'cumulative_index'
indexes from the beginning of the original strain series.
"""
if not self._fourier_segments:
self._fourier_segments = []
for seg_slice, ana in zip(self.segment_slices, self.analyze_slices):
if seg_slice.start >= 0 and seg_slice.stop <= len(self.strain):
freq_seg = make_frequency_series(self.strain[seg_slice])
# Assume that we cannot have a case where we both zero-pad on
# both sides
elif seg_slice.start < 0:
strain_chunk = self.strain[:seg_slice.stop]
strain_chunk.prepend_zeros(-seg_slice.start)
freq_seg = make_frequency_series(strain_chunk)
elif seg_slice.stop > len(self.strain):
strain_chunk = self.strain[seg_slice.start:]
strain_chunk.append_zeros(seg_slice.stop - len(self.strain))
freq_seg = make_frequency_series(strain_chunk)
freq_seg.analyze = ana
freq_seg.cumulative_index = seg_slice.start + ana.start
freq_seg.seg_slice = seg_slice
self._fourier_segments.append(freq_seg)
return self._fourier_segments | python | def fourier_segments(self):
if not self._fourier_segments:
self._fourier_segments = []
for seg_slice, ana in zip(self.segment_slices, self.analyze_slices):
if seg_slice.start >= 0 and seg_slice.stop <= len(self.strain):
freq_seg = make_frequency_series(self.strain[seg_slice])
# Assume that we cannot have a case where we both zero-pad on
# both sides
elif seg_slice.start < 0:
strain_chunk = self.strain[:seg_slice.stop]
strain_chunk.prepend_zeros(-seg_slice.start)
freq_seg = make_frequency_series(strain_chunk)
elif seg_slice.stop > len(self.strain):
strain_chunk = self.strain[seg_slice.start:]
strain_chunk.append_zeros(seg_slice.stop - len(self.strain))
freq_seg = make_frequency_series(strain_chunk)
freq_seg.analyze = ana
freq_seg.cumulative_index = seg_slice.start + ana.start
freq_seg.seg_slice = seg_slice
self._fourier_segments.append(freq_seg)
return self._fourier_segments | [
"def",
"fourier_segments",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_fourier_segments",
":",
"self",
".",
"_fourier_segments",
"=",
"[",
"]",
"for",
"seg_slice",
",",
"ana",
"in",
"zip",
"(",
"self",
".",
"segment_slices",
",",
"self",
".",
"ana... | Return a list of the FFT'd segments.
Return the list of FrequencySeries. Additional properties are
added that describe the strain segment. The property 'analyze'
is a slice corresponding to the portion of the time domain equivelant
of the segment to analyze for triggers. The value 'cumulative_index'
indexes from the beginning of the original strain series. | [
"Return",
"a",
"list",
"of",
"the",
"FFT",
"d",
"segments",
".",
"Return",
"the",
"list",
"of",
"FrequencySeries",
".",
"Additional",
"properties",
"are",
"added",
"that",
"describe",
"the",
"strain",
"segment",
".",
"The",
"property",
"analyze",
"is",
"a",
... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/strain/strain.py#L1010-L1038 |
227,844 | gwastro/pycbc | pycbc/strain/strain.py | StrainBuffer.end_time | def end_time(self):
""" Return the end time of the current valid segment of data """
return float(self.strain.start_time + (len(self.strain) - self.total_corruption) / self.sample_rate) | python | def end_time(self):
return float(self.strain.start_time + (len(self.strain) - self.total_corruption) / self.sample_rate) | [
"def",
"end_time",
"(",
"self",
")",
":",
"return",
"float",
"(",
"self",
".",
"strain",
".",
"start_time",
"+",
"(",
"len",
"(",
"self",
".",
"strain",
")",
"-",
"self",
".",
"total_corruption",
")",
"/",
"self",
".",
"sample_rate",
")"
] | Return the end time of the current valid segment of data | [
"Return",
"the",
"end",
"time",
"of",
"the",
"current",
"valid",
"segment",
"of",
"data"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/strain/strain.py#L1360-L1362 |
227,845 | gwastro/pycbc | pycbc/strain/strain.py | StrainBuffer.add_hard_count | def add_hard_count(self):
""" Reset the countdown timer, so that we don't analyze data long enough
to generate a new PSD.
"""
self.wait_duration = int(numpy.ceil(self.total_corruption / self.sample_rate + self.psd_duration))
self.invalidate_psd() | python | def add_hard_count(self):
self.wait_duration = int(numpy.ceil(self.total_corruption / self.sample_rate + self.psd_duration))
self.invalidate_psd() | [
"def",
"add_hard_count",
"(",
"self",
")",
":",
"self",
".",
"wait_duration",
"=",
"int",
"(",
"numpy",
".",
"ceil",
"(",
"self",
".",
"total_corruption",
"/",
"self",
".",
"sample_rate",
"+",
"self",
".",
"psd_duration",
")",
")",
"self",
".",
"invalida... | Reset the countdown timer, so that we don't analyze data long enough
to generate a new PSD. | [
"Reset",
"the",
"countdown",
"timer",
"so",
"that",
"we",
"don",
"t",
"analyze",
"data",
"long",
"enough",
"to",
"generate",
"a",
"new",
"PSD",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/strain/strain.py#L1364-L1369 |
227,846 | gwastro/pycbc | pycbc/strain/strain.py | StrainBuffer.recalculate_psd | def recalculate_psd(self):
""" Recalculate the psd
"""
seg_len = self.sample_rate * self.psd_segment_length
e = len(self.strain)
s = e - ((self.psd_samples + 1) * self.psd_segment_length / 2) * self.sample_rate
psd = pycbc.psd.welch(self.strain[s:e], seg_len=seg_len, seg_stride=seg_len / 2)
psd.dist = spa_distance(psd, 1.4, 1.4, self.low_frequency_cutoff) * pycbc.DYN_RANGE_FAC
# If the new psd is similar to the old one, don't replace it
if self.psd and self.psd_recalculate_difference:
if abs(self.psd.dist - psd.dist) / self.psd.dist < self.psd_recalculate_difference:
logging.info("Skipping recalculation of %s PSD, %s-%s",
self.detector, self.psd.dist, psd.dist)
return True
# If the new psd is *really* different than the old one, return an error
if self.psd and self.psd_abort_difference:
if abs(self.psd.dist - psd.dist) / self.psd.dist > self.psd_abort_difference:
logging.info("%s PSD is CRAZY, aborting!!!!, %s-%s",
self.detector, self.psd.dist, psd.dist)
self.psd = psd
self.psds = {}
return False
# If the new estimate replaces the current one, invalide the ineterpolate PSDs
self.psd = psd
self.psds = {}
logging.info("Recalculating %s PSD, %s", self.detector, psd.dist)
return True | python | def recalculate_psd(self):
seg_len = self.sample_rate * self.psd_segment_length
e = len(self.strain)
s = e - ((self.psd_samples + 1) * self.psd_segment_length / 2) * self.sample_rate
psd = pycbc.psd.welch(self.strain[s:e], seg_len=seg_len, seg_stride=seg_len / 2)
psd.dist = spa_distance(psd, 1.4, 1.4, self.low_frequency_cutoff) * pycbc.DYN_RANGE_FAC
# If the new psd is similar to the old one, don't replace it
if self.psd and self.psd_recalculate_difference:
if abs(self.psd.dist - psd.dist) / self.psd.dist < self.psd_recalculate_difference:
logging.info("Skipping recalculation of %s PSD, %s-%s",
self.detector, self.psd.dist, psd.dist)
return True
# If the new psd is *really* different than the old one, return an error
if self.psd and self.psd_abort_difference:
if abs(self.psd.dist - psd.dist) / self.psd.dist > self.psd_abort_difference:
logging.info("%s PSD is CRAZY, aborting!!!!, %s-%s",
self.detector, self.psd.dist, psd.dist)
self.psd = psd
self.psds = {}
return False
# If the new estimate replaces the current one, invalide the ineterpolate PSDs
self.psd = psd
self.psds = {}
logging.info("Recalculating %s PSD, %s", self.detector, psd.dist)
return True | [
"def",
"recalculate_psd",
"(",
"self",
")",
":",
"seg_len",
"=",
"self",
".",
"sample_rate",
"*",
"self",
".",
"psd_segment_length",
"e",
"=",
"len",
"(",
"self",
".",
"strain",
")",
"s",
"=",
"e",
"-",
"(",
"(",
"self",
".",
"psd_samples",
"+",
"1",... | Recalculate the psd | [
"Recalculate",
"the",
"psd"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/strain/strain.py#L1377-L1408 |
227,847 | gwastro/pycbc | pycbc/strain/strain.py | StrainBuffer.overwhitened_data | def overwhitened_data(self, delta_f):
""" Return overwhitened data
Parameters
----------
delta_f: float
The sample step to generate overwhitened frequency domain data for
Returns
-------
htilde: FrequencySeries
Overwhited strain data
"""
# we haven't already computed htilde for this delta_f
if delta_f not in self.segments:
buffer_length = int(1.0 / delta_f)
e = len(self.strain)
s = int(e - buffer_length * self.sample_rate - self.reduced_pad * 2)
fseries = make_frequency_series(self.strain[s:e])
# we haven't calculated a resample psd for this delta_f
if delta_f not in self.psds:
psdt = pycbc.psd.interpolate(self.psd, fseries.delta_f)
psdt = pycbc.psd.inverse_spectrum_truncation(psdt,
int(self.sample_rate * self.psd_inverse_length),
low_frequency_cutoff=self.low_frequency_cutoff)
psdt._delta_f = fseries.delta_f
psd = pycbc.psd.interpolate(self.psd, delta_f)
psd = pycbc.psd.inverse_spectrum_truncation(psd,
int(self.sample_rate * self.psd_inverse_length),
low_frequency_cutoff=self.low_frequency_cutoff)
psd.psdt = psdt
self.psds[delta_f] = psd
psd = self.psds[delta_f]
fseries /= psd.psdt
# trim ends of strain
if self.reduced_pad != 0:
overwhite = TimeSeries(zeros(e-s, dtype=self.strain.dtype),
delta_t=self.strain.delta_t)
pycbc.fft.ifft(fseries, overwhite)
overwhite2 = overwhite[self.reduced_pad:len(overwhite)-self.reduced_pad]
taper_window = self.trim_padding / 2.0 / overwhite.sample_rate
gate_params = [(overwhite2.start_time, 0., taper_window),
(overwhite2.end_time, 0., taper_window)]
gate_data(overwhite2, gate_params)
fseries_trimmed = FrequencySeries(zeros(len(overwhite2) / 2 + 1,
dtype=fseries.dtype), delta_f=delta_f)
pycbc.fft.fft(overwhite2, fseries_trimmed)
fseries_trimmed.start_time = fseries.start_time + self.reduced_pad * self.strain.delta_t
else:
fseries_trimmed = fseries
fseries_trimmed.psd = psd
self.segments[delta_f] = fseries_trimmed
stilde = self.segments[delta_f]
return stilde | python | def overwhitened_data(self, delta_f):
# we haven't already computed htilde for this delta_f
if delta_f not in self.segments:
buffer_length = int(1.0 / delta_f)
e = len(self.strain)
s = int(e - buffer_length * self.sample_rate - self.reduced_pad * 2)
fseries = make_frequency_series(self.strain[s:e])
# we haven't calculated a resample psd for this delta_f
if delta_f not in self.psds:
psdt = pycbc.psd.interpolate(self.psd, fseries.delta_f)
psdt = pycbc.psd.inverse_spectrum_truncation(psdt,
int(self.sample_rate * self.psd_inverse_length),
low_frequency_cutoff=self.low_frequency_cutoff)
psdt._delta_f = fseries.delta_f
psd = pycbc.psd.interpolate(self.psd, delta_f)
psd = pycbc.psd.inverse_spectrum_truncation(psd,
int(self.sample_rate * self.psd_inverse_length),
low_frequency_cutoff=self.low_frequency_cutoff)
psd.psdt = psdt
self.psds[delta_f] = psd
psd = self.psds[delta_f]
fseries /= psd.psdt
# trim ends of strain
if self.reduced_pad != 0:
overwhite = TimeSeries(zeros(e-s, dtype=self.strain.dtype),
delta_t=self.strain.delta_t)
pycbc.fft.ifft(fseries, overwhite)
overwhite2 = overwhite[self.reduced_pad:len(overwhite)-self.reduced_pad]
taper_window = self.trim_padding / 2.0 / overwhite.sample_rate
gate_params = [(overwhite2.start_time, 0., taper_window),
(overwhite2.end_time, 0., taper_window)]
gate_data(overwhite2, gate_params)
fseries_trimmed = FrequencySeries(zeros(len(overwhite2) / 2 + 1,
dtype=fseries.dtype), delta_f=delta_f)
pycbc.fft.fft(overwhite2, fseries_trimmed)
fseries_trimmed.start_time = fseries.start_time + self.reduced_pad * self.strain.delta_t
else:
fseries_trimmed = fseries
fseries_trimmed.psd = psd
self.segments[delta_f] = fseries_trimmed
stilde = self.segments[delta_f]
return stilde | [
"def",
"overwhitened_data",
"(",
"self",
",",
"delta_f",
")",
":",
"# we haven't already computed htilde for this delta_f",
"if",
"delta_f",
"not",
"in",
"self",
".",
"segments",
":",
"buffer_length",
"=",
"int",
"(",
"1.0",
"/",
"delta_f",
")",
"e",
"=",
"len",... | Return overwhitened data
Parameters
----------
delta_f: float
The sample step to generate overwhitened frequency domain data for
Returns
-------
htilde: FrequencySeries
Overwhited strain data | [
"Return",
"overwhitened",
"data"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/strain/strain.py#L1410-L1470 |
227,848 | gwastro/pycbc | pycbc/strain/strain.py | StrainBuffer.near_hwinj | def near_hwinj(self):
"""Check that the current set of triggers could be influenced by
a hardware injection.
"""
if not self.state:
return False
if not self.state.is_extent_valid(self.start_time, self.blocksize, pycbc.frame.NO_HWINJ):
return True
return False | python | def near_hwinj(self):
if not self.state:
return False
if not self.state.is_extent_valid(self.start_time, self.blocksize, pycbc.frame.NO_HWINJ):
return True
return False | [
"def",
"near_hwinj",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"state",
":",
"return",
"False",
"if",
"not",
"self",
".",
"state",
".",
"is_extent_valid",
"(",
"self",
".",
"start_time",
",",
"self",
".",
"blocksize",
",",
"pycbc",
".",
"frame",... | Check that the current set of triggers could be influenced by
a hardware injection. | [
"Check",
"that",
"the",
"current",
"set",
"of",
"triggers",
"could",
"be",
"influenced",
"by",
"a",
"hardware",
"injection",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/strain/strain.py#L1472-L1481 |
227,849 | gwastro/pycbc | pycbc/strain/strain.py | StrainBuffer.advance | def advance(self, blocksize, timeout=10):
"""Advanced buffer blocksize seconds.
Add blocksize seconds more to the buffer, push blocksize seconds
from the beginning.
Parameters
----------
blocksize: int
The number of seconds to attempt to read from the channel
Returns
-------
status: boolean
Returns True if this block is analyzable.
"""
ts = super(StrainBuffer, self).attempt_advance(blocksize, timeout=timeout)
self.blocksize = blocksize
# We have given up so there is no time series
if ts is None:
logging.info("%s frame is late, giving up", self.detector)
self.null_advance_strain(blocksize)
if self.state:
self.state.null_advance(blocksize)
if self.dq:
self.dq.null_advance(blocksize)
return False
# We collected some data so we are closer to being able to analyze data
self.wait_duration -= blocksize
# If the data we got was invalid, reset the counter on how much to collect
# This behavior corresponds to how we handle CAT1 vetoes
if self.state and self.state.advance(blocksize) is False:
self.add_hard_count()
self.null_advance_strain(blocksize)
if self.dq:
self.dq.null_advance(blocksize)
logging.info("%s time has invalid data, resetting buffer",
self.detector)
return False
# Also advance the dq vector in lockstep
if self.dq:
self.dq.advance(blocksize)
self.segments = {}
# only condition with the needed raw data so we can continuously add
# to the existing result
# Precondition
sample_step = int(blocksize * self.sample_rate)
csize = sample_step + self.corruption * 2
start = len(self.raw_buffer) - csize * self.factor
strain = self.raw_buffer[start:]
strain = pycbc.filter.highpass_fir(strain, self.highpass_frequency,
self.highpass_samples,
beta=self.beta)
strain = (strain * self.dyn_range_fac).astype(numpy.float32)
strain = pycbc.filter.resample_to_delta_t(strain,
1.0/self.sample_rate, method='ldas')
# remove corruption at beginning
strain = strain[self.corruption:]
# taper beginning if needed
if self.taper_immediate_strain:
logging.info("Tapering start of %s strain block", self.detector)
strain = gate_data(strain, [(strain.start_time, 0., self.autogating_pad)])
self.taper_immediate_strain = False
# Stitch into continuous stream
self.strain.roll(-sample_step)
self.strain[len(self.strain) - csize + self.corruption:] = strain[:]
self.strain.start_time += blocksize
# apply gating if need be: NOT YET IMPLEMENTED
if self.psd is None and self.wait_duration <=0:
self.recalculate_psd()
if self.wait_duration > 0:
return False
else:
return True | python | def advance(self, blocksize, timeout=10):
ts = super(StrainBuffer, self).attempt_advance(blocksize, timeout=timeout)
self.blocksize = blocksize
# We have given up so there is no time series
if ts is None:
logging.info("%s frame is late, giving up", self.detector)
self.null_advance_strain(blocksize)
if self.state:
self.state.null_advance(blocksize)
if self.dq:
self.dq.null_advance(blocksize)
return False
# We collected some data so we are closer to being able to analyze data
self.wait_duration -= blocksize
# If the data we got was invalid, reset the counter on how much to collect
# This behavior corresponds to how we handle CAT1 vetoes
if self.state and self.state.advance(blocksize) is False:
self.add_hard_count()
self.null_advance_strain(blocksize)
if self.dq:
self.dq.null_advance(blocksize)
logging.info("%s time has invalid data, resetting buffer",
self.detector)
return False
# Also advance the dq vector in lockstep
if self.dq:
self.dq.advance(blocksize)
self.segments = {}
# only condition with the needed raw data so we can continuously add
# to the existing result
# Precondition
sample_step = int(blocksize * self.sample_rate)
csize = sample_step + self.corruption * 2
start = len(self.raw_buffer) - csize * self.factor
strain = self.raw_buffer[start:]
strain = pycbc.filter.highpass_fir(strain, self.highpass_frequency,
self.highpass_samples,
beta=self.beta)
strain = (strain * self.dyn_range_fac).astype(numpy.float32)
strain = pycbc.filter.resample_to_delta_t(strain,
1.0/self.sample_rate, method='ldas')
# remove corruption at beginning
strain = strain[self.corruption:]
# taper beginning if needed
if self.taper_immediate_strain:
logging.info("Tapering start of %s strain block", self.detector)
strain = gate_data(strain, [(strain.start_time, 0., self.autogating_pad)])
self.taper_immediate_strain = False
# Stitch into continuous stream
self.strain.roll(-sample_step)
self.strain[len(self.strain) - csize + self.corruption:] = strain[:]
self.strain.start_time += blocksize
# apply gating if need be: NOT YET IMPLEMENTED
if self.psd is None and self.wait_duration <=0:
self.recalculate_psd()
if self.wait_duration > 0:
return False
else:
return True | [
"def",
"advance",
"(",
"self",
",",
"blocksize",
",",
"timeout",
"=",
"10",
")",
":",
"ts",
"=",
"super",
"(",
"StrainBuffer",
",",
"self",
")",
".",
"attempt_advance",
"(",
"blocksize",
",",
"timeout",
"=",
"timeout",
")",
"self",
".",
"blocksize",
"=... | Advanced buffer blocksize seconds.
Add blocksize seconds more to the buffer, push blocksize seconds
from the beginning.
Parameters
----------
blocksize: int
The number of seconds to attempt to read from the channel
Returns
-------
status: boolean
Returns True if this block is analyzable. | [
"Advanced",
"buffer",
"blocksize",
"seconds",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/strain/strain.py#L1502-L1589 |
227,850 | gwastro/pycbc | pycbc/psd/analytical.py | from_string | def from_string(psd_name, length, delta_f, low_freq_cutoff):
"""Generate a frequency series containing a LALSimulation PSD specified
by name.
Parameters
----------
psd_name : string
PSD name as found in LALSimulation, minus the SimNoisePSD prefix.
length : int
Length of the frequency series in samples.
delta_f : float
Frequency resolution of the frequency series.
low_freq_cutoff : float
Frequencies below this value are set to zero.
Returns
-------
psd : FrequencySeries
The generated frequency series.
"""
# check if valid PSD model
if psd_name not in get_psd_model_list():
raise ValueError(psd_name + ' not found among analytical '
'PSD functions.')
# if PSD model is in LALSimulation
if psd_name in get_lalsim_psd_list():
lalseries = lal.CreateREAL8FrequencySeries(
'', lal.LIGOTimeGPS(0), 0, delta_f, lal.DimensionlessUnit, length)
try:
func = lalsimulation.__dict__[
_name_prefix + psd_name + _name_suffix]
except KeyError:
func = lalsimulation.__dict__[_name_prefix + psd_name]
func(lalseries, low_freq_cutoff)
else:
lalsimulation.SimNoisePSD(lalseries, 0, func)
psd = FrequencySeries(lalseries.data.data, delta_f=delta_f)
# if PSD model is coded in PyCBC
else:
func = pycbc_analytical_psds[psd_name]
psd = func(length, delta_f, low_freq_cutoff)
# zero-out content below low-frequency cutoff
kmin = int(low_freq_cutoff / delta_f)
psd.data[:kmin] = 0
return psd | python | def from_string(psd_name, length, delta_f, low_freq_cutoff):
# check if valid PSD model
if psd_name not in get_psd_model_list():
raise ValueError(psd_name + ' not found among analytical '
'PSD functions.')
# if PSD model is in LALSimulation
if psd_name in get_lalsim_psd_list():
lalseries = lal.CreateREAL8FrequencySeries(
'', lal.LIGOTimeGPS(0), 0, delta_f, lal.DimensionlessUnit, length)
try:
func = lalsimulation.__dict__[
_name_prefix + psd_name + _name_suffix]
except KeyError:
func = lalsimulation.__dict__[_name_prefix + psd_name]
func(lalseries, low_freq_cutoff)
else:
lalsimulation.SimNoisePSD(lalseries, 0, func)
psd = FrequencySeries(lalseries.data.data, delta_f=delta_f)
# if PSD model is coded in PyCBC
else:
func = pycbc_analytical_psds[psd_name]
psd = func(length, delta_f, low_freq_cutoff)
# zero-out content below low-frequency cutoff
kmin = int(low_freq_cutoff / delta_f)
psd.data[:kmin] = 0
return psd | [
"def",
"from_string",
"(",
"psd_name",
",",
"length",
",",
"delta_f",
",",
"low_freq_cutoff",
")",
":",
"# check if valid PSD model",
"if",
"psd_name",
"not",
"in",
"get_psd_model_list",
"(",
")",
":",
"raise",
"ValueError",
"(",
"psd_name",
"+",
"' not found amon... | Generate a frequency series containing a LALSimulation PSD specified
by name.
Parameters
----------
psd_name : string
PSD name as found in LALSimulation, minus the SimNoisePSD prefix.
length : int
Length of the frequency series in samples.
delta_f : float
Frequency resolution of the frequency series.
low_freq_cutoff : float
Frequencies below this value are set to zero.
Returns
-------
psd : FrequencySeries
The generated frequency series. | [
"Generate",
"a",
"frequency",
"series",
"containing",
"a",
"LALSimulation",
"PSD",
"specified",
"by",
"name",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/psd/analytical.py#L73-L122 |
227,851 | gwastro/pycbc | pycbc/psd/analytical.py | flat_unity | def flat_unity(length, delta_f, low_freq_cutoff):
""" Returns a FrequencySeries of ones above the low_frequency_cutoff.
Parameters
----------
length : int
Length of output Frequencyseries.
delta_f : float
Frequency step for output FrequencySeries.
low_freq_cutoff : int
Low-frequency cutoff for output FrequencySeries.
Returns
-------
FrequencySeries
Returns a FrequencySeries containing the unity PSD model.
"""
fseries = FrequencySeries(numpy.ones(length), delta_f=delta_f)
kmin = int(low_freq_cutoff / fseries.delta_f)
fseries.data[:kmin] = 0
return fseries | python | def flat_unity(length, delta_f, low_freq_cutoff):
fseries = FrequencySeries(numpy.ones(length), delta_f=delta_f)
kmin = int(low_freq_cutoff / fseries.delta_f)
fseries.data[:kmin] = 0
return fseries | [
"def",
"flat_unity",
"(",
"length",
",",
"delta_f",
",",
"low_freq_cutoff",
")",
":",
"fseries",
"=",
"FrequencySeries",
"(",
"numpy",
".",
"ones",
"(",
"length",
")",
",",
"delta_f",
"=",
"delta_f",
")",
"kmin",
"=",
"int",
"(",
"low_freq_cutoff",
"/",
... | Returns a FrequencySeries of ones above the low_frequency_cutoff.
Parameters
----------
length : int
Length of output Frequencyseries.
delta_f : float
Frequency step for output FrequencySeries.
low_freq_cutoff : int
Low-frequency cutoff for output FrequencySeries.
Returns
-------
FrequencySeries
Returns a FrequencySeries containing the unity PSD model. | [
"Returns",
"a",
"FrequencySeries",
"of",
"ones",
"above",
"the",
"low_frequency_cutoff",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/psd/analytical.py#L124-L144 |
227,852 | gwastro/pycbc | pycbc/waveform/compress.py | rough_time_estimate | def rough_time_estimate(m1, m2, flow, fudge_length=1.1, fudge_min=0.02):
""" A very rough estimate of the duration of the waveform.
An estimate of the waveform duration starting from flow. This is intended
to be fast but not necessarily accurate. It should be an overestimate of
the length. It is derived from a simplification of the 0PN post-newtonian
terms and includes a fudge factor for possible ringdown, etc.
Parameters
----------
m1: float
mass of first component object in solar masses
m2: float
mass of second component object in solar masses
flow: float
starting frequency of the waveform
fudge_length: optional, {1.1, float}
Factor to multiply length estimate by to ensure it is a convservative
value
fudge_min: optional, {0.2, float}
Minimum signal duration that can be returned. This should be long
enough to encompass the ringdown and errors in the precise end time.
Returns
-------
time: float
Time from flow untill the end of the waveform
"""
m = m1 + m2
msun = m * lal.MTSUN_SI
t = 5.0 / 256.0 * m * m * msun / (m1 * m2) / \
(numpy.pi * msun * flow) ** (8.0 / 3.0)
# fudge factoriness
return .022 if t < 0 else (t + fudge_min) * fudge_length | python | def rough_time_estimate(m1, m2, flow, fudge_length=1.1, fudge_min=0.02):
m = m1 + m2
msun = m * lal.MTSUN_SI
t = 5.0 / 256.0 * m * m * msun / (m1 * m2) / \
(numpy.pi * msun * flow) ** (8.0 / 3.0)
# fudge factoriness
return .022 if t < 0 else (t + fudge_min) * fudge_length | [
"def",
"rough_time_estimate",
"(",
"m1",
",",
"m2",
",",
"flow",
",",
"fudge_length",
"=",
"1.1",
",",
"fudge_min",
"=",
"0.02",
")",
":",
"m",
"=",
"m1",
"+",
"m2",
"msun",
"=",
"m",
"*",
"lal",
".",
"MTSUN_SI",
"t",
"=",
"5.0",
"/",
"256.0",
"*... | A very rough estimate of the duration of the waveform.
An estimate of the waveform duration starting from flow. This is intended
to be fast but not necessarily accurate. It should be an overestimate of
the length. It is derived from a simplification of the 0PN post-newtonian
terms and includes a fudge factor for possible ringdown, etc.
Parameters
----------
m1: float
mass of first component object in solar masses
m2: float
mass of second component object in solar masses
flow: float
starting frequency of the waveform
fudge_length: optional, {1.1, float}
Factor to multiply length estimate by to ensure it is a convservative
value
fudge_min: optional, {0.2, float}
Minimum signal duration that can be returned. This should be long
enough to encompass the ringdown and errors in the precise end time.
Returns
-------
time: float
Time from flow untill the end of the waveform | [
"A",
"very",
"rough",
"estimate",
"of",
"the",
"duration",
"of",
"the",
"waveform",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/compress.py#L34-L68 |
227,853 | gwastro/pycbc | pycbc/waveform/compress.py | mchirp_compression | def mchirp_compression(m1, m2, fmin, fmax, min_seglen=0.02, df_multiple=None):
"""Return the frequencies needed to compress a waveform with the given
chirp mass. This is based on the estimate in rough_time_estimate.
Parameters
----------
m1: float
mass of first component object in solar masses
m2: float
mass of second component object in solar masses
fmin : float
The starting frequency of the compressed waveform.
fmax : float
The ending frequency of the compressed waveform.
min_seglen : float
The inverse of this gives the maximum frequency step that is used.
df_multiple : {None, float}
Make the compressed sampling frequencies a multiple of the given value.
If None provided, the returned sample points can have any floating
point value.
Returns
-------
array
The frequencies at which to evaluate the compressed waveform.
"""
sample_points = []
f = fmin
while f < fmax:
if df_multiple is not None:
f = int(f/df_multiple)*df_multiple
sample_points.append(f)
f += 1.0 / rough_time_estimate(m1, m2, f, fudge_min=min_seglen)
# add the last point
if sample_points[-1] < fmax:
sample_points.append(fmax)
return numpy.array(sample_points) | python | def mchirp_compression(m1, m2, fmin, fmax, min_seglen=0.02, df_multiple=None):
sample_points = []
f = fmin
while f < fmax:
if df_multiple is not None:
f = int(f/df_multiple)*df_multiple
sample_points.append(f)
f += 1.0 / rough_time_estimate(m1, m2, f, fudge_min=min_seglen)
# add the last point
if sample_points[-1] < fmax:
sample_points.append(fmax)
return numpy.array(sample_points) | [
"def",
"mchirp_compression",
"(",
"m1",
",",
"m2",
",",
"fmin",
",",
"fmax",
",",
"min_seglen",
"=",
"0.02",
",",
"df_multiple",
"=",
"None",
")",
":",
"sample_points",
"=",
"[",
"]",
"f",
"=",
"fmin",
"while",
"f",
"<",
"fmax",
":",
"if",
"df_multip... | Return the frequencies needed to compress a waveform with the given
chirp mass. This is based on the estimate in rough_time_estimate.
Parameters
----------
m1: float
mass of first component object in solar masses
m2: float
mass of second component object in solar masses
fmin : float
The starting frequency of the compressed waveform.
fmax : float
The ending frequency of the compressed waveform.
min_seglen : float
The inverse of this gives the maximum frequency step that is used.
df_multiple : {None, float}
Make the compressed sampling frequencies a multiple of the given value.
If None provided, the returned sample points can have any floating
point value.
Returns
-------
array
The frequencies at which to evaluate the compressed waveform. | [
"Return",
"the",
"frequencies",
"needed",
"to",
"compress",
"a",
"waveform",
"with",
"the",
"given",
"chirp",
"mass",
".",
"This",
"is",
"based",
"on",
"the",
"estimate",
"in",
"rough_time_estimate",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/compress.py#L70-L106 |
227,854 | gwastro/pycbc | pycbc/waveform/compress.py | vecdiff | def vecdiff(htilde, hinterp, sample_points, psd=None):
"""Computes a statistic indicating between which sample points a waveform
and the interpolated waveform differ the most.
"""
vecdiffs = numpy.zeros(sample_points.size-1, dtype=float)
for kk,thisf in enumerate(sample_points[:-1]):
nextf = sample_points[kk+1]
vecdiffs[kk] = abs(_vecdiff(htilde, hinterp, thisf, nextf, psd=psd))
return vecdiffs | python | def vecdiff(htilde, hinterp, sample_points, psd=None):
vecdiffs = numpy.zeros(sample_points.size-1, dtype=float)
for kk,thisf in enumerate(sample_points[:-1]):
nextf = sample_points[kk+1]
vecdiffs[kk] = abs(_vecdiff(htilde, hinterp, thisf, nextf, psd=psd))
return vecdiffs | [
"def",
"vecdiff",
"(",
"htilde",
",",
"hinterp",
",",
"sample_points",
",",
"psd",
"=",
"None",
")",
":",
"vecdiffs",
"=",
"numpy",
".",
"zeros",
"(",
"sample_points",
".",
"size",
"-",
"1",
",",
"dtype",
"=",
"float",
")",
"for",
"kk",
",",
"thisf",... | Computes a statistic indicating between which sample points a waveform
and the interpolated waveform differ the most. | [
"Computes",
"a",
"statistic",
"indicating",
"between",
"which",
"sample",
"points",
"a",
"waveform",
"and",
"the",
"interpolated",
"waveform",
"differ",
"the",
"most",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/compress.py#L168-L176 |
227,855 | gwastro/pycbc | pycbc/waveform/compress.py | fd_decompress | def fd_decompress(amp, phase, sample_frequencies, out=None, df=None,
f_lower=None, interpolation='inline_linear'):
"""Decompresses an FD waveform using the given amplitude, phase, and the
frequencies at which they are sampled at.
Parameters
----------
amp : array
The amplitude of the waveform at the sample frequencies.
phase : array
The phase of the waveform at the sample frequencies.
sample_frequencies : array
The frequency (in Hz) of the waveform at the sample frequencies.
out : {None, FrequencySeries}
The output array to save the decompressed waveform to. If this contains
slots for frequencies > the maximum frequency in sample_frequencies,
the rest of the values are zeroed. If not provided, must provide a df.
df : {None, float}
The frequency step to use for the decompressed waveform. Must be
provided if out is None.
f_lower : {None, float}
The frequency to start the decompression at. If None, will use whatever
the lowest frequency is in sample_frequencies. All values at
frequencies less than this will be 0 in the decompressed waveform.
interpolation : {'inline_linear', str}
The interpolation to use for the amplitude and phase. Default is
'inline_linear'. If 'inline_linear' a custom interpolater is used.
Otherwise, ``scipy.interpolate.interp1d`` is used; for other options,
see possible values for that function's ``kind`` argument.
Returns
-------
out : FrequencySeries
If out was provided, writes to that array. Otherwise, a new
FrequencySeries with the decompressed waveform.
"""
precision = _precision_map[sample_frequencies.dtype.name]
if _precision_map[amp.dtype.name] != precision or \
_precision_map[phase.dtype.name] != precision:
raise ValueError("amp, phase, and sample_points must all have the "
"same precision")
if out is None:
if df is None:
raise ValueError("Either provide output memory or a df")
hlen = int(numpy.ceil(sample_frequencies.max()/df+1))
out = FrequencySeries(numpy.zeros(hlen,
dtype=_complex_dtypes[precision]), copy=False,
delta_f=df)
else:
# check for precision compatibility
if out.precision == 'double' and precision == 'single':
raise ValueError("cannot cast single precision to double")
df = out.delta_f
hlen = len(out)
if f_lower is None:
imin = 0 # pylint:disable=unused-variable
f_lower = sample_frequencies[0]
start_index = 0
else:
if f_lower >= sample_frequencies.max():
raise ValueError("f_lower is > than the maximum sample frequency")
if f_lower < sample_frequencies.min():
raise ValueError("f_lower is < than the minimum sample frequency")
imin = int(numpy.searchsorted(sample_frequencies, f_lower,
side='right')) - 1 # pylint:disable=unused-variable
start_index = int(numpy.ceil(f_lower/df))
if start_index >= hlen:
raise ValueError('requested f_lower >= largest frequency in out')
# interpolate the amplitude and the phase
if interpolation == "inline_linear":
# Call the scheme-dependent function
inline_linear_interp(amp, phase, sample_frequencies, out,
df, f_lower, imin, start_index)
else:
# use scipy for fancier interpolation
sample_frequencies = numpy.array(sample_frequencies)
amp = numpy.array(amp)
phase = numpy.array(phase)
outfreq = out.sample_frequencies.numpy()
amp_interp = interpolate.interp1d(sample_frequencies, amp,
kind=interpolation,
bounds_error=False,
fill_value=0.,
assume_sorted=True)
phase_interp = interpolate.interp1d(sample_frequencies, phase,
kind=interpolation,
bounds_error=False,
fill_value=0.,
assume_sorted=True)
A = amp_interp(outfreq)
phi = phase_interp(outfreq)
out.data[:] = A*numpy.cos(phi) + (1j)*A*numpy.sin(phi)
return out | python | def fd_decompress(amp, phase, sample_frequencies, out=None, df=None,
f_lower=None, interpolation='inline_linear'):
precision = _precision_map[sample_frequencies.dtype.name]
if _precision_map[amp.dtype.name] != precision or \
_precision_map[phase.dtype.name] != precision:
raise ValueError("amp, phase, and sample_points must all have the "
"same precision")
if out is None:
if df is None:
raise ValueError("Either provide output memory or a df")
hlen = int(numpy.ceil(sample_frequencies.max()/df+1))
out = FrequencySeries(numpy.zeros(hlen,
dtype=_complex_dtypes[precision]), copy=False,
delta_f=df)
else:
# check for precision compatibility
if out.precision == 'double' and precision == 'single':
raise ValueError("cannot cast single precision to double")
df = out.delta_f
hlen = len(out)
if f_lower is None:
imin = 0 # pylint:disable=unused-variable
f_lower = sample_frequencies[0]
start_index = 0
else:
if f_lower >= sample_frequencies.max():
raise ValueError("f_lower is > than the maximum sample frequency")
if f_lower < sample_frequencies.min():
raise ValueError("f_lower is < than the minimum sample frequency")
imin = int(numpy.searchsorted(sample_frequencies, f_lower,
side='right')) - 1 # pylint:disable=unused-variable
start_index = int(numpy.ceil(f_lower/df))
if start_index >= hlen:
raise ValueError('requested f_lower >= largest frequency in out')
# interpolate the amplitude and the phase
if interpolation == "inline_linear":
# Call the scheme-dependent function
inline_linear_interp(amp, phase, sample_frequencies, out,
df, f_lower, imin, start_index)
else:
# use scipy for fancier interpolation
sample_frequencies = numpy.array(sample_frequencies)
amp = numpy.array(amp)
phase = numpy.array(phase)
outfreq = out.sample_frequencies.numpy()
amp_interp = interpolate.interp1d(sample_frequencies, amp,
kind=interpolation,
bounds_error=False,
fill_value=0.,
assume_sorted=True)
phase_interp = interpolate.interp1d(sample_frequencies, phase,
kind=interpolation,
bounds_error=False,
fill_value=0.,
assume_sorted=True)
A = amp_interp(outfreq)
phi = phase_interp(outfreq)
out.data[:] = A*numpy.cos(phi) + (1j)*A*numpy.sin(phi)
return out | [
"def",
"fd_decompress",
"(",
"amp",
",",
"phase",
",",
"sample_frequencies",
",",
"out",
"=",
"None",
",",
"df",
"=",
"None",
",",
"f_lower",
"=",
"None",
",",
"interpolation",
"=",
"'inline_linear'",
")",
":",
"precision",
"=",
"_precision_map",
"[",
"sam... | Decompresses an FD waveform using the given amplitude, phase, and the
frequencies at which they are sampled at.
Parameters
----------
amp : array
The amplitude of the waveform at the sample frequencies.
phase : array
The phase of the waveform at the sample frequencies.
sample_frequencies : array
The frequency (in Hz) of the waveform at the sample frequencies.
out : {None, FrequencySeries}
The output array to save the decompressed waveform to. If this contains
slots for frequencies > the maximum frequency in sample_frequencies,
the rest of the values are zeroed. If not provided, must provide a df.
df : {None, float}
The frequency step to use for the decompressed waveform. Must be
provided if out is None.
f_lower : {None, float}
The frequency to start the decompression at. If None, will use whatever
the lowest frequency is in sample_frequencies. All values at
frequencies less than this will be 0 in the decompressed waveform.
interpolation : {'inline_linear', str}
The interpolation to use for the amplitude and phase. Default is
'inline_linear'. If 'inline_linear' a custom interpolater is used.
Otherwise, ``scipy.interpolate.interp1d`` is used; for other options,
see possible values for that function's ``kind`` argument.
Returns
-------
out : FrequencySeries
If out was provided, writes to that array. Otherwise, a new
FrequencySeries with the decompressed waveform. | [
"Decompresses",
"an",
"FD",
"waveform",
"using",
"the",
"given",
"amplitude",
"phase",
"and",
"the",
"frequencies",
"at",
"which",
"they",
"are",
"sampled",
"at",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/compress.py#L369-L462 |
227,856 | gwastro/pycbc | pycbc/waveform/compress.py | CompressedWaveform.decompress | def decompress(self, out=None, df=None, f_lower=None, interpolation=None):
"""Decompress self.
Parameters
----------
out : {None, FrequencySeries}
Write the decompressed waveform to the given frequency series. The
decompressed waveform will have the same `delta_f` as `out`.
Either this or `df` must be provided.
df : {None, float}
Decompress the waveform such that its `delta_f` has the given
value. Either this or `out` must be provided.
f_lower : {None, float}
The starting frequency at which to decompress the waveform. Cannot
be less than the minimum frequency in `sample_points`. If `None`
provided, will default to the minimum frequency in `sample_points`.
interpolation : {None, str}
The interpolation to use for decompressing the waveform. If `None`
provided, will default to `self.interpolation`.
Returns
-------
FrequencySeries
The decompressed waveform.
"""
if f_lower is None:
# use the minimum of the samlpe points
f_lower = self.sample_points.min()
if interpolation is None:
interpolation = self.interpolation
return fd_decompress(self.amplitude, self.phase, self.sample_points,
out=out, df=df, f_lower=f_lower,
interpolation=interpolation) | python | def decompress(self, out=None, df=None, f_lower=None, interpolation=None):
if f_lower is None:
# use the minimum of the samlpe points
f_lower = self.sample_points.min()
if interpolation is None:
interpolation = self.interpolation
return fd_decompress(self.amplitude, self.phase, self.sample_points,
out=out, df=df, f_lower=f_lower,
interpolation=interpolation) | [
"def",
"decompress",
"(",
"self",
",",
"out",
"=",
"None",
",",
"df",
"=",
"None",
",",
"f_lower",
"=",
"None",
",",
"interpolation",
"=",
"None",
")",
":",
"if",
"f_lower",
"is",
"None",
":",
"# use the minimum of the samlpe points",
"f_lower",
"=",
"self... | Decompress self.
Parameters
----------
out : {None, FrequencySeries}
Write the decompressed waveform to the given frequency series. The
decompressed waveform will have the same `delta_f` as `out`.
Either this or `df` must be provided.
df : {None, float}
Decompress the waveform such that its `delta_f` has the given
value. Either this or `out` must be provided.
f_lower : {None, float}
The starting frequency at which to decompress the waveform. Cannot
be less than the minimum frequency in `sample_points`. If `None`
provided, will default to the minimum frequency in `sample_points`.
interpolation : {None, str}
The interpolation to use for decompressing the waveform. If `None`
provided, will default to `self.interpolation`.
Returns
-------
FrequencySeries
The decompressed waveform. | [
"Decompress",
"self",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/compress.py#L610-L642 |
227,857 | gwastro/pycbc | pycbc/waveform/compress.py | CompressedWaveform.write_to_hdf | def write_to_hdf(self, fp, template_hash, root=None, precision=None):
"""Write the compressed waveform to the given hdf file handler.
The waveform is written to:
`fp['[{root}/]compressed_waveforms/{template_hash}/{param}']`,
where `param` is the `sample_points`, `amplitude`, and `phase`. The
`interpolation`, `tolerance`, `mismatch` and `precision` are saved
to the group's attributes.
Parameters
----------
fp : h5py.File
An open hdf file to write the compressed waveform to.
template_hash : {hash, int, str}
A hash, int, or string to map the template to the waveform.
root : {None, str}
Put the `compressed_waveforms` group in the given directory in the
hdf file. If `None`, `compressed_waveforms` will be the root
directory.
precision : {None, str}
Cast the saved parameters to the given precision before saving. If
None provided, will use whatever their current precision is. This
will raise an error if the parameters have single precision but the
requested precision is double.
"""
if root is None:
root = ''
else:
root = '%s/'%(root)
if precision is None:
precision = self.precision
elif precision == 'double' and self.precision == 'single':
raise ValueError("cannot cast single precision to double")
outdtype = _real_dtypes[precision]
group = '%scompressed_waveforms/%s' %(root, str(template_hash))
for param in ['amplitude', 'phase', 'sample_points']:
fp['%s/%s' %(group, param)] = self._get(param).astype(outdtype)
fp_group = fp[group]
fp_group.attrs['mismatch'] = self.mismatch
fp_group.attrs['interpolation'] = self.interpolation
fp_group.attrs['tolerance'] = self.tolerance
fp_group.attrs['precision'] = precision | python | def write_to_hdf(self, fp, template_hash, root=None, precision=None):
if root is None:
root = ''
else:
root = '%s/'%(root)
if precision is None:
precision = self.precision
elif precision == 'double' and self.precision == 'single':
raise ValueError("cannot cast single precision to double")
outdtype = _real_dtypes[precision]
group = '%scompressed_waveforms/%s' %(root, str(template_hash))
for param in ['amplitude', 'phase', 'sample_points']:
fp['%s/%s' %(group, param)] = self._get(param).astype(outdtype)
fp_group = fp[group]
fp_group.attrs['mismatch'] = self.mismatch
fp_group.attrs['interpolation'] = self.interpolation
fp_group.attrs['tolerance'] = self.tolerance
fp_group.attrs['precision'] = precision | [
"def",
"write_to_hdf",
"(",
"self",
",",
"fp",
",",
"template_hash",
",",
"root",
"=",
"None",
",",
"precision",
"=",
"None",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"''",
"else",
":",
"root",
"=",
"'%s/'",
"%",
"(",
"root",
")",
... | Write the compressed waveform to the given hdf file handler.
The waveform is written to:
`fp['[{root}/]compressed_waveforms/{template_hash}/{param}']`,
where `param` is the `sample_points`, `amplitude`, and `phase`. The
`interpolation`, `tolerance`, `mismatch` and `precision` are saved
to the group's attributes.
Parameters
----------
fp : h5py.File
An open hdf file to write the compressed waveform to.
template_hash : {hash, int, str}
A hash, int, or string to map the template to the waveform.
root : {None, str}
Put the `compressed_waveforms` group in the given directory in the
hdf file. If `None`, `compressed_waveforms` will be the root
directory.
precision : {None, str}
Cast the saved parameters to the given precision before saving. If
None provided, will use whatever their current precision is. This
will raise an error if the parameters have single precision but the
requested precision is double. | [
"Write",
"the",
"compressed",
"waveform",
"to",
"the",
"given",
"hdf",
"file",
"handler",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/compress.py#L644-L685 |
227,858 | gwastro/pycbc | pycbc/waveform/compress.py | CompressedWaveform.from_hdf | def from_hdf(cls, fp, template_hash, root=None, load_to_memory=True,
load_now=False):
"""Load a compressed waveform from the given hdf file handler.
The waveform is retrieved from:
`fp['[{root}/]compressed_waveforms/{template_hash}/{param}']`,
where `param` is the `sample_points`, `amplitude`, and `phase`.
Parameters
----------
fp : h5py.File
An open hdf file to write the compressed waveform to.
template_hash : {hash, int, str}
The id of the waveform.
root : {None, str}
Retrieve the `compressed_waveforms` group from the given string.
If `None`, `compressed_waveforms` will be assumed to be in the
top level.
load_to_memory : {True, bool}
Set the `load_to_memory` attribute to the given value in the
returned instance.
load_now : {False, bool}
Immediately load the `sample_points`/`amplitude`/`phase` to memory.
Returns
-------
CompressedWaveform
An instance of this class with parameters loaded from the hdf file.
"""
if root is None:
root = ''
else:
root = '%s/'%(root)
group = '%scompressed_waveforms/%s' %(root, str(template_hash))
fp_group = fp[group]
sample_points = fp_group['sample_points']
amp = fp_group['amplitude']
phase = fp_group['phase']
if load_now:
sample_points = sample_points[:]
amp = amp[:]
phase = phase[:]
return cls(sample_points, amp, phase,
interpolation=fp_group.attrs['interpolation'],
tolerance=fp_group.attrs['tolerance'],
mismatch=fp_group.attrs['mismatch'],
precision=fp_group.attrs['precision'],
load_to_memory=load_to_memory) | python | def from_hdf(cls, fp, template_hash, root=None, load_to_memory=True,
load_now=False):
if root is None:
root = ''
else:
root = '%s/'%(root)
group = '%scompressed_waveforms/%s' %(root, str(template_hash))
fp_group = fp[group]
sample_points = fp_group['sample_points']
amp = fp_group['amplitude']
phase = fp_group['phase']
if load_now:
sample_points = sample_points[:]
amp = amp[:]
phase = phase[:]
return cls(sample_points, amp, phase,
interpolation=fp_group.attrs['interpolation'],
tolerance=fp_group.attrs['tolerance'],
mismatch=fp_group.attrs['mismatch'],
precision=fp_group.attrs['precision'],
load_to_memory=load_to_memory) | [
"def",
"from_hdf",
"(",
"cls",
",",
"fp",
",",
"template_hash",
",",
"root",
"=",
"None",
",",
"load_to_memory",
"=",
"True",
",",
"load_now",
"=",
"False",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"''",
"else",
":",
"root",
"=",
"'%... | Load a compressed waveform from the given hdf file handler.
The waveform is retrieved from:
`fp['[{root}/]compressed_waveforms/{template_hash}/{param}']`,
where `param` is the `sample_points`, `amplitude`, and `phase`.
Parameters
----------
fp : h5py.File
An open hdf file to write the compressed waveform to.
template_hash : {hash, int, str}
The id of the waveform.
root : {None, str}
Retrieve the `compressed_waveforms` group from the given string.
If `None`, `compressed_waveforms` will be assumed to be in the
top level.
load_to_memory : {True, bool}
Set the `load_to_memory` attribute to the given value in the
returned instance.
load_now : {False, bool}
Immediately load the `sample_points`/`amplitude`/`phase` to memory.
Returns
-------
CompressedWaveform
An instance of this class with parameters loaded from the hdf file. | [
"Load",
"a",
"compressed",
"waveform",
"from",
"the",
"given",
"hdf",
"file",
"handler",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/compress.py#L688-L736 |
227,859 | gwastro/pycbc | pycbc/vetoes/autochisq.py | SingleDetAutoChisq.values | def values(self, sn, indices, template, psd, norm, stilde=None,
low_frequency_cutoff=None, high_frequency_cutoff=None):
"""
Calculate the auto-chisq at the specified indices.
Parameters
-----------
sn : Array[complex]
SNR time series of the template for which auto-chisq is being
computed. Provided unnormalized.
indices : Array[int]
List of points at which to calculate auto-chisq
template : Pycbc template object
The template for which we are calculating auto-chisq
psd : Pycbc psd object
The PSD of the data being analysed
norm : float
The normalization factor to apply to sn
stilde : Pycbc data object, needed if using reverse-template
The data being analysed. Only needed if using reverse-template,
otherwise ignored
low_frequency_cutoff : float
The lower frequency to consider in matched-filters
high_frequency_cutoff : float
The upper frequency to consider in matched-filters
"""
if self.do and (len(indices) > 0):
htilde = make_frequency_series(template)
# Check if we need to recompute the autocorrelation
key = (id(template), id(psd))
if key != self._autocor_id:
logging.info("Calculating autocorrelation")
if not self.reverse_template:
Pt, _, P_norm = matched_filter_core(htilde,
htilde, psd=psd,
low_frequency_cutoff=low_frequency_cutoff,
high_frequency_cutoff=high_frequency_cutoff)
Pt = Pt * (1./ Pt[0])
self._autocor = Array(Pt, copy=True)
else:
Pt, _, P_norm = matched_filter_core(htilde.conj(),
htilde, psd=psd,
low_frequency_cutoff=low_frequency_cutoff,
high_frequency_cutoff=high_frequency_cutoff)
# T-reversed template has same norm as forward template
# so we can normalize using that
# FIXME: Here sigmasq has to be cast to a float or the
# code is really slow ... why??
norm_fac = P_norm / float(((template.sigmasq(psd))**0.5))
Pt *= norm_fac
self._autocor = Array(Pt, copy=True)
self._autocor_id = key
logging.info("...Calculating autochisquare")
sn = sn*norm
if self.reverse_template:
assert(stilde is not None)
asn, _, ahnrm = matched_filter_core(htilde.conj(), stilde,
low_frequency_cutoff=low_frequency_cutoff,
high_frequency_cutoff=high_frequency_cutoff,
h_norm=template.sigmasq(psd))
correlation_snr = asn * ahnrm
else:
correlation_snr = sn
achi_list = np.array([])
index_list = np.array(indices)
dof, achi_list, _ = autochisq_from_precomputed(sn, correlation_snr,
self._autocor, index_list, stride=self.stride,
num_points=self.num_points,
oneside=self.one_sided, twophase=self.two_phase,
maxvalued=self.take_maximum_value)
self.dof = dof
return achi_list | python | def values(self, sn, indices, template, psd, norm, stilde=None,
low_frequency_cutoff=None, high_frequency_cutoff=None):
if self.do and (len(indices) > 0):
htilde = make_frequency_series(template)
# Check if we need to recompute the autocorrelation
key = (id(template), id(psd))
if key != self._autocor_id:
logging.info("Calculating autocorrelation")
if not self.reverse_template:
Pt, _, P_norm = matched_filter_core(htilde,
htilde, psd=psd,
low_frequency_cutoff=low_frequency_cutoff,
high_frequency_cutoff=high_frequency_cutoff)
Pt = Pt * (1./ Pt[0])
self._autocor = Array(Pt, copy=True)
else:
Pt, _, P_norm = matched_filter_core(htilde.conj(),
htilde, psd=psd,
low_frequency_cutoff=low_frequency_cutoff,
high_frequency_cutoff=high_frequency_cutoff)
# T-reversed template has same norm as forward template
# so we can normalize using that
# FIXME: Here sigmasq has to be cast to a float or the
# code is really slow ... why??
norm_fac = P_norm / float(((template.sigmasq(psd))**0.5))
Pt *= norm_fac
self._autocor = Array(Pt, copy=True)
self._autocor_id = key
logging.info("...Calculating autochisquare")
sn = sn*norm
if self.reverse_template:
assert(stilde is not None)
asn, _, ahnrm = matched_filter_core(htilde.conj(), stilde,
low_frequency_cutoff=low_frequency_cutoff,
high_frequency_cutoff=high_frequency_cutoff,
h_norm=template.sigmasq(psd))
correlation_snr = asn * ahnrm
else:
correlation_snr = sn
achi_list = np.array([])
index_list = np.array(indices)
dof, achi_list, _ = autochisq_from_precomputed(sn, correlation_snr,
self._autocor, index_list, stride=self.stride,
num_points=self.num_points,
oneside=self.one_sided, twophase=self.two_phase,
maxvalued=self.take_maximum_value)
self.dof = dof
return achi_list | [
"def",
"values",
"(",
"self",
",",
"sn",
",",
"indices",
",",
"template",
",",
"psd",
",",
"norm",
",",
"stilde",
"=",
"None",
",",
"low_frequency_cutoff",
"=",
"None",
",",
"high_frequency_cutoff",
"=",
"None",
")",
":",
"if",
"self",
".",
"do",
"and"... | Calculate the auto-chisq at the specified indices.
Parameters
-----------
sn : Array[complex]
SNR time series of the template for which auto-chisq is being
computed. Provided unnormalized.
indices : Array[int]
List of points at which to calculate auto-chisq
template : Pycbc template object
The template for which we are calculating auto-chisq
psd : Pycbc psd object
The PSD of the data being analysed
norm : float
The normalization factor to apply to sn
stilde : Pycbc data object, needed if using reverse-template
The data being analysed. Only needed if using reverse-template,
otherwise ignored
low_frequency_cutoff : float
The lower frequency to consider in matched-filters
high_frequency_cutoff : float
The upper frequency to consider in matched-filters | [
"Calculate",
"the",
"auto",
"-",
"chisq",
"at",
"the",
"specified",
"indices",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/vetoes/autochisq.py#L201-L277 |
227,860 | gwastro/pycbc | pycbc/distributions/bounded.py | get_param_bounds_from_config | def get_param_bounds_from_config(cp, section, tag, param):
"""Gets bounds for the given parameter from a section in a config file.
Minimum and maximum values for bounds are specified by adding
`min-{param}` and `max-{param}` options, where `{param}` is the name of
the parameter. The types of boundary (open, closed, or reflected) to create
may also be specified by adding options `btype-min-{param}` and
`btype-max-{param}`. Cyclic conditions can be adding option
`cyclic-{param}`. If no `btype` arguments are provided, the
left bound will be closed and the right open.
For example, the following will create right-open bounds for parameter
`foo`:
.. code-block:: ini
[{section}-{tag}]
min-foo = -1
max-foo = 1
This would make the boundaries cyclic:
.. code-block:: ini
[{section}-{tag}]
min-foo = -1
max-foo = 1
cyclic-foo =
For more details on boundary types and their meaning, see
`boundaries.Bounds`.
If the parameter is not found in the section will just return None (in
this case, all `btype` and `cyclic` arguments are ignored for that
parameter). If bounds are specified, both a minimum and maximum must be
provided, else a Value or Type Error will be raised.
Parameters
----------
cp : ConfigParser instance
The config file.
section : str
The name of the section.
tag : str
Any tag in the section name. The full section name searched for in
the config file is `{section}(-{tag})`.
param : str
The name of the parameter to retrieve bounds for.
Returns
-------
bounds : {Bounds instance | None}
If bounds were provided, a `boundaries.Bounds` instance
representing the bounds. Otherwise, `None`.
"""
try:
minbnd = float(cp.get_opt_tag(section, 'min-'+param, tag))
except Error:
minbnd = None
try:
maxbnd = float(cp.get_opt_tag(section, 'max-'+param, tag))
except Error:
maxbnd = None
if minbnd is None and maxbnd is None:
bnds = None
elif minbnd is None or maxbnd is None:
raise ValueError("if specifying bounds for %s, " %(param) +
"you must provide both a minimum and a maximum")
else:
bndargs = {'min_bound': minbnd, 'max_bound': maxbnd}
# try to get any other conditions, if provided
try:
minbtype = cp.get_opt_tag(section, 'btype-min-{}'.format(param),
tag)
except Error:
minbtype = 'closed'
try:
maxbtype = cp.get_opt_tag(section, 'btype-max-{}'.format(param),
tag)
except Error:
maxbtype = 'open'
bndargs.update({'btype_min': minbtype, 'btype_max': maxbtype})
cyclic = cp.has_option_tag(section, 'cyclic-{}'.format(param), tag)
bndargs.update({'cyclic': cyclic})
bnds = boundaries.Bounds(**bndargs)
return bnds | python | def get_param_bounds_from_config(cp, section, tag, param):
try:
minbnd = float(cp.get_opt_tag(section, 'min-'+param, tag))
except Error:
minbnd = None
try:
maxbnd = float(cp.get_opt_tag(section, 'max-'+param, tag))
except Error:
maxbnd = None
if minbnd is None and maxbnd is None:
bnds = None
elif minbnd is None or maxbnd is None:
raise ValueError("if specifying bounds for %s, " %(param) +
"you must provide both a minimum and a maximum")
else:
bndargs = {'min_bound': minbnd, 'max_bound': maxbnd}
# try to get any other conditions, if provided
try:
minbtype = cp.get_opt_tag(section, 'btype-min-{}'.format(param),
tag)
except Error:
minbtype = 'closed'
try:
maxbtype = cp.get_opt_tag(section, 'btype-max-{}'.format(param),
tag)
except Error:
maxbtype = 'open'
bndargs.update({'btype_min': minbtype, 'btype_max': maxbtype})
cyclic = cp.has_option_tag(section, 'cyclic-{}'.format(param), tag)
bndargs.update({'cyclic': cyclic})
bnds = boundaries.Bounds(**bndargs)
return bnds | [
"def",
"get_param_bounds_from_config",
"(",
"cp",
",",
"section",
",",
"tag",
",",
"param",
")",
":",
"try",
":",
"minbnd",
"=",
"float",
"(",
"cp",
".",
"get_opt_tag",
"(",
"section",
",",
"'min-'",
"+",
"param",
",",
"tag",
")",
")",
"except",
"Error... | Gets bounds for the given parameter from a section in a config file.
Minimum and maximum values for bounds are specified by adding
`min-{param}` and `max-{param}` options, where `{param}` is the name of
the parameter. The types of boundary (open, closed, or reflected) to create
may also be specified by adding options `btype-min-{param}` and
`btype-max-{param}`. Cyclic conditions can be adding option
`cyclic-{param}`. If no `btype` arguments are provided, the
left bound will be closed and the right open.
For example, the following will create right-open bounds for parameter
`foo`:
.. code-block:: ini
[{section}-{tag}]
min-foo = -1
max-foo = 1
This would make the boundaries cyclic:
.. code-block:: ini
[{section}-{tag}]
min-foo = -1
max-foo = 1
cyclic-foo =
For more details on boundary types and their meaning, see
`boundaries.Bounds`.
If the parameter is not found in the section will just return None (in
this case, all `btype` and `cyclic` arguments are ignored for that
parameter). If bounds are specified, both a minimum and maximum must be
provided, else a Value or Type Error will be raised.
Parameters
----------
cp : ConfigParser instance
The config file.
section : str
The name of the section.
tag : str
Any tag in the section name. The full section name searched for in
the config file is `{section}(-{tag})`.
param : str
The name of the parameter to retrieve bounds for.
Returns
-------
bounds : {Bounds instance | None}
If bounds were provided, a `boundaries.Bounds` instance
representing the bounds. Otherwise, `None`. | [
"Gets",
"bounds",
"for",
"the",
"given",
"parameter",
"from",
"a",
"section",
"in",
"a",
"config",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/distributions/bounded.py#L30-L115 |
227,861 | gwastro/pycbc | pycbc/fft/mkl.py | check_status | def check_status(status):
""" Check the status of a mkl functions and raise a python exeption if
there is an error.
"""
if status:
msg = lib.DftiErrorMessage(status)
msg = ctypes.c_char_p(msg).value
raise RuntimeError(msg) | python | def check_status(status):
if status:
msg = lib.DftiErrorMessage(status)
msg = ctypes.c_char_p(msg).value
raise RuntimeError(msg) | [
"def",
"check_status",
"(",
"status",
")",
":",
"if",
"status",
":",
"msg",
"=",
"lib",
".",
"DftiErrorMessage",
"(",
"status",
")",
"msg",
"=",
"ctypes",
".",
"c_char_p",
"(",
"msg",
")",
".",
"value",
"raise",
"RuntimeError",
"(",
"msg",
")"
] | Check the status of a mkl functions and raise a python exeption if
there is an error. | [
"Check",
"the",
"status",
"of",
"a",
"mkl",
"functions",
"and",
"raise",
"a",
"python",
"exeption",
"if",
"there",
"is",
"an",
"error",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/fft/mkl.py#L67-L74 |
227,862 | gwastro/pycbc | pycbc/workflow/pegasus_workflow.py | Node.add_arg | def add_arg(self, arg):
""" Add an argument
"""
if not isinstance(arg, File):
arg = str(arg)
self._args += [arg] | python | def add_arg(self, arg):
if not isinstance(arg, File):
arg = str(arg)
self._args += [arg] | [
"def",
"add_arg",
"(",
"self",
",",
"arg",
")",
":",
"if",
"not",
"isinstance",
"(",
"arg",
",",
"File",
")",
":",
"arg",
"=",
"str",
"(",
"arg",
")",
"self",
".",
"_args",
"+=",
"[",
"arg",
"]"
] | Add an argument | [
"Add",
"an",
"argument"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/pegasus_workflow.py#L133-L139 |
227,863 | gwastro/pycbc | pycbc/workflow/pegasus_workflow.py | Node.add_opt | def add_opt(self, opt, value=None):
""" Add a option
"""
if value is not None:
if not isinstance(value, File):
value = str(value)
self._options += [opt, value]
else:
self._options += [opt] | python | def add_opt(self, opt, value=None):
if value is not None:
if not isinstance(value, File):
value = str(value)
self._options += [opt, value]
else:
self._options += [opt] | [
"def",
"add_opt",
"(",
"self",
",",
"opt",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"File",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"self",
".",
"_option... | Add a option | [
"Add",
"a",
"option"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/pegasus_workflow.py#L151-L159 |
227,864 | gwastro/pycbc | pycbc/workflow/pegasus_workflow.py | Node._add_output | def _add_output(self, out):
""" Add as destination of output data
"""
self._outputs += [out]
out.node = self
out._set_as_output_of(self) | python | def _add_output(self, out):
self._outputs += [out]
out.node = self
out._set_as_output_of(self) | [
"def",
"_add_output",
"(",
"self",
",",
"out",
")",
":",
"self",
".",
"_outputs",
"+=",
"[",
"out",
"]",
"out",
".",
"node",
"=",
"self",
"out",
".",
"_set_as_output_of",
"(",
"self",
")"
] | Add as destination of output data | [
"Add",
"as",
"destination",
"of",
"output",
"data"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/pegasus_workflow.py#L168-L173 |
227,865 | gwastro/pycbc | pycbc/workflow/pegasus_workflow.py | Node.add_input_opt | def add_input_opt(self, opt, inp):
""" Add an option that determines an input
"""
self.add_opt(opt, inp._dax_repr())
self._add_input(inp) | python | def add_input_opt(self, opt, inp):
self.add_opt(opt, inp._dax_repr())
self._add_input(inp) | [
"def",
"add_input_opt",
"(",
"self",
",",
"opt",
",",
"inp",
")",
":",
"self",
".",
"add_opt",
"(",
"opt",
",",
"inp",
".",
"_dax_repr",
"(",
")",
")",
"self",
".",
"_add_input",
"(",
"inp",
")"
] | Add an option that determines an input | [
"Add",
"an",
"option",
"that",
"determines",
"an",
"input"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/pegasus_workflow.py#L176-L180 |
227,866 | gwastro/pycbc | pycbc/workflow/pegasus_workflow.py | Node.add_output_opt | def add_output_opt(self, opt, out):
""" Add an option that determines an output
"""
self.add_opt(opt, out._dax_repr())
self._add_output(out) | python | def add_output_opt(self, opt, out):
self.add_opt(opt, out._dax_repr())
self._add_output(out) | [
"def",
"add_output_opt",
"(",
"self",
",",
"opt",
",",
"out",
")",
":",
"self",
".",
"add_opt",
"(",
"opt",
",",
"out",
".",
"_dax_repr",
"(",
")",
")",
"self",
".",
"_add_output",
"(",
"out",
")"
] | Add an option that determines an output | [
"Add",
"an",
"option",
"that",
"determines",
"an",
"output"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/pegasus_workflow.py#L182-L186 |
227,867 | gwastro/pycbc | pycbc/workflow/pegasus_workflow.py | Node.add_output_list_opt | def add_output_list_opt(self, opt, outputs):
""" Add an option that determines a list of outputs
"""
self.add_opt(opt)
for out in outputs:
self.add_opt(out)
self._add_output(out) | python | def add_output_list_opt(self, opt, outputs):
self.add_opt(opt)
for out in outputs:
self.add_opt(out)
self._add_output(out) | [
"def",
"add_output_list_opt",
"(",
"self",
",",
"opt",
",",
"outputs",
")",
":",
"self",
".",
"add_opt",
"(",
"opt",
")",
"for",
"out",
"in",
"outputs",
":",
"self",
".",
"add_opt",
"(",
"out",
")",
"self",
".",
"_add_output",
"(",
"out",
")"
] | Add an option that determines a list of outputs | [
"Add",
"an",
"option",
"that",
"determines",
"a",
"list",
"of",
"outputs"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/pegasus_workflow.py#L188-L194 |
227,868 | gwastro/pycbc | pycbc/workflow/pegasus_workflow.py | Node.add_input_list_opt | def add_input_list_opt(self, opt, inputs):
""" Add an option that determines a list of inputs
"""
self.add_opt(opt)
for inp in inputs:
self.add_opt(inp)
self._add_input(inp) | python | def add_input_list_opt(self, opt, inputs):
self.add_opt(opt)
for inp in inputs:
self.add_opt(inp)
self._add_input(inp) | [
"def",
"add_input_list_opt",
"(",
"self",
",",
"opt",
",",
"inputs",
")",
":",
"self",
".",
"add_opt",
"(",
"opt",
")",
"for",
"inp",
"in",
"inputs",
":",
"self",
".",
"add_opt",
"(",
"inp",
")",
"self",
".",
"_add_input",
"(",
"inp",
")"
] | Add an option that determines a list of inputs | [
"Add",
"an",
"option",
"that",
"determines",
"a",
"list",
"of",
"inputs"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/pegasus_workflow.py#L196-L202 |
227,869 | gwastro/pycbc | pycbc/workflow/pegasus_workflow.py | Node.add_list_opt | def add_list_opt(self, opt, values):
""" Add an option with a list of non-file parameters.
"""
self.add_opt(opt)
for val in values:
self.add_opt(val) | python | def add_list_opt(self, opt, values):
self.add_opt(opt)
for val in values:
self.add_opt(val) | [
"def",
"add_list_opt",
"(",
"self",
",",
"opt",
",",
"values",
")",
":",
"self",
".",
"add_opt",
"(",
"opt",
")",
"for",
"val",
"in",
"values",
":",
"self",
".",
"add_opt",
"(",
"val",
")"
] | Add an option with a list of non-file parameters. | [
"Add",
"an",
"option",
"with",
"a",
"list",
"of",
"non",
"-",
"file",
"parameters",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/pegasus_workflow.py#L204-L209 |
227,870 | gwastro/pycbc | pycbc/workflow/pegasus_workflow.py | Node.add_input_arg | def add_input_arg(self, inp):
""" Add an input as an argument
"""
self.add_arg(inp._dax_repr())
self._add_input(inp) | python | def add_input_arg(self, inp):
self.add_arg(inp._dax_repr())
self._add_input(inp) | [
"def",
"add_input_arg",
"(",
"self",
",",
"inp",
")",
":",
"self",
".",
"add_arg",
"(",
"inp",
".",
"_dax_repr",
"(",
")",
")",
"self",
".",
"_add_input",
"(",
"inp",
")"
] | Add an input as an argument | [
"Add",
"an",
"input",
"as",
"an",
"argument"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/pegasus_workflow.py#L211-L215 |
227,871 | gwastro/pycbc | pycbc/workflow/pegasus_workflow.py | Node.add_output_arg | def add_output_arg(self, out):
""" Add an output as an argument
"""
self.add_arg(out._dax_repr())
self._add_output(out) | python | def add_output_arg(self, out):
self.add_arg(out._dax_repr())
self._add_output(out) | [
"def",
"add_output_arg",
"(",
"self",
",",
"out",
")",
":",
"self",
".",
"add_arg",
"(",
"out",
".",
"_dax_repr",
"(",
")",
")",
"self",
".",
"_add_output",
"(",
"out",
")"
] | Add an output as an argument | [
"Add",
"an",
"output",
"as",
"an",
"argument"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/pegasus_workflow.py#L217-L221 |
227,872 | gwastro/pycbc | pycbc/workflow/pegasus_workflow.py | Node.new_output_file_opt | def new_output_file_opt(self, opt, name):
""" Add an option and return a new file handle
"""
fil = File(name)
self.add_output_opt(opt, fil)
return fil | python | def new_output_file_opt(self, opt, name):
fil = File(name)
self.add_output_opt(opt, fil)
return fil | [
"def",
"new_output_file_opt",
"(",
"self",
",",
"opt",
",",
"name",
")",
":",
"fil",
"=",
"File",
"(",
"name",
")",
"self",
".",
"add_output_opt",
"(",
"opt",
",",
"fil",
")",
"return",
"fil"
] | Add an option and return a new file handle | [
"Add",
"an",
"option",
"and",
"return",
"a",
"new",
"file",
"handle"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/pegasus_workflow.py#L223-L228 |
227,873 | gwastro/pycbc | pycbc/workflow/pegasus_workflow.py | Node.add_profile | def add_profile(self, namespace, key, value, force=False):
""" Add profile information to this node at the DAX level
"""
try:
entry = dax.Profile(namespace, key, value)
self._dax_node.addProfile(entry)
except dax.DuplicateError:
if force:
# Replace with the new key
self._dax_node.removeProfile(entry)
self._dax_node.addProfile(entry) | python | def add_profile(self, namespace, key, value, force=False):
try:
entry = dax.Profile(namespace, key, value)
self._dax_node.addProfile(entry)
except dax.DuplicateError:
if force:
# Replace with the new key
self._dax_node.removeProfile(entry)
self._dax_node.addProfile(entry) | [
"def",
"add_profile",
"(",
"self",
",",
"namespace",
",",
"key",
",",
"value",
",",
"force",
"=",
"False",
")",
":",
"try",
":",
"entry",
"=",
"dax",
".",
"Profile",
"(",
"namespace",
",",
"key",
",",
"value",
")",
"self",
".",
"_dax_node",
".",
"a... | Add profile information to this node at the DAX level | [
"Add",
"profile",
"information",
"to",
"this",
"node",
"at",
"the",
"DAX",
"level"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/pegasus_workflow.py#L231-L241 |
227,874 | gwastro/pycbc | pycbc/workflow/pegasus_workflow.py | Workflow.add_workflow | def add_workflow(self, workflow):
""" Add a sub-workflow to this workflow
This function adds a sub-workflow of Workflow class to this workflow.
Parent child relationships are determined by data dependencies
Parameters
----------
workflow : Workflow instance
The sub-workflow to add to this one
"""
workflow.in_workflow = self
self.sub_workflows += [workflow]
node = workflow.as_job
self._adag.addJob(node)
node.file.PFN(os.path.join(os.getcwd(), node.file.name), site='local')
self._adag.addFile(node.file)
for inp in self._external_workflow_inputs:
workflow._make_root_dependency(inp.node)
return self | python | def add_workflow(self, workflow):
workflow.in_workflow = self
self.sub_workflows += [workflow]
node = workflow.as_job
self._adag.addJob(node)
node.file.PFN(os.path.join(os.getcwd(), node.file.name), site='local')
self._adag.addFile(node.file)
for inp in self._external_workflow_inputs:
workflow._make_root_dependency(inp.node)
return self | [
"def",
"add_workflow",
"(",
"self",
",",
"workflow",
")",
":",
"workflow",
".",
"in_workflow",
"=",
"self",
"self",
".",
"sub_workflows",
"+=",
"[",
"workflow",
"]",
"node",
"=",
"workflow",
".",
"as_job",
"self",
".",
"_adag",
".",
"addJob",
"(",
"node"... | Add a sub-workflow to this workflow
This function adds a sub-workflow of Workflow class to this workflow.
Parent child relationships are determined by data dependencies
Parameters
----------
workflow : Workflow instance
The sub-workflow to add to this one | [
"Add",
"a",
"sub",
"-",
"workflow",
"to",
"this",
"workflow"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/pegasus_workflow.py#L287-L310 |
227,875 | gwastro/pycbc | pycbc/workflow/pegasus_workflow.py | Workflow.add_node | def add_node(self, node):
""" Add a node to this workflow
This function adds nodes to the workflow. It also determines
parent/child relations from the DataStorage inputs to this job.
Parameters
----------
node : pycbc.workflow.pegasus_workflow.Node
A node that should be executed as part of this workflow.
"""
node._finalize()
node.in_workflow = self
self._adag.addJob(node._dax_node)
# Determine the parent child relationships based on the inputs that
# this node requires.
added_nodes = []
for inp in node._inputs:
if inp.node is not None and inp.node.in_workflow == self:
if inp.node not in added_nodes:
parent = inp.node._dax_node
child = node._dax_node
dep = dax.Dependency(parent=parent, child=child)
self._adag.addDependency(dep)
added_nodes.append(inp.node)
elif inp.node is not None and not inp.node.in_workflow:
raise ValueError('Parents of this node must be added to the '
'workflow first.')
elif inp.node is None and not inp.workflow_input:
self._inputs += [inp]
inp.workflow_input = True
elif inp.node is not None and inp.node.in_workflow != self and inp not in self._inputs:
self._inputs += [inp]
self._external_workflow_inputs += [inp]
# Record the outputs that this node generates
self._outputs += node._outputs
# Record the executable that this node uses
if not node.executable.in_workflow:
node.executable.in_workflow = True
self._executables += [node.executable]
return self | python | def add_node(self, node):
node._finalize()
node.in_workflow = self
self._adag.addJob(node._dax_node)
# Determine the parent child relationships based on the inputs that
# this node requires.
added_nodes = []
for inp in node._inputs:
if inp.node is not None and inp.node.in_workflow == self:
if inp.node not in added_nodes:
parent = inp.node._dax_node
child = node._dax_node
dep = dax.Dependency(parent=parent, child=child)
self._adag.addDependency(dep)
added_nodes.append(inp.node)
elif inp.node is not None and not inp.node.in_workflow:
raise ValueError('Parents of this node must be added to the '
'workflow first.')
elif inp.node is None and not inp.workflow_input:
self._inputs += [inp]
inp.workflow_input = True
elif inp.node is not None and inp.node.in_workflow != self and inp not in self._inputs:
self._inputs += [inp]
self._external_workflow_inputs += [inp]
# Record the outputs that this node generates
self._outputs += node._outputs
# Record the executable that this node uses
if not node.executable.in_workflow:
node.executable.in_workflow = True
self._executables += [node.executable]
return self | [
"def",
"add_node",
"(",
"self",
",",
"node",
")",
":",
"node",
".",
"_finalize",
"(",
")",
"node",
".",
"in_workflow",
"=",
"self",
"self",
".",
"_adag",
".",
"addJob",
"(",
"node",
".",
"_dax_node",
")",
"# Determine the parent child relationships based on th... | Add a node to this workflow
This function adds nodes to the workflow. It also determines
parent/child relations from the DataStorage inputs to this job.
Parameters
----------
node : pycbc.workflow.pegasus_workflow.Node
A node that should be executed as part of this workflow. | [
"Add",
"a",
"node",
"to",
"this",
"workflow"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/pegasus_workflow.py#L313-L361 |
227,876 | gwastro/pycbc | pycbc/workflow/pegasus_workflow.py | Workflow.save | def save(self, filename=None, tc=None):
""" Write this workflow to DAX file
"""
if filename is None:
filename = self.filename
for sub in self.sub_workflows:
sub.save()
# FIXME this is ugly as pegasus 4.9.0 does not support the full
# transformation catalog in the DAX. I have asked Karan to fix this so
# that executables and containers can be specified in the DAX itself.
# Karan says that XML is going away in Pegasus 5.x and so this code
# will need to be re-written anyway.
#
# the transformation catalog is written in the same directory as the
# DAX. pycbc_submit_dax needs to know this so that the right
# transformation catalog is used when the DAX is planned.
if tc is None:
tc = '{}.tc.txt'.format(filename)
p = os.path.dirname(tc)
f = os.path.basename(tc)
if not p:
p = '.'
tc = TransformationCatalog(p, f)
for e in self._adag.executables.copy():
tc.add(e)
try:
tc.add_container(e.container)
except:
pass
self._adag.removeExecutable(e)
f = open(filename, "w")
self._adag.writeXML(f)
tc.write() | python | def save(self, filename=None, tc=None):
if filename is None:
filename = self.filename
for sub in self.sub_workflows:
sub.save()
# FIXME this is ugly as pegasus 4.9.0 does not support the full
# transformation catalog in the DAX. I have asked Karan to fix this so
# that executables and containers can be specified in the DAX itself.
# Karan says that XML is going away in Pegasus 5.x and so this code
# will need to be re-written anyway.
#
# the transformation catalog is written in the same directory as the
# DAX. pycbc_submit_dax needs to know this so that the right
# transformation catalog is used when the DAX is planned.
if tc is None:
tc = '{}.tc.txt'.format(filename)
p = os.path.dirname(tc)
f = os.path.basename(tc)
if not p:
p = '.'
tc = TransformationCatalog(p, f)
for e in self._adag.executables.copy():
tc.add(e)
try:
tc.add_container(e.container)
except:
pass
self._adag.removeExecutable(e)
f = open(filename, "w")
self._adag.writeXML(f)
tc.write() | [
"def",
"save",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"tc",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"self",
".",
"filename",
"for",
"sub",
"in",
"self",
".",
"sub_workflows",
":",
"sub",
".",
"save",
"(... | Write this workflow to DAX file | [
"Write",
"this",
"workflow",
"to",
"DAX",
"file"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/pegasus_workflow.py#L372-L409 |
227,877 | gwastro/pycbc | pycbc/workflow/pegasus_workflow.py | File.has_pfn | def has_pfn(self, url, site=None):
""" Wrapper of the pegasus hasPFN function, that allows it to be called
outside of specific pegasus functions.
"""
curr_pfn = dax.PFN(url, site)
return self.hasPFN(curr_pfn) | python | def has_pfn(self, url, site=None):
curr_pfn = dax.PFN(url, site)
return self.hasPFN(curr_pfn) | [
"def",
"has_pfn",
"(",
"self",
",",
"url",
",",
"site",
"=",
"None",
")",
":",
"curr_pfn",
"=",
"dax",
".",
"PFN",
"(",
"url",
",",
"site",
")",
"return",
"self",
".",
"hasPFN",
"(",
"curr_pfn",
")"
] | Wrapper of the pegasus hasPFN function, that allows it to be called
outside of specific pegasus functions. | [
"Wrapper",
"of",
"the",
"pegasus",
"hasPFN",
"function",
"that",
"allows",
"it",
"to",
"be",
"called",
"outside",
"of",
"specific",
"pegasus",
"functions",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/pegasus_workflow.py#L472-L477 |
227,878 | gwastro/pycbc | pycbc/workflow/pegasus_workflow.py | File.from_path | def from_path(cls, path):
"""Takes a path and returns a File object with the path as the PFN."""
urlparts = urlparse.urlsplit(path)
site = 'nonlocal'
if (urlparts.scheme == '' or urlparts.scheme == 'file'):
if os.path.isfile(urlparts.path):
path = os.path.abspath(urlparts.path)
path = urlparse.urljoin('file:',
urllib.pathname2url(path))
site = 'local'
fil = File(os.path.basename(path))
fil.PFN(path, site)
return fil | python | def from_path(cls, path):
urlparts = urlparse.urlsplit(path)
site = 'nonlocal'
if (urlparts.scheme == '' or urlparts.scheme == 'file'):
if os.path.isfile(urlparts.path):
path = os.path.abspath(urlparts.path)
path = urlparse.urljoin('file:',
urllib.pathname2url(path))
site = 'local'
fil = File(os.path.basename(path))
fil.PFN(path, site)
return fil | [
"def",
"from_path",
"(",
"cls",
",",
"path",
")",
":",
"urlparts",
"=",
"urlparse",
".",
"urlsplit",
"(",
"path",
")",
"site",
"=",
"'nonlocal'",
"if",
"(",
"urlparts",
".",
"scheme",
"==",
"''",
"or",
"urlparts",
".",
"scheme",
"==",
"'file'",
")",
... | Takes a path and returns a File object with the path as the PFN. | [
"Takes",
"a",
"path",
"and",
"returns",
"a",
"File",
"object",
"with",
"the",
"path",
"as",
"the",
"PFN",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/pegasus_workflow.py#L483-L496 |
227,879 | gwastro/pycbc | pycbc/inference/models/__init__.py | read_from_config | def read_from_config(cp, **kwargs):
"""Initializes a model from the given config file.
The section must have a ``name`` argument. The name argument corresponds to
the name of the class to initialize.
Parameters
----------
cp : WorkflowConfigParser
Config file parser to read.
\**kwargs :
All other keyword arguments are passed to the ``from_config`` method
of the class specified by the name argument.
Returns
-------
cls
The initialized model.
"""
# use the name to get the distribution
name = cp.get("model", "name")
return models[name].from_config(cp, **kwargs) | python | def read_from_config(cp, **kwargs):
# use the name to get the distribution
name = cp.get("model", "name")
return models[name].from_config(cp, **kwargs) | [
"def",
"read_from_config",
"(",
"cp",
",",
"*",
"*",
"kwargs",
")",
":",
"# use the name to get the distribution",
"name",
"=",
"cp",
".",
"get",
"(",
"\"model\"",
",",
"\"name\"",
")",
"return",
"models",
"[",
"name",
"]",
".",
"from_config",
"(",
"cp",
"... | Initializes a model from the given config file.
The section must have a ``name`` argument. The name argument corresponds to
the name of the class to initialize.
Parameters
----------
cp : WorkflowConfigParser
Config file parser to read.
\**kwargs :
All other keyword arguments are passed to the ``from_config`` method
of the class specified by the name argument.
Returns
-------
cls
The initialized model. | [
"Initializes",
"a",
"model",
"from",
"the",
"given",
"config",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/__init__.py#L153-L174 |
227,880 | gwastro/pycbc | pycbc/distributions/__init__.py | read_distributions_from_config | def read_distributions_from_config(cp, section="prior"):
"""Returns a list of PyCBC distribution instances for a section in the
given configuration file.
Parameters
----------
cp : WorflowConfigParser
An open config file to read.
section : {"prior", string}
Prefix on section names from which to retrieve the distributions.
Returns
-------
list
A list of the parsed distributions.
"""
dists = []
variable_args = []
for subsection in cp.get_subsections(section):
name = cp.get_opt_tag(section, "name", subsection)
dist = distribs[name].from_config(cp, section, subsection)
if set(dist.params).isdisjoint(variable_args):
dists.append(dist)
variable_args += dist.params
else:
raise ValueError("Same parameter in more than one distribution.")
return dists | python | def read_distributions_from_config(cp, section="prior"):
dists = []
variable_args = []
for subsection in cp.get_subsections(section):
name = cp.get_opt_tag(section, "name", subsection)
dist = distribs[name].from_config(cp, section, subsection)
if set(dist.params).isdisjoint(variable_args):
dists.append(dist)
variable_args += dist.params
else:
raise ValueError("Same parameter in more than one distribution.")
return dists | [
"def",
"read_distributions_from_config",
"(",
"cp",
",",
"section",
"=",
"\"prior\"",
")",
":",
"dists",
"=",
"[",
"]",
"variable_args",
"=",
"[",
"]",
"for",
"subsection",
"in",
"cp",
".",
"get_subsections",
"(",
"section",
")",
":",
"name",
"=",
"cp",
... | Returns a list of PyCBC distribution instances for a section in the
given configuration file.
Parameters
----------
cp : WorflowConfigParser
An open config file to read.
section : {"prior", string}
Prefix on section names from which to retrieve the distributions.
Returns
-------
list
A list of the parsed distributions. | [
"Returns",
"a",
"list",
"of",
"PyCBC",
"distribution",
"instances",
"for",
"a",
"section",
"in",
"the",
"given",
"configuration",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/distributions/__init__.py#L57-L83 |
227,881 | gwastro/pycbc | pycbc/distributions/__init__.py | read_params_from_config | def read_params_from_config(cp, prior_section='prior',
vargs_section='variable_args',
sargs_section='static_args'):
"""Loads static and variable parameters from a configuration file.
Parameters
----------
cp : WorkflowConfigParser
An open config parser to read from.
prior_section : str, optional
Check that priors exist in the given section. Default is 'prior.'
vargs_section : str, optional
The section to get the parameters that will be varied/need priors
defined for them. Default is 'variable_args'.
sargs_section : str, optional
The section to get the parameters that will remain fixed. Default is
'static_args'.
Returns
-------
variable_args : list
The names of the parameters to vary in the PE run.
static_args : dict
Dictionary of names -> values giving the parameters to keep fixed.
"""
# sanity check that each parameter in [variable_args] has a priors section
variable_args = cp.options(vargs_section)
subsections = cp.get_subsections(prior_section)
tags = set([p for tag in subsections for p in tag.split('+')])
missing_prior = set(variable_args) - tags
if any(missing_prior):
raise KeyError("You are missing a priors section in the config file "
"for parameter(s): {}".format(', '.join(missing_prior)))
# get static args
try:
static_args = dict([(key, cp.get_opt_tags(sargs_section, key, []))
for key in cp.options(sargs_section)])
except _ConfigParser.NoSectionError:
static_args = {}
# try converting values to float
for key in static_args:
val = static_args[key]
try:
# the following will raise a ValueError if it cannot be cast to
# float (as we would expect for string arguments)
static_args[key] = float(val)
except ValueError:
# try converting to a list of strings; this function will just
# return val if it does not begin (end) with [ (])
static_args[key] = _convert_liststring_to_list(val)
return variable_args, static_args | python | def read_params_from_config(cp, prior_section='prior',
vargs_section='variable_args',
sargs_section='static_args'):
# sanity check that each parameter in [variable_args] has a priors section
variable_args = cp.options(vargs_section)
subsections = cp.get_subsections(prior_section)
tags = set([p for tag in subsections for p in tag.split('+')])
missing_prior = set(variable_args) - tags
if any(missing_prior):
raise KeyError("You are missing a priors section in the config file "
"for parameter(s): {}".format(', '.join(missing_prior)))
# get static args
try:
static_args = dict([(key, cp.get_opt_tags(sargs_section, key, []))
for key in cp.options(sargs_section)])
except _ConfigParser.NoSectionError:
static_args = {}
# try converting values to float
for key in static_args:
val = static_args[key]
try:
# the following will raise a ValueError if it cannot be cast to
# float (as we would expect for string arguments)
static_args[key] = float(val)
except ValueError:
# try converting to a list of strings; this function will just
# return val if it does not begin (end) with [ (])
static_args[key] = _convert_liststring_to_list(val)
return variable_args, static_args | [
"def",
"read_params_from_config",
"(",
"cp",
",",
"prior_section",
"=",
"'prior'",
",",
"vargs_section",
"=",
"'variable_args'",
",",
"sargs_section",
"=",
"'static_args'",
")",
":",
"# sanity check that each parameter in [variable_args] has a priors section",
"variable_args",
... | Loads static and variable parameters from a configuration file.
Parameters
----------
cp : WorkflowConfigParser
An open config parser to read from.
prior_section : str, optional
Check that priors exist in the given section. Default is 'prior.'
vargs_section : str, optional
The section to get the parameters that will be varied/need priors
defined for them. Default is 'variable_args'.
sargs_section : str, optional
The section to get the parameters that will remain fixed. Default is
'static_args'.
Returns
-------
variable_args : list
The names of the parameters to vary in the PE run.
static_args : dict
Dictionary of names -> values giving the parameters to keep fixed. | [
"Loads",
"static",
"and",
"variable",
"parameters",
"from",
"a",
"configuration",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/distributions/__init__.py#L102-L152 |
227,882 | gwastro/pycbc | pycbc/distributions/__init__.py | read_constraints_from_config | def read_constraints_from_config(cp, transforms=None,
constraint_section='constraint'):
"""Loads parameter constraints from a configuration file.
Parameters
----------
cp : WorkflowConfigParser
An open config parser to read from.
transforms : list, optional
List of transforms to apply to parameters before applying constraints.
constraint_section : str, optional
The section to get the constraints from. Default is 'constraint'.
Returns
-------
list
List of ``Constraint`` objects. Empty if no constraints were provided.
"""
cons = []
for subsection in cp.get_subsections(constraint_section):
name = cp.get_opt_tag(constraint_section, "name", subsection)
constraint_arg = cp.get_opt_tag(
constraint_section, "constraint_arg", subsection)
# get any other keyword arguments
kwargs = {}
section = constraint_section + "-" + subsection
extra_opts = [key for key in cp.options(section)
if key not in ["name", "constraint_arg"]]
for key in extra_opts:
val = cp.get(section, key)
if key == "required_parameters":
val = val.split(_VARARGS_DELIM)
else:
try:
val = float(val)
except ValueError:
pass
kwargs[key] = val
cons.append(constraints.constraints[name](constraint_arg,
transforms=transforms,
**kwargs))
return cons | python | def read_constraints_from_config(cp, transforms=None,
constraint_section='constraint'):
cons = []
for subsection in cp.get_subsections(constraint_section):
name = cp.get_opt_tag(constraint_section, "name", subsection)
constraint_arg = cp.get_opt_tag(
constraint_section, "constraint_arg", subsection)
# get any other keyword arguments
kwargs = {}
section = constraint_section + "-" + subsection
extra_opts = [key for key in cp.options(section)
if key not in ["name", "constraint_arg"]]
for key in extra_opts:
val = cp.get(section, key)
if key == "required_parameters":
val = val.split(_VARARGS_DELIM)
else:
try:
val = float(val)
except ValueError:
pass
kwargs[key] = val
cons.append(constraints.constraints[name](constraint_arg,
transforms=transforms,
**kwargs))
return cons | [
"def",
"read_constraints_from_config",
"(",
"cp",
",",
"transforms",
"=",
"None",
",",
"constraint_section",
"=",
"'constraint'",
")",
":",
"cons",
"=",
"[",
"]",
"for",
"subsection",
"in",
"cp",
".",
"get_subsections",
"(",
"constraint_section",
")",
":",
"na... | Loads parameter constraints from a configuration file.
Parameters
----------
cp : WorkflowConfigParser
An open config parser to read from.
transforms : list, optional
List of transforms to apply to parameters before applying constraints.
constraint_section : str, optional
The section to get the constraints from. Default is 'constraint'.
Returns
-------
list
List of ``Constraint`` objects. Empty if no constraints were provided. | [
"Loads",
"parameter",
"constraints",
"from",
"a",
"configuration",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/distributions/__init__.py#L155-L197 |
227,883 | gwastro/pycbc | pycbc/inject/injfilterrejector.py | insert_injfilterrejector_option_group | def insert_injfilterrejector_option_group(parser):
"""Add options for injfilterrejector to executable."""
injfilterrejector_group = \
parser.add_argument_group(_injfilterrejector_group_help)
curr_arg = "--injection-filter-rejector-chirp-time-window"
injfilterrejector_group.add_argument(curr_arg, type=float, default=None,
help=_injfilterer_cthresh_help)
curr_arg = "--injection-filter-rejector-match-threshold"
injfilterrejector_group.add_argument(curr_arg, type=float, default=None,
help=_injfilterer_mthresh_help)
curr_arg = "--injection-filter-rejector-coarsematch-deltaf"
injfilterrejector_group.add_argument(curr_arg, type=float, default=1.,
help=_injfilterer_deltaf_help)
curr_arg = "--injection-filter-rejector-coarsematch-fmax"
injfilterrejector_group.add_argument(curr_arg, type=float, default=256.,
help=_injfilterer_fmax_help)
curr_arg = "--injection-filter-rejector-seg-buffer"
injfilterrejector_group.add_argument(curr_arg, type=int, default=10,
help=_injfilterer_buffer_help)
curr_arg = "--injection-filter-rejector-f-lower"
injfilterrejector_group.add_argument(curr_arg, type=int, default=None,
help=_injfilterer_flower_help) | python | def insert_injfilterrejector_option_group(parser):
injfilterrejector_group = \
parser.add_argument_group(_injfilterrejector_group_help)
curr_arg = "--injection-filter-rejector-chirp-time-window"
injfilterrejector_group.add_argument(curr_arg, type=float, default=None,
help=_injfilterer_cthresh_help)
curr_arg = "--injection-filter-rejector-match-threshold"
injfilterrejector_group.add_argument(curr_arg, type=float, default=None,
help=_injfilterer_mthresh_help)
curr_arg = "--injection-filter-rejector-coarsematch-deltaf"
injfilterrejector_group.add_argument(curr_arg, type=float, default=1.,
help=_injfilterer_deltaf_help)
curr_arg = "--injection-filter-rejector-coarsematch-fmax"
injfilterrejector_group.add_argument(curr_arg, type=float, default=256.,
help=_injfilterer_fmax_help)
curr_arg = "--injection-filter-rejector-seg-buffer"
injfilterrejector_group.add_argument(curr_arg, type=int, default=10,
help=_injfilterer_buffer_help)
curr_arg = "--injection-filter-rejector-f-lower"
injfilterrejector_group.add_argument(curr_arg, type=int, default=None,
help=_injfilterer_flower_help) | [
"def",
"insert_injfilterrejector_option_group",
"(",
"parser",
")",
":",
"injfilterrejector_group",
"=",
"parser",
".",
"add_argument_group",
"(",
"_injfilterrejector_group_help",
")",
"curr_arg",
"=",
"\"--injection-filter-rejector-chirp-time-window\"",
"injfilterrejector_group",
... | Add options for injfilterrejector to executable. | [
"Add",
"options",
"for",
"injfilterrejector",
"to",
"executable",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inject/injfilterrejector.py#L88-L109 |
227,884 | gwastro/pycbc | pycbc/inject/injfilterrejector.py | InjFilterRejector.from_cli | def from_cli(cls, opt):
"""Create an InjFilterRejector instance from command-line options."""
injection_file = opt.injection_file
chirp_time_window = \
opt.injection_filter_rejector_chirp_time_window
match_threshold = opt.injection_filter_rejector_match_threshold
coarsematch_deltaf = opt.injection_filter_rejector_coarsematch_deltaf
coarsematch_fmax = opt.injection_filter_rejector_coarsematch_fmax
seg_buffer = opt.injection_filter_rejector_seg_buffer
if opt.injection_filter_rejector_f_lower is not None:
f_lower = opt.injection_filter_rejector_f_lower
else:
# NOTE: Uses main low-frequency cutoff as default option. This may
# need some editing if using this in multi_inspiral, which I
# leave for future work, or if this is being used in another
# code which doesn't have --low-frequency-cutoff
f_lower = opt.low_frequency_cutoff
return cls(injection_file, chirp_time_window, match_threshold,
f_lower, coarsematch_deltaf=coarsematch_deltaf,
coarsematch_fmax=coarsematch_fmax,
seg_buffer=seg_buffer) | python | def from_cli(cls, opt):
injection_file = opt.injection_file
chirp_time_window = \
opt.injection_filter_rejector_chirp_time_window
match_threshold = opt.injection_filter_rejector_match_threshold
coarsematch_deltaf = opt.injection_filter_rejector_coarsematch_deltaf
coarsematch_fmax = opt.injection_filter_rejector_coarsematch_fmax
seg_buffer = opt.injection_filter_rejector_seg_buffer
if opt.injection_filter_rejector_f_lower is not None:
f_lower = opt.injection_filter_rejector_f_lower
else:
# NOTE: Uses main low-frequency cutoff as default option. This may
# need some editing if using this in multi_inspiral, which I
# leave for future work, or if this is being used in another
# code which doesn't have --low-frequency-cutoff
f_lower = opt.low_frequency_cutoff
return cls(injection_file, chirp_time_window, match_threshold,
f_lower, coarsematch_deltaf=coarsematch_deltaf,
coarsematch_fmax=coarsematch_fmax,
seg_buffer=seg_buffer) | [
"def",
"from_cli",
"(",
"cls",
",",
"opt",
")",
":",
"injection_file",
"=",
"opt",
".",
"injection_file",
"chirp_time_window",
"=",
"opt",
".",
"injection_filter_rejector_chirp_time_window",
"match_threshold",
"=",
"opt",
".",
"injection_filter_rejector_match_threshold",
... | Create an InjFilterRejector instance from command-line options. | [
"Create",
"an",
"InjFilterRejector",
"instance",
"from",
"command",
"-",
"line",
"options",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inject/injfilterrejector.py#L150-L170 |
227,885 | gwastro/pycbc | pycbc/inject/injfilterrejector.py | InjFilterRejector.generate_short_inj_from_inj | def generate_short_inj_from_inj(self, inj_waveform, simulation_id):
"""Generate and a store a truncated representation of inj_waveform."""
if not self.enabled:
# Do nothing!
return
if simulation_id in self.short_injections:
err_msg = "An injection with simulation id "
err_msg += str(simulation_id)
err_msg += " has already been added. This suggests "
err_msg += "that your injection file contains injections with "
err_msg += "duplicate simulation_ids. This is not allowed."
raise ValueError(err_msg)
curr_length = len(inj_waveform)
new_length = int(nearest_larger_binary_number(curr_length))
# Don't want length less than 1/delta_f
while new_length * inj_waveform.delta_t < 1./self.coarsematch_deltaf:
new_length = new_length * 2
inj_waveform.resize(new_length)
inj_tilde = inj_waveform.to_frequencyseries()
# Dynamic range is important here!
inj_tilde_np = inj_tilde.numpy() * DYN_RANGE_FAC
delta_f = inj_tilde.get_delta_f()
new_freq_len = int(self.coarsematch_fmax / delta_f + 1)
# This shouldn't be a problem if injections are generated at
# 16384 Hz ... It is only a problem of injection sample rate
# gives a lower Nyquist than the trunc_f_max. If this error is
# ever raised one could consider zero-padding the injection.
assert(new_freq_len <= len(inj_tilde))
df_ratio = int(self.coarsematch_deltaf/delta_f)
inj_tilde_np = inj_tilde_np[:new_freq_len:df_ratio]
new_inj = FrequencySeries(inj_tilde_np, dtype=np.complex64,
delta_f=self.coarsematch_deltaf)
self.short_injections[simulation_id] = new_inj | python | def generate_short_inj_from_inj(self, inj_waveform, simulation_id):
if not self.enabled:
# Do nothing!
return
if simulation_id in self.short_injections:
err_msg = "An injection with simulation id "
err_msg += str(simulation_id)
err_msg += " has already been added. This suggests "
err_msg += "that your injection file contains injections with "
err_msg += "duplicate simulation_ids. This is not allowed."
raise ValueError(err_msg)
curr_length = len(inj_waveform)
new_length = int(nearest_larger_binary_number(curr_length))
# Don't want length less than 1/delta_f
while new_length * inj_waveform.delta_t < 1./self.coarsematch_deltaf:
new_length = new_length * 2
inj_waveform.resize(new_length)
inj_tilde = inj_waveform.to_frequencyseries()
# Dynamic range is important here!
inj_tilde_np = inj_tilde.numpy() * DYN_RANGE_FAC
delta_f = inj_tilde.get_delta_f()
new_freq_len = int(self.coarsematch_fmax / delta_f + 1)
# This shouldn't be a problem if injections are generated at
# 16384 Hz ... It is only a problem of injection sample rate
# gives a lower Nyquist than the trunc_f_max. If this error is
# ever raised one could consider zero-padding the injection.
assert(new_freq_len <= len(inj_tilde))
df_ratio = int(self.coarsematch_deltaf/delta_f)
inj_tilde_np = inj_tilde_np[:new_freq_len:df_ratio]
new_inj = FrequencySeries(inj_tilde_np, dtype=np.complex64,
delta_f=self.coarsematch_deltaf)
self.short_injections[simulation_id] = new_inj | [
"def",
"generate_short_inj_from_inj",
"(",
"self",
",",
"inj_waveform",
",",
"simulation_id",
")",
":",
"if",
"not",
"self",
".",
"enabled",
":",
"# Do nothing!",
"return",
"if",
"simulation_id",
"in",
"self",
".",
"short_injections",
":",
"err_msg",
"=",
"\"An ... | Generate and a store a truncated representation of inj_waveform. | [
"Generate",
"and",
"a",
"store",
"a",
"truncated",
"representation",
"of",
"inj_waveform",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inject/injfilterrejector.py#L172-L204 |
227,886 | gwastro/pycbc | pycbc/inject/injfilterrejector.py | InjFilterRejector.template_segment_checker | def template_segment_checker(self, bank, t_num, segment, start_time):
"""Test if injections in segment are worth filtering with template.
Using the current template, current segment, and injections within that
segment. Test if the injections and sufficiently "similar" to any of
the injections to justify actually performing a matched-filter call.
Ther are two parts to this test: First we check if the chirp time of
the template is within a provided window of any of the injections. If
not then stop here, it is not worth filtering this template, segment
combination for this injection set. If this check passes we compute a
match between a coarse representation of the template and a coarse
representation of each of the injections. If that match is above a
user-provided value for any of the injections then filtering can
proceed. This is currently only available if using frequency-domain
templates.
Parameters
-----------
FIXME
Returns
--------
FIXME
"""
if not self.enabled:
# If disabled, always filter (ie. return True)
return True
# Get times covered by segment analyze
sample_rate = 2. * (len(segment) - 1) * segment.delta_f
cum_ind = segment.cumulative_index
diff = segment.analyze.stop - segment.analyze.start
seg_start_time = cum_ind / sample_rate + start_time
seg_end_time = (cum_ind + diff) / sample_rate + start_time
# And add buffer
seg_start_time = seg_start_time - self.seg_buffer
seg_end_time = seg_end_time + self.seg_buffer
# Chirp time test
if self.chirp_time_window is not None:
m1 = bank.table[t_num]['mass1']
m2 = bank.table[t_num]['mass2']
tau0_temp, _ = mass1_mass2_to_tau0_tau3(m1, m2, self.f_lower)
for inj in self.injection_params.table:
end_time = inj.geocent_end_time + \
1E-9 * inj.geocent_end_time_ns
if not(seg_start_time <= end_time <= seg_end_time):
continue
tau0_inj, _ = \
mass1_mass2_to_tau0_tau3(inj.mass1, inj.mass2,
self.f_lower)
tau_diff = abs(tau0_temp - tau0_inj)
if tau_diff <= self.chirp_time_window:
break
else:
# Get's here if all injections are outside chirp-time window
return False
# Coarse match test
if self.match_threshold:
if self._short_template_mem is None:
# Set the memory for the short templates
wav_len = 1 + int(self.coarsematch_fmax /
self.coarsematch_deltaf)
self._short_template_mem = zeros(wav_len, dtype=np.complex64)
# Set the current short PSD to red_psd
try:
red_psd = self._short_psd_storage[id(segment.psd)]
except KeyError:
# PSD doesn't exist yet, so make it!
curr_psd = segment.psd.numpy()
step_size = int(self.coarsematch_deltaf / segment.psd.delta_f)
max_idx = int(self.coarsematch_fmax / segment.psd.delta_f) + 1
red_psd_data = curr_psd[:max_idx:step_size]
red_psd = FrequencySeries(red_psd_data, #copy=False,
delta_f=self.coarsematch_deltaf)
self._short_psd_storage[id(curr_psd)] = red_psd
# Set htilde to be the current short template
if not t_num == self._short_template_id:
# Set the memory for the short templates if unset
if self._short_template_mem is None:
wav_len = 1 + int(self.coarsematch_fmax /
self.coarsematch_deltaf)
self._short_template_mem = zeros(wav_len,
dtype=np.complex64)
# Generate short waveform
htilde = bank.generate_with_delta_f_and_max_freq(
t_num, self.coarsematch_fmax, self.coarsematch_deltaf,
low_frequency_cutoff=bank.table[t_num].f_lower,
cached_mem=self._short_template_mem)
self._short_template_id = t_num
self._short_template_wav = htilde
else:
htilde = self._short_template_wav
for inj in self.injection_params.table:
end_time = inj.geocent_end_time + \
1E-9 * inj.geocent_end_time_ns
if not(seg_start_time < end_time < seg_end_time):
continue
curr_inj = self.short_injections[inj.simulation_id]
o, _ = match(htilde, curr_inj, psd=red_psd,
low_frequency_cutoff=self.f_lower)
if o > self.match_threshold:
break
else:
# Get's here if all injections are outside match threshold
return False
return True | python | def template_segment_checker(self, bank, t_num, segment, start_time):
if not self.enabled:
# If disabled, always filter (ie. return True)
return True
# Get times covered by segment analyze
sample_rate = 2. * (len(segment) - 1) * segment.delta_f
cum_ind = segment.cumulative_index
diff = segment.analyze.stop - segment.analyze.start
seg_start_time = cum_ind / sample_rate + start_time
seg_end_time = (cum_ind + diff) / sample_rate + start_time
# And add buffer
seg_start_time = seg_start_time - self.seg_buffer
seg_end_time = seg_end_time + self.seg_buffer
# Chirp time test
if self.chirp_time_window is not None:
m1 = bank.table[t_num]['mass1']
m2 = bank.table[t_num]['mass2']
tau0_temp, _ = mass1_mass2_to_tau0_tau3(m1, m2, self.f_lower)
for inj in self.injection_params.table:
end_time = inj.geocent_end_time + \
1E-9 * inj.geocent_end_time_ns
if not(seg_start_time <= end_time <= seg_end_time):
continue
tau0_inj, _ = \
mass1_mass2_to_tau0_tau3(inj.mass1, inj.mass2,
self.f_lower)
tau_diff = abs(tau0_temp - tau0_inj)
if tau_diff <= self.chirp_time_window:
break
else:
# Get's here if all injections are outside chirp-time window
return False
# Coarse match test
if self.match_threshold:
if self._short_template_mem is None:
# Set the memory for the short templates
wav_len = 1 + int(self.coarsematch_fmax /
self.coarsematch_deltaf)
self._short_template_mem = zeros(wav_len, dtype=np.complex64)
# Set the current short PSD to red_psd
try:
red_psd = self._short_psd_storage[id(segment.psd)]
except KeyError:
# PSD doesn't exist yet, so make it!
curr_psd = segment.psd.numpy()
step_size = int(self.coarsematch_deltaf / segment.psd.delta_f)
max_idx = int(self.coarsematch_fmax / segment.psd.delta_f) + 1
red_psd_data = curr_psd[:max_idx:step_size]
red_psd = FrequencySeries(red_psd_data, #copy=False,
delta_f=self.coarsematch_deltaf)
self._short_psd_storage[id(curr_psd)] = red_psd
# Set htilde to be the current short template
if not t_num == self._short_template_id:
# Set the memory for the short templates if unset
if self._short_template_mem is None:
wav_len = 1 + int(self.coarsematch_fmax /
self.coarsematch_deltaf)
self._short_template_mem = zeros(wav_len,
dtype=np.complex64)
# Generate short waveform
htilde = bank.generate_with_delta_f_and_max_freq(
t_num, self.coarsematch_fmax, self.coarsematch_deltaf,
low_frequency_cutoff=bank.table[t_num].f_lower,
cached_mem=self._short_template_mem)
self._short_template_id = t_num
self._short_template_wav = htilde
else:
htilde = self._short_template_wav
for inj in self.injection_params.table:
end_time = inj.geocent_end_time + \
1E-9 * inj.geocent_end_time_ns
if not(seg_start_time < end_time < seg_end_time):
continue
curr_inj = self.short_injections[inj.simulation_id]
o, _ = match(htilde, curr_inj, psd=red_psd,
low_frequency_cutoff=self.f_lower)
if o > self.match_threshold:
break
else:
# Get's here if all injections are outside match threshold
return False
return True | [
"def",
"template_segment_checker",
"(",
"self",
",",
"bank",
",",
"t_num",
",",
"segment",
",",
"start_time",
")",
":",
"if",
"not",
"self",
".",
"enabled",
":",
"# If disabled, always filter (ie. return True)",
"return",
"True",
"# Get times covered by segment analyze"... | Test if injections in segment are worth filtering with template.
Using the current template, current segment, and injections within that
segment. Test if the injections and sufficiently "similar" to any of
the injections to justify actually performing a matched-filter call.
Ther are two parts to this test: First we check if the chirp time of
the template is within a provided window of any of the injections. If
not then stop here, it is not worth filtering this template, segment
combination for this injection set. If this check passes we compute a
match between a coarse representation of the template and a coarse
representation of each of the injections. If that match is above a
user-provided value for any of the injections then filtering can
proceed. This is currently only available if using frequency-domain
templates.
Parameters
-----------
FIXME
Returns
--------
FIXME | [
"Test",
"if",
"injections",
"in",
"segment",
"are",
"worth",
"filtering",
"with",
"template",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inject/injfilterrejector.py#L206-L317 |
227,887 | gwastro/pycbc | pycbc/events/trigger_fits.py | fit_above_thresh | def fit_above_thresh(distr, vals, thresh=None):
"""
Maximum likelihood fit for the coefficient alpha
Fitting a distribution of discrete values above a given threshold.
Exponential p(x) = alpha exp(-alpha (x-x_t))
Rayleigh p(x) = alpha x exp(-alpha (x**2-x_t**2)/2)
Power p(x) = ((alpha-1)/x_t) (x/x_t)**-alpha
Values below threshold will be discarded.
If no threshold is specified the minimum sample value will be used.
Parameters
----------
distr : {'exponential', 'rayleigh', 'power'}
Name of distribution
vals : sequence of floats
Values to fit
thresh : float
Threshold to apply before fitting; if None, use min(vals)
Returns
-------
alpha : float
Fitted value
sigma_alpha : float
Standard error in fitted value
"""
vals = numpy.array(vals)
if thresh is None:
thresh = min(vals)
else:
vals = vals[vals >= thresh]
alpha = fitalpha_dict[distr](vals, thresh)
return alpha, fitstd_dict[distr](vals, alpha) | python | def fit_above_thresh(distr, vals, thresh=None):
vals = numpy.array(vals)
if thresh is None:
thresh = min(vals)
else:
vals = vals[vals >= thresh]
alpha = fitalpha_dict[distr](vals, thresh)
return alpha, fitstd_dict[distr](vals, alpha) | [
"def",
"fit_above_thresh",
"(",
"distr",
",",
"vals",
",",
"thresh",
"=",
"None",
")",
":",
"vals",
"=",
"numpy",
".",
"array",
"(",
"vals",
")",
"if",
"thresh",
"is",
"None",
":",
"thresh",
"=",
"min",
"(",
"vals",
")",
"else",
":",
"vals",
"=",
... | Maximum likelihood fit for the coefficient alpha
Fitting a distribution of discrete values above a given threshold.
Exponential p(x) = alpha exp(-alpha (x-x_t))
Rayleigh p(x) = alpha x exp(-alpha (x**2-x_t**2)/2)
Power p(x) = ((alpha-1)/x_t) (x/x_t)**-alpha
Values below threshold will be discarded.
If no threshold is specified the minimum sample value will be used.
Parameters
----------
distr : {'exponential', 'rayleigh', 'power'}
Name of distribution
vals : sequence of floats
Values to fit
thresh : float
Threshold to apply before fitting; if None, use min(vals)
Returns
-------
alpha : float
Fitted value
sigma_alpha : float
Standard error in fitted value | [
"Maximum",
"likelihood",
"fit",
"for",
"the",
"coefficient",
"alpha"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/trigger_fits.py#L65-L98 |
227,888 | gwastro/pycbc | pycbc/events/trigger_fits.py | fit_fn | def fit_fn(distr, xvals, alpha, thresh):
"""
The fitted function normalized to 1 above threshold
To normalize to a given total count multiply by the count.
Parameters
----------
xvals : sequence of floats
Values where the function is to be evaluated
alpha : float
The fitted parameter
thresh : float
Threshold value applied to fitted values
Returns
-------
fit : array of floats
Fitted function at the requested xvals
"""
xvals = numpy.array(xvals)
fit = fitfn_dict[distr](xvals, alpha, thresh)
# set fitted values below threshold to 0
numpy.putmask(fit, xvals < thresh, 0.)
return fit | python | def fit_fn(distr, xvals, alpha, thresh):
xvals = numpy.array(xvals)
fit = fitfn_dict[distr](xvals, alpha, thresh)
# set fitted values below threshold to 0
numpy.putmask(fit, xvals < thresh, 0.)
return fit | [
"def",
"fit_fn",
"(",
"distr",
",",
"xvals",
",",
"alpha",
",",
"thresh",
")",
":",
"xvals",
"=",
"numpy",
".",
"array",
"(",
"xvals",
")",
"fit",
"=",
"fitfn_dict",
"[",
"distr",
"]",
"(",
"xvals",
",",
"alpha",
",",
"thresh",
")",
"# set fitted val... | The fitted function normalized to 1 above threshold
To normalize to a given total count multiply by the count.
Parameters
----------
xvals : sequence of floats
Values where the function is to be evaluated
alpha : float
The fitted parameter
thresh : float
Threshold value applied to fitted values
Returns
-------
fit : array of floats
Fitted function at the requested xvals | [
"The",
"fitted",
"function",
"normalized",
"to",
"1",
"above",
"threshold"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/trigger_fits.py#L108-L132 |
227,889 | gwastro/pycbc | pycbc/events/trigger_fits.py | tail_threshold | def tail_threshold(vals, N=1000):
"""Determine a threshold above which there are N louder values"""
vals = numpy.array(vals)
if len(vals) < N:
raise RuntimeError('Not enough input values to determine threshold')
vals.sort()
return min(vals[-N:]) | python | def tail_threshold(vals, N=1000):
vals = numpy.array(vals)
if len(vals) < N:
raise RuntimeError('Not enough input values to determine threshold')
vals.sort()
return min(vals[-N:]) | [
"def",
"tail_threshold",
"(",
"vals",
",",
"N",
"=",
"1000",
")",
":",
"vals",
"=",
"numpy",
".",
"array",
"(",
"vals",
")",
"if",
"len",
"(",
"vals",
")",
"<",
"N",
":",
"raise",
"RuntimeError",
"(",
"'Not enough input values to determine threshold'",
")"... | Determine a threshold above which there are N louder values | [
"Determine",
"a",
"threshold",
"above",
"which",
"there",
"are",
"N",
"louder",
"values"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/trigger_fits.py#L168-L174 |
227,890 | gwastro/pycbc | pycbc/inference/sampler/base_multitemper.py | MultiTemperedAutocorrSupport.compute_acl | def compute_acl(cls, filename, start_index=None, end_index=None,
min_nsamples=10):
"""Computes the autocorrleation length for all model params and
temperatures in the given file.
Parameter values are averaged over all walkers at each iteration and
temperature. The ACL is then calculated over the averaged chain.
Parameters
-----------
filename : str
Name of a samples file to compute ACLs for.
start_index : {None, int}
The start index to compute the acl from. If None, will try to use
the number of burn-in iterations in the file; otherwise, will start
at the first sample.
end_index : {None, int}
The end index to compute the acl to. If None, will go to the end
of the current iteration.
min_nsamples : int, optional
Require a minimum number of samples to compute an ACL. If the
number of samples per walker is less than this, will just set to
``inf``. Default is 10.
Returns
-------
dict
A dictionary of ntemps-long arrays of the ACLs of each parameter.
"""
acls = {}
with cls._io(filename, 'r') as fp:
if end_index is None:
end_index = fp.niterations
tidx = numpy.arange(fp.ntemps)
for param in fp.variable_params:
these_acls = numpy.zeros(fp.ntemps)
for tk in tidx:
samples = fp.read_raw_samples(
param, thin_start=start_index, thin_interval=1,
thin_end=end_index, temps=tk, flatten=False)[param]
# contract the walker dimension using the mean, and flatten
# the (length 1) temp dimension
samples = samples.mean(axis=1)[0, :]
if samples.size < min_nsamples:
acl = numpy.inf
else:
acl = autocorrelation.calculate_acl(samples)
if acl <= 0:
acl = numpy.inf
these_acls[tk] = acl
acls[param] = these_acls
return acls | python | def compute_acl(cls, filename, start_index=None, end_index=None,
min_nsamples=10):
acls = {}
with cls._io(filename, 'r') as fp:
if end_index is None:
end_index = fp.niterations
tidx = numpy.arange(fp.ntemps)
for param in fp.variable_params:
these_acls = numpy.zeros(fp.ntemps)
for tk in tidx:
samples = fp.read_raw_samples(
param, thin_start=start_index, thin_interval=1,
thin_end=end_index, temps=tk, flatten=False)[param]
# contract the walker dimension using the mean, and flatten
# the (length 1) temp dimension
samples = samples.mean(axis=1)[0, :]
if samples.size < min_nsamples:
acl = numpy.inf
else:
acl = autocorrelation.calculate_acl(samples)
if acl <= 0:
acl = numpy.inf
these_acls[tk] = acl
acls[param] = these_acls
return acls | [
"def",
"compute_acl",
"(",
"cls",
",",
"filename",
",",
"start_index",
"=",
"None",
",",
"end_index",
"=",
"None",
",",
"min_nsamples",
"=",
"10",
")",
":",
"acls",
"=",
"{",
"}",
"with",
"cls",
".",
"_io",
"(",
"filename",
",",
"'r'",
")",
"as",
"... | Computes the autocorrleation length for all model params and
temperatures in the given file.
Parameter values are averaged over all walkers at each iteration and
temperature. The ACL is then calculated over the averaged chain.
Parameters
-----------
filename : str
Name of a samples file to compute ACLs for.
start_index : {None, int}
The start index to compute the acl from. If None, will try to use
the number of burn-in iterations in the file; otherwise, will start
at the first sample.
end_index : {None, int}
The end index to compute the acl to. If None, will go to the end
of the current iteration.
min_nsamples : int, optional
Require a minimum number of samples to compute an ACL. If the
number of samples per walker is less than this, will just set to
``inf``. Default is 10.
Returns
-------
dict
A dictionary of ntemps-long arrays of the ACLs of each parameter. | [
"Computes",
"the",
"autocorrleation",
"length",
"for",
"all",
"model",
"params",
"and",
"temperatures",
"in",
"the",
"given",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/sampler/base_multitemper.py#L141-L192 |
227,891 | gwastro/pycbc | pycbc/weave.py | pycbc_compile_function | def pycbc_compile_function(code,arg_names,local_dict,global_dict,
module_dir,
compiler='',
verbose=1,
support_code=None,
headers=None,
customize=None,
type_converters=None,
auto_downcast=1,
**kw):
""" Dummy wrapper around scipy weave compile to implement file locking
"""
headers = [] if headers is None else headers
lockfile_dir = os.environ['PYTHONCOMPILED']
lockfile_name = os.path.join(lockfile_dir, 'code_lockfile')
logging.info("attempting to aquire lock '%s' for "
"compiling code" % lockfile_name)
if not os.path.exists(lockfile_dir):
os.makedirs(lockfile_dir)
lockfile = open(lockfile_name, 'w')
fcntl.lockf(lockfile, fcntl.LOCK_EX)
logging.info("we have aquired the lock")
func = _compile_function(code,arg_names, local_dict, global_dict,
module_dir, compiler, verbose,
support_code, headers, customize,
type_converters,
auto_downcast, **kw)
fcntl.lockf(lockfile, fcntl.LOCK_UN)
logging.info("the lock has been released")
return func | python | def pycbc_compile_function(code,arg_names,local_dict,global_dict,
module_dir,
compiler='',
verbose=1,
support_code=None,
headers=None,
customize=None,
type_converters=None,
auto_downcast=1,
**kw):
headers = [] if headers is None else headers
lockfile_dir = os.environ['PYTHONCOMPILED']
lockfile_name = os.path.join(lockfile_dir, 'code_lockfile')
logging.info("attempting to aquire lock '%s' for "
"compiling code" % lockfile_name)
if not os.path.exists(lockfile_dir):
os.makedirs(lockfile_dir)
lockfile = open(lockfile_name, 'w')
fcntl.lockf(lockfile, fcntl.LOCK_EX)
logging.info("we have aquired the lock")
func = _compile_function(code,arg_names, local_dict, global_dict,
module_dir, compiler, verbose,
support_code, headers, customize,
type_converters,
auto_downcast, **kw)
fcntl.lockf(lockfile, fcntl.LOCK_UN)
logging.info("the lock has been released")
return func | [
"def",
"pycbc_compile_function",
"(",
"code",
",",
"arg_names",
",",
"local_dict",
",",
"global_dict",
",",
"module_dir",
",",
"compiler",
"=",
"''",
",",
"verbose",
"=",
"1",
",",
"support_code",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"customize",
... | Dummy wrapper around scipy weave compile to implement file locking | [
"Dummy",
"wrapper",
"around",
"scipy",
"weave",
"compile",
"to",
"implement",
"file",
"locking"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/weave.py#L32-L64 |
227,892 | gwastro/pycbc | pycbc/workflow/coincidence.py | convert_bank_to_hdf | def convert_bank_to_hdf(workflow, xmlbank, out_dir, tags=None):
"""Return the template bank in hdf format"""
if tags is None:
tags = []
#FIXME, make me not needed
if len(xmlbank) > 1:
raise ValueError('Can only convert a single template bank')
logging.info('convert template bank to HDF')
make_analysis_dir(out_dir)
bank2hdf_exe = PyCBCBank2HDFExecutable(workflow.cp, 'bank2hdf',
ifos=workflow.ifos,
out_dir=out_dir, tags=tags)
bank2hdf_node = bank2hdf_exe.create_node(xmlbank[0])
workflow.add_node(bank2hdf_node)
return bank2hdf_node.output_files | python | def convert_bank_to_hdf(workflow, xmlbank, out_dir, tags=None):
if tags is None:
tags = []
#FIXME, make me not needed
if len(xmlbank) > 1:
raise ValueError('Can only convert a single template bank')
logging.info('convert template bank to HDF')
make_analysis_dir(out_dir)
bank2hdf_exe = PyCBCBank2HDFExecutable(workflow.cp, 'bank2hdf',
ifos=workflow.ifos,
out_dir=out_dir, tags=tags)
bank2hdf_node = bank2hdf_exe.create_node(xmlbank[0])
workflow.add_node(bank2hdf_node)
return bank2hdf_node.output_files | [
"def",
"convert_bank_to_hdf",
"(",
"workflow",
",",
"xmlbank",
",",
"out_dir",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"#FIXME, make me not needed",
"if",
"len",
"(",
"xmlbank",
")",
">",
"1",
":",
"r... | Return the template bank in hdf format | [
"Return",
"the",
"template",
"bank",
"in",
"hdf",
"format"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/coincidence.py#L333-L348 |
227,893 | gwastro/pycbc | pycbc/workflow/coincidence.py | convert_trig_to_hdf | def convert_trig_to_hdf(workflow, hdfbank, xml_trigger_files, out_dir, tags=None):
"""Return the list of hdf5 trigger files outputs"""
if tags is None:
tags = []
#FIXME, make me not needed
logging.info('convert single inspiral trigger files to hdf5')
make_analysis_dir(out_dir)
trig_files = FileList()
for ifo, insp_group in zip(*xml_trigger_files.categorize_by_attr('ifo')):
trig2hdf_exe = PyCBCTrig2HDFExecutable(workflow.cp, 'trig2hdf',
ifos=ifo, out_dir=out_dir, tags=tags)
_, insp_bundles = insp_group.categorize_by_attr('segment')
for insps in insp_bundles:
trig2hdf_node = trig2hdf_exe.create_node(insps, hdfbank[0])
workflow.add_node(trig2hdf_node)
trig_files += trig2hdf_node.output_files
return trig_files | python | def convert_trig_to_hdf(workflow, hdfbank, xml_trigger_files, out_dir, tags=None):
if tags is None:
tags = []
#FIXME, make me not needed
logging.info('convert single inspiral trigger files to hdf5')
make_analysis_dir(out_dir)
trig_files = FileList()
for ifo, insp_group in zip(*xml_trigger_files.categorize_by_attr('ifo')):
trig2hdf_exe = PyCBCTrig2HDFExecutable(workflow.cp, 'trig2hdf',
ifos=ifo, out_dir=out_dir, tags=tags)
_, insp_bundles = insp_group.categorize_by_attr('segment')
for insps in insp_bundles:
trig2hdf_node = trig2hdf_exe.create_node(insps, hdfbank[0])
workflow.add_node(trig2hdf_node)
trig_files += trig2hdf_node.output_files
return trig_files | [
"def",
"convert_trig_to_hdf",
"(",
"workflow",
",",
"hdfbank",
",",
"xml_trigger_files",
",",
"out_dir",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"#FIXME, make me not needed",
"logging",
".",
"info",
"(",
... | Return the list of hdf5 trigger files outputs | [
"Return",
"the",
"list",
"of",
"hdf5",
"trigger",
"files",
"outputs"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/coincidence.py#L350-L367 |
227,894 | gwastro/pycbc | pycbc/workflow/coincidence.py | setup_multiifo_interval_coinc_inj | def setup_multiifo_interval_coinc_inj(workflow, hdfbank, full_data_trig_files, inj_trig_files,
stat_files, background_file, veto_file, veto_name,
out_dir, pivot_ifo, fixed_ifo, tags=None):
"""
This function sets up exact match multiifo coincidence for injections
"""
if tags is None:
tags = []
make_analysis_dir(out_dir)
logging.info('Setting up coincidence for injections')
if len(hdfbank) != 1:
raise ValueError('Must use exactly 1 bank file for this coincidence '
'method, I got %i !' % len(hdfbank))
hdfbank = hdfbank[0]
# Wall time knob and memory knob
factor = int(workflow.cp.get_opt_tags('workflow-coincidence', 'parallelization-factor', tags))
ffiles = {}
ifiles = {}
for ifo, ffi in zip(*full_data_trig_files.categorize_by_attr('ifo')):
ffiles[ifo] = ffi[0]
for ifo, ifi in zip(*inj_trig_files.categorize_by_attr('ifo')):
ifiles[ifo] = ifi[0]
injinj_files = FileList()
injfull_files = FileList()
fullinj_files = FileList()
# For the injfull and fullinj separation we take the pivot_ifo on one side,
# and the rest that are attached to the fixed_ifo on the other side
for ifo in ifiles: # ifiles is keyed on ifo
if ifo == pivot_ifo:
injinj_files.append(ifiles[ifo])
injfull_files.append(ifiles[ifo])
fullinj_files.append(ffiles[ifo])
else:
injinj_files.append(ifiles[ifo])
injfull_files.append(ffiles[ifo])
fullinj_files.append(ifiles[ifo])
combo = [(injinj_files, "injinj"),
(injfull_files, "injfull"),
(fullinj_files, "fullinj"),
]
bg_files = {'injinj':[], 'injfull':[], 'fullinj':[]}
for trig_files, ctag in combo:
findcoinc_exe = PyCBCFindMultiifoCoincExecutable(workflow.cp,
'multiifo_coinc',
ifos=ifiles.keys(),
tags=tags + [ctag],
out_dir=out_dir)
for i in range(factor):
group_str = '%s/%s' % (i, factor)
coinc_node = findcoinc_exe.create_node(trig_files, hdfbank,
stat_files,
veto_file, veto_name,
group_str,
pivot_ifo,
fixed_ifo,
tags=[veto_name, str(i)])
bg_files[ctag] += coinc_node.output_files
workflow.add_node(coinc_node)
logging.info('...leaving coincidence for injections')
return setup_multiifo_statmap_inj(workflow, ifiles.keys(), bg_files, background_file, out_dir, tags=tags + [veto_name]) | python | def setup_multiifo_interval_coinc_inj(workflow, hdfbank, full_data_trig_files, inj_trig_files,
stat_files, background_file, veto_file, veto_name,
out_dir, pivot_ifo, fixed_ifo, tags=None):
if tags is None:
tags = []
make_analysis_dir(out_dir)
logging.info('Setting up coincidence for injections')
if len(hdfbank) != 1:
raise ValueError('Must use exactly 1 bank file for this coincidence '
'method, I got %i !' % len(hdfbank))
hdfbank = hdfbank[0]
# Wall time knob and memory knob
factor = int(workflow.cp.get_opt_tags('workflow-coincidence', 'parallelization-factor', tags))
ffiles = {}
ifiles = {}
for ifo, ffi in zip(*full_data_trig_files.categorize_by_attr('ifo')):
ffiles[ifo] = ffi[0]
for ifo, ifi in zip(*inj_trig_files.categorize_by_attr('ifo')):
ifiles[ifo] = ifi[0]
injinj_files = FileList()
injfull_files = FileList()
fullinj_files = FileList()
# For the injfull and fullinj separation we take the pivot_ifo on one side,
# and the rest that are attached to the fixed_ifo on the other side
for ifo in ifiles: # ifiles is keyed on ifo
if ifo == pivot_ifo:
injinj_files.append(ifiles[ifo])
injfull_files.append(ifiles[ifo])
fullinj_files.append(ffiles[ifo])
else:
injinj_files.append(ifiles[ifo])
injfull_files.append(ffiles[ifo])
fullinj_files.append(ifiles[ifo])
combo = [(injinj_files, "injinj"),
(injfull_files, "injfull"),
(fullinj_files, "fullinj"),
]
bg_files = {'injinj':[], 'injfull':[], 'fullinj':[]}
for trig_files, ctag in combo:
findcoinc_exe = PyCBCFindMultiifoCoincExecutable(workflow.cp,
'multiifo_coinc',
ifos=ifiles.keys(),
tags=tags + [ctag],
out_dir=out_dir)
for i in range(factor):
group_str = '%s/%s' % (i, factor)
coinc_node = findcoinc_exe.create_node(trig_files, hdfbank,
stat_files,
veto_file, veto_name,
group_str,
pivot_ifo,
fixed_ifo,
tags=[veto_name, str(i)])
bg_files[ctag] += coinc_node.output_files
workflow.add_node(coinc_node)
logging.info('...leaving coincidence for injections')
return setup_multiifo_statmap_inj(workflow, ifiles.keys(), bg_files, background_file, out_dir, tags=tags + [veto_name]) | [
"def",
"setup_multiifo_interval_coinc_inj",
"(",
"workflow",
",",
"hdfbank",
",",
"full_data_trig_files",
",",
"inj_trig_files",
",",
"stat_files",
",",
"background_file",
",",
"veto_file",
",",
"veto_name",
",",
"out_dir",
",",
"pivot_ifo",
",",
"fixed_ifo",
",",
"... | This function sets up exact match multiifo coincidence for injections | [
"This",
"function",
"sets",
"up",
"exact",
"match",
"multiifo",
"coincidence",
"for",
"injections"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/coincidence.py#L594-L662 |
227,895 | gwastro/pycbc | pycbc/workflow/coincidence.py | setup_multiifo_interval_coinc | def setup_multiifo_interval_coinc(workflow, hdfbank, trig_files, stat_files,
veto_files, veto_names, out_dir, pivot_ifo, fixed_ifo, tags=None):
"""
This function sets up exact match multiifo coincidence
"""
if tags is None:
tags = []
make_analysis_dir(out_dir)
logging.info('Setting up coincidence')
if len(hdfbank) != 1:
raise ValueError('Must use exactly 1 bank file for this coincidence '
'method, I got %i !' % len(hdfbank))
hdfbank = hdfbank[0]
ifos, _ = trig_files.categorize_by_attr('ifo')
findcoinc_exe = PyCBCFindMultiifoCoincExecutable(workflow.cp, 'multiifo_coinc',
ifos=ifos,
tags=tags, out_dir=out_dir)
# Wall time knob and memory knob
factor = int(workflow.cp.get_opt_tags('workflow-coincidence', 'parallelization-factor', tags))
statmap_files = []
for veto_file, veto_name in zip(veto_files, veto_names):
bg_files = FileList()
for i in range(factor):
group_str = '%s/%s' % (i, factor)
coinc_node = findcoinc_exe.create_node(trig_files, hdfbank,
stat_files,
veto_file, veto_name,
group_str,
pivot_ifo,
fixed_ifo,
tags=[veto_name, str(i)])
bg_files += coinc_node.output_files
workflow.add_node(coinc_node)
statmap_files += [setup_multiifo_statmap(workflow, ifos, bg_files, out_dir, tags=tags + [veto_name])]
logging.info('...leaving coincidence ')
return statmap_files | python | def setup_multiifo_interval_coinc(workflow, hdfbank, trig_files, stat_files,
veto_files, veto_names, out_dir, pivot_ifo, fixed_ifo, tags=None):
if tags is None:
tags = []
make_analysis_dir(out_dir)
logging.info('Setting up coincidence')
if len(hdfbank) != 1:
raise ValueError('Must use exactly 1 bank file for this coincidence '
'method, I got %i !' % len(hdfbank))
hdfbank = hdfbank[0]
ifos, _ = trig_files.categorize_by_attr('ifo')
findcoinc_exe = PyCBCFindMultiifoCoincExecutable(workflow.cp, 'multiifo_coinc',
ifos=ifos,
tags=tags, out_dir=out_dir)
# Wall time knob and memory knob
factor = int(workflow.cp.get_opt_tags('workflow-coincidence', 'parallelization-factor', tags))
statmap_files = []
for veto_file, veto_name in zip(veto_files, veto_names):
bg_files = FileList()
for i in range(factor):
group_str = '%s/%s' % (i, factor)
coinc_node = findcoinc_exe.create_node(trig_files, hdfbank,
stat_files,
veto_file, veto_name,
group_str,
pivot_ifo,
fixed_ifo,
tags=[veto_name, str(i)])
bg_files += coinc_node.output_files
workflow.add_node(coinc_node)
statmap_files += [setup_multiifo_statmap(workflow, ifos, bg_files, out_dir, tags=tags + [veto_name])]
logging.info('...leaving coincidence ')
return statmap_files | [
"def",
"setup_multiifo_interval_coinc",
"(",
"workflow",
",",
"hdfbank",
",",
"trig_files",
",",
"stat_files",
",",
"veto_files",
",",
"veto_names",
",",
"out_dir",
",",
"pivot_ifo",
",",
"fixed_ifo",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"... | This function sets up exact match multiifo coincidence | [
"This",
"function",
"sets",
"up",
"exact",
"match",
"multiifo",
"coincidence"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/coincidence.py#L664-L705 |
227,896 | gwastro/pycbc | pycbc/workflow/coincidence.py | setup_multiifo_combine_statmap | def setup_multiifo_combine_statmap(workflow, final_bg_file_list, out_dir, tags):
"""
Combine the multiifo statmap files into one background file
"""
if tags is None:
tags = []
make_analysis_dir(out_dir)
logging.info('Setting up multiifo combine statmap')
cstat_exe = PyCBCMultiifoCombineStatmap(workflow.cp,
'combine_statmap',
ifos=workflow.ifos,
tags=tags,
out_dir=out_dir)
ifolist = ' '.join(workflow.ifos)
cluster_window = float(workflow.cp.get_opt_tags('combine_statmap',
'cluster-window',
tags))
combine_statmap_node = cstat_exe.create_node(final_bg_file_list,
ifolist,
cluster_window,
tags)
workflow.add_node(combine_statmap_node)
return combine_statmap_node.output_file | python | def setup_multiifo_combine_statmap(workflow, final_bg_file_list, out_dir, tags):
if tags is None:
tags = []
make_analysis_dir(out_dir)
logging.info('Setting up multiifo combine statmap')
cstat_exe = PyCBCMultiifoCombineStatmap(workflow.cp,
'combine_statmap',
ifos=workflow.ifos,
tags=tags,
out_dir=out_dir)
ifolist = ' '.join(workflow.ifos)
cluster_window = float(workflow.cp.get_opt_tags('combine_statmap',
'cluster-window',
tags))
combine_statmap_node = cstat_exe.create_node(final_bg_file_list,
ifolist,
cluster_window,
tags)
workflow.add_node(combine_statmap_node)
return combine_statmap_node.output_file | [
"def",
"setup_multiifo_combine_statmap",
"(",
"workflow",
",",
"final_bg_file_list",
",",
"out_dir",
",",
"tags",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"make_analysis_dir",
"(",
"out_dir",
")",
"logging",
".",
"info",
"(",
"'Setti... | Combine the multiifo statmap files into one background file | [
"Combine",
"the",
"multiifo",
"statmap",
"files",
"into",
"one",
"background",
"file"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/coincidence.py#L732-L756 |
227,897 | gwastro/pycbc | pycbc/fft/fftw_pruned.py | first_phase | def first_phase(invec, outvec, N1, N2):
"""
This implements the first phase of the FFT decomposition, using
the standard FFT many plans.
Parameters
-----------
invec : array
The input array.
outvec : array
The output array.
N1 : int
Number of rows.
N2 : int
Number of columns.
"""
global _theplan
if _theplan is None:
_theplan = plan_first_phase(N1, N2)
fexecute(_theplan, invec.ptr, outvec.ptr) | python | def first_phase(invec, outvec, N1, N2):
global _theplan
if _theplan is None:
_theplan = plan_first_phase(N1, N2)
fexecute(_theplan, invec.ptr, outvec.ptr) | [
"def",
"first_phase",
"(",
"invec",
",",
"outvec",
",",
"N1",
",",
"N2",
")",
":",
"global",
"_theplan",
"if",
"_theplan",
"is",
"None",
":",
"_theplan",
"=",
"plan_first_phase",
"(",
"N1",
",",
"N2",
")",
"fexecute",
"(",
"_theplan",
",",
"invec",
"."... | This implements the first phase of the FFT decomposition, using
the standard FFT many plans.
Parameters
-----------
invec : array
The input array.
outvec : array
The output array.
N1 : int
Number of rows.
N2 : int
Number of columns. | [
"This",
"implements",
"the",
"first",
"phase",
"of",
"the",
"FFT",
"decomposition",
"using",
"the",
"standard",
"FFT",
"many",
"plans",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/fft/fftw_pruned.py#L106-L125 |
227,898 | gwastro/pycbc | pycbc/fft/fftw_pruned.py | second_phase | def second_phase(invec, indices, N1, N2):
"""
This is the second phase of the FFT decomposition that actually performs
the pruning. It is an explicit calculation for the subset of points. Note
that there seem to be some numerical accumulation issues at various values
of N1 and N2.
Parameters
----------
invec :
The result of the first phase FFT
indices : array of ints
The index locations to calculate the FFT
N1 : int
The length of the second phase "FFT"
N2 : int
The length of the first phase FFT
Returns
-------
out : array of floats
"""
invec = numpy.array(invec.data, copy=False)
NI = len(indices) # pylint:disable=unused-variable
N1=int(N1)
N2=int(N2)
out = numpy.zeros(len(indices), dtype=numpy.complex64)
code = """
float pi = 3.14159265359;
for(int i=0; i<NI; i++){
std::complex<double> val= (0, 0);
unsigned int k = indices[i];
int N = N1*N2;
float k2 = k % N2;
float phase_inc = 2 * pi * float(k) / float(N);
float sp, cp;
for (float n1=0; n1<N1; n1+=1){
sincosf(phase_inc * n1, &sp, &cp);
val += std::complex<float>(cp, sp) * invec[int(k2 + N2*n1)];
}
out[i] = val;
}
"""
weave.inline(code, ['N1', 'N2', 'NI', 'indices', 'out', 'invec'],
)
return out | python | def second_phase(invec, indices, N1, N2):
invec = numpy.array(invec.data, copy=False)
NI = len(indices) # pylint:disable=unused-variable
N1=int(N1)
N2=int(N2)
out = numpy.zeros(len(indices), dtype=numpy.complex64)
code = """
float pi = 3.14159265359;
for(int i=0; i<NI; i++){
std::complex<double> val= (0, 0);
unsigned int k = indices[i];
int N = N1*N2;
float k2 = k % N2;
float phase_inc = 2 * pi * float(k) / float(N);
float sp, cp;
for (float n1=0; n1<N1; n1+=1){
sincosf(phase_inc * n1, &sp, &cp);
val += std::complex<float>(cp, sp) * invec[int(k2 + N2*n1)];
}
out[i] = val;
}
"""
weave.inline(code, ['N1', 'N2', 'NI', 'indices', 'out', 'invec'],
)
return out | [
"def",
"second_phase",
"(",
"invec",
",",
"indices",
",",
"N1",
",",
"N2",
")",
":",
"invec",
"=",
"numpy",
".",
"array",
"(",
"invec",
".",
"data",
",",
"copy",
"=",
"False",
")",
"NI",
"=",
"len",
"(",
"indices",
")",
"# pylint:disable=unused-variabl... | This is the second phase of the FFT decomposition that actually performs
the pruning. It is an explicit calculation for the subset of points. Note
that there seem to be some numerical accumulation issues at various values
of N1 and N2.
Parameters
----------
invec :
The result of the first phase FFT
indices : array of ints
The index locations to calculate the FFT
N1 : int
The length of the second phase "FFT"
N2 : int
The length of the first phase FFT
Returns
-------
out : array of floats | [
"This",
"is",
"the",
"second",
"phase",
"of",
"the",
"FFT",
"decomposition",
"that",
"actually",
"performs",
"the",
"pruning",
".",
"It",
"is",
"an",
"explicit",
"calculation",
"for",
"the",
"subset",
"of",
"points",
".",
"Note",
"that",
"there",
"seem",
"... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/fft/fftw_pruned.py#L127-L173 |
227,899 | gwastro/pycbc | pycbc/fft/fftw_pruned.py | splay | def splay(vec):
""" Determine two lengths to split stride the input vector by
"""
N2 = 2 ** int(numpy.log2( len(vec) ) / 2)
N1 = len(vec) / N2
return N1, N2 | python | def splay(vec):
N2 = 2 ** int(numpy.log2( len(vec) ) / 2)
N1 = len(vec) / N2
return N1, N2 | [
"def",
"splay",
"(",
"vec",
")",
":",
"N2",
"=",
"2",
"**",
"int",
"(",
"numpy",
".",
"log2",
"(",
"len",
"(",
"vec",
")",
")",
"/",
"2",
")",
"N1",
"=",
"len",
"(",
"vec",
")",
"/",
"N2",
"return",
"N1",
",",
"N2"
] | Determine two lengths to split stride the input vector by | [
"Determine",
"two",
"lengths",
"to",
"split",
"stride",
"the",
"input",
"vector",
"by"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/fft/fftw_pruned.py#L274-L279 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.