id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
228,300 | gwastro/pycbc | pycbc/workflow/jobsetup.py | PycbcSplitBankExecutable.create_node | def create_node(self, bank, tags=None):
"""
Set up a CondorDagmanNode class to run splitbank code
Parameters
----------
bank : pycbc.workflow.core.File
The File containing the template bank to be split
Returns
--------
node : pycbc.workflow.core.Node
The node to run the job
"""
if tags is None:
tags = []
node = Node(self)
node.add_input_opt('--bank-file', bank)
# Get the output (taken from inspiral.py)
out_files = FileList([])
for i in range( 0, self.num_banks):
curr_tag = 'bank%d' %(i)
# FIXME: What should the tags actually be? The job.tags values are
# currently ignored.
curr_tags = bank.tags + [curr_tag] + tags
job_tag = bank.description + "_" + self.name.upper()
out_file = File(bank.ifo_list, job_tag, bank.segment,
extension=self.extension, directory=self.out_dir,
tags=curr_tags, store_file=self.retain_files)
out_files.append(out_file)
node.add_output_list_opt('--output-filenames', out_files)
return node | python | def create_node(self, bank, tags=None):
if tags is None:
tags = []
node = Node(self)
node.add_input_opt('--bank-file', bank)
# Get the output (taken from inspiral.py)
out_files = FileList([])
for i in range( 0, self.num_banks):
curr_tag = 'bank%d' %(i)
# FIXME: What should the tags actually be? The job.tags values are
# currently ignored.
curr_tags = bank.tags + [curr_tag] + tags
job_tag = bank.description + "_" + self.name.upper()
out_file = File(bank.ifo_list, job_tag, bank.segment,
extension=self.extension, directory=self.out_dir,
tags=curr_tags, store_file=self.retain_files)
out_files.append(out_file)
node.add_output_list_opt('--output-filenames', out_files)
return node | [
"def",
"create_node",
"(",
"self",
",",
"bank",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"node",
"=",
"Node",
"(",
"self",
")",
"node",
".",
"add_input_opt",
"(",
"'--bank-file'",
",",
"bank",
")",... | Set up a CondorDagmanNode class to run splitbank code
Parameters
----------
bank : pycbc.workflow.core.File
The File containing the template bank to be split
Returns
--------
node : pycbc.workflow.core.Node
The node to run the job | [
"Set",
"up",
"a",
"CondorDagmanNode",
"class",
"to",
"run",
"splitbank",
"code"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/jobsetup.py#L1682-L1714 |
228,301 | gwastro/pycbc | pycbc/workflow/jobsetup.py | PycbcCreateInjectionsExecutable.create_node | def create_node(self, config_file=None, seed=None, tags=None):
""" Set up a CondorDagmanNode class to run ``pycbc_create_injections``.
Parameters
----------
config_file : pycbc.workflow.core.File
A ``pycbc.workflow.core.File`` for inference configuration file
to be used with ``--config-files`` option.
seed : int
Seed to use for generating injections.
tags : list
A list of tags to include in filenames.
Returns
--------
node : pycbc.workflow.core.Node
The node to run the job.
"""
# default for tags is empty list
tags = [] if tags is None else tags
# get analysis start and end time
start_time = self.cp.get("workflow", "start-time")
end_time = self.cp.get("workflow", "end-time")
analysis_time = segments.segment(int(start_time), int(end_time))
# make node for running executable
node = Node(self)
node.add_input_opt("--config-file", config_file)
if seed:
node.add_opt("--seed", seed)
injection_file = node.new_output_file_opt(analysis_time,
".hdf", "--output-file",
tags=tags)
return node, injection_file | python | def create_node(self, config_file=None, seed=None, tags=None):
# default for tags is empty list
tags = [] if tags is None else tags
# get analysis start and end time
start_time = self.cp.get("workflow", "start-time")
end_time = self.cp.get("workflow", "end-time")
analysis_time = segments.segment(int(start_time), int(end_time))
# make node for running executable
node = Node(self)
node.add_input_opt("--config-file", config_file)
if seed:
node.add_opt("--seed", seed)
injection_file = node.new_output_file_opt(analysis_time,
".hdf", "--output-file",
tags=tags)
return node, injection_file | [
"def",
"create_node",
"(",
"self",
",",
"config_file",
"=",
"None",
",",
"seed",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"# default for tags is empty list",
"tags",
"=",
"[",
"]",
"if",
"tags",
"is",
"None",
"else",
"tags",
"# get analysis start and... | Set up a CondorDagmanNode class to run ``pycbc_create_injections``.
Parameters
----------
config_file : pycbc.workflow.core.File
A ``pycbc.workflow.core.File`` for inference configuration file
to be used with ``--config-files`` option.
seed : int
Seed to use for generating injections.
tags : list
A list of tags to include in filenames.
Returns
--------
node : pycbc.workflow.core.Node
The node to run the job. | [
"Set",
"up",
"a",
"CondorDagmanNode",
"class",
"to",
"run",
"pycbc_create_injections",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/jobsetup.py#L1766-L1802 |
228,302 | gwastro/pycbc | pycbc/workflow/jobsetup.py | PycbcInferenceExecutable.create_node | def create_node(self, channel_names, config_file, injection_file=None,
seed=None, fake_strain_seed=None, tags=None):
""" Set up a CondorDagmanNode class to run ``pycbc_inference``.
Parameters
----------
channel_names : dict
A ``dict`` of ``str`` to use for ``--channel-name`` option.
config_file : pycbc.workflow.core.File
A ``pycbc.workflow.core.File`` for inference configuration file
to be used with ``--config-files`` option.
injection_file : pycbc.workflow.core.File
A ``pycbc.workflow.core.File`` for injection file to be used
with ``--injection-file`` option.
seed : int
An ``int`` to be used with ``--seed`` option.
fake_strain_seed : dict
An ``int`` to be used with ``--fake-strain-seed`` option.
tags : list
A list of tags to include in filenames.
Returns
--------
node : pycbc.workflow.core.Node
The node to run the job.
"""
# default for tags is empty list
tags = [] if tags is None else tags
# get analysis start and end time
start_time = self.cp.get("workflow", "start-time")
end_time = self.cp.get("workflow", "end-time")
analysis_time = segments.segment(int(start_time), int(end_time))
# get multi-IFO opts
channel_names_opt = " ".join(["{}:{}".format(k, v)
for k, v in channel_names.iteritems()])
if fake_strain_seed is not None:
fake_strain_seed_opt = " ".join([
"{}:{}".format(k, v)
for k, v in fake_strain_seed.iteritems()])
# make node for running executable
node = Node(self)
node.add_opt("--instruments", " ".join(self.ifo_list))
node.add_opt("--gps-start-time", start_time)
node.add_opt("--gps-end-time", end_time)
node.add_opt("--channel-name", channel_names_opt)
node.add_input_opt("--config-file", config_file)
if fake_strain_seed is not None:
node.add_opt("--fake-strain-seed", fake_strain_seed_opt)
if injection_file:
node.add_input_opt("--injection-file", injection_file)
if seed:
node.add_opt("--seed", seed)
inference_file = node.new_output_file_opt(analysis_time,
".hdf", "--output-file",
tags=tags)
if self.cp.has_option("pegasus_profile-inference",
"condor|+CheckpointSig"):
ckpt_file_name = "{}.checkpoint".format(inference_file.name)
ckpt_file = dax.File(ckpt_file_name)
node._dax_node.uses(ckpt_file, link=dax.Link.OUTPUT,
register=False, transfer=False)
return node, inference_file | python | def create_node(self, channel_names, config_file, injection_file=None,
seed=None, fake_strain_seed=None, tags=None):
# default for tags is empty list
tags = [] if tags is None else tags
# get analysis start and end time
start_time = self.cp.get("workflow", "start-time")
end_time = self.cp.get("workflow", "end-time")
analysis_time = segments.segment(int(start_time), int(end_time))
# get multi-IFO opts
channel_names_opt = " ".join(["{}:{}".format(k, v)
for k, v in channel_names.iteritems()])
if fake_strain_seed is not None:
fake_strain_seed_opt = " ".join([
"{}:{}".format(k, v)
for k, v in fake_strain_seed.iteritems()])
# make node for running executable
node = Node(self)
node.add_opt("--instruments", " ".join(self.ifo_list))
node.add_opt("--gps-start-time", start_time)
node.add_opt("--gps-end-time", end_time)
node.add_opt("--channel-name", channel_names_opt)
node.add_input_opt("--config-file", config_file)
if fake_strain_seed is not None:
node.add_opt("--fake-strain-seed", fake_strain_seed_opt)
if injection_file:
node.add_input_opt("--injection-file", injection_file)
if seed:
node.add_opt("--seed", seed)
inference_file = node.new_output_file_opt(analysis_time,
".hdf", "--output-file",
tags=tags)
if self.cp.has_option("pegasus_profile-inference",
"condor|+CheckpointSig"):
ckpt_file_name = "{}.checkpoint".format(inference_file.name)
ckpt_file = dax.File(ckpt_file_name)
node._dax_node.uses(ckpt_file, link=dax.Link.OUTPUT,
register=False, transfer=False)
return node, inference_file | [
"def",
"create_node",
"(",
"self",
",",
"channel_names",
",",
"config_file",
",",
"injection_file",
"=",
"None",
",",
"seed",
"=",
"None",
",",
"fake_strain_seed",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"# default for tags is empty list",
"tags",
"="... | Set up a CondorDagmanNode class to run ``pycbc_inference``.
Parameters
----------
channel_names : dict
A ``dict`` of ``str`` to use for ``--channel-name`` option.
config_file : pycbc.workflow.core.File
A ``pycbc.workflow.core.File`` for inference configuration file
to be used with ``--config-files`` option.
injection_file : pycbc.workflow.core.File
A ``pycbc.workflow.core.File`` for injection file to be used
with ``--injection-file`` option.
seed : int
An ``int`` to be used with ``--seed`` option.
fake_strain_seed : dict
An ``int`` to be used with ``--fake-strain-seed`` option.
tags : list
A list of tags to include in filenames.
Returns
--------
node : pycbc.workflow.core.Node
The node to run the job. | [
"Set",
"up",
"a",
"CondorDagmanNode",
"class",
"to",
"run",
"pycbc_inference",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/jobsetup.py#L1814-L1881 |
228,303 | gwastro/pycbc | pycbc/conversions.py | ensurearray | def ensurearray(*args):
"""Apply numpy's broadcast rules to the given arguments.
This will ensure that all of the arguments are numpy arrays and that they
all have the same shape. See ``numpy.broadcast_arrays`` for more details.
It also returns a boolean indicating whether any of the inputs were
originally arrays.
Parameters
----------
*args :
The arguments to check.
Returns
-------
list :
A list with length ``N+1`` where ``N`` is the number of given
arguments. The first N values are the input arguments as ``ndarrays``s.
The last value is a boolean indicating whether any of the
inputs was an array.
"""
input_is_array = any(isinstance(arg, numpy.ndarray) for arg in args)
args = numpy.broadcast_arrays(*args)
args.append(input_is_array)
return args | python | def ensurearray(*args):
input_is_array = any(isinstance(arg, numpy.ndarray) for arg in args)
args = numpy.broadcast_arrays(*args)
args.append(input_is_array)
return args | [
"def",
"ensurearray",
"(",
"*",
"args",
")",
":",
"input_is_array",
"=",
"any",
"(",
"isinstance",
"(",
"arg",
",",
"numpy",
".",
"ndarray",
")",
"for",
"arg",
"in",
"args",
")",
"args",
"=",
"numpy",
".",
"broadcast_arrays",
"(",
"*",
"args",
")",
"... | Apply numpy's broadcast rules to the given arguments.
This will ensure that all of the arguments are numpy arrays and that they
all have the same shape. See ``numpy.broadcast_arrays`` for more details.
It also returns a boolean indicating whether any of the inputs were
originally arrays.
Parameters
----------
*args :
The arguments to check.
Returns
-------
list :
A list with length ``N+1`` where ``N`` is the number of given
arguments. The first N values are the input arguments as ``ndarrays``s.
The last value is a boolean indicating whether any of the
inputs was an array. | [
"Apply",
"numpy",
"s",
"broadcast",
"rules",
"to",
"the",
"given",
"arguments",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L47-L72 |
228,304 | gwastro/pycbc | pycbc/conversions.py | _mass2_from_mchirp_mass1 | def _mass2_from_mchirp_mass1(mchirp, mass1):
r"""Returns the secondary mass from the chirp mass and primary mass.
As this is a cubic equation this requires finding the roots and returning
the one that is real. Basically it can be shown that:
.. math::
m_2^3 - a(m_2 + m_1) = 0,
where
.. math::
a = \frac{\mathcal{M}^5}{m_1^3}.
This has 3 solutions but only one will be real.
"""
a = mchirp**5 / mass1**3
roots = numpy.roots([1,0,-a,-a*mass1])
# Find the real one
real_root = roots[(abs(roots - roots.real)).argmin()]
return real_root.real | python | def _mass2_from_mchirp_mass1(mchirp, mass1):
r"""Returns the secondary mass from the chirp mass and primary mass.
As this is a cubic equation this requires finding the roots and returning
the one that is real. Basically it can be shown that:
.. math::
m_2^3 - a(m_2 + m_1) = 0,
where
.. math::
a = \frac{\mathcal{M}^5}{m_1^3}.
This has 3 solutions but only one will be real.
"""
a = mchirp**5 / mass1**3
roots = numpy.roots([1,0,-a,-a*mass1])
# Find the real one
real_root = roots[(abs(roots - roots.real)).argmin()]
return real_root.real | [
"def",
"_mass2_from_mchirp_mass1",
"(",
"mchirp",
",",
"mass1",
")",
":",
"a",
"=",
"mchirp",
"**",
"5",
"/",
"mass1",
"**",
"3",
"roots",
"=",
"numpy",
".",
"roots",
"(",
"[",
"1",
",",
"0",
",",
"-",
"a",
",",
"-",
"a",
"*",
"mass1",
"]",
")"... | r"""Returns the secondary mass from the chirp mass and primary mass.
As this is a cubic equation this requires finding the roots and returning
the one that is real. Basically it can be shown that:
.. math::
m_2^3 - a(m_2 + m_1) = 0,
where
.. math::
a = \frac{\mathcal{M}^5}{m_1^3}.
This has 3 solutions but only one will be real. | [
"r",
"Returns",
"the",
"secondary",
"mass",
"from",
"the",
"chirp",
"mass",
"and",
"primary",
"mass",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L201-L221 |
228,305 | gwastro/pycbc | pycbc/conversions.py | _mass_from_knownmass_eta | def _mass_from_knownmass_eta(known_mass, eta, known_is_secondary=False,
force_real=True):
r"""Returns the other component mass given one of the component masses
and the symmetric mass ratio.
This requires finding the roots of the quadratic equation:
.. math::
\eta m_2^2 + (2\eta - 1)m_1 m_2 + \eta m_1^2 = 0.
This has two solutions which correspond to :math:`m_1` being the heavier
mass or it being the lighter mass. By default, `known_mass` is assumed to
be the heavier (primary) mass, and the smaller solution is returned. Use
the `other_is_secondary` to invert.
Parameters
----------
known_mass : float
The known component mass.
eta : float
The symmetric mass ratio.
known_is_secondary : {False, bool}
Whether the known component mass is the primary or the secondary. If
True, `known_mass` is assumed to be the secondary (lighter) mass and
the larger solution is returned. Otherwise, the smaller solution is
returned. Default is False.
force_real : {True, bool}
Force the returned mass to be real.
Returns
-------
float
The other component mass.
"""
roots = numpy.roots([eta, (2*eta - 1)*known_mass, eta*known_mass**2.])
if force_real:
roots = numpy.real(roots)
if known_is_secondary:
return roots[roots.argmax()]
else:
return roots[roots.argmin()] | python | def _mass_from_knownmass_eta(known_mass, eta, known_is_secondary=False,
force_real=True):
r"""Returns the other component mass given one of the component masses
and the symmetric mass ratio.
This requires finding the roots of the quadratic equation:
.. math::
\eta m_2^2 + (2\eta - 1)m_1 m_2 + \eta m_1^2 = 0.
This has two solutions which correspond to :math:`m_1` being the heavier
mass or it being the lighter mass. By default, `known_mass` is assumed to
be the heavier (primary) mass, and the smaller solution is returned. Use
the `other_is_secondary` to invert.
Parameters
----------
known_mass : float
The known component mass.
eta : float
The symmetric mass ratio.
known_is_secondary : {False, bool}
Whether the known component mass is the primary or the secondary. If
True, `known_mass` is assumed to be the secondary (lighter) mass and
the larger solution is returned. Otherwise, the smaller solution is
returned. Default is False.
force_real : {True, bool}
Force the returned mass to be real.
Returns
-------
float
The other component mass.
"""
roots = numpy.roots([eta, (2*eta - 1)*known_mass, eta*known_mass**2.])
if force_real:
roots = numpy.real(roots)
if known_is_secondary:
return roots[roots.argmax()]
else:
return roots[roots.argmin()] | [
"def",
"_mass_from_knownmass_eta",
"(",
"known_mass",
",",
"eta",
",",
"known_is_secondary",
"=",
"False",
",",
"force_real",
"=",
"True",
")",
":",
"roots",
"=",
"numpy",
".",
"roots",
"(",
"[",
"eta",
",",
"(",
"2",
"*",
"eta",
"-",
"1",
")",
"*",
... | r"""Returns the other component mass given one of the component masses
and the symmetric mass ratio.
This requires finding the roots of the quadratic equation:
.. math::
\eta m_2^2 + (2\eta - 1)m_1 m_2 + \eta m_1^2 = 0.
This has two solutions which correspond to :math:`m_1` being the heavier
mass or it being the lighter mass. By default, `known_mass` is assumed to
be the heavier (primary) mass, and the smaller solution is returned. Use
the `other_is_secondary` to invert.
Parameters
----------
known_mass : float
The known component mass.
eta : float
The symmetric mass ratio.
known_is_secondary : {False, bool}
Whether the known component mass is the primary or the secondary. If
True, `known_mass` is assumed to be the secondary (lighter) mass and
the larger solution is returned. Otherwise, the smaller solution is
returned. Default is False.
force_real : {True, bool}
Force the returned mass to be real.
Returns
-------
float
The other component mass. | [
"r",
"Returns",
"the",
"other",
"component",
"mass",
"given",
"one",
"of",
"the",
"component",
"masses",
"and",
"the",
"symmetric",
"mass",
"ratio",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L226-L266 |
228,306 | gwastro/pycbc | pycbc/conversions.py | mass2_from_mass1_eta | def mass2_from_mass1_eta(mass1, eta, force_real=True):
"""Returns the secondary mass from the primary mass and symmetric mass
ratio.
"""
return mass_from_knownmass_eta(mass1, eta, known_is_secondary=False,
force_real=force_real) | python | def mass2_from_mass1_eta(mass1, eta, force_real=True):
return mass_from_knownmass_eta(mass1, eta, known_is_secondary=False,
force_real=force_real) | [
"def",
"mass2_from_mass1_eta",
"(",
"mass1",
",",
"eta",
",",
"force_real",
"=",
"True",
")",
":",
"return",
"mass_from_knownmass_eta",
"(",
"mass1",
",",
"eta",
",",
"known_is_secondary",
"=",
"False",
",",
"force_real",
"=",
"force_real",
")"
] | Returns the secondary mass from the primary mass and symmetric mass
ratio. | [
"Returns",
"the",
"secondary",
"mass",
"from",
"the",
"primary",
"mass",
"and",
"symmetric",
"mass",
"ratio",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L271-L276 |
228,307 | gwastro/pycbc | pycbc/conversions.py | mass1_from_mass2_eta | def mass1_from_mass2_eta(mass2, eta, force_real=True):
"""Returns the primary mass from the secondary mass and symmetric mass
ratio.
"""
return mass_from_knownmass_eta(mass2, eta, known_is_secondary=True,
force_real=force_real) | python | def mass1_from_mass2_eta(mass2, eta, force_real=True):
return mass_from_knownmass_eta(mass2, eta, known_is_secondary=True,
force_real=force_real) | [
"def",
"mass1_from_mass2_eta",
"(",
"mass2",
",",
"eta",
",",
"force_real",
"=",
"True",
")",
":",
"return",
"mass_from_knownmass_eta",
"(",
"mass2",
",",
"eta",
",",
"known_is_secondary",
"=",
"True",
",",
"force_real",
"=",
"force_real",
")"
] | Returns the primary mass from the secondary mass and symmetric mass
ratio. | [
"Returns",
"the",
"primary",
"mass",
"from",
"the",
"secondary",
"mass",
"and",
"symmetric",
"mass",
"ratio",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L279-L284 |
228,308 | gwastro/pycbc | pycbc/conversions.py | lambda_tilde | def lambda_tilde(mass1, mass2, lambda1, lambda2):
""" The effective lambda parameter
The mass-weighted dominant effective lambda parameter defined in
https://journals.aps.org/prd/pdf/10.1103/PhysRevD.91.043002
"""
m1, m2, lambda1, lambda2, input_is_array = ensurearray(
mass1, mass2, lambda1, lambda2)
lsum = lambda1 + lambda2
ldiff, _ = ensurearray(lambda1 - lambda2)
mask = m1 < m2
ldiff[mask] = -ldiff[mask]
eta = eta_from_mass1_mass2(m1, m2)
p1 = (lsum) * (1 + 7. * eta - 31 * eta ** 2.0)
p2 = (1 - 4 * eta)**0.5 * (1 + 9 * eta - 11 * eta ** 2.0) * (ldiff)
return formatreturn(8.0 / 13.0 * (p1 + p2), input_is_array) | python | def lambda_tilde(mass1, mass2, lambda1, lambda2):
m1, m2, lambda1, lambda2, input_is_array = ensurearray(
mass1, mass2, lambda1, lambda2)
lsum = lambda1 + lambda2
ldiff, _ = ensurearray(lambda1 - lambda2)
mask = m1 < m2
ldiff[mask] = -ldiff[mask]
eta = eta_from_mass1_mass2(m1, m2)
p1 = (lsum) * (1 + 7. * eta - 31 * eta ** 2.0)
p2 = (1 - 4 * eta)**0.5 * (1 + 9 * eta - 11 * eta ** 2.0) * (ldiff)
return formatreturn(8.0 / 13.0 * (p1 + p2), input_is_array) | [
"def",
"lambda_tilde",
"(",
"mass1",
",",
"mass2",
",",
"lambda1",
",",
"lambda2",
")",
":",
"m1",
",",
"m2",
",",
"lambda1",
",",
"lambda2",
",",
"input_is_array",
"=",
"ensurearray",
"(",
"mass1",
",",
"mass2",
",",
"lambda1",
",",
"lambda2",
")",
"l... | The effective lambda parameter
The mass-weighted dominant effective lambda parameter defined in
https://journals.aps.org/prd/pdf/10.1103/PhysRevD.91.043002 | [
"The",
"effective",
"lambda",
"parameter"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L389-L404 |
228,309 | gwastro/pycbc | pycbc/conversions.py | chi_eff | def chi_eff(mass1, mass2, spin1z, spin2z):
"""Returns the effective spin from mass1, mass2, spin1z, and spin2z."""
return (spin1z * mass1 + spin2z * mass2) / (mass1 + mass2) | python | def chi_eff(mass1, mass2, spin1z, spin2z):
return (spin1z * mass1 + spin2z * mass2) / (mass1 + mass2) | [
"def",
"chi_eff",
"(",
"mass1",
",",
"mass2",
",",
"spin1z",
",",
"spin2z",
")",
":",
"return",
"(",
"spin1z",
"*",
"mass1",
"+",
"spin2z",
"*",
"mass2",
")",
"/",
"(",
"mass1",
"+",
"mass2",
")"
] | Returns the effective spin from mass1, mass2, spin1z, and spin2z. | [
"Returns",
"the",
"effective",
"spin",
"from",
"mass1",
"mass2",
"spin1z",
"and",
"spin2z",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L413-L415 |
228,310 | gwastro/pycbc | pycbc/conversions.py | chi_a | def chi_a(mass1, mass2, spin1z, spin2z):
""" Returns the aligned mass-weighted spin difference from mass1, mass2,
spin1z, and spin2z.
"""
return (spin2z * mass2 - spin1z * mass1) / (mass2 + mass1) | python | def chi_a(mass1, mass2, spin1z, spin2z):
return (spin2z * mass2 - spin1z * mass1) / (mass2 + mass1) | [
"def",
"chi_a",
"(",
"mass1",
",",
"mass2",
",",
"spin1z",
",",
"spin2z",
")",
":",
"return",
"(",
"spin2z",
"*",
"mass2",
"-",
"spin1z",
"*",
"mass1",
")",
"/",
"(",
"mass2",
"+",
"mass1",
")"
] | Returns the aligned mass-weighted spin difference from mass1, mass2,
spin1z, and spin2z. | [
"Returns",
"the",
"aligned",
"mass",
"-",
"weighted",
"spin",
"difference",
"from",
"mass1",
"mass2",
"spin1z",
"and",
"spin2z",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L418-L422 |
228,311 | gwastro/pycbc | pycbc/conversions.py | chi_p | def chi_p(mass1, mass2, spin1x, spin1y, spin2x, spin2y):
"""Returns the effective precession spin from mass1, mass2, spin1x,
spin1y, spin2x, and spin2y.
"""
xi1 = secondary_xi(mass1, mass2, spin1x, spin1y, spin2x, spin2y)
xi2 = primary_xi(mass1, mass2, spin1x, spin1y, spin2x, spin2y)
return chi_p_from_xi1_xi2(xi1, xi2) | python | def chi_p(mass1, mass2, spin1x, spin1y, spin2x, spin2y):
xi1 = secondary_xi(mass1, mass2, spin1x, spin1y, spin2x, spin2y)
xi2 = primary_xi(mass1, mass2, spin1x, spin1y, spin2x, spin2y)
return chi_p_from_xi1_xi2(xi1, xi2) | [
"def",
"chi_p",
"(",
"mass1",
",",
"mass2",
",",
"spin1x",
",",
"spin1y",
",",
"spin2x",
",",
"spin2y",
")",
":",
"xi1",
"=",
"secondary_xi",
"(",
"mass1",
",",
"mass2",
",",
"spin1x",
",",
"spin1y",
",",
"spin2x",
",",
"spin2y",
")",
"xi2",
"=",
"... | Returns the effective precession spin from mass1, mass2, spin1x,
spin1y, spin2x, and spin2y. | [
"Returns",
"the",
"effective",
"precession",
"spin",
"from",
"mass1",
"mass2",
"spin1x",
"spin1y",
"spin2x",
"and",
"spin2y",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L425-L431 |
228,312 | gwastro/pycbc | pycbc/conversions.py | phi_a | def phi_a(mass1, mass2, spin1x, spin1y, spin2x, spin2y):
""" Returns the angle between the in-plane perpendicular spins."""
phi1 = phi_from_spinx_spiny(primary_spin(mass1, mass2, spin1x, spin2x),
primary_spin(mass1, mass2, spin1y, spin2y))
phi2 = phi_from_spinx_spiny(secondary_spin(mass1, mass2, spin1x, spin2x),
secondary_spin(mass1, mass2, spin1y, spin2y))
return (phi1 - phi2) % (2 * numpy.pi) | python | def phi_a(mass1, mass2, spin1x, spin1y, spin2x, spin2y):
phi1 = phi_from_spinx_spiny(primary_spin(mass1, mass2, spin1x, spin2x),
primary_spin(mass1, mass2, spin1y, spin2y))
phi2 = phi_from_spinx_spiny(secondary_spin(mass1, mass2, spin1x, spin2x),
secondary_spin(mass1, mass2, spin1y, spin2y))
return (phi1 - phi2) % (2 * numpy.pi) | [
"def",
"phi_a",
"(",
"mass1",
",",
"mass2",
",",
"spin1x",
",",
"spin1y",
",",
"spin2x",
",",
"spin2y",
")",
":",
"phi1",
"=",
"phi_from_spinx_spiny",
"(",
"primary_spin",
"(",
"mass1",
",",
"mass2",
",",
"spin1x",
",",
"spin2x",
")",
",",
"primary_spin"... | Returns the angle between the in-plane perpendicular spins. | [
"Returns",
"the",
"angle",
"between",
"the",
"in",
"-",
"plane",
"perpendicular",
"spins",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L434-L440 |
228,313 | gwastro/pycbc | pycbc/conversions.py | phi_s | def phi_s(spin1x, spin1y, spin2x, spin2y):
""" Returns the sum of the in-plane perpendicular spins."""
phi1 = phi_from_spinx_spiny(spin1x, spin1y)
phi2 = phi_from_spinx_spiny(spin2x, spin2y)
return (phi1 + phi2) % (2 * numpy.pi) | python | def phi_s(spin1x, spin1y, spin2x, spin2y):
phi1 = phi_from_spinx_spiny(spin1x, spin1y)
phi2 = phi_from_spinx_spiny(spin2x, spin2y)
return (phi1 + phi2) % (2 * numpy.pi) | [
"def",
"phi_s",
"(",
"spin1x",
",",
"spin1y",
",",
"spin2x",
",",
"spin2y",
")",
":",
"phi1",
"=",
"phi_from_spinx_spiny",
"(",
"spin1x",
",",
"spin1y",
")",
"phi2",
"=",
"phi_from_spinx_spiny",
"(",
"spin2x",
",",
"spin2y",
")",
"return",
"(",
"phi1",
"... | Returns the sum of the in-plane perpendicular spins. | [
"Returns",
"the",
"sum",
"of",
"the",
"in",
"-",
"plane",
"perpendicular",
"spins",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L443-L447 |
228,314 | gwastro/pycbc | pycbc/conversions.py | chi_eff_from_spherical | def chi_eff_from_spherical(mass1, mass2, spin1_a, spin1_polar,
spin2_a, spin2_polar):
"""Returns the effective spin using spins in spherical coordinates."""
spin1z = spin1_a * numpy.cos(spin1_polar)
spin2z = spin2_a * numpy.cos(spin2_polar)
return chi_eff(mass1, mass2, spin1z, spin2z) | python | def chi_eff_from_spherical(mass1, mass2, spin1_a, spin1_polar,
spin2_a, spin2_polar):
spin1z = spin1_a * numpy.cos(spin1_polar)
spin2z = spin2_a * numpy.cos(spin2_polar)
return chi_eff(mass1, mass2, spin1z, spin2z) | [
"def",
"chi_eff_from_spherical",
"(",
"mass1",
",",
"mass2",
",",
"spin1_a",
",",
"spin1_polar",
",",
"spin2_a",
",",
"spin2_polar",
")",
":",
"spin1z",
"=",
"spin1_a",
"*",
"numpy",
".",
"cos",
"(",
"spin1_polar",
")",
"spin2z",
"=",
"spin2_a",
"*",
"nump... | Returns the effective spin using spins in spherical coordinates. | [
"Returns",
"the",
"effective",
"spin",
"using",
"spins",
"in",
"spherical",
"coordinates",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L450-L455 |
228,315 | gwastro/pycbc | pycbc/conversions.py | chi_p_from_spherical | def chi_p_from_spherical(mass1, mass2, spin1_a, spin1_azimuthal, spin1_polar,
spin2_a, spin2_azimuthal, spin2_polar):
"""Returns the effective precession spin using spins in spherical
coordinates.
"""
spin1x, spin1y, _ = _spherical_to_cartesian(
spin1_a, spin1_azimuthal, spin1_polar)
spin2x, spin2y, _ = _spherical_to_cartesian(
spin2_a, spin2_azimuthal, spin2_polar)
return chi_p(mass1, mass2, spin1x, spin1y, spin2x, spin2y) | python | def chi_p_from_spherical(mass1, mass2, spin1_a, spin1_azimuthal, spin1_polar,
spin2_a, spin2_azimuthal, spin2_polar):
spin1x, spin1y, _ = _spherical_to_cartesian(
spin1_a, spin1_azimuthal, spin1_polar)
spin2x, spin2y, _ = _spherical_to_cartesian(
spin2_a, spin2_azimuthal, spin2_polar)
return chi_p(mass1, mass2, spin1x, spin1y, spin2x, spin2y) | [
"def",
"chi_p_from_spherical",
"(",
"mass1",
",",
"mass2",
",",
"spin1_a",
",",
"spin1_azimuthal",
",",
"spin1_polar",
",",
"spin2_a",
",",
"spin2_azimuthal",
",",
"spin2_polar",
")",
":",
"spin1x",
",",
"spin1y",
",",
"_",
"=",
"_spherical_to_cartesian",
"(",
... | Returns the effective precession spin using spins in spherical
coordinates. | [
"Returns",
"the",
"effective",
"precession",
"spin",
"using",
"spins",
"in",
"spherical",
"coordinates",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L458-L467 |
228,316 | gwastro/pycbc | pycbc/conversions.py | primary_spin | def primary_spin(mass1, mass2, spin1, spin2):
"""Returns the dimensionless spin of the primary mass."""
mass1, mass2, spin1, spin2, input_is_array = ensurearray(
mass1, mass2, spin1, spin2)
sp = copy.copy(spin1)
mask = mass1 < mass2
sp[mask] = spin2[mask]
return formatreturn(sp, input_is_array) | python | def primary_spin(mass1, mass2, spin1, spin2):
mass1, mass2, spin1, spin2, input_is_array = ensurearray(
mass1, mass2, spin1, spin2)
sp = copy.copy(spin1)
mask = mass1 < mass2
sp[mask] = spin2[mask]
return formatreturn(sp, input_is_array) | [
"def",
"primary_spin",
"(",
"mass1",
",",
"mass2",
",",
"spin1",
",",
"spin2",
")",
":",
"mass1",
",",
"mass2",
",",
"spin1",
",",
"spin2",
",",
"input_is_array",
"=",
"ensurearray",
"(",
"mass1",
",",
"mass2",
",",
"spin1",
",",
"spin2",
")",
"sp",
... | Returns the dimensionless spin of the primary mass. | [
"Returns",
"the",
"dimensionless",
"spin",
"of",
"the",
"primary",
"mass",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L470-L477 |
228,317 | gwastro/pycbc | pycbc/conversions.py | secondary_spin | def secondary_spin(mass1, mass2, spin1, spin2):
"""Returns the dimensionless spin of the secondary mass."""
mass1, mass2, spin1, spin2, input_is_array = ensurearray(
mass1, mass2, spin1, spin2)
ss = copy.copy(spin2)
mask = mass1 < mass2
ss[mask] = spin1[mask]
return formatreturn(ss, input_is_array) | python | def secondary_spin(mass1, mass2, spin1, spin2):
mass1, mass2, spin1, spin2, input_is_array = ensurearray(
mass1, mass2, spin1, spin2)
ss = copy.copy(spin2)
mask = mass1 < mass2
ss[mask] = spin1[mask]
return formatreturn(ss, input_is_array) | [
"def",
"secondary_spin",
"(",
"mass1",
",",
"mass2",
",",
"spin1",
",",
"spin2",
")",
":",
"mass1",
",",
"mass2",
",",
"spin1",
",",
"spin2",
",",
"input_is_array",
"=",
"ensurearray",
"(",
"mass1",
",",
"mass2",
",",
"spin1",
",",
"spin2",
")",
"ss",
... | Returns the dimensionless spin of the secondary mass. | [
"Returns",
"the",
"dimensionless",
"spin",
"of",
"the",
"secondary",
"mass",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L480-L487 |
228,318 | gwastro/pycbc | pycbc/conversions.py | primary_xi | def primary_xi(mass1, mass2, spin1x, spin1y, spin2x, spin2y):
"""Returns the effective precession spin argument for the larger mass.
"""
spinx = primary_spin(mass1, mass2, spin1x, spin2x)
spiny = primary_spin(mass1, mass2, spin1y, spin2y)
return chi_perp_from_spinx_spiny(spinx, spiny) | python | def primary_xi(mass1, mass2, spin1x, spin1y, spin2x, spin2y):
spinx = primary_spin(mass1, mass2, spin1x, spin2x)
spiny = primary_spin(mass1, mass2, spin1y, spin2y)
return chi_perp_from_spinx_spiny(spinx, spiny) | [
"def",
"primary_xi",
"(",
"mass1",
",",
"mass2",
",",
"spin1x",
",",
"spin1y",
",",
"spin2x",
",",
"spin2y",
")",
":",
"spinx",
"=",
"primary_spin",
"(",
"mass1",
",",
"mass2",
",",
"spin1x",
",",
"spin2x",
")",
"spiny",
"=",
"primary_spin",
"(",
"mass... | Returns the effective precession spin argument for the larger mass. | [
"Returns",
"the",
"effective",
"precession",
"spin",
"argument",
"for",
"the",
"larger",
"mass",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L490-L495 |
228,319 | gwastro/pycbc | pycbc/conversions.py | secondary_xi | def secondary_xi(mass1, mass2, spin1x, spin1y, spin2x, spin2y):
"""Returns the effective precession spin argument for the smaller mass.
"""
spinx = secondary_spin(mass1, mass2, spin1x, spin2x)
spiny = secondary_spin(mass1, mass2, spin1y, spin2y)
return xi2_from_mass1_mass2_spin2x_spin2y(mass1, mass2, spinx, spiny) | python | def secondary_xi(mass1, mass2, spin1x, spin1y, spin2x, spin2y):
spinx = secondary_spin(mass1, mass2, spin1x, spin2x)
spiny = secondary_spin(mass1, mass2, spin1y, spin2y)
return xi2_from_mass1_mass2_spin2x_spin2y(mass1, mass2, spinx, spiny) | [
"def",
"secondary_xi",
"(",
"mass1",
",",
"mass2",
",",
"spin1x",
",",
"spin1y",
",",
"spin2x",
",",
"spin2y",
")",
":",
"spinx",
"=",
"secondary_spin",
"(",
"mass1",
",",
"mass2",
",",
"spin1x",
",",
"spin2x",
")",
"spiny",
"=",
"secondary_spin",
"(",
... | Returns the effective precession spin argument for the smaller mass. | [
"Returns",
"the",
"effective",
"precession",
"spin",
"argument",
"for",
"the",
"smaller",
"mass",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L498-L503 |
228,320 | gwastro/pycbc | pycbc/conversions.py | xi2_from_mass1_mass2_spin2x_spin2y | def xi2_from_mass1_mass2_spin2x_spin2y(mass1, mass2, spin2x, spin2y):
"""Returns the effective precession spin argument for the smaller mass.
This function assumes it's given spins of the secondary mass.
"""
q = q_from_mass1_mass2(mass1, mass2)
a1 = 2 + 3 * q / 2
a2 = 2 + 3 / (2 * q)
return a1 / (q**2 * a2) * chi_perp_from_spinx_spiny(spin2x, spin2y) | python | def xi2_from_mass1_mass2_spin2x_spin2y(mass1, mass2, spin2x, spin2y):
q = q_from_mass1_mass2(mass1, mass2)
a1 = 2 + 3 * q / 2
a2 = 2 + 3 / (2 * q)
return a1 / (q**2 * a2) * chi_perp_from_spinx_spiny(spin2x, spin2y) | [
"def",
"xi2_from_mass1_mass2_spin2x_spin2y",
"(",
"mass1",
",",
"mass2",
",",
"spin2x",
",",
"spin2y",
")",
":",
"q",
"=",
"q_from_mass1_mass2",
"(",
"mass1",
",",
"mass2",
")",
"a1",
"=",
"2",
"+",
"3",
"*",
"q",
"/",
"2",
"a2",
"=",
"2",
"+",
"3",
... | Returns the effective precession spin argument for the smaller mass.
This function assumes it's given spins of the secondary mass. | [
"Returns",
"the",
"effective",
"precession",
"spin",
"argument",
"for",
"the",
"smaller",
"mass",
".",
"This",
"function",
"assumes",
"it",
"s",
"given",
"spins",
"of",
"the",
"secondary",
"mass",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L513-L520 |
228,321 | gwastro/pycbc | pycbc/conversions.py | chi_perp_from_mass1_mass2_xi2 | def chi_perp_from_mass1_mass2_xi2(mass1, mass2, xi2):
"""Returns the in-plane spin from mass1, mass2, and xi2 for the
secondary mass.
"""
q = q_from_mass1_mass2(mass1, mass2)
a1 = 2 + 3 * q / 2
a2 = 2 + 3 / (2 * q)
return q**2 * a2 / a1 * xi2 | python | def chi_perp_from_mass1_mass2_xi2(mass1, mass2, xi2):
q = q_from_mass1_mass2(mass1, mass2)
a1 = 2 + 3 * q / 2
a2 = 2 + 3 / (2 * q)
return q**2 * a2 / a1 * xi2 | [
"def",
"chi_perp_from_mass1_mass2_xi2",
"(",
"mass1",
",",
"mass2",
",",
"xi2",
")",
":",
"q",
"=",
"q_from_mass1_mass2",
"(",
"mass1",
",",
"mass2",
")",
"a1",
"=",
"2",
"+",
"3",
"*",
"q",
"/",
"2",
"a2",
"=",
"2",
"+",
"3",
"/",
"(",
"2",
"*",... | Returns the in-plane spin from mass1, mass2, and xi2 for the
secondary mass. | [
"Returns",
"the",
"in",
"-",
"plane",
"spin",
"from",
"mass1",
"mass2",
"and",
"xi2",
"for",
"the",
"secondary",
"mass",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L529-L536 |
228,322 | gwastro/pycbc | pycbc/conversions.py | chi_p_from_xi1_xi2 | def chi_p_from_xi1_xi2(xi1, xi2):
"""Returns effective precession spin from xi1 and xi2.
"""
xi1, xi2, input_is_array = ensurearray(xi1, xi2)
chi_p = copy.copy(xi1)
mask = xi1 < xi2
chi_p[mask] = xi2[mask]
return formatreturn(chi_p, input_is_array) | python | def chi_p_from_xi1_xi2(xi1, xi2):
xi1, xi2, input_is_array = ensurearray(xi1, xi2)
chi_p = copy.copy(xi1)
mask = xi1 < xi2
chi_p[mask] = xi2[mask]
return formatreturn(chi_p, input_is_array) | [
"def",
"chi_p_from_xi1_xi2",
"(",
"xi1",
",",
"xi2",
")",
":",
"xi1",
",",
"xi2",
",",
"input_is_array",
"=",
"ensurearray",
"(",
"xi1",
",",
"xi2",
")",
"chi_p",
"=",
"copy",
".",
"copy",
"(",
"xi1",
")",
"mask",
"=",
"xi1",
"<",
"xi2",
"chi_p",
"... | Returns effective precession spin from xi1 and xi2. | [
"Returns",
"effective",
"precession",
"spin",
"from",
"xi1",
"and",
"xi2",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L539-L546 |
228,323 | gwastro/pycbc | pycbc/conversions.py | phi_from_spinx_spiny | def phi_from_spinx_spiny(spinx, spiny):
"""Returns the angle between the x-component axis and the in-plane spin.
"""
phi = numpy.arctan2(spiny, spinx)
return phi % (2 * numpy.pi) | python | def phi_from_spinx_spiny(spinx, spiny):
phi = numpy.arctan2(spiny, spinx)
return phi % (2 * numpy.pi) | [
"def",
"phi_from_spinx_spiny",
"(",
"spinx",
",",
"spiny",
")",
":",
"phi",
"=",
"numpy",
".",
"arctan2",
"(",
"spiny",
",",
"spinx",
")",
"return",
"phi",
"%",
"(",
"2",
"*",
"numpy",
".",
"pi",
")"
] | Returns the angle between the x-component axis and the in-plane spin. | [
"Returns",
"the",
"angle",
"between",
"the",
"x",
"-",
"component",
"axis",
"and",
"the",
"in",
"-",
"plane",
"spin",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L563-L567 |
228,324 | gwastro/pycbc | pycbc/conversions.py | spin1z_from_mass1_mass2_chi_eff_chi_a | def spin1z_from_mass1_mass2_chi_eff_chi_a(mass1, mass2, chi_eff, chi_a):
"""Returns spin1z.
"""
return (mass1 + mass2) / (2.0 * mass1) * (chi_eff - chi_a) | python | def spin1z_from_mass1_mass2_chi_eff_chi_a(mass1, mass2, chi_eff, chi_a):
return (mass1 + mass2) / (2.0 * mass1) * (chi_eff - chi_a) | [
"def",
"spin1z_from_mass1_mass2_chi_eff_chi_a",
"(",
"mass1",
",",
"mass2",
",",
"chi_eff",
",",
"chi_a",
")",
":",
"return",
"(",
"mass1",
"+",
"mass2",
")",
"/",
"(",
"2.0",
"*",
"mass1",
")",
"*",
"(",
"chi_eff",
"-",
"chi_a",
")"
] | Returns spin1z. | [
"Returns",
"spin1z",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L570-L573 |
228,325 | gwastro/pycbc | pycbc/conversions.py | spin2z_from_mass1_mass2_chi_eff_chi_a | def spin2z_from_mass1_mass2_chi_eff_chi_a(mass1, mass2, chi_eff, chi_a):
"""Returns spin2z.
"""
return (mass1 + mass2) / (2.0 * mass2) * (chi_eff + chi_a) | python | def spin2z_from_mass1_mass2_chi_eff_chi_a(mass1, mass2, chi_eff, chi_a):
return (mass1 + mass2) / (2.0 * mass2) * (chi_eff + chi_a) | [
"def",
"spin2z_from_mass1_mass2_chi_eff_chi_a",
"(",
"mass1",
",",
"mass2",
",",
"chi_eff",
",",
"chi_a",
")",
":",
"return",
"(",
"mass1",
"+",
"mass2",
")",
"/",
"(",
"2.0",
"*",
"mass2",
")",
"*",
"(",
"chi_eff",
"+",
"chi_a",
")"
] | Returns spin2z. | [
"Returns",
"spin2z",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L576-L579 |
228,326 | gwastro/pycbc | pycbc/conversions.py | spin1x_from_xi1_phi_a_phi_s | def spin1x_from_xi1_phi_a_phi_s(xi1, phi_a, phi_s):
"""Returns x-component spin for primary mass.
"""
phi1 = phi1_from_phi_a_phi_s(phi_a, phi_s)
return xi1 * numpy.cos(phi1) | python | def spin1x_from_xi1_phi_a_phi_s(xi1, phi_a, phi_s):
phi1 = phi1_from_phi_a_phi_s(phi_a, phi_s)
return xi1 * numpy.cos(phi1) | [
"def",
"spin1x_from_xi1_phi_a_phi_s",
"(",
"xi1",
",",
"phi_a",
",",
"phi_s",
")",
":",
"phi1",
"=",
"phi1_from_phi_a_phi_s",
"(",
"phi_a",
",",
"phi_s",
")",
"return",
"xi1",
"*",
"numpy",
".",
"cos",
"(",
"phi1",
")"
] | Returns x-component spin for primary mass. | [
"Returns",
"x",
"-",
"component",
"spin",
"for",
"primary",
"mass",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L582-L586 |
228,327 | gwastro/pycbc | pycbc/conversions.py | spin1y_from_xi1_phi_a_phi_s | def spin1y_from_xi1_phi_a_phi_s(xi1, phi_a, phi_s):
"""Returns y-component spin for primary mass.
"""
phi1 = phi1_from_phi_a_phi_s(phi_s, phi_a)
return xi1 * numpy.sin(phi1) | python | def spin1y_from_xi1_phi_a_phi_s(xi1, phi_a, phi_s):
phi1 = phi1_from_phi_a_phi_s(phi_s, phi_a)
return xi1 * numpy.sin(phi1) | [
"def",
"spin1y_from_xi1_phi_a_phi_s",
"(",
"xi1",
",",
"phi_a",
",",
"phi_s",
")",
":",
"phi1",
"=",
"phi1_from_phi_a_phi_s",
"(",
"phi_s",
",",
"phi_a",
")",
"return",
"xi1",
"*",
"numpy",
".",
"sin",
"(",
"phi1",
")"
] | Returns y-component spin for primary mass. | [
"Returns",
"y",
"-",
"component",
"spin",
"for",
"primary",
"mass",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L589-L593 |
228,328 | gwastro/pycbc | pycbc/conversions.py | spin2x_from_mass1_mass2_xi2_phi_a_phi_s | def spin2x_from_mass1_mass2_xi2_phi_a_phi_s(mass1, mass2, xi2, phi_a, phi_s):
"""Returns x-component spin for secondary mass.
"""
chi_perp = chi_perp_from_mass1_mass2_xi2(mass1, mass2, xi2)
phi2 = phi2_from_phi_a_phi_s(phi_a, phi_s)
return chi_perp * numpy.cos(phi2) | python | def spin2x_from_mass1_mass2_xi2_phi_a_phi_s(mass1, mass2, xi2, phi_a, phi_s):
chi_perp = chi_perp_from_mass1_mass2_xi2(mass1, mass2, xi2)
phi2 = phi2_from_phi_a_phi_s(phi_a, phi_s)
return chi_perp * numpy.cos(phi2) | [
"def",
"spin2x_from_mass1_mass2_xi2_phi_a_phi_s",
"(",
"mass1",
",",
"mass2",
",",
"xi2",
",",
"phi_a",
",",
"phi_s",
")",
":",
"chi_perp",
"=",
"chi_perp_from_mass1_mass2_xi2",
"(",
"mass1",
",",
"mass2",
",",
"xi2",
")",
"phi2",
"=",
"phi2_from_phi_a_phi_s",
"... | Returns x-component spin for secondary mass. | [
"Returns",
"x",
"-",
"component",
"spin",
"for",
"secondary",
"mass",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L596-L601 |
228,329 | gwastro/pycbc | pycbc/conversions.py | spin2y_from_mass1_mass2_xi2_phi_a_phi_s | def spin2y_from_mass1_mass2_xi2_phi_a_phi_s(mass1, mass2, xi2, phi_a, phi_s):
"""Returns y-component spin for secondary mass.
"""
chi_perp = chi_perp_from_mass1_mass2_xi2(mass1, mass2, xi2)
phi2 = phi2_from_phi_a_phi_s(phi_a, phi_s)
return chi_perp * numpy.sin(phi2) | python | def spin2y_from_mass1_mass2_xi2_phi_a_phi_s(mass1, mass2, xi2, phi_a, phi_s):
chi_perp = chi_perp_from_mass1_mass2_xi2(mass1, mass2, xi2)
phi2 = phi2_from_phi_a_phi_s(phi_a, phi_s)
return chi_perp * numpy.sin(phi2) | [
"def",
"spin2y_from_mass1_mass2_xi2_phi_a_phi_s",
"(",
"mass1",
",",
"mass2",
",",
"xi2",
",",
"phi_a",
",",
"phi_s",
")",
":",
"chi_perp",
"=",
"chi_perp_from_mass1_mass2_xi2",
"(",
"mass1",
",",
"mass2",
",",
"xi2",
")",
"phi2",
"=",
"phi2_from_phi_a_phi_s",
"... | Returns y-component spin for secondary mass. | [
"Returns",
"y",
"-",
"component",
"spin",
"for",
"secondary",
"mass",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L604-L609 |
228,330 | gwastro/pycbc | pycbc/conversions.py | dquadmon_from_lambda | def dquadmon_from_lambda(lambdav):
r"""Return the quadrupole moment of a neutron star given its lambda
We use the relations defined here. https://arxiv.org/pdf/1302.4499.pdf.
Note that the convention we use is that:
.. math::
\mathrm{dquadmon} = \bar{Q} - 1.
Where :math:`\bar{Q}` (dimensionless) is the reduced quadrupole moment.
"""
ll = numpy.log(lambdav)
ai = .194
bi = .0936
ci = 0.0474
di = -4.21 * 10**-3.0
ei = 1.23 * 10**-4.0
ln_quad_moment = ai + bi*ll + ci*ll**2.0 + di*ll**3.0 + ei*ll**4.0
return numpy.exp(ln_quad_moment) - 1 | python | def dquadmon_from_lambda(lambdav):
r"""Return the quadrupole moment of a neutron star given its lambda
We use the relations defined here. https://arxiv.org/pdf/1302.4499.pdf.
Note that the convention we use is that:
.. math::
\mathrm{dquadmon} = \bar{Q} - 1.
Where :math:`\bar{Q}` (dimensionless) is the reduced quadrupole moment.
"""
ll = numpy.log(lambdav)
ai = .194
bi = .0936
ci = 0.0474
di = -4.21 * 10**-3.0
ei = 1.23 * 10**-4.0
ln_quad_moment = ai + bi*ll + ci*ll**2.0 + di*ll**3.0 + ei*ll**4.0
return numpy.exp(ln_quad_moment) - 1 | [
"def",
"dquadmon_from_lambda",
"(",
"lambdav",
")",
":",
"ll",
"=",
"numpy",
".",
"log",
"(",
"lambdav",
")",
"ai",
"=",
".194",
"bi",
"=",
".0936",
"ci",
"=",
"0.0474",
"di",
"=",
"-",
"4.21",
"*",
"10",
"**",
"-",
"3.0",
"ei",
"=",
"1.23",
"*",... | r"""Return the quadrupole moment of a neutron star given its lambda
We use the relations defined here. https://arxiv.org/pdf/1302.4499.pdf.
Note that the convention we use is that:
.. math::
\mathrm{dquadmon} = \bar{Q} - 1.
Where :math:`\bar{Q}` (dimensionless) is the reduced quadrupole moment. | [
"r",
"Return",
"the",
"quadrupole",
"moment",
"of",
"a",
"neutron",
"star",
"given",
"its",
"lambda"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L612-L631 |
228,331 | gwastro/pycbc | pycbc/conversions.py | _det_tc | def _det_tc(detector_name, ra, dec, tc, ref_frame='geocentric'):
"""Returns the coalescence time of a signal in the given detector.
Parameters
----------
detector_name : string
The name of the detector, e.g., 'H1'.
ra : float
The right ascension of the signal, in radians.
dec : float
The declination of the signal, in radians.
tc : float
The GPS time of the coalescence of the signal in the `ref_frame`.
ref_frame : {'geocentric', string}
The reference frame that the given coalescence time is defined in.
May specify 'geocentric', or a detector name; default is 'geocentric'.
Returns
-------
float :
The GPS time of the coalescence in detector `detector_name`.
"""
if ref_frame == detector_name:
return tc
detector = Detector(detector_name)
if ref_frame == 'geocentric':
return tc + detector.time_delay_from_earth_center(ra, dec, tc)
else:
other = Detector(ref_frame)
return tc + detector.time_delay_from_detector(other, ra, dec, tc) | python | def _det_tc(detector_name, ra, dec, tc, ref_frame='geocentric'):
if ref_frame == detector_name:
return tc
detector = Detector(detector_name)
if ref_frame == 'geocentric':
return tc + detector.time_delay_from_earth_center(ra, dec, tc)
else:
other = Detector(ref_frame)
return tc + detector.time_delay_from_detector(other, ra, dec, tc) | [
"def",
"_det_tc",
"(",
"detector_name",
",",
"ra",
",",
"dec",
",",
"tc",
",",
"ref_frame",
"=",
"'geocentric'",
")",
":",
"if",
"ref_frame",
"==",
"detector_name",
":",
"return",
"tc",
"detector",
"=",
"Detector",
"(",
"detector_name",
")",
"if",
"ref_fra... | Returns the coalescence time of a signal in the given detector.
Parameters
----------
detector_name : string
The name of the detector, e.g., 'H1'.
ra : float
The right ascension of the signal, in radians.
dec : float
The declination of the signal, in radians.
tc : float
The GPS time of the coalescence of the signal in the `ref_frame`.
ref_frame : {'geocentric', string}
The reference frame that the given coalescence time is defined in.
May specify 'geocentric', or a detector name; default is 'geocentric'.
Returns
-------
float :
The GPS time of the coalescence in detector `detector_name`. | [
"Returns",
"the",
"coalescence",
"time",
"of",
"a",
"signal",
"in",
"the",
"given",
"detector",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L652-L681 |
228,332 | gwastro/pycbc | pycbc/conversions.py | _optimal_orientation_from_detector | def _optimal_orientation_from_detector(detector_name, tc):
""" Low-level function to be called from _optimal_dec_from_detector
and _optimal_ra_from_detector"""
d = Detector(detector_name)
ra, dec = d.optimal_orientation(tc)
return ra, dec | python | def _optimal_orientation_from_detector(detector_name, tc):
d = Detector(detector_name)
ra, dec = d.optimal_orientation(tc)
return ra, dec | [
"def",
"_optimal_orientation_from_detector",
"(",
"detector_name",
",",
"tc",
")",
":",
"d",
"=",
"Detector",
"(",
"detector_name",
")",
"ra",
",",
"dec",
"=",
"d",
".",
"optimal_orientation",
"(",
"tc",
")",
"return",
"ra",
",",
"dec"
] | Low-level function to be called from _optimal_dec_from_detector
and _optimal_ra_from_detector | [
"Low",
"-",
"level",
"function",
"to",
"be",
"called",
"from",
"_optimal_dec_from_detector",
"and",
"_optimal_ra_from_detector"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L685-L692 |
228,333 | gwastro/pycbc | pycbc/conversions.py | _genqnmfreq | def _genqnmfreq(mass, spin, l, m, nmodes, qnmfreq=None):
"""Convenience function to generate QNM frequencies from lalsimulation.
Parameters
----------
mass : float
The mass of the black hole (in solar masses).
spin : float
The dimensionless spin of the black hole.
l : int
l-index of the harmonic.
m : int
m-index of the harmonic.
nmodes : int
The number of overtones to generate.
qnmfreq : lal.COMPLEX16Vector, optional
LAL vector to write the results into. Must be the same length as
``nmodes``. If None, will create one.
Returns
-------
lal.COMPLEX16Vector
LAL vector containing the complex QNM frequencies.
"""
if qnmfreq is None:
qnmfreq = lal.CreateCOMPLEX16Vector(int(nmodes))
lalsim.SimIMREOBGenerateQNMFreqV2fromFinal(
qnmfreq, float(mass), float(spin), int(l), int(m), int(nmodes))
return qnmfreq | python | def _genqnmfreq(mass, spin, l, m, nmodes, qnmfreq=None):
if qnmfreq is None:
qnmfreq = lal.CreateCOMPLEX16Vector(int(nmodes))
lalsim.SimIMREOBGenerateQNMFreqV2fromFinal(
qnmfreq, float(mass), float(spin), int(l), int(m), int(nmodes))
return qnmfreq | [
"def",
"_genqnmfreq",
"(",
"mass",
",",
"spin",
",",
"l",
",",
"m",
",",
"nmodes",
",",
"qnmfreq",
"=",
"None",
")",
":",
"if",
"qnmfreq",
"is",
"None",
":",
"qnmfreq",
"=",
"lal",
".",
"CreateCOMPLEX16Vector",
"(",
"int",
"(",
"nmodes",
")",
")",
... | Convenience function to generate QNM frequencies from lalsimulation.
Parameters
----------
mass : float
The mass of the black hole (in solar masses).
spin : float
The dimensionless spin of the black hole.
l : int
l-index of the harmonic.
m : int
m-index of the harmonic.
nmodes : int
The number of overtones to generate.
qnmfreq : lal.COMPLEX16Vector, optional
LAL vector to write the results into. Must be the same length as
``nmodes``. If None, will create one.
Returns
-------
lal.COMPLEX16Vector
LAL vector containing the complex QNM frequencies. | [
"Convenience",
"function",
"to",
"generate",
"QNM",
"frequencies",
"from",
"lalsimulation",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L781-L809 |
228,334 | gwastro/pycbc | pycbc/conversions.py | get_lm_f0tau | def get_lm_f0tau(mass, spin, l, m, nmodes):
"""Return the f0 and the tau of each overtone for a given l, m mode.
Parameters
----------
mass : float or array
Mass of the black hole (in solar masses).
spin : float or array
Dimensionless spin of the final black hole.
l : int or array
l-index of the harmonic.
m : int or array
m-index of the harmonic.
nmodes : int
The number of overtones to generate.
Returns
-------
f0 : float or array
The frequency of the QNM(s), in Hz. If only a single mode is requested
(and mass, spin, l, and m are not arrays), this will be a float. If
multiple modes requested, will be an array with shape
``[input shape x] nmodes``, where ``input shape`` is the broadcasted
shape of the inputs.
tau : float or array
The damping time of the QNM(s), in seconds. Return type is same as f0.
"""
# convert to arrays
mass, spin, l, m, input_is_array = ensurearray(
mass, spin, l, m)
# we'll ravel the arrays so we can evaluate each parameter combination
# one at a a time
origshape = mass.shape
if nmodes < 1:
raise ValueError("nmodes must be >= 1")
if nmodes > 1:
newshape = tuple(list(origshape)+[nmodes])
else:
newshape = origshape
f0s = numpy.zeros((mass.size, nmodes))
taus = numpy.zeros((mass.size, nmodes))
mass = mass.ravel()
spin = spin.ravel()
l = l.ravel()
m = m.ravel()
qnmfreq = None
modes = range(nmodes)
for ii in range(mass.size):
qnmfreq = _genqnmfreq(mass[ii], spin[ii], l[ii], m[ii], nmodes,
qnmfreq=qnmfreq)
f0s[ii, :] = [qnmfreq.data[n].real/(2 * numpy.pi) for n in modes]
taus[ii, :] = [1./qnmfreq.data[n].imag for n in modes]
f0s = f0s.reshape(newshape)
taus = taus.reshape(newshape)
return (formatreturn(f0s, input_is_array),
formatreturn(taus, input_is_array)) | python | def get_lm_f0tau(mass, spin, l, m, nmodes):
# convert to arrays
mass, spin, l, m, input_is_array = ensurearray(
mass, spin, l, m)
# we'll ravel the arrays so we can evaluate each parameter combination
# one at a a time
origshape = mass.shape
if nmodes < 1:
raise ValueError("nmodes must be >= 1")
if nmodes > 1:
newshape = tuple(list(origshape)+[nmodes])
else:
newshape = origshape
f0s = numpy.zeros((mass.size, nmodes))
taus = numpy.zeros((mass.size, nmodes))
mass = mass.ravel()
spin = spin.ravel()
l = l.ravel()
m = m.ravel()
qnmfreq = None
modes = range(nmodes)
for ii in range(mass.size):
qnmfreq = _genqnmfreq(mass[ii], spin[ii], l[ii], m[ii], nmodes,
qnmfreq=qnmfreq)
f0s[ii, :] = [qnmfreq.data[n].real/(2 * numpy.pi) for n in modes]
taus[ii, :] = [1./qnmfreq.data[n].imag for n in modes]
f0s = f0s.reshape(newshape)
taus = taus.reshape(newshape)
return (formatreturn(f0s, input_is_array),
formatreturn(taus, input_is_array)) | [
"def",
"get_lm_f0tau",
"(",
"mass",
",",
"spin",
",",
"l",
",",
"m",
",",
"nmodes",
")",
":",
"# convert to arrays",
"mass",
",",
"spin",
",",
"l",
",",
"m",
",",
"input_is_array",
"=",
"ensurearray",
"(",
"mass",
",",
"spin",
",",
"l",
",",
"m",
"... | Return the f0 and the tau of each overtone for a given l, m mode.
Parameters
----------
mass : float or array
Mass of the black hole (in solar masses).
spin : float or array
Dimensionless spin of the final black hole.
l : int or array
l-index of the harmonic.
m : int or array
m-index of the harmonic.
nmodes : int
The number of overtones to generate.
Returns
-------
f0 : float or array
The frequency of the QNM(s), in Hz. If only a single mode is requested
(and mass, spin, l, and m are not arrays), this will be a float. If
multiple modes requested, will be an array with shape
``[input shape x] nmodes``, where ``input shape`` is the broadcasted
shape of the inputs.
tau : float or array
The damping time of the QNM(s), in seconds. Return type is same as f0. | [
"Return",
"the",
"f0",
"and",
"the",
"tau",
"of",
"each",
"overtone",
"for",
"a",
"given",
"l",
"m",
"mode",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L812-L867 |
228,335 | gwastro/pycbc | pycbc/conversions.py | get_lm_f0tau_allmodes | def get_lm_f0tau_allmodes(mass, spin, modes):
"""Returns a dictionary of all of the frequencies and damping times for the
requested modes.
Parameters
----------
mass : float or array
Mass of the black hole (in solar masses).
spin : float or array
Dimensionless spin of the final black hole.
modes : list of str
The modes to get. Each string in the list should be formatted 'lmN',
where l (m) is the l (m) index of the harmonic and N is the number of
overtones to generate (note, N is not the index of the overtone). For
example, '221' will generate the 0th overtone of the l = m = 2 mode.
Returns
-------
f0 : dict
Dictionary mapping the modes to the frequencies. The dictionary keys
are 'lmn' string, where l (m) is the l (m) index of the harmonic and
n is the index of the overtone. For example, '220' is the l = m = 2
mode and the 0th overtone.
tau : dict
Dictionary mapping the modes to the damping times. The keys are the
same as ``f0``.
"""
f0, tau = {}, {}
key = '{}{}{}'
for lmn in modes:
l, m, nmodes = int(lmn[0]), int(lmn[1]), int(lmn[2])
tmp_f0, tmp_tau = get_lm_f0tau(mass, spin, l, m, nmodes)
if nmodes == 1:
# in this case, tmp_f0 and tmp_tau will just be floats
f0[key.format(l, m, '0')] = tmp_f0
tau[key.format(l, m, '0')] = tmp_tau
else:
for n in range(nmodes):
# we need to wrap tmp_f0 with formatreturn to ensure that if
# only a mass, spin pair was requested, the value stored to
# the dict is a float
f0[key.format(l, m, n)] = formatreturn(tmp_f0[..., n])
tau[key.format(l, m, n)] = formatreturn(tmp_tau[..., n])
return f0, tau | python | def get_lm_f0tau_allmodes(mass, spin, modes):
f0, tau = {}, {}
key = '{}{}{}'
for lmn in modes:
l, m, nmodes = int(lmn[0]), int(lmn[1]), int(lmn[2])
tmp_f0, tmp_tau = get_lm_f0tau(mass, spin, l, m, nmodes)
if nmodes == 1:
# in this case, tmp_f0 and tmp_tau will just be floats
f0[key.format(l, m, '0')] = tmp_f0
tau[key.format(l, m, '0')] = tmp_tau
else:
for n in range(nmodes):
# we need to wrap tmp_f0 with formatreturn to ensure that if
# only a mass, spin pair was requested, the value stored to
# the dict is a float
f0[key.format(l, m, n)] = formatreturn(tmp_f0[..., n])
tau[key.format(l, m, n)] = formatreturn(tmp_tau[..., n])
return f0, tau | [
"def",
"get_lm_f0tau_allmodes",
"(",
"mass",
",",
"spin",
",",
"modes",
")",
":",
"f0",
",",
"tau",
"=",
"{",
"}",
",",
"{",
"}",
"key",
"=",
"'{}{}{}'",
"for",
"lmn",
"in",
"modes",
":",
"l",
",",
"m",
",",
"nmodes",
"=",
"int",
"(",
"lmn",
"[... | Returns a dictionary of all of the frequencies and damping times for the
requested modes.
Parameters
----------
mass : float or array
Mass of the black hole (in solar masses).
spin : float or array
Dimensionless spin of the final black hole.
modes : list of str
The modes to get. Each string in the list should be formatted 'lmN',
where l (m) is the l (m) index of the harmonic and N is the number of
overtones to generate (note, N is not the index of the overtone). For
example, '221' will generate the 0th overtone of the l = m = 2 mode.
Returns
-------
f0 : dict
Dictionary mapping the modes to the frequencies. The dictionary keys
are 'lmn' string, where l (m) is the l (m) index of the harmonic and
n is the index of the overtone. For example, '220' is the l = m = 2
mode and the 0th overtone.
tau : dict
Dictionary mapping the modes to the damping times. The keys are the
same as ``f0``. | [
"Returns",
"a",
"dictionary",
"of",
"all",
"of",
"the",
"frequencies",
"and",
"damping",
"times",
"for",
"the",
"requested",
"modes",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L870-L913 |
228,336 | gwastro/pycbc | pycbc/conversions.py | freq_from_final_mass_spin | def freq_from_final_mass_spin(final_mass, final_spin, l=2, m=2, nmodes=1):
"""Returns QNM frequency for the given mass and spin and mode.
Parameters
----------
final_mass : float or array
Mass of the black hole (in solar masses).
final_spin : float or array
Dimensionless spin of the final black hole.
l : int or array, optional
l-index of the harmonic. Default is 2.
m : int or array, optional
m-index of the harmonic. Default is 2.
nmodes : int, optional
The number of overtones to generate. Default is 1.
Returns
-------
float or array
The frequency of the QNM(s), in Hz. If only a single mode is requested
(and mass, spin, l, and m are not arrays), this will be a float. If
multiple modes requested, will be an array with shape
``[input shape x] nmodes``, where ``input shape`` is the broadcasted
shape of the inputs.
"""
return get_lm_f0tau(final_mass, final_spin, l, m, nmodes)[0] | python | def freq_from_final_mass_spin(final_mass, final_spin, l=2, m=2, nmodes=1):
return get_lm_f0tau(final_mass, final_spin, l, m, nmodes)[0] | [
"def",
"freq_from_final_mass_spin",
"(",
"final_mass",
",",
"final_spin",
",",
"l",
"=",
"2",
",",
"m",
"=",
"2",
",",
"nmodes",
"=",
"1",
")",
":",
"return",
"get_lm_f0tau",
"(",
"final_mass",
",",
"final_spin",
",",
"l",
",",
"m",
",",
"nmodes",
")",... | Returns QNM frequency for the given mass and spin and mode.
Parameters
----------
final_mass : float or array
Mass of the black hole (in solar masses).
final_spin : float or array
Dimensionless spin of the final black hole.
l : int or array, optional
l-index of the harmonic. Default is 2.
m : int or array, optional
m-index of the harmonic. Default is 2.
nmodes : int, optional
The number of overtones to generate. Default is 1.
Returns
-------
float or array
The frequency of the QNM(s), in Hz. If only a single mode is requested
(and mass, spin, l, and m are not arrays), this will be a float. If
multiple modes requested, will be an array with shape
``[input shape x] nmodes``, where ``input shape`` is the broadcasted
shape of the inputs. | [
"Returns",
"QNM",
"frequency",
"for",
"the",
"given",
"mass",
"and",
"spin",
"and",
"mode",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L916-L941 |
228,337 | gwastro/pycbc | pycbc/conversions.py | tau_from_final_mass_spin | def tau_from_final_mass_spin(final_mass, final_spin, l=2, m=2, nmodes=1):
"""Returns QNM damping time for the given mass and spin and mode.
Parameters
----------
final_mass : float or array
Mass of the black hole (in solar masses).
final_spin : float or array
Dimensionless spin of the final black hole.
l : int or array, optional
l-index of the harmonic. Default is 2.
m : int or array, optional
m-index of the harmonic. Default is 2.
nmodes : int, optional
The number of overtones to generate. Default is 1.
Returns
-------
float or array
The damping time of the QNM(s), in seconds. If only a single mode is
requested (and mass, spin, l, and m are not arrays), this will be a
float. If multiple modes requested, will be an array with shape
``[input shape x] nmodes``, where ``input shape`` is the broadcasted
shape of the inputs.
"""
return get_lm_f0tau(final_mass, final_spin, l, m, nmodes)[1] | python | def tau_from_final_mass_spin(final_mass, final_spin, l=2, m=2, nmodes=1):
return get_lm_f0tau(final_mass, final_spin, l, m, nmodes)[1] | [
"def",
"tau_from_final_mass_spin",
"(",
"final_mass",
",",
"final_spin",
",",
"l",
"=",
"2",
",",
"m",
"=",
"2",
",",
"nmodes",
"=",
"1",
")",
":",
"return",
"get_lm_f0tau",
"(",
"final_mass",
",",
"final_spin",
",",
"l",
",",
"m",
",",
"nmodes",
")",
... | Returns QNM damping time for the given mass and spin and mode.
Parameters
----------
final_mass : float or array
Mass of the black hole (in solar masses).
final_spin : float or array
Dimensionless spin of the final black hole.
l : int or array, optional
l-index of the harmonic. Default is 2.
m : int or array, optional
m-index of the harmonic. Default is 2.
nmodes : int, optional
The number of overtones to generate. Default is 1.
Returns
-------
float or array
The damping time of the QNM(s), in seconds. If only a single mode is
requested (and mass, spin, l, and m are not arrays), this will be a
float. If multiple modes requested, will be an array with shape
``[input shape x] nmodes``, where ``input shape`` is the broadcasted
shape of the inputs. | [
"Returns",
"QNM",
"damping",
"time",
"for",
"the",
"given",
"mass",
"and",
"spin",
"and",
"mode",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L944-L969 |
228,338 | gwastro/pycbc | pycbc/conversions.py | final_spin_from_f0_tau | def final_spin_from_f0_tau(f0, tau, l=2, m=2):
"""Returns the final spin based on the given frequency and damping time.
.. note::
Currently, only l = m = 2 is supported. Any other indices will raise
a ``KeyError``.
Parameters
----------
f0 : float or array
Frequency of the QNM (in Hz).
tau : float or array
Damping time of the QNM (in seconds).
l : int, optional
l-index of the harmonic. Default is 2.
m : int, optional
m-index of the harmonic. Default is 2.
Returns
-------
float or array
The spin of the final black hole. If the combination of frequency
and damping times give an unphysical result, ``numpy.nan`` will be
returned.
"""
f0, tau, input_is_array = ensurearray(f0, tau)
# from Berti et al. 2006
a, b, c = _berti_spin_constants[l,m]
origshape = f0.shape
# flatten inputs for storing results
f0 = f0.ravel()
tau = tau.ravel()
spins = numpy.zeros(f0.size)
for ii in range(spins.size):
Q = f0[ii] * tau[ii] * numpy.pi
try:
s = 1. - ((Q-a)/b)**(1./c)
except ValueError:
s = numpy.nan
spins[ii] = s
spins = spins.reshape(origshape)
return formatreturn(spins, input_is_array) | python | def final_spin_from_f0_tau(f0, tau, l=2, m=2):
f0, tau, input_is_array = ensurearray(f0, tau)
# from Berti et al. 2006
a, b, c = _berti_spin_constants[l,m]
origshape = f0.shape
# flatten inputs for storing results
f0 = f0.ravel()
tau = tau.ravel()
spins = numpy.zeros(f0.size)
for ii in range(spins.size):
Q = f0[ii] * tau[ii] * numpy.pi
try:
s = 1. - ((Q-a)/b)**(1./c)
except ValueError:
s = numpy.nan
spins[ii] = s
spins = spins.reshape(origshape)
return formatreturn(spins, input_is_array) | [
"def",
"final_spin_from_f0_tau",
"(",
"f0",
",",
"tau",
",",
"l",
"=",
"2",
",",
"m",
"=",
"2",
")",
":",
"f0",
",",
"tau",
",",
"input_is_array",
"=",
"ensurearray",
"(",
"f0",
",",
"tau",
")",
"# from Berti et al. 2006",
"a",
",",
"b",
",",
"c",
... | Returns the final spin based on the given frequency and damping time.
.. note::
Currently, only l = m = 2 is supported. Any other indices will raise
a ``KeyError``.
Parameters
----------
f0 : float or array
Frequency of the QNM (in Hz).
tau : float or array
Damping time of the QNM (in seconds).
l : int, optional
l-index of the harmonic. Default is 2.
m : int, optional
m-index of the harmonic. Default is 2.
Returns
-------
float or array
The spin of the final black hole. If the combination of frequency
and damping times give an unphysical result, ``numpy.nan`` will be
returned. | [
"Returns",
"the",
"final",
"spin",
"based",
"on",
"the",
"given",
"frequency",
"and",
"damping",
"time",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L985-L1026 |
228,339 | gwastro/pycbc | pycbc/conversions.py | get_final_from_initial | def get_final_from_initial(mass1, mass2, spin1x=0., spin1y=0., spin1z=0.,
spin2x=0., spin2y=0., spin2z=0.,
approximant='SEOBNRv4'):
"""Estimates the final mass and spin from the given initial parameters.
This uses the fits used by the EOBNR models for converting from initial
parameters to final. Which version used can be controlled by the
``approximant`` argument.
Parameters
----------
mass1 : float
The mass of one of the components, in solar masses.
mass2 : float
The mass of the other component, in solar masses.
spin1x : float, optional
The dimensionless x-component of the spin of mass1. Default is 0.
spin1y : float, optional
The dimensionless y-component of the spin of mass1. Default is 0.
spin1z : float, optional
The dimensionless z-component of the spin of mass1. Default is 0.
spin2x : float, optional
The dimensionless x-component of the spin of mass2. Default is 0.
spin2y : float, optional
The dimensionless y-component of the spin of mass2. Default is 0.
spin2z : float, optional
The dimensionless z-component of the spin of mass2. Default is 0.
approximant : str, optional
The waveform approximant to use for the fit function. Default is
"SEOBNRv4".
Returns
-------
final_mass : float
The final mass, in solar masses.
final_spin : float
The dimensionless final spin.
"""
args = (mass1, mass2, spin1x, spin1y, spin1z, spin2x, spin2y, spin2z)
args = ensurearray(*args)
input_is_array = args[-1]
origshape = args[0].shape
# flatten inputs for storing results
args = [a.ravel() for a in args[:-1]]
mass1, mass2, spin1x, spin1y, spin1z, spin2x, spin2y, spin2z = args
final_mass = numpy.zeros(mass1.shape)
final_spin = numpy.zeros(mass1.shape)
for ii in range(final_mass.size):
m1 = mass1[ii]
m2 = mass2[ii]
spin1 = [spin1x[ii], spin1y[ii], spin1z[ii]]
spin2 = [spin2x[ii], spin2y[ii], spin2z[ii]]
_, fm, fs = lalsim.SimIMREOBFinalMassSpin(m1, m2, spin1, spin2,
getattr(lalsim, approximant))
final_mass[ii] = fm * (m1 + m2)
final_spin[ii] = fs
final_mass = final_mass.reshape(origshape)
final_spin = final_spin.reshape(origshape)
return (formatreturn(final_mass, input_is_array),
formatreturn(final_spin, input_is_array)) | python | def get_final_from_initial(mass1, mass2, spin1x=0., spin1y=0., spin1z=0.,
spin2x=0., spin2y=0., spin2z=0.,
approximant='SEOBNRv4'):
args = (mass1, mass2, spin1x, spin1y, spin1z, spin2x, spin2y, spin2z)
args = ensurearray(*args)
input_is_array = args[-1]
origshape = args[0].shape
# flatten inputs for storing results
args = [a.ravel() for a in args[:-1]]
mass1, mass2, spin1x, spin1y, spin1z, spin2x, spin2y, spin2z = args
final_mass = numpy.zeros(mass1.shape)
final_spin = numpy.zeros(mass1.shape)
for ii in range(final_mass.size):
m1 = mass1[ii]
m2 = mass2[ii]
spin1 = [spin1x[ii], spin1y[ii], spin1z[ii]]
spin2 = [spin2x[ii], spin2y[ii], spin2z[ii]]
_, fm, fs = lalsim.SimIMREOBFinalMassSpin(m1, m2, spin1, spin2,
getattr(lalsim, approximant))
final_mass[ii] = fm * (m1 + m2)
final_spin[ii] = fs
final_mass = final_mass.reshape(origshape)
final_spin = final_spin.reshape(origshape)
return (formatreturn(final_mass, input_is_array),
formatreturn(final_spin, input_is_array)) | [
"def",
"get_final_from_initial",
"(",
"mass1",
",",
"mass2",
",",
"spin1x",
"=",
"0.",
",",
"spin1y",
"=",
"0.",
",",
"spin1z",
"=",
"0.",
",",
"spin2x",
"=",
"0.",
",",
"spin2y",
"=",
"0.",
",",
"spin2z",
"=",
"0.",
",",
"approximant",
"=",
"'SEOBNR... | Estimates the final mass and spin from the given initial parameters.
This uses the fits used by the EOBNR models for converting from initial
parameters to final. Which version used can be controlled by the
``approximant`` argument.
Parameters
----------
mass1 : float
The mass of one of the components, in solar masses.
mass2 : float
The mass of the other component, in solar masses.
spin1x : float, optional
The dimensionless x-component of the spin of mass1. Default is 0.
spin1y : float, optional
The dimensionless y-component of the spin of mass1. Default is 0.
spin1z : float, optional
The dimensionless z-component of the spin of mass1. Default is 0.
spin2x : float, optional
The dimensionless x-component of the spin of mass2. Default is 0.
spin2y : float, optional
The dimensionless y-component of the spin of mass2. Default is 0.
spin2z : float, optional
The dimensionless z-component of the spin of mass2. Default is 0.
approximant : str, optional
The waveform approximant to use for the fit function. Default is
"SEOBNRv4".
Returns
-------
final_mass : float
The final mass, in solar masses.
final_spin : float
The dimensionless final spin. | [
"Estimates",
"the",
"final",
"mass",
"and",
"spin",
"from",
"the",
"given",
"initial",
"parameters",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L1061-L1120 |
228,340 | gwastro/pycbc | pycbc/conversions.py | final_mass_from_initial | def final_mass_from_initial(mass1, mass2, spin1x=0., spin1y=0., spin1z=0.,
spin2x=0., spin2y=0., spin2z=0.,
approximant='SEOBNRv4'):
"""Estimates the final mass from the given initial parameters.
This uses the fits used by the EOBNR models for converting from initial
parameters to final. Which version used can be controlled by the
``approximant`` argument.
Parameters
----------
mass1 : float
The mass of one of the components, in solar masses.
mass2 : float
The mass of the other component, in solar masses.
spin1x : float, optional
The dimensionless x-component of the spin of mass1. Default is 0.
spin1y : float, optional
The dimensionless y-component of the spin of mass1. Default is 0.
spin1z : float, optional
The dimensionless z-component of the spin of mass1. Default is 0.
spin2x : float, optional
The dimensionless x-component of the spin of mass2. Default is 0.
spin2y : float, optional
The dimensionless y-component of the spin of mass2. Default is 0.
spin2z : float, optional
The dimensionless z-component of the spin of mass2. Default is 0.
approximant : str, optional
The waveform approximant to use for the fit function. Default is
"SEOBNRv4".
Returns
-------
float
The final mass, in solar masses.
"""
return get_final_from_initial(mass1, mass2, spin1x, spin1y, spin1z,
spin2x, spin2y, spin2z, approximant)[0] | python | def final_mass_from_initial(mass1, mass2, spin1x=0., spin1y=0., spin1z=0.,
spin2x=0., spin2y=0., spin2z=0.,
approximant='SEOBNRv4'):
return get_final_from_initial(mass1, mass2, spin1x, spin1y, spin1z,
spin2x, spin2y, spin2z, approximant)[0] | [
"def",
"final_mass_from_initial",
"(",
"mass1",
",",
"mass2",
",",
"spin1x",
"=",
"0.",
",",
"spin1y",
"=",
"0.",
",",
"spin1z",
"=",
"0.",
",",
"spin2x",
"=",
"0.",
",",
"spin2y",
"=",
"0.",
",",
"spin2z",
"=",
"0.",
",",
"approximant",
"=",
"'SEOBN... | Estimates the final mass from the given initial parameters.
This uses the fits used by the EOBNR models for converting from initial
parameters to final. Which version used can be controlled by the
``approximant`` argument.
Parameters
----------
mass1 : float
The mass of one of the components, in solar masses.
mass2 : float
The mass of the other component, in solar masses.
spin1x : float, optional
The dimensionless x-component of the spin of mass1. Default is 0.
spin1y : float, optional
The dimensionless y-component of the spin of mass1. Default is 0.
spin1z : float, optional
The dimensionless z-component of the spin of mass1. Default is 0.
spin2x : float, optional
The dimensionless x-component of the spin of mass2. Default is 0.
spin2y : float, optional
The dimensionless y-component of the spin of mass2. Default is 0.
spin2z : float, optional
The dimensionless z-component of the spin of mass2. Default is 0.
approximant : str, optional
The waveform approximant to use for the fit function. Default is
"SEOBNRv4".
Returns
-------
float
The final mass, in solar masses. | [
"Estimates",
"the",
"final",
"mass",
"from",
"the",
"given",
"initial",
"parameters",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L1123-L1160 |
228,341 | gwastro/pycbc | pycbc/conversions.py | nltides_gw_phase_diff_isco | def nltides_gw_phase_diff_isco(f_low, f0, amplitude, n, m1, m2):
"""Calculate the gravitational-wave phase shift bwtween
f_low and f_isco due to non-linear tides.
Parameters
----------
f_low: float
Frequency from which to compute phase. If the other
arguments are passed as numpy arrays then the value
of f_low is duplicated for all elements in the array
f0: float or numpy.array
Frequency that NL effects switch on
amplitude: float or numpy.array
Amplitude of effect
n: float or numpy.array
Growth dependence of effect
m1: float or numpy.array
Mass of component 1
m2: float or numpy.array
Mass of component 2
Returns
-------
delta_phi: float or numpy.array
Phase in radians
"""
f0, amplitude, n, m1, m2, input_is_array = ensurearray(
f0, amplitude, n, m1, m2)
f_low = numpy.zeros(m1.shape) + f_low
phi_l = nltides_gw_phase_difference(
f_low, f0, amplitude, n, m1, m2)
f_isco = f_schwarzchild_isco(m1+m2)
phi_i = nltides_gw_phase_difference(
f_isco, f0, amplitude, n, m1, m2)
return formatreturn(phi_i - phi_l, input_is_array) | python | def nltides_gw_phase_diff_isco(f_low, f0, amplitude, n, m1, m2):
f0, amplitude, n, m1, m2, input_is_array = ensurearray(
f0, amplitude, n, m1, m2)
f_low = numpy.zeros(m1.shape) + f_low
phi_l = nltides_gw_phase_difference(
f_low, f0, amplitude, n, m1, m2)
f_isco = f_schwarzchild_isco(m1+m2)
phi_i = nltides_gw_phase_difference(
f_isco, f0, amplitude, n, m1, m2)
return formatreturn(phi_i - phi_l, input_is_array) | [
"def",
"nltides_gw_phase_diff_isco",
"(",
"f_low",
",",
"f0",
",",
"amplitude",
",",
"n",
",",
"m1",
",",
"m2",
")",
":",
"f0",
",",
"amplitude",
",",
"n",
",",
"m1",
",",
"m2",
",",
"input_is_array",
"=",
"ensurearray",
"(",
"f0",
",",
"amplitude",
... | Calculate the gravitational-wave phase shift bwtween
f_low and f_isco due to non-linear tides.
Parameters
----------
f_low: float
Frequency from which to compute phase. If the other
arguments are passed as numpy arrays then the value
of f_low is duplicated for all elements in the array
f0: float or numpy.array
Frequency that NL effects switch on
amplitude: float or numpy.array
Amplitude of effect
n: float or numpy.array
Growth dependence of effect
m1: float or numpy.array
Mass of component 1
m2: float or numpy.array
Mass of component 2
Returns
-------
delta_phi: float or numpy.array
Phase in radians | [
"Calculate",
"the",
"gravitational",
"-",
"wave",
"phase",
"shift",
"bwtween",
"f_low",
"and",
"f_isco",
"due",
"to",
"non",
"-",
"linear",
"tides",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L1358-L1397 |
228,342 | gwastro/pycbc | pycbc/inference/sampler/emcee.py | EmceeEnsembleSampler.model_stats | def model_stats(self):
"""A dict mapping the model's ``default_stats`` to arrays of values.
The returned array has shape ``nwalkers x niterations``.
"""
stats = self.model.default_stats
return blob_data_to_dict(stats, self._sampler.blobs) | python | def model_stats(self):
stats = self.model.default_stats
return blob_data_to_dict(stats, self._sampler.blobs) | [
"def",
"model_stats",
"(",
"self",
")",
":",
"stats",
"=",
"self",
".",
"model",
".",
"default_stats",
"return",
"blob_data_to_dict",
"(",
"stats",
",",
"self",
".",
"_sampler",
".",
"blobs",
")"
] | A dict mapping the model's ``default_stats`` to arrays of values.
The returned array has shape ``nwalkers x niterations``. | [
"A",
"dict",
"mapping",
"the",
"model",
"s",
"default_stats",
"to",
"arrays",
"of",
"values",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/sampler/emcee.py#L122-L128 |
228,343 | gwastro/pycbc | pycbc/inference/sampler/emcee.py | EmceeEnsembleSampler.set_state_from_file | def set_state_from_file(self, filename):
"""Sets the state of the sampler back to the instance saved in a file.
"""
with self.io(filename, 'r') as fp:
rstate = fp.read_random_state()
# set the numpy random state
numpy.random.set_state(rstate)
# set emcee's generator to the same state
self._sampler.random_state = rstate | python | def set_state_from_file(self, filename):
with self.io(filename, 'r') as fp:
rstate = fp.read_random_state()
# set the numpy random state
numpy.random.set_state(rstate)
# set emcee's generator to the same state
self._sampler.random_state = rstate | [
"def",
"set_state_from_file",
"(",
"self",
",",
"filename",
")",
":",
"with",
"self",
".",
"io",
"(",
"filename",
",",
"'r'",
")",
"as",
"fp",
":",
"rstate",
"=",
"fp",
".",
"read_random_state",
"(",
")",
"# set the numpy random state",
"numpy",
".",
"rand... | Sets the state of the sampler back to the instance saved in a file. | [
"Sets",
"the",
"state",
"of",
"the",
"sampler",
"back",
"to",
"the",
"instance",
"saved",
"in",
"a",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/sampler/emcee.py#L140-L148 |
228,344 | gwastro/pycbc | pycbc/inference/sampler/emcee.py | EmceeEnsembleSampler.write_results | def write_results(self, filename):
"""Writes samples, model stats, acceptance fraction, and random state
to the given file.
Parameters
-----------
filename : str
The file to write to. The file is opened using the ``io`` class
in an an append state.
"""
with self.io(filename, 'a') as fp:
# write samples
fp.write_samples(self.samples, self.model.variable_params,
last_iteration=self.niterations)
# write stats
fp.write_samples(self.model_stats,
last_iteration=self.niterations)
# write accpetance
fp.write_acceptance_fraction(self._sampler.acceptance_fraction)
# write random state
fp.write_random_state(state=self._sampler.random_state) | python | def write_results(self, filename):
with self.io(filename, 'a') as fp:
# write samples
fp.write_samples(self.samples, self.model.variable_params,
last_iteration=self.niterations)
# write stats
fp.write_samples(self.model_stats,
last_iteration=self.niterations)
# write accpetance
fp.write_acceptance_fraction(self._sampler.acceptance_fraction)
# write random state
fp.write_random_state(state=self._sampler.random_state) | [
"def",
"write_results",
"(",
"self",
",",
"filename",
")",
":",
"with",
"self",
".",
"io",
"(",
"filename",
",",
"'a'",
")",
"as",
"fp",
":",
"# write samples",
"fp",
".",
"write_samples",
"(",
"self",
".",
"samples",
",",
"self",
".",
"model",
".",
... | Writes samples, model stats, acceptance fraction, and random state
to the given file.
Parameters
-----------
filename : str
The file to write to. The file is opened using the ``io`` class
in an an append state. | [
"Writes",
"samples",
"model",
"stats",
"acceptance",
"fraction",
"and",
"random",
"state",
"to",
"the",
"given",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/sampler/emcee.py#L166-L186 |
228,345 | gwastro/pycbc | pycbc/io/record.py | default_empty | def default_empty(shape, dtype):
"""Numpy's empty array can have random values in it. To prevent that, we
define here a default emtpy array. This default empty is a numpy.zeros
array, except that objects are set to None, and all ints to ID_NOT_SET.
"""
default = numpy.zeros(shape, dtype=dtype)
set_default_empty(default)
return default | python | def default_empty(shape, dtype):
default = numpy.zeros(shape, dtype=dtype)
set_default_empty(default)
return default | [
"def",
"default_empty",
"(",
"shape",
",",
"dtype",
")",
":",
"default",
"=",
"numpy",
".",
"zeros",
"(",
"shape",
",",
"dtype",
"=",
"dtype",
")",
"set_default_empty",
"(",
"default",
")",
"return",
"default"
] | Numpy's empty array can have random values in it. To prevent that, we
define here a default emtpy array. This default empty is a numpy.zeros
array, except that objects are set to None, and all ints to ID_NOT_SET. | [
"Numpy",
"s",
"empty",
"array",
"can",
"have",
"random",
"values",
"in",
"it",
".",
"To",
"prevent",
"that",
"we",
"define",
"here",
"a",
"default",
"emtpy",
"array",
".",
"This",
"default",
"empty",
"is",
"a",
"numpy",
".",
"zeros",
"array",
"except",
... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L74-L81 |
228,346 | gwastro/pycbc | pycbc/io/record.py | lstring_as_obj | def lstring_as_obj(true_or_false=None):
"""Toggles whether lstrings should be treated as strings or as objects.
When FieldArrays is first loaded, the default is True.
Parameters
----------
true_or_false : {None|bool}
Pass True to map lstrings to objects; False otherwise. If None
provided, just returns the current state.
Return
------
current_stat : bool
The current state of lstring_as_obj.
Examples
--------
>>> from pycbc.io import FieldArray
>>> FieldArray.lstring_as_obj()
True
>>> FieldArray.FieldArray.from_arrays([numpy.zeros(10)], dtype=[('foo', 'lstring')])
FieldArray([(0.0,), (0.0,), (0.0,), (0.0,), (0.0,), (0.0,), (0.0,), (0.0,),
(0.0,), (0.0,)],
dtype=[('foo', 'O')])
>>> FieldArray.lstring_as_obj(False)
False
>>> FieldArray.FieldArray.from_arrays([numpy.zeros(10)], dtype=[('foo', 'lstring')])
FieldArray([('0.0',), ('0.0',), ('0.0',), ('0.0',), ('0.0',), ('0.0',),
('0.0',), ('0.0',), ('0.0',), ('0.0',)],
dtype=[('foo', 'S50')])
"""
if true_or_false is not None:
_default_types_status['lstring_as_obj'] = true_or_false
# update the typeDict
numpy.typeDict[u'lstring'] = numpy.object_ \
if _default_types_status['lstring_as_obj'] \
else 'S%i' % _default_types_status['default_strlen']
return _default_types_status['lstring_as_obj'] | python | def lstring_as_obj(true_or_false=None):
if true_or_false is not None:
_default_types_status['lstring_as_obj'] = true_or_false
# update the typeDict
numpy.typeDict[u'lstring'] = numpy.object_ \
if _default_types_status['lstring_as_obj'] \
else 'S%i' % _default_types_status['default_strlen']
return _default_types_status['lstring_as_obj'] | [
"def",
"lstring_as_obj",
"(",
"true_or_false",
"=",
"None",
")",
":",
"if",
"true_or_false",
"is",
"not",
"None",
":",
"_default_types_status",
"[",
"'lstring_as_obj'",
"]",
"=",
"true_or_false",
"# update the typeDict",
"numpy",
".",
"typeDict",
"[",
"u'lstring'",
... | Toggles whether lstrings should be treated as strings or as objects.
When FieldArrays is first loaded, the default is True.
Parameters
----------
true_or_false : {None|bool}
Pass True to map lstrings to objects; False otherwise. If None
provided, just returns the current state.
Return
------
current_stat : bool
The current state of lstring_as_obj.
Examples
--------
>>> from pycbc.io import FieldArray
>>> FieldArray.lstring_as_obj()
True
>>> FieldArray.FieldArray.from_arrays([numpy.zeros(10)], dtype=[('foo', 'lstring')])
FieldArray([(0.0,), (0.0,), (0.0,), (0.0,), (0.0,), (0.0,), (0.0,), (0.0,),
(0.0,), (0.0,)],
dtype=[('foo', 'O')])
>>> FieldArray.lstring_as_obj(False)
False
>>> FieldArray.FieldArray.from_arrays([numpy.zeros(10)], dtype=[('foo', 'lstring')])
FieldArray([('0.0',), ('0.0',), ('0.0',), ('0.0',), ('0.0',), ('0.0',),
('0.0',), ('0.0',), ('0.0',), ('0.0',)],
dtype=[('foo', 'S50')]) | [
"Toggles",
"whether",
"lstrings",
"should",
"be",
"treated",
"as",
"strings",
"or",
"as",
"objects",
".",
"When",
"FieldArrays",
"is",
"first",
"loaded",
"the",
"default",
"is",
"True",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L90-L127 |
228,347 | gwastro/pycbc | pycbc/io/record.py | get_needed_fieldnames | def get_needed_fieldnames(arr, names):
"""Given a FieldArray-like array and a list of names, determines what
fields are needed from the array so that using the names does not result
in an error.
Parameters
----------
arr : instance of a FieldArray or similar
The array from which to determine what fields to get.
names : (list of) strings
A list of the names that are desired. The names may be either a field,
a virtualfield, a property, a method of ``arr``, or any function of
these. If a virtualfield/property or a method, the source code of that
property/method will be analyzed to pull out what fields are used in
it.
Returns
-------
set
The set of the fields needed to evaluate the names.
"""
fieldnames = set([])
# we'll need the class that the array is an instance of to evaluate some
# things
cls = arr.__class__
if isinstance(names, string_types):
names = [names]
# parse names for variables, incase some of them are functions of fields
parsed_names = set([])
for name in names:
parsed_names.update(get_fields_from_arg(name))
# only include things that are in the array's namespace
names = list(parsed_names & (set(dir(arr)) | set(arr.fieldnames)))
for name in names:
if name in arr.fieldnames:
# is a field, just add the name
fieldnames.update([name])
else:
# the name is either a virtualfield, a method, or some other
# property; we need to evaluate the source code to figure out what
# fields we need
try:
# the underlying functions of properties need to be retrieved
# using their fget attribute
func = getattr(cls, name).fget
except AttributeError:
# no fget attribute, assume is an instance method
func = getattr(arr, name)
# evaluate the source code of the function
try:
sourcecode = inspect.getsource(func)
except TypeError:
# not a function, just pass
continue
# evaluate the source code for the fields
possible_fields = get_instance_fields_from_arg(sourcecode)
# some of the variables returned by possible fields may themselves
# be methods/properties that depend on other fields. For instance,
# mchirp relies on eta and mtotal, which each use mass1 and mass2;
# we therefore need to anayze each of the possible fields
fieldnames.update(get_needed_fieldnames(arr, possible_fields))
return fieldnames | python | def get_needed_fieldnames(arr, names):
fieldnames = set([])
# we'll need the class that the array is an instance of to evaluate some
# things
cls = arr.__class__
if isinstance(names, string_types):
names = [names]
# parse names for variables, incase some of them are functions of fields
parsed_names = set([])
for name in names:
parsed_names.update(get_fields_from_arg(name))
# only include things that are in the array's namespace
names = list(parsed_names & (set(dir(arr)) | set(arr.fieldnames)))
for name in names:
if name in arr.fieldnames:
# is a field, just add the name
fieldnames.update([name])
else:
# the name is either a virtualfield, a method, or some other
# property; we need to evaluate the source code to figure out what
# fields we need
try:
# the underlying functions of properties need to be retrieved
# using their fget attribute
func = getattr(cls, name).fget
except AttributeError:
# no fget attribute, assume is an instance method
func = getattr(arr, name)
# evaluate the source code of the function
try:
sourcecode = inspect.getsource(func)
except TypeError:
# not a function, just pass
continue
# evaluate the source code for the fields
possible_fields = get_instance_fields_from_arg(sourcecode)
# some of the variables returned by possible fields may themselves
# be methods/properties that depend on other fields. For instance,
# mchirp relies on eta and mtotal, which each use mass1 and mass2;
# we therefore need to anayze each of the possible fields
fieldnames.update(get_needed_fieldnames(arr, possible_fields))
return fieldnames | [
"def",
"get_needed_fieldnames",
"(",
"arr",
",",
"names",
")",
":",
"fieldnames",
"=",
"set",
"(",
"[",
"]",
")",
"# we'll need the class that the array is an instance of to evaluate some",
"# things",
"cls",
"=",
"arr",
".",
"__class__",
"if",
"isinstance",
"(",
"n... | Given a FieldArray-like array and a list of names, determines what
fields are needed from the array so that using the names does not result
in an error.
Parameters
----------
arr : instance of a FieldArray or similar
The array from which to determine what fields to get.
names : (list of) strings
A list of the names that are desired. The names may be either a field,
a virtualfield, a property, a method of ``arr``, or any function of
these. If a virtualfield/property or a method, the source code of that
property/method will be analyzed to pull out what fields are used in
it.
Returns
-------
set
The set of the fields needed to evaluate the names. | [
"Given",
"a",
"FieldArray",
"-",
"like",
"array",
"and",
"a",
"list",
"of",
"names",
"determines",
"what",
"fields",
"are",
"needed",
"from",
"the",
"array",
"so",
"that",
"using",
"the",
"names",
"does",
"not",
"result",
"in",
"an",
"error",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L202-L263 |
228,348 | gwastro/pycbc | pycbc/io/record.py | combine_fields | def combine_fields(dtypes):
"""Combines the fields in the list of given dtypes into a single dtype.
Parameters
----------
dtypes : (list of) numpy.dtype(s)
Either a numpy.dtype, or a list of numpy.dtypes.
Returns
-------
numpy.dtype
A new dtype combining the fields in the list of dtypes.
"""
if not isinstance(dtypes, list):
dtypes = [dtypes]
# Note: incase any of the dtypes have offsets, we won't include any fields
# that have no names and are void
new_dt = numpy.dtype([dt for dtype in dtypes \
for dt in get_dtype_descr(dtype)])
return new_dt | python | def combine_fields(dtypes):
if not isinstance(dtypes, list):
dtypes = [dtypes]
# Note: incase any of the dtypes have offsets, we won't include any fields
# that have no names and are void
new_dt = numpy.dtype([dt for dtype in dtypes \
for dt in get_dtype_descr(dtype)])
return new_dt | [
"def",
"combine_fields",
"(",
"dtypes",
")",
":",
"if",
"not",
"isinstance",
"(",
"dtypes",
",",
"list",
")",
":",
"dtypes",
"=",
"[",
"dtypes",
"]",
"# Note: incase any of the dtypes have offsets, we won't include any fields",
"# that have no names and are void",
"new_dt... | Combines the fields in the list of given dtypes into a single dtype.
Parameters
----------
dtypes : (list of) numpy.dtype(s)
Either a numpy.dtype, or a list of numpy.dtypes.
Returns
-------
numpy.dtype
A new dtype combining the fields in the list of dtypes. | [
"Combines",
"the",
"fields",
"in",
"the",
"list",
"of",
"given",
"dtypes",
"into",
"a",
"single",
"dtype",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L274-L293 |
228,349 | gwastro/pycbc | pycbc/io/record.py | _ensure_array_list | def _ensure_array_list(arrays):
"""Ensures that every element in a list is an instance of a numpy array."""
# Note: the isinstance test is needed below so that instances of FieldArray
# are not converted to numpy arrays
return [numpy.array(arr, ndmin=1) if not isinstance(arr, numpy.ndarray)
else arr for arr in arrays] | python | def _ensure_array_list(arrays):
# Note: the isinstance test is needed below so that instances of FieldArray
# are not converted to numpy arrays
return [numpy.array(arr, ndmin=1) if not isinstance(arr, numpy.ndarray)
else arr for arr in arrays] | [
"def",
"_ensure_array_list",
"(",
"arrays",
")",
":",
"# Note: the isinstance test is needed below so that instances of FieldArray",
"# are not converted to numpy arrays",
"return",
"[",
"numpy",
".",
"array",
"(",
"arr",
",",
"ndmin",
"=",
"1",
")",
"if",
"not",
"isinsta... | Ensures that every element in a list is an instance of a numpy array. | [
"Ensures",
"that",
"every",
"element",
"in",
"a",
"list",
"is",
"an",
"instance",
"of",
"a",
"numpy",
"array",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L296-L301 |
228,350 | gwastro/pycbc | pycbc/io/record.py | merge_arrays | def merge_arrays(merge_list, names=None, flatten=True, outtype=None):
"""Merges the given arrays into a single array. The arrays must all have
the same shape. If one or more of the given arrays has multiple fields,
all of the fields will be included as separate fields in the new array.
Parameters
----------
merge_list : list of arrays
The list of arrays to merge.
names : {None | sequence of strings}
Optional, the names of the fields in the output array. If flatten is
True, must be the same length as the total number of fields in
merge_list. Otherise, must be the same length as the number of
arrays in merge_list. If None provided, and flatten is True, names
used will be the same as the name of the fields in the given arrays.
If the datatype has no name, or flatten is False, the new field will
be `fi` where i is the index of the array in arrays.
flatten : bool
Make all of the fields in the given arrays separate fields in the
new array. Otherwise, each array will be added as a field. If an
array has fields, they will be subfields in the output array. Default
is True.
outtype : {None | class}
Cast the new array to the given type. Default is to return a
numpy structured array.
Returns
-------
new array : {numpy.ndarray | outtype}
A new array with all of the fields in all of the arrays merged into
a single array.
"""
# make sure everything in merge_list is an array
merge_list = _ensure_array_list(merge_list)
if not all(merge_list[0].shape == arr.shape for arr in merge_list):
raise ValueError("all of the arrays in merge_list must have the " +
"same shape")
if flatten:
new_dt = combine_fields([arr.dtype for arr in merge_list])
else:
new_dt = numpy.dtype([('f%i' %ii, arr.dtype.descr) \
for ii,arr in enumerate(merge_list)])
new_arr = merge_list[0].__class__(merge_list[0].shape, dtype=new_dt)
# ii is a counter to keep track of which fields from the new array
# go with which arrays in merge list
ii = 0
for arr in merge_list:
if arr.dtype.names is None:
new_arr[new_dt.names[ii]] = arr
ii += 1
else:
for field in arr.dtype.names:
new_arr[field] = arr[field]
ii += 1
# set the names if desired
if names is not None:
new_arr.dtype.names = names
# ditto the outtype
if outtype is not None:
new_arr = new_arr.view(type=outtype)
return new_arr | python | def merge_arrays(merge_list, names=None, flatten=True, outtype=None):
# make sure everything in merge_list is an array
merge_list = _ensure_array_list(merge_list)
if not all(merge_list[0].shape == arr.shape for arr in merge_list):
raise ValueError("all of the arrays in merge_list must have the " +
"same shape")
if flatten:
new_dt = combine_fields([arr.dtype for arr in merge_list])
else:
new_dt = numpy.dtype([('f%i' %ii, arr.dtype.descr) \
for ii,arr in enumerate(merge_list)])
new_arr = merge_list[0].__class__(merge_list[0].shape, dtype=new_dt)
# ii is a counter to keep track of which fields from the new array
# go with which arrays in merge list
ii = 0
for arr in merge_list:
if arr.dtype.names is None:
new_arr[new_dt.names[ii]] = arr
ii += 1
else:
for field in arr.dtype.names:
new_arr[field] = arr[field]
ii += 1
# set the names if desired
if names is not None:
new_arr.dtype.names = names
# ditto the outtype
if outtype is not None:
new_arr = new_arr.view(type=outtype)
return new_arr | [
"def",
"merge_arrays",
"(",
"merge_list",
",",
"names",
"=",
"None",
",",
"flatten",
"=",
"True",
",",
"outtype",
"=",
"None",
")",
":",
"# make sure everything in merge_list is an array",
"merge_list",
"=",
"_ensure_array_list",
"(",
"merge_list",
")",
"if",
"not... | Merges the given arrays into a single array. The arrays must all have
the same shape. If one or more of the given arrays has multiple fields,
all of the fields will be included as separate fields in the new array.
Parameters
----------
merge_list : list of arrays
The list of arrays to merge.
names : {None | sequence of strings}
Optional, the names of the fields in the output array. If flatten is
True, must be the same length as the total number of fields in
merge_list. Otherise, must be the same length as the number of
arrays in merge_list. If None provided, and flatten is True, names
used will be the same as the name of the fields in the given arrays.
If the datatype has no name, or flatten is False, the new field will
be `fi` where i is the index of the array in arrays.
flatten : bool
Make all of the fields in the given arrays separate fields in the
new array. Otherwise, each array will be added as a field. If an
array has fields, they will be subfields in the output array. Default
is True.
outtype : {None | class}
Cast the new array to the given type. Default is to return a
numpy structured array.
Returns
-------
new array : {numpy.ndarray | outtype}
A new array with all of the fields in all of the arrays merged into
a single array. | [
"Merges",
"the",
"given",
"arrays",
"into",
"a",
"single",
"array",
".",
"The",
"arrays",
"must",
"all",
"have",
"the",
"same",
"shape",
".",
"If",
"one",
"or",
"more",
"of",
"the",
"given",
"arrays",
"has",
"multiple",
"fields",
"all",
"of",
"the",
"f... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L304-L364 |
228,351 | gwastro/pycbc | pycbc/io/record.py | _isstring | def _isstring(dtype):
"""Given a numpy dtype, determines whether it is a string. Returns True
if the dtype is string or unicode.
"""
return dtype.type == numpy.unicode_ or dtype.type == numpy.string_ | python | def _isstring(dtype):
return dtype.type == numpy.unicode_ or dtype.type == numpy.string_ | [
"def",
"_isstring",
"(",
"dtype",
")",
":",
"return",
"dtype",
".",
"type",
"==",
"numpy",
".",
"unicode_",
"or",
"dtype",
".",
"type",
"==",
"numpy",
".",
"string_"
] | Given a numpy dtype, determines whether it is a string. Returns True
if the dtype is string or unicode. | [
"Given",
"a",
"numpy",
"dtype",
"determines",
"whether",
"it",
"is",
"a",
"string",
".",
"Returns",
"True",
"if",
"the",
"dtype",
"is",
"string",
"or",
"unicode",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1463-L1467 |
228,352 | gwastro/pycbc | pycbc/io/record.py | fields_from_names | def fields_from_names(fields, names=None):
"""Given a dictionary of fields and a list of names, will return a
dictionary consisting of the fields specified by names. Names can be
either the names of fields, or their aliases.
"""
if names is None:
return fields
if isinstance(names, string_types):
names = [names]
aliases_to_names = aliases_from_fields(fields)
names_to_aliases = dict(zip(aliases_to_names.values(),
aliases_to_names.keys()))
outfields = {}
for name in names:
try:
outfields[name] = fields[name]
except KeyError:
if name in aliases_to_names:
key = (name, aliases_to_names[name])
elif name in names_to_aliases:
key = (names_to_aliases[name], name)
else:
raise KeyError('default fields has no field %s' % name)
outfields[key] = fields[key]
return outfields | python | def fields_from_names(fields, names=None):
if names is None:
return fields
if isinstance(names, string_types):
names = [names]
aliases_to_names = aliases_from_fields(fields)
names_to_aliases = dict(zip(aliases_to_names.values(),
aliases_to_names.keys()))
outfields = {}
for name in names:
try:
outfields[name] = fields[name]
except KeyError:
if name in aliases_to_names:
key = (name, aliases_to_names[name])
elif name in names_to_aliases:
key = (names_to_aliases[name], name)
else:
raise KeyError('default fields has no field %s' % name)
outfields[key] = fields[key]
return outfields | [
"def",
"fields_from_names",
"(",
"fields",
",",
"names",
"=",
"None",
")",
":",
"if",
"names",
"is",
"None",
":",
"return",
"fields",
"if",
"isinstance",
"(",
"names",
",",
"string_types",
")",
":",
"names",
"=",
"[",
"names",
"]",
"aliases_to_names",
"=... | Given a dictionary of fields and a list of names, will return a
dictionary consisting of the fields specified by names. Names can be
either the names of fields, or their aliases. | [
"Given",
"a",
"dictionary",
"of",
"fields",
"and",
"a",
"list",
"of",
"names",
"will",
"return",
"a",
"dictionary",
"consisting",
"of",
"the",
"fields",
"specified",
"by",
"names",
".",
"Names",
"can",
"be",
"either",
"the",
"names",
"of",
"fields",
"or",
... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1477-L1502 |
228,353 | gwastro/pycbc | pycbc/io/record.py | FieldArray.sort | def sort(self, axis=-1, kind='quicksort', order=None):
"""Sort an array, in-place.
This function extends the standard numpy record array in-place sort
to allow the basic use of Field array virtual fields. Only a single
field is currently supported when referencing a virtual field.
Parameters
----------
axis : int, optional
Axis along which to sort. Default is -1, which means sort along the
last axis.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm. Default is 'quicksort'.
order : list, optional
When `a` is an array with fields defined, this argument specifies
which fields to compare first, second, etc. Not all fields need be
specified.
"""
try:
numpy.recarray.sort(self, axis=axis, kind=kind, order=order)
except ValueError:
if isinstance(order, list):
raise ValueError("Cannot process more than one order field")
self[:] = self[numpy.argsort(self[order])] | python | def sort(self, axis=-1, kind='quicksort', order=None):
try:
numpy.recarray.sort(self, axis=axis, kind=kind, order=order)
except ValueError:
if isinstance(order, list):
raise ValueError("Cannot process more than one order field")
self[:] = self[numpy.argsort(self[order])] | [
"def",
"sort",
"(",
"self",
",",
"axis",
"=",
"-",
"1",
",",
"kind",
"=",
"'quicksort'",
",",
"order",
"=",
"None",
")",
":",
"try",
":",
"numpy",
".",
"recarray",
".",
"sort",
"(",
"self",
",",
"axis",
"=",
"axis",
",",
"kind",
"=",
"kind",
",... | Sort an array, in-place.
This function extends the standard numpy record array in-place sort
to allow the basic use of Field array virtual fields. Only a single
field is currently supported when referencing a virtual field.
Parameters
----------
axis : int, optional
Axis along which to sort. Default is -1, which means sort along the
last axis.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm. Default is 'quicksort'.
order : list, optional
When `a` is an array with fields defined, this argument specifies
which fields to compare first, second, etc. Not all fields need be
specified. | [
"Sort",
"an",
"array",
"in",
"-",
"place",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L896-L920 |
228,354 | gwastro/pycbc | pycbc/io/record.py | FieldArray.addattr | def addattr(self, attrname, value=None, persistent=True):
"""Adds an attribute to self. If persistent is True, the attribute will
be made a persistent attribute. Persistent attributes are copied
whenever a view or copy of this array is created. Otherwise, new views
or copies of this will not have the attribute.
"""
setattr(self, attrname, value)
# add as persistent
if persistent and attrname not in self.__persistent_attributes__:
self.__persistent_attributes__.append(attrname) | python | def addattr(self, attrname, value=None, persistent=True):
setattr(self, attrname, value)
# add as persistent
if persistent and attrname not in self.__persistent_attributes__:
self.__persistent_attributes__.append(attrname) | [
"def",
"addattr",
"(",
"self",
",",
"attrname",
",",
"value",
"=",
"None",
",",
"persistent",
"=",
"True",
")",
":",
"setattr",
"(",
"self",
",",
"attrname",
",",
"value",
")",
"# add as persistent",
"if",
"persistent",
"and",
"attrname",
"not",
"in",
"s... | Adds an attribute to self. If persistent is True, the attribute will
be made a persistent attribute. Persistent attributes are copied
whenever a view or copy of this array is created. Otherwise, new views
or copies of this will not have the attribute. | [
"Adds",
"an",
"attribute",
"to",
"self",
".",
"If",
"persistent",
"is",
"True",
"the",
"attribute",
"will",
"be",
"made",
"a",
"persistent",
"attribute",
".",
"Persistent",
"attributes",
"are",
"copied",
"whenever",
"a",
"view",
"or",
"copy",
"of",
"this",
... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L922-L931 |
228,355 | gwastro/pycbc | pycbc/io/record.py | FieldArray.add_properties | def add_properties(self, names, methods):
"""Returns a view of self with the given methods added as properties.
From: <http://stackoverflow.com/a/2954373/1366472>.
"""
cls = type(self)
cls = type(cls.__name__, (cls,), dict(cls.__dict__))
if isinstance(names, string_types):
names = [names]
methods = [methods]
for name,method in zip(names, methods):
setattr(cls, name, property(method))
return self.view(type=cls) | python | def add_properties(self, names, methods):
cls = type(self)
cls = type(cls.__name__, (cls,), dict(cls.__dict__))
if isinstance(names, string_types):
names = [names]
methods = [methods]
for name,method in zip(names, methods):
setattr(cls, name, property(method))
return self.view(type=cls) | [
"def",
"add_properties",
"(",
"self",
",",
"names",
",",
"methods",
")",
":",
"cls",
"=",
"type",
"(",
"self",
")",
"cls",
"=",
"type",
"(",
"cls",
".",
"__name__",
",",
"(",
"cls",
",",
")",
",",
"dict",
"(",
"cls",
".",
"__dict__",
")",
")",
... | Returns a view of self with the given methods added as properties.
From: <http://stackoverflow.com/a/2954373/1366472>. | [
"Returns",
"a",
"view",
"of",
"self",
"with",
"the",
"given",
"methods",
"added",
"as",
"properties",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L943-L955 |
228,356 | gwastro/pycbc | pycbc/io/record.py | FieldArray.add_virtualfields | def add_virtualfields(self, names, methods):
"""Returns a view of this array with the given methods added as virtual
fields. Specifically, the given methods are added using add_properties
and their names are added to the list of virtual fields. Virtual fields
are properties that are assumed to operate on one or more of self's
fields, thus returning an array of values.
"""
if isinstance(names, string_types):
names = [names]
methods = [methods]
out = self.add_properties(names, methods)
if out._virtualfields is None:
out._virtualfields = []
out._virtualfields.extend(names)
return out | python | def add_virtualfields(self, names, methods):
if isinstance(names, string_types):
names = [names]
methods = [methods]
out = self.add_properties(names, methods)
if out._virtualfields is None:
out._virtualfields = []
out._virtualfields.extend(names)
return out | [
"def",
"add_virtualfields",
"(",
"self",
",",
"names",
",",
"methods",
")",
":",
"if",
"isinstance",
"(",
"names",
",",
"string_types",
")",
":",
"names",
"=",
"[",
"names",
"]",
"methods",
"=",
"[",
"methods",
"]",
"out",
"=",
"self",
".",
"add_proper... | Returns a view of this array with the given methods added as virtual
fields. Specifically, the given methods are added using add_properties
and their names are added to the list of virtual fields. Virtual fields
are properties that are assumed to operate on one or more of self's
fields, thus returning an array of values. | [
"Returns",
"a",
"view",
"of",
"this",
"array",
"with",
"the",
"given",
"methods",
"added",
"as",
"virtual",
"fields",
".",
"Specifically",
"the",
"given",
"methods",
"are",
"added",
"using",
"add_properties",
"and",
"their",
"names",
"are",
"added",
"to",
"t... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L957-L971 |
228,357 | gwastro/pycbc | pycbc/io/record.py | FieldArray.add_functions | def add_functions(self, names, functions):
"""Adds the given functions to the function library.
Functions are added to this instance of the array; all copies of
and slices of this array will also have the new functions included.
Parameters
----------
names : (list of) string(s)
Name or list of names of the functions.
functions : (list of) function(s)
The function(s) to call.
"""
if isinstance(names, string_types):
names = [names]
functions = [functions]
if len(functions) != len(names):
raise ValueError("number of provided names must be same as number "
"of functions")
self._functionlib.update(dict(zip(names, functions))) | python | def add_functions(self, names, functions):
if isinstance(names, string_types):
names = [names]
functions = [functions]
if len(functions) != len(names):
raise ValueError("number of provided names must be same as number "
"of functions")
self._functionlib.update(dict(zip(names, functions))) | [
"def",
"add_functions",
"(",
"self",
",",
"names",
",",
"functions",
")",
":",
"if",
"isinstance",
"(",
"names",
",",
"string_types",
")",
":",
"names",
"=",
"[",
"names",
"]",
"functions",
"=",
"[",
"functions",
"]",
"if",
"len",
"(",
"functions",
")"... | Adds the given functions to the function library.
Functions are added to this instance of the array; all copies of
and slices of this array will also have the new functions included.
Parameters
----------
names : (list of) string(s)
Name or list of names of the functions.
functions : (list of) function(s)
The function(s) to call. | [
"Adds",
"the",
"given",
"functions",
"to",
"the",
"function",
"library",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L973-L992 |
228,358 | gwastro/pycbc | pycbc/io/record.py | FieldArray.del_functions | def del_functions(self, names):
"""Removes the specified function names from the function library.
Functions are removed from this instance of the array; all copies
and slices of this array will also have the functions removed.
Parameters
----------
names : (list of) string(s)
Name or list of names of the functions to remove.
"""
if isinstance(names, string_types):
names = [names]
for name in names:
self._functionlib.pop(name) | python | def del_functions(self, names):
if isinstance(names, string_types):
names = [names]
for name in names:
self._functionlib.pop(name) | [
"def",
"del_functions",
"(",
"self",
",",
"names",
")",
":",
"if",
"isinstance",
"(",
"names",
",",
"string_types",
")",
":",
"names",
"=",
"[",
"names",
"]",
"for",
"name",
"in",
"names",
":",
"self",
".",
"_functionlib",
".",
"pop",
"(",
"name",
")... | Removes the specified function names from the function library.
Functions are removed from this instance of the array; all copies
and slices of this array will also have the functions removed.
Parameters
----------
names : (list of) string(s)
Name or list of names of the functions to remove. | [
"Removes",
"the",
"specified",
"function",
"names",
"from",
"the",
"function",
"library",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L994-L1008 |
228,359 | gwastro/pycbc | pycbc/io/record.py | FieldArray.from_ligolw_table | def from_ligolw_table(cls, table, columns=None, cast_to_dtypes=None):
"""Converts the given ligolw table into an FieldArray. The `tableName`
attribute is copied to the array's `name`.
Parameters
----------
table : LIGOLw table instance
The table to convert.
columns : {None|list}
Optionally specify a list of columns to retrieve. All of the
columns must be in the table's validcolumns attribute. If None
provided, all the columns in the table will be converted.
dtype : {None | dict}
Override the columns' dtypes using the given dictionary. The
dictionary should be keyed by the column names, with the values
a tuple that can be understood by numpy.dtype. For example, to
cast a ligolw column called "foo" to a field called "bar" with
type float, cast_to_dtypes would be: ``{"foo": ("bar", float)}``.
Returns
-------
array : FieldArray
The input table as an FieldArray.
"""
name = table.tableName.split(':')[0]
if columns is None:
# get all the columns
columns = table.validcolumns
else:
# note: this will raise a KeyError if one or more columns is
# not in the table's validcolumns
new_columns = {}
for col in columns:
new_columns[col] = table.validcolumns[col]
columns = new_columns
if cast_to_dtypes is not None:
dtype = [cast_to_dtypes[col] for col in columns]
else:
dtype = columns.items()
# get the values
if _default_types_status['ilwd_as_int']:
input_array = \
[tuple(getattr(row, col) if dt != 'ilwd:char'
else int(getattr(row, col))
for col,dt in columns.items())
for row in table]
else:
input_array = \
[tuple(getattr(row, col) for col in columns) for row in table]
# return the values as an instance of cls
return cls.from_records(input_array, dtype=dtype,
name=name) | python | def from_ligolw_table(cls, table, columns=None, cast_to_dtypes=None):
name = table.tableName.split(':')[0]
if columns is None:
# get all the columns
columns = table.validcolumns
else:
# note: this will raise a KeyError if one or more columns is
# not in the table's validcolumns
new_columns = {}
for col in columns:
new_columns[col] = table.validcolumns[col]
columns = new_columns
if cast_to_dtypes is not None:
dtype = [cast_to_dtypes[col] for col in columns]
else:
dtype = columns.items()
# get the values
if _default_types_status['ilwd_as_int']:
input_array = \
[tuple(getattr(row, col) if dt != 'ilwd:char'
else int(getattr(row, col))
for col,dt in columns.items())
for row in table]
else:
input_array = \
[tuple(getattr(row, col) for col in columns) for row in table]
# return the values as an instance of cls
return cls.from_records(input_array, dtype=dtype,
name=name) | [
"def",
"from_ligolw_table",
"(",
"cls",
",",
"table",
",",
"columns",
"=",
"None",
",",
"cast_to_dtypes",
"=",
"None",
")",
":",
"name",
"=",
"table",
".",
"tableName",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
"if",
"columns",
"is",
"None",
":",... | Converts the given ligolw table into an FieldArray. The `tableName`
attribute is copied to the array's `name`.
Parameters
----------
table : LIGOLw table instance
The table to convert.
columns : {None|list}
Optionally specify a list of columns to retrieve. All of the
columns must be in the table's validcolumns attribute. If None
provided, all the columns in the table will be converted.
dtype : {None | dict}
Override the columns' dtypes using the given dictionary. The
dictionary should be keyed by the column names, with the values
a tuple that can be understood by numpy.dtype. For example, to
cast a ligolw column called "foo" to a field called "bar" with
type float, cast_to_dtypes would be: ``{"foo": ("bar", float)}``.
Returns
-------
array : FieldArray
The input table as an FieldArray. | [
"Converts",
"the",
"given",
"ligolw",
"table",
"into",
"an",
"FieldArray",
".",
"The",
"tableName",
"attribute",
"is",
"copied",
"to",
"the",
"array",
"s",
"name",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1104-L1155 |
228,360 | gwastro/pycbc | pycbc/io/record.py | FieldArray.to_array | def to_array(self, fields=None, axis=0):
"""Returns an `numpy.ndarray` of self in which the fields are included
as an extra dimension.
Parameters
----------
fields : {None, (list of) strings}
The fields to get. All of the fields must have the same datatype.
If None, will try to return all of the fields.
axis : {0, int}
Which dimension to put the fields in in the returned array. For
example, if `self` has shape `(l,m,n)` and `k` fields, the
returned array will have shape `(k,l,m,n)` if `axis=0`, `(l,k,m,n)`
if `axis=1`, etc. Setting `axis=-1` will put the fields in the
last dimension. Default is 0.
Returns
-------
numpy.ndarray
The desired fields as a numpy array.
"""
if fields is None:
fields = self.fieldnames
if isinstance(fields, string_types):
fields = [fields]
return numpy.stack([self[f] for f in fields], axis=axis) | python | def to_array(self, fields=None, axis=0):
if fields is None:
fields = self.fieldnames
if isinstance(fields, string_types):
fields = [fields]
return numpy.stack([self[f] for f in fields], axis=axis) | [
"def",
"to_array",
"(",
"self",
",",
"fields",
"=",
"None",
",",
"axis",
"=",
"0",
")",
":",
"if",
"fields",
"is",
"None",
":",
"fields",
"=",
"self",
".",
"fieldnames",
"if",
"isinstance",
"(",
"fields",
",",
"string_types",
")",
":",
"fields",
"=",... | Returns an `numpy.ndarray` of self in which the fields are included
as an extra dimension.
Parameters
----------
fields : {None, (list of) strings}
The fields to get. All of the fields must have the same datatype.
If None, will try to return all of the fields.
axis : {0, int}
Which dimension to put the fields in in the returned array. For
example, if `self` has shape `(l,m,n)` and `k` fields, the
returned array will have shape `(k,l,m,n)` if `axis=0`, `(l,k,m,n)`
if `axis=1`, etc. Setting `axis=-1` will put the fields in the
last dimension. Default is 0.
Returns
-------
numpy.ndarray
The desired fields as a numpy array. | [
"Returns",
"an",
"numpy",
".",
"ndarray",
"of",
"self",
"in",
"which",
"the",
"fields",
"are",
"included",
"as",
"an",
"extra",
"dimension",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1157-L1182 |
228,361 | gwastro/pycbc | pycbc/io/record.py | FieldArray.virtualfields | def virtualfields(self):
"""Returns a tuple listing the names of virtual fields in self.
"""
if self._virtualfields is None:
vfs = tuple()
else:
vfs = tuple(self._virtualfields)
return vfs | python | def virtualfields(self):
if self._virtualfields is None:
vfs = tuple()
else:
vfs = tuple(self._virtualfields)
return vfs | [
"def",
"virtualfields",
"(",
"self",
")",
":",
"if",
"self",
".",
"_virtualfields",
"is",
"None",
":",
"vfs",
"=",
"tuple",
"(",
")",
"else",
":",
"vfs",
"=",
"tuple",
"(",
"self",
".",
"_virtualfields",
")",
"return",
"vfs"
] | Returns a tuple listing the names of virtual fields in self. | [
"Returns",
"a",
"tuple",
"listing",
"the",
"names",
"of",
"virtual",
"fields",
"in",
"self",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1192-L1199 |
228,362 | gwastro/pycbc | pycbc/io/record.py | FieldArray.parse_boolargs | def parse_boolargs(self, args):
"""Returns an array populated by given values, with the indices of
those values dependent on given boolen tests on self.
The given `args` should be a list of tuples, with the first element the
return value and the second argument a string that evaluates to either
True or False for each element in self.
Each boolean argument is evaluated on elements for which every prior
boolean argument was False. For example, if array `foo` has a field
`bar`, and `args = [(1, 'bar < 10'), (2, 'bar < 20'), (3, 'bar < 30')]`,
then the returned array will have `1`s at the indices for
which `foo.bar < 10`, `2`s where `foo.bar < 20 and not foo.bar < 10`,
and `3`s where `foo.bar < 30 and not (foo.bar < 10 or foo.bar < 20)`.
The last argument in the list may have "else", an empty string, None,
or simply list a return value. In any of these cases, any element not
yet populated will be assigned the last return value.
Parameters
----------
args : {(list of) tuples, value}
One or more return values and boolean argument determining where
they should go.
Returns
-------
return_values : array
An array with length equal to self, with values populated with the
return values.
leftover_indices : array
An array of indices that evaluated to False for all arguments.
These indices will not have been popluated with any value,
defaulting to whatever numpy uses for a zero for the return
values' dtype. If there are no leftovers, an empty array is
returned.
Examples
--------
Given the following array:
>>> arr = FieldArray(5, dtype=[('mtotal', float)])
>>> arr['mtotal'] = numpy.array([3., 5., 2., 1., 4.])
Return `"TaylorF2"` for all elements with `mtotal < 4` (note that the
elements 1 and 4 are leftover):
>>> arr.parse_boolargs(('TaylorF2', 'mtotal<4'))
(array(['TaylorF2', '', 'TaylorF2', 'TaylorF2', ''],
dtype='|S8'),
array([1, 4]))
Return `"TaylorF2"` for all elements with `mtotal < 4`,
`"SEOBNR_ROM_DoubleSpin"` otherwise:
>>> arr.parse_boolargs([('TaylorF2', 'mtotal<4'), ('SEOBNRv2_ROM_DoubleSpin', 'else')])
(array(['TaylorF2', 'SEOBNRv2_ROM_DoubleSpin', 'TaylorF2', 'TaylorF2',
'SEOBNRv2_ROM_DoubleSpin'],
dtype='|S23'),
array([], dtype=int64))
The following will also return the same:
>>> arr.parse_boolargs([('TaylorF2', 'mtotal<4'), ('SEOBNRv2_ROM_DoubleSpin',)])
>>> arr.parse_boolargs([('TaylorF2', 'mtotal<4'), ('SEOBNRv2_ROM_DoubleSpin', '')])
>>> arr.parse_boolargs([('TaylorF2', 'mtotal<4'), 'SEOBNRv2_ROM_DoubleSpin'])
Return `"TaylorF2"` for all elements with `mtotal < 3`, `"IMRPhenomD"`
for all elements with `3 <= mtotal < 4`, `"SEOBNRv2_ROM_DoubleSpin"`
otherwise:
>>> arr.parse_boolargs([('TaylorF2', 'mtotal<3'), ('IMRPhenomD', 'mtotal<4'), 'SEOBNRv2_ROM_DoubleSpin'])
(array(['IMRPhenomD', 'SEOBNRv2_ROM_DoubleSpin', 'TaylorF2', 'TaylorF2',
'SEOBNRv2_ROM_DoubleSpin'],
dtype='|S23'),
array([], dtype=int64))
Just return `"TaylorF2"` for all elements:
>>> arr.parse_boolargs('TaylorF2')
(array(['TaylorF2', 'TaylorF2', 'TaylorF2', 'TaylorF2', 'TaylorF2'],
dtype='|S8'),
array([], dtype=int64))
"""
if not isinstance(args, list):
args = [args]
# format the arguments
return_vals = []
bool_args = []
for arg in args:
if not isinstance(arg, tuple):
return_val = arg
bool_arg = None
elif len(arg) == 1:
return_val = arg[0]
bool_arg = None
elif len(arg) == 2:
return_val, bool_arg = arg
else:
raise ValueError("argument not formatted correctly")
return_vals.append(return_val)
bool_args.append(bool_arg)
# get the output dtype
outdtype = numpy.array(return_vals).dtype
out = numpy.zeros(self.size, dtype=outdtype)
mask = numpy.zeros(self.size, dtype=bool)
leftovers = numpy.ones(self.size, dtype=bool)
for ii,(boolarg,val) in enumerate(zip(bool_args, return_vals)):
if boolarg is None or boolarg == '' or boolarg.lower() == 'else':
if ii+1 != len(bool_args):
raise ValueError("only the last item may not provide "
"any boolean arguments")
mask = leftovers
else:
mask = leftovers & self[boolarg]
out[mask] = val
leftovers &= ~mask
return out, numpy.where(leftovers)[0] | python | def parse_boolargs(self, args):
if not isinstance(args, list):
args = [args]
# format the arguments
return_vals = []
bool_args = []
for arg in args:
if not isinstance(arg, tuple):
return_val = arg
bool_arg = None
elif len(arg) == 1:
return_val = arg[0]
bool_arg = None
elif len(arg) == 2:
return_val, bool_arg = arg
else:
raise ValueError("argument not formatted correctly")
return_vals.append(return_val)
bool_args.append(bool_arg)
# get the output dtype
outdtype = numpy.array(return_vals).dtype
out = numpy.zeros(self.size, dtype=outdtype)
mask = numpy.zeros(self.size, dtype=bool)
leftovers = numpy.ones(self.size, dtype=bool)
for ii,(boolarg,val) in enumerate(zip(bool_args, return_vals)):
if boolarg is None or boolarg == '' or boolarg.lower() == 'else':
if ii+1 != len(bool_args):
raise ValueError("only the last item may not provide "
"any boolean arguments")
mask = leftovers
else:
mask = leftovers & self[boolarg]
out[mask] = val
leftovers &= ~mask
return out, numpy.where(leftovers)[0] | [
"def",
"parse_boolargs",
"(",
"self",
",",
"args",
")",
":",
"if",
"not",
"isinstance",
"(",
"args",
",",
"list",
")",
":",
"args",
"=",
"[",
"args",
"]",
"# format the arguments",
"return_vals",
"=",
"[",
"]",
"bool_args",
"=",
"[",
"]",
"for",
"arg",... | Returns an array populated by given values, with the indices of
those values dependent on given boolen tests on self.
The given `args` should be a list of tuples, with the first element the
return value and the second argument a string that evaluates to either
True or False for each element in self.
Each boolean argument is evaluated on elements for which every prior
boolean argument was False. For example, if array `foo` has a field
`bar`, and `args = [(1, 'bar < 10'), (2, 'bar < 20'), (3, 'bar < 30')]`,
then the returned array will have `1`s at the indices for
which `foo.bar < 10`, `2`s where `foo.bar < 20 and not foo.bar < 10`,
and `3`s where `foo.bar < 30 and not (foo.bar < 10 or foo.bar < 20)`.
The last argument in the list may have "else", an empty string, None,
or simply list a return value. In any of these cases, any element not
yet populated will be assigned the last return value.
Parameters
----------
args : {(list of) tuples, value}
One or more return values and boolean argument determining where
they should go.
Returns
-------
return_values : array
An array with length equal to self, with values populated with the
return values.
leftover_indices : array
An array of indices that evaluated to False for all arguments.
These indices will not have been popluated with any value,
defaulting to whatever numpy uses for a zero for the return
values' dtype. If there are no leftovers, an empty array is
returned.
Examples
--------
Given the following array:
>>> arr = FieldArray(5, dtype=[('mtotal', float)])
>>> arr['mtotal'] = numpy.array([3., 5., 2., 1., 4.])
Return `"TaylorF2"` for all elements with `mtotal < 4` (note that the
elements 1 and 4 are leftover):
>>> arr.parse_boolargs(('TaylorF2', 'mtotal<4'))
(array(['TaylorF2', '', 'TaylorF2', 'TaylorF2', ''],
dtype='|S8'),
array([1, 4]))
Return `"TaylorF2"` for all elements with `mtotal < 4`,
`"SEOBNR_ROM_DoubleSpin"` otherwise:
>>> arr.parse_boolargs([('TaylorF2', 'mtotal<4'), ('SEOBNRv2_ROM_DoubleSpin', 'else')])
(array(['TaylorF2', 'SEOBNRv2_ROM_DoubleSpin', 'TaylorF2', 'TaylorF2',
'SEOBNRv2_ROM_DoubleSpin'],
dtype='|S23'),
array([], dtype=int64))
The following will also return the same:
>>> arr.parse_boolargs([('TaylorF2', 'mtotal<4'), ('SEOBNRv2_ROM_DoubleSpin',)])
>>> arr.parse_boolargs([('TaylorF2', 'mtotal<4'), ('SEOBNRv2_ROM_DoubleSpin', '')])
>>> arr.parse_boolargs([('TaylorF2', 'mtotal<4'), 'SEOBNRv2_ROM_DoubleSpin'])
Return `"TaylorF2"` for all elements with `mtotal < 3`, `"IMRPhenomD"`
for all elements with `3 <= mtotal < 4`, `"SEOBNRv2_ROM_DoubleSpin"`
otherwise:
>>> arr.parse_boolargs([('TaylorF2', 'mtotal<3'), ('IMRPhenomD', 'mtotal<4'), 'SEOBNRv2_ROM_DoubleSpin'])
(array(['IMRPhenomD', 'SEOBNRv2_ROM_DoubleSpin', 'TaylorF2', 'TaylorF2',
'SEOBNRv2_ROM_DoubleSpin'],
dtype='|S23'),
array([], dtype=int64))
Just return `"TaylorF2"` for all elements:
>>> arr.parse_boolargs('TaylorF2')
(array(['TaylorF2', 'TaylorF2', 'TaylorF2', 'TaylorF2', 'TaylorF2'],
dtype='|S8'),
array([], dtype=int64)) | [
"Returns",
"an",
"array",
"populated",
"by",
"given",
"values",
"with",
"the",
"indices",
"of",
"those",
"values",
"dependent",
"on",
"given",
"boolen",
"tests",
"on",
"self",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1261-L1379 |
228,363 | gwastro/pycbc | pycbc/io/record.py | FieldArray.append | def append(self, other):
"""Appends another array to this array.
The returned array will have all of the class methods and virutal
fields of this array, including any that were added using `add_method`
or `add_virtualfield`. If this array and other array have one or more
string fields, the dtype for those fields are updated to a string
length that can encompass the longest string in both arrays.
.. note::
Increasing the length of strings only works for fields, not
sub-fields.
Parameters
----------
other : array
The array to append values from. It must have the same fields and
dtype as this array, modulo the length of strings. If the other
array does not have the same dtype, a TypeError is raised.
Returns
-------
array
An array with others values appended to this array's values. The
returned array is an instance of the same class as this array,
including all methods and virtual fields.
"""
try:
return numpy.append(self, other).view(type=self.__class__)
except TypeError:
# see if the dtype error was due to string fields having different
# lengths; if so, we'll make the joint field the larger of the
# two
str_fields = [name for name in self.fieldnames
if _isstring(self.dtype[name])]
# get the larger of the two
new_strlens = dict(
[[name,
max(self.dtype[name].itemsize, other.dtype[name].itemsize)]
for name in str_fields]
)
# cast both to the new string lengths
new_dt = []
for dt in self.dtype.descr:
name = dt[0]
if name in new_strlens:
dt = (name, self.dtype[name].type, new_strlens[name])
new_dt.append(dt)
new_dt = numpy.dtype(new_dt)
return numpy.append(
self.astype(new_dt),
other.astype(new_dt)
).view(type=self.__class__) | python | def append(self, other):
try:
return numpy.append(self, other).view(type=self.__class__)
except TypeError:
# see if the dtype error was due to string fields having different
# lengths; if so, we'll make the joint field the larger of the
# two
str_fields = [name for name in self.fieldnames
if _isstring(self.dtype[name])]
# get the larger of the two
new_strlens = dict(
[[name,
max(self.dtype[name].itemsize, other.dtype[name].itemsize)]
for name in str_fields]
)
# cast both to the new string lengths
new_dt = []
for dt in self.dtype.descr:
name = dt[0]
if name in new_strlens:
dt = (name, self.dtype[name].type, new_strlens[name])
new_dt.append(dt)
new_dt = numpy.dtype(new_dt)
return numpy.append(
self.astype(new_dt),
other.astype(new_dt)
).view(type=self.__class__) | [
"def",
"append",
"(",
"self",
",",
"other",
")",
":",
"try",
":",
"return",
"numpy",
".",
"append",
"(",
"self",
",",
"other",
")",
".",
"view",
"(",
"type",
"=",
"self",
".",
"__class__",
")",
"except",
"TypeError",
":",
"# see if the dtype error was du... | Appends another array to this array.
The returned array will have all of the class methods and virutal
fields of this array, including any that were added using `add_method`
or `add_virtualfield`. If this array and other array have one or more
string fields, the dtype for those fields are updated to a string
length that can encompass the longest string in both arrays.
.. note::
Increasing the length of strings only works for fields, not
sub-fields.
Parameters
----------
other : array
The array to append values from. It must have the same fields and
dtype as this array, modulo the length of strings. If the other
array does not have the same dtype, a TypeError is raised.
Returns
-------
array
An array with others values appended to this array's values. The
returned array is an instance of the same class as this array,
including all methods and virtual fields. | [
"Appends",
"another",
"array",
"to",
"this",
"array",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1381-L1433 |
228,364 | gwastro/pycbc | pycbc/io/record.py | _FieldArrayWithDefaults.add_default_fields | def add_default_fields(self, names, **kwargs):
"""
Adds one or more empty default fields to self.
Parameters
----------
names : (list of) string(s)
The names of the fields to add. Must be a field in self's default
fields.
Other keyword args are any arguments passed to self's default fields.
Returns
-------
new array : instance of this array
A copy of this array with the field added.
"""
if isinstance(names, string_types):
names = [names]
default_fields = self.default_fields(include_virtual=False, **kwargs)
# parse out any virtual fields
arr = self.__class__(1, field_kwargs=kwargs)
# try to perserve order
sortdict = dict([[nm, ii] for ii,nm in enumerate(names)])
names = list(get_needed_fieldnames(arr, names))
names.sort(key=lambda x: sortdict[x] if x in sortdict
else len(names))
fields = [(name, default_fields[name]) for name in names]
arrays = []
names = []
for name,dt in fields:
arrays.append(default_empty(self.size, dtype=[(name, dt)]))
names.append(name)
return self.add_fields(arrays, names) | python | def add_default_fields(self, names, **kwargs):
if isinstance(names, string_types):
names = [names]
default_fields = self.default_fields(include_virtual=False, **kwargs)
# parse out any virtual fields
arr = self.__class__(1, field_kwargs=kwargs)
# try to perserve order
sortdict = dict([[nm, ii] for ii,nm in enumerate(names)])
names = list(get_needed_fieldnames(arr, names))
names.sort(key=lambda x: sortdict[x] if x in sortdict
else len(names))
fields = [(name, default_fields[name]) for name in names]
arrays = []
names = []
for name,dt in fields:
arrays.append(default_empty(self.size, dtype=[(name, dt)]))
names.append(name)
return self.add_fields(arrays, names) | [
"def",
"add_default_fields",
"(",
"self",
",",
"names",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"names",
",",
"string_types",
")",
":",
"names",
"=",
"[",
"names",
"]",
"default_fields",
"=",
"self",
".",
"default_fields",
"(",
"inclu... | Adds one or more empty default fields to self.
Parameters
----------
names : (list of) string(s)
The names of the fields to add. Must be a field in self's default
fields.
Other keyword args are any arguments passed to self's default fields.
Returns
-------
new array : instance of this array
A copy of this array with the field added. | [
"Adds",
"one",
"or",
"more",
"empty",
"default",
"fields",
"to",
"self",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1609-L1642 |
228,365 | gwastro/pycbc | pycbc/io/record.py | WaveformArray.chi_eff | def chi_eff(self):
"""Returns the effective spin."""
return conversions.chi_eff(self.mass1, self.mass2, self.spin1z,
self.spin2z) | python | def chi_eff(self):
return conversions.chi_eff(self.mass1, self.mass2, self.spin1z,
self.spin2z) | [
"def",
"chi_eff",
"(",
"self",
")",
":",
"return",
"conversions",
".",
"chi_eff",
"(",
"self",
".",
"mass1",
",",
"self",
".",
"mass2",
",",
"self",
".",
"spin1z",
",",
"self",
".",
"spin2z",
")"
] | Returns the effective spin. | [
"Returns",
"the",
"effective",
"spin",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1798-L1801 |
228,366 | gwastro/pycbc | pycbc/io/record.py | WaveformArray.spin_px | def spin_px(self):
"""Returns the x-component of the spin of the primary mass."""
return conversions.primary_spin(self.mass1, self.mass2, self.spin1x,
self.spin2x) | python | def spin_px(self):
return conversions.primary_spin(self.mass1, self.mass2, self.spin1x,
self.spin2x) | [
"def",
"spin_px",
"(",
"self",
")",
":",
"return",
"conversions",
".",
"primary_spin",
"(",
"self",
".",
"mass1",
",",
"self",
".",
"mass2",
",",
"self",
".",
"spin1x",
",",
"self",
".",
"spin2x",
")"
] | Returns the x-component of the spin of the primary mass. | [
"Returns",
"the",
"x",
"-",
"component",
"of",
"the",
"spin",
"of",
"the",
"primary",
"mass",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1804-L1807 |
228,367 | gwastro/pycbc | pycbc/io/record.py | WaveformArray.spin_py | def spin_py(self):
"""Returns the y-component of the spin of the primary mass."""
return conversions.primary_spin(self.mass1, self.mass2, self.spin1y,
self.spin2y) | python | def spin_py(self):
return conversions.primary_spin(self.mass1, self.mass2, self.spin1y,
self.spin2y) | [
"def",
"spin_py",
"(",
"self",
")",
":",
"return",
"conversions",
".",
"primary_spin",
"(",
"self",
".",
"mass1",
",",
"self",
".",
"mass2",
",",
"self",
".",
"spin1y",
",",
"self",
".",
"spin2y",
")"
] | Returns the y-component of the spin of the primary mass. | [
"Returns",
"the",
"y",
"-",
"component",
"of",
"the",
"spin",
"of",
"the",
"primary",
"mass",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1810-L1813 |
228,368 | gwastro/pycbc | pycbc/io/record.py | WaveformArray.spin_pz | def spin_pz(self):
"""Returns the z-component of the spin of the primary mass."""
return conversions.primary_spin(self.mass1, self.mass2, self.spin1z,
self.spin2z) | python | def spin_pz(self):
return conversions.primary_spin(self.mass1, self.mass2, self.spin1z,
self.spin2z) | [
"def",
"spin_pz",
"(",
"self",
")",
":",
"return",
"conversions",
".",
"primary_spin",
"(",
"self",
".",
"mass1",
",",
"self",
".",
"mass2",
",",
"self",
".",
"spin1z",
",",
"self",
".",
"spin2z",
")"
] | Returns the z-component of the spin of the primary mass. | [
"Returns",
"the",
"z",
"-",
"component",
"of",
"the",
"spin",
"of",
"the",
"primary",
"mass",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1816-L1819 |
228,369 | gwastro/pycbc | pycbc/io/record.py | WaveformArray.spin_sx | def spin_sx(self):
"""Returns the x-component of the spin of the secondary mass."""
return conversions.secondary_spin(self.mass1, self.mass2, self.spin1x,
self.spin2x) | python | def spin_sx(self):
return conversions.secondary_spin(self.mass1, self.mass2, self.spin1x,
self.spin2x) | [
"def",
"spin_sx",
"(",
"self",
")",
":",
"return",
"conversions",
".",
"secondary_spin",
"(",
"self",
".",
"mass1",
",",
"self",
".",
"mass2",
",",
"self",
".",
"spin1x",
",",
"self",
".",
"spin2x",
")"
] | Returns the x-component of the spin of the secondary mass. | [
"Returns",
"the",
"x",
"-",
"component",
"of",
"the",
"spin",
"of",
"the",
"secondary",
"mass",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1822-L1825 |
228,370 | gwastro/pycbc | pycbc/io/record.py | WaveformArray.spin_sy | def spin_sy(self):
"""Returns the y-component of the spin of the secondary mass."""
return conversions.secondary_spin(self.mass1, self.mass2, self.spin1y,
self.spin2y) | python | def spin_sy(self):
return conversions.secondary_spin(self.mass1, self.mass2, self.spin1y,
self.spin2y) | [
"def",
"spin_sy",
"(",
"self",
")",
":",
"return",
"conversions",
".",
"secondary_spin",
"(",
"self",
".",
"mass1",
",",
"self",
".",
"mass2",
",",
"self",
".",
"spin1y",
",",
"self",
".",
"spin2y",
")"
] | Returns the y-component of the spin of the secondary mass. | [
"Returns",
"the",
"y",
"-",
"component",
"of",
"the",
"spin",
"of",
"the",
"secondary",
"mass",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1828-L1831 |
228,371 | gwastro/pycbc | pycbc/io/record.py | WaveformArray.spin_sz | def spin_sz(self):
"""Returns the z-component of the spin of the secondary mass."""
return conversions.secondary_spin(self.mass1, self.mass2, self.spin1z,
self.spin2z) | python | def spin_sz(self):
return conversions.secondary_spin(self.mass1, self.mass2, self.spin1z,
self.spin2z) | [
"def",
"spin_sz",
"(",
"self",
")",
":",
"return",
"conversions",
".",
"secondary_spin",
"(",
"self",
".",
"mass1",
",",
"self",
".",
"mass2",
",",
"self",
".",
"spin1z",
",",
"self",
".",
"spin2z",
")"
] | Returns the z-component of the spin of the secondary mass. | [
"Returns",
"the",
"z",
"-",
"component",
"of",
"the",
"spin",
"of",
"the",
"secondary",
"mass",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1834-L1837 |
228,372 | gwastro/pycbc | pycbc/io/record.py | WaveformArray.spin1_a | def spin1_a(self):
"""Returns the dimensionless spin magnitude of mass 1."""
return coordinates.cartesian_to_spherical_rho(
self.spin1x, self.spin1y, self.spin1z) | python | def spin1_a(self):
return coordinates.cartesian_to_spherical_rho(
self.spin1x, self.spin1y, self.spin1z) | [
"def",
"spin1_a",
"(",
"self",
")",
":",
"return",
"coordinates",
".",
"cartesian_to_spherical_rho",
"(",
"self",
".",
"spin1x",
",",
"self",
".",
"spin1y",
",",
"self",
".",
"spin1z",
")"
] | Returns the dimensionless spin magnitude of mass 1. | [
"Returns",
"the",
"dimensionless",
"spin",
"magnitude",
"of",
"mass",
"1",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1840-L1843 |
228,373 | gwastro/pycbc | pycbc/io/record.py | WaveformArray.spin1_polar | def spin1_polar(self):
"""Returns the polar spin angle of mass 1."""
return coordinates.cartesian_to_spherical_polar(
self.spin1x, self.spin1y, self.spin1z) | python | def spin1_polar(self):
return coordinates.cartesian_to_spherical_polar(
self.spin1x, self.spin1y, self.spin1z) | [
"def",
"spin1_polar",
"(",
"self",
")",
":",
"return",
"coordinates",
".",
"cartesian_to_spherical_polar",
"(",
"self",
".",
"spin1x",
",",
"self",
".",
"spin1y",
",",
"self",
".",
"spin1z",
")"
] | Returns the polar spin angle of mass 1. | [
"Returns",
"the",
"polar",
"spin",
"angle",
"of",
"mass",
"1",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1852-L1855 |
228,374 | gwastro/pycbc | pycbc/io/record.py | WaveformArray.spin2_a | def spin2_a(self):
"""Returns the dimensionless spin magnitude of mass 2."""
return coordinates.cartesian_to_spherical_rho(
self.spin1x, self.spin1y, self.spin1z) | python | def spin2_a(self):
return coordinates.cartesian_to_spherical_rho(
self.spin1x, self.spin1y, self.spin1z) | [
"def",
"spin2_a",
"(",
"self",
")",
":",
"return",
"coordinates",
".",
"cartesian_to_spherical_rho",
"(",
"self",
".",
"spin1x",
",",
"self",
".",
"spin1y",
",",
"self",
".",
"spin1z",
")"
] | Returns the dimensionless spin magnitude of mass 2. | [
"Returns",
"the",
"dimensionless",
"spin",
"magnitude",
"of",
"mass",
"2",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1858-L1861 |
228,375 | gwastro/pycbc | pycbc/io/record.py | WaveformArray.spin2_polar | def spin2_polar(self):
"""Returns the polar spin angle of mass 2."""
return coordinates.cartesian_to_spherical_polar(
self.spin2x, self.spin2y, self.spin2z) | python | def spin2_polar(self):
return coordinates.cartesian_to_spherical_polar(
self.spin2x, self.spin2y, self.spin2z) | [
"def",
"spin2_polar",
"(",
"self",
")",
":",
"return",
"coordinates",
".",
"cartesian_to_spherical_polar",
"(",
"self",
".",
"spin2x",
",",
"self",
".",
"spin2y",
",",
"self",
".",
"spin2z",
")"
] | Returns the polar spin angle of mass 2. | [
"Returns",
"the",
"polar",
"spin",
"angle",
"of",
"mass",
"2",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L1870-L1873 |
228,376 | gwastro/pycbc | pycbc/workflow/splittable.py | setup_splittable_workflow | def setup_splittable_workflow(workflow, input_tables, out_dir=None, tags=None):
'''
This function aims to be the gateway for code that is responsible for taking
some input file containing some table, and splitting into multiple files
containing different parts of that table. For now the only supported operation
is using lalapps_splitbank to split a template bank xml file into multiple
template bank xml files.
Parameters
-----------
workflow : pycbc.workflow.core.Workflow
The Workflow instance that the jobs will be added to.
input_tables : pycbc.workflow.core.FileList
The input files to be split up.
out_dir : path
The directory in which output will be written.
Returns
--------
split_table_outs : pycbc.workflow.core.FileList
The list of split up files as output from this job.
'''
if tags is None:
tags = []
logging.info("Entering split output files module.")
make_analysis_dir(out_dir)
# Parse for options in .ini file
splitMethod = workflow.cp.get_opt_tags("workflow-splittable",
"splittable-method", tags)
if splitMethod == "IN_WORKFLOW":
# Scope here for choosing different options
logging.info("Adding split output file jobs to workflow.")
split_table_outs = setup_splittable_dax_generated(workflow,
input_tables, out_dir, tags)
elif splitMethod == "NOOP":
# Probably better not to call the module at all, but this option will
# return the input file list.
split_table_outs = input_tables
else:
errMsg = "Splittable method not recognized. Must be one of "
errMsg += "IN_WORKFLOW or NOOP."
raise ValueError(errMsg)
logging.info("Leaving split output files module.")
return split_table_outs | python | def setup_splittable_workflow(workflow, input_tables, out_dir=None, tags=None):
'''
This function aims to be the gateway for code that is responsible for taking
some input file containing some table, and splitting into multiple files
containing different parts of that table. For now the only supported operation
is using lalapps_splitbank to split a template bank xml file into multiple
template bank xml files.
Parameters
-----------
workflow : pycbc.workflow.core.Workflow
The Workflow instance that the jobs will be added to.
input_tables : pycbc.workflow.core.FileList
The input files to be split up.
out_dir : path
The directory in which output will be written.
Returns
--------
split_table_outs : pycbc.workflow.core.FileList
The list of split up files as output from this job.
'''
if tags is None:
tags = []
logging.info("Entering split output files module.")
make_analysis_dir(out_dir)
# Parse for options in .ini file
splitMethod = workflow.cp.get_opt_tags("workflow-splittable",
"splittable-method", tags)
if splitMethod == "IN_WORKFLOW":
# Scope here for choosing different options
logging.info("Adding split output file jobs to workflow.")
split_table_outs = setup_splittable_dax_generated(workflow,
input_tables, out_dir, tags)
elif splitMethod == "NOOP":
# Probably better not to call the module at all, but this option will
# return the input file list.
split_table_outs = input_tables
else:
errMsg = "Splittable method not recognized. Must be one of "
errMsg += "IN_WORKFLOW or NOOP."
raise ValueError(errMsg)
logging.info("Leaving split output files module.")
return split_table_outs | [
"def",
"setup_splittable_workflow",
"(",
"workflow",
",",
"input_tables",
",",
"out_dir",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"logging",
".",
"info",
"(",
"\"Entering split output files mod... | This function aims to be the gateway for code that is responsible for taking
some input file containing some table, and splitting into multiple files
containing different parts of that table. For now the only supported operation
is using lalapps_splitbank to split a template bank xml file into multiple
template bank xml files.
Parameters
-----------
workflow : pycbc.workflow.core.Workflow
The Workflow instance that the jobs will be added to.
input_tables : pycbc.workflow.core.FileList
The input files to be split up.
out_dir : path
The directory in which output will be written.
Returns
--------
split_table_outs : pycbc.workflow.core.FileList
The list of split up files as output from this job. | [
"This",
"function",
"aims",
"to",
"be",
"the",
"gateway",
"for",
"code",
"that",
"is",
"responsible",
"for",
"taking",
"some",
"input",
"file",
"containing",
"some",
"table",
"and",
"splitting",
"into",
"multiple",
"files",
"containing",
"different",
"parts",
... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/splittable.py#L74-L119 |
228,377 | gwastro/pycbc | pycbc/workflow/splittable.py | setup_splittable_dax_generated | def setup_splittable_dax_generated(workflow, input_tables, out_dir, tags):
'''
Function for setting up the splitting jobs as part of the workflow.
Parameters
-----------
workflow : pycbc.workflow.core.Workflow
The Workflow instance that the jobs will be added to.
input_tables : pycbc.workflow.core.FileList
The input files to be split up.
out_dir : path
The directory in which output will be written.
Returns
--------
split_table_outs : pycbc.workflow.core.FileList
The list of split up files as output from this job.
'''
cp = workflow.cp
# Get values from ini file
try:
num_splits = cp.get_opt_tags("workflow-splittable",
"splittable-num-banks", tags)
except BaseException:
inj_interval = int(cp.get_opt_tags("workflow-splittable",
"splitinjtable-interval", tags))
if cp.has_option_tags("em_bright_filter", "max-keep", tags) and \
cp.has_option("workflow-injections", "em-bright-only"):
num_injs = int(cp.get_opt_tags("em_bright_filter", "max-keep",
tags))
else:
num_injs = int(cp.get_opt_tags("workflow-injections", "num-injs",
tags))
inj_tspace = float(abs(workflow.analysis_time)) / num_injs
num_splits = int(inj_interval // inj_tspace) + 1
split_exe_tag = cp.get_opt_tags("workflow-splittable",
"splittable-exe-tag", tags)
split_exe = os.path.basename(cp.get("executables", split_exe_tag))
# Select the appropriate class
exe_class = select_splitfilejob_instance(split_exe)
# Set up output structure
out_file_groups = FileList([])
# Set up the condorJob class for the current executable
curr_exe_job = exe_class(workflow.cp, split_exe_tag, num_splits,
out_dir=out_dir)
for input in input_tables:
node = curr_exe_job.create_node(input, tags=tags)
workflow.add_node(node)
out_file_groups += node.output_files
return out_file_groups | python | def setup_splittable_dax_generated(workflow, input_tables, out_dir, tags):
'''
Function for setting up the splitting jobs as part of the workflow.
Parameters
-----------
workflow : pycbc.workflow.core.Workflow
The Workflow instance that the jobs will be added to.
input_tables : pycbc.workflow.core.FileList
The input files to be split up.
out_dir : path
The directory in which output will be written.
Returns
--------
split_table_outs : pycbc.workflow.core.FileList
The list of split up files as output from this job.
'''
cp = workflow.cp
# Get values from ini file
try:
num_splits = cp.get_opt_tags("workflow-splittable",
"splittable-num-banks", tags)
except BaseException:
inj_interval = int(cp.get_opt_tags("workflow-splittable",
"splitinjtable-interval", tags))
if cp.has_option_tags("em_bright_filter", "max-keep", tags) and \
cp.has_option("workflow-injections", "em-bright-only"):
num_injs = int(cp.get_opt_tags("em_bright_filter", "max-keep",
tags))
else:
num_injs = int(cp.get_opt_tags("workflow-injections", "num-injs",
tags))
inj_tspace = float(abs(workflow.analysis_time)) / num_injs
num_splits = int(inj_interval // inj_tspace) + 1
split_exe_tag = cp.get_opt_tags("workflow-splittable",
"splittable-exe-tag", tags)
split_exe = os.path.basename(cp.get("executables", split_exe_tag))
# Select the appropriate class
exe_class = select_splitfilejob_instance(split_exe)
# Set up output structure
out_file_groups = FileList([])
# Set up the condorJob class for the current executable
curr_exe_job = exe_class(workflow.cp, split_exe_tag, num_splits,
out_dir=out_dir)
for input in input_tables:
node = curr_exe_job.create_node(input, tags=tags)
workflow.add_node(node)
out_file_groups += node.output_files
return out_file_groups | [
"def",
"setup_splittable_dax_generated",
"(",
"workflow",
",",
"input_tables",
",",
"out_dir",
",",
"tags",
")",
":",
"cp",
"=",
"workflow",
".",
"cp",
"# Get values from ini file",
"try",
":",
"num_splits",
"=",
"cp",
".",
"get_opt_tags",
"(",
"\"workflow-splitta... | Function for setting up the splitting jobs as part of the workflow.
Parameters
-----------
workflow : pycbc.workflow.core.Workflow
The Workflow instance that the jobs will be added to.
input_tables : pycbc.workflow.core.FileList
The input files to be split up.
out_dir : path
The directory in which output will be written.
Returns
--------
split_table_outs : pycbc.workflow.core.FileList
The list of split up files as output from this job. | [
"Function",
"for",
"setting",
"up",
"the",
"splitting",
"jobs",
"as",
"part",
"of",
"the",
"workflow",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/splittable.py#L121-L175 |
228,378 | gwastro/pycbc | pycbc/results/dq.py | get_summary_page_link | def get_summary_page_link(ifo, utc_time):
"""Return a string that links to the summary page and aLOG for this ifo
Parameters
----------
ifo : string
The detector name
utc_time : sequence
First three elements must be strings giving year, month, day resp.
Returns
-------
return_string : string
String containing HTML for links to summary page and aLOG search
"""
search_form = search_form_string
data = {'H1': data_h1_string, 'L1': data_l1_string}
if ifo not in data:
return ifo
else:
# alog format is day-month-year
alog_utc = '%02d-%02d-%4d' % (utc_time[2], utc_time[1], utc_time[0])
# summary page is exactly the reverse
ext = '%4d%02d%02d' % (utc_time[0], utc_time[1], utc_time[2])
return_string = search_form % (ifo.lower(), ifo.lower(), alog_utc, alog_utc)
return return_string + data[ifo] % ext | python | def get_summary_page_link(ifo, utc_time):
search_form = search_form_string
data = {'H1': data_h1_string, 'L1': data_l1_string}
if ifo not in data:
return ifo
else:
# alog format is day-month-year
alog_utc = '%02d-%02d-%4d' % (utc_time[2], utc_time[1], utc_time[0])
# summary page is exactly the reverse
ext = '%4d%02d%02d' % (utc_time[0], utc_time[1], utc_time[2])
return_string = search_form % (ifo.lower(), ifo.lower(), alog_utc, alog_utc)
return return_string + data[ifo] % ext | [
"def",
"get_summary_page_link",
"(",
"ifo",
",",
"utc_time",
")",
":",
"search_form",
"=",
"search_form_string",
"data",
"=",
"{",
"'H1'",
":",
"data_h1_string",
",",
"'L1'",
":",
"data_l1_string",
"}",
"if",
"ifo",
"not",
"in",
"data",
":",
"return",
"ifo",... | Return a string that links to the summary page and aLOG for this ifo
Parameters
----------
ifo : string
The detector name
utc_time : sequence
First three elements must be strings giving year, month, day resp.
Returns
-------
return_string : string
String containing HTML for links to summary page and aLOG search | [
"Return",
"a",
"string",
"that",
"links",
"to",
"the",
"summary",
"page",
"and",
"aLOG",
"for",
"this",
"ifo"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/results/dq.py#L44-L69 |
228,379 | gwastro/pycbc | pycbc/libutils.py | pkg_config | def pkg_config(pkg_libraries):
"""Use pkg-config to query for the location of libraries, library directories,
and header directories
Arguments:
pkg_libries(list): A list of packages as strings
Returns:
libraries(list), library_dirs(list), include_dirs(list)
"""
libraries=[]
library_dirs=[]
include_dirs=[]
# Check that we have the packages
for pkg in pkg_libraries:
if os.system('pkg-config --exists %s 2>/dev/null' % pkg) == 0:
pass
else:
print("Could not find library {0}".format(pkg))
sys.exit(1)
# Get the pck-config flags
if len(pkg_libraries)>0 :
# PKG_CONFIG_ALLOW_SYSTEM_CFLAGS explicitly lists system paths.
# On system-wide LAL installs, this is needed for swig to find lalswig.i
for token in getoutput("PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=1 pkg-config --libs --cflags %s" % ' '.join(pkg_libraries)).split():
if token.startswith("-l"):
libraries.append(token[2:])
elif token.startswith("-L"):
library_dirs.append(token[2:])
elif token.startswith("-I"):
include_dirs.append(token[2:])
return libraries, library_dirs, include_dirs | python | def pkg_config(pkg_libraries):
libraries=[]
library_dirs=[]
include_dirs=[]
# Check that we have the packages
for pkg in pkg_libraries:
if os.system('pkg-config --exists %s 2>/dev/null' % pkg) == 0:
pass
else:
print("Could not find library {0}".format(pkg))
sys.exit(1)
# Get the pck-config flags
if len(pkg_libraries)>0 :
# PKG_CONFIG_ALLOW_SYSTEM_CFLAGS explicitly lists system paths.
# On system-wide LAL installs, this is needed for swig to find lalswig.i
for token in getoutput("PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=1 pkg-config --libs --cflags %s" % ' '.join(pkg_libraries)).split():
if token.startswith("-l"):
libraries.append(token[2:])
elif token.startswith("-L"):
library_dirs.append(token[2:])
elif token.startswith("-I"):
include_dirs.append(token[2:])
return libraries, library_dirs, include_dirs | [
"def",
"pkg_config",
"(",
"pkg_libraries",
")",
":",
"libraries",
"=",
"[",
"]",
"library_dirs",
"=",
"[",
"]",
"include_dirs",
"=",
"[",
"]",
"# Check that we have the packages",
"for",
"pkg",
"in",
"pkg_libraries",
":",
"if",
"os",
".",
"system",
"(",
"'pk... | Use pkg-config to query for the location of libraries, library directories,
and header directories
Arguments:
pkg_libries(list): A list of packages as strings
Returns:
libraries(list), library_dirs(list), include_dirs(list) | [
"Use",
"pkg",
"-",
"config",
"to",
"query",
"for",
"the",
"location",
"of",
"libraries",
"library",
"directories",
"and",
"header",
"directories"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/libutils.py#L32-L66 |
228,380 | gwastro/pycbc | pycbc/libutils.py | pkg_config_header_strings | def pkg_config_header_strings(pkg_libraries):
""" Returns a list of header strings that could be passed to a compiler
"""
_, _, header_dirs = pkg_config(pkg_libraries)
header_strings = []
for header_dir in header_dirs:
header_strings.append("-I" + header_dir)
return header_strings | python | def pkg_config_header_strings(pkg_libraries):
_, _, header_dirs = pkg_config(pkg_libraries)
header_strings = []
for header_dir in header_dirs:
header_strings.append("-I" + header_dir)
return header_strings | [
"def",
"pkg_config_header_strings",
"(",
"pkg_libraries",
")",
":",
"_",
",",
"_",
",",
"header_dirs",
"=",
"pkg_config",
"(",
"pkg_libraries",
")",
"header_strings",
"=",
"[",
"]",
"for",
"header_dir",
"in",
"header_dirs",
":",
"header_strings",
".",
"append",
... | Returns a list of header strings that could be passed to a compiler | [
"Returns",
"a",
"list",
"of",
"header",
"strings",
"that",
"could",
"be",
"passed",
"to",
"a",
"compiler"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/libutils.py#L68-L78 |
228,381 | gwastro/pycbc | pycbc/libutils.py | pkg_config_libdirs | def pkg_config_libdirs(packages):
"""
Returns a list of all library paths that pkg-config says should be included when
linking against the list of packages given as 'packages'. An empty return list means
that the package may be found in the standard system locations, irrespective of
pkg-config.
"""
# don't try calling pkg-config if NO_PKGCONFIG is set in environment
if os.environ.get("NO_PKGCONFIG", None):
return []
# if calling pkg-config failes, don't continue and don't try again.
try:
FNULL = open(os.devnull, 'w')
subprocess.check_call(["pkg-config", "--version"], stdout=FNULL, close_fds=True)
except:
print("PyCBC.libutils: pkg-config call failed, setting NO_PKGCONFIG=1",
file=sys.stderr)
os.environ['NO_PKGCONFIG'] = "1"
return []
# First, check that we can call pkg-config on each package in the list
for pkg in packages:
if not pkg_config_check_exists(pkg):
raise ValueError("Package {0} cannot be found on the pkg-config search path".format(pkg))
libdirs = []
for token in getoutput("PKG_CONFIG_ALLOW_SYSTEM_LIBS=1 pkg-config --libs-only-L {0}".format(' '.join(packages))).split():
if token.startswith("-L"):
libdirs.append(token[2:])
return libdirs | python | def pkg_config_libdirs(packages):
# don't try calling pkg-config if NO_PKGCONFIG is set in environment
if os.environ.get("NO_PKGCONFIG", None):
return []
# if calling pkg-config failes, don't continue and don't try again.
try:
FNULL = open(os.devnull, 'w')
subprocess.check_call(["pkg-config", "--version"], stdout=FNULL, close_fds=True)
except:
print("PyCBC.libutils: pkg-config call failed, setting NO_PKGCONFIG=1",
file=sys.stderr)
os.environ['NO_PKGCONFIG'] = "1"
return []
# First, check that we can call pkg-config on each package in the list
for pkg in packages:
if not pkg_config_check_exists(pkg):
raise ValueError("Package {0} cannot be found on the pkg-config search path".format(pkg))
libdirs = []
for token in getoutput("PKG_CONFIG_ALLOW_SYSTEM_LIBS=1 pkg-config --libs-only-L {0}".format(' '.join(packages))).split():
if token.startswith("-L"):
libdirs.append(token[2:])
return libdirs | [
"def",
"pkg_config_libdirs",
"(",
"packages",
")",
":",
"# don't try calling pkg-config if NO_PKGCONFIG is set in environment",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"NO_PKGCONFIG\"",
",",
"None",
")",
":",
"return",
"[",
"]",
"# if calling pkg-config failes, don... | Returns a list of all library paths that pkg-config says should be included when
linking against the list of packages given as 'packages'. An empty return list means
that the package may be found in the standard system locations, irrespective of
pkg-config. | [
"Returns",
"a",
"list",
"of",
"all",
"library",
"paths",
"that",
"pkg",
"-",
"config",
"says",
"should",
"be",
"included",
"when",
"linking",
"against",
"the",
"list",
"of",
"packages",
"given",
"as",
"packages",
".",
"An",
"empty",
"return",
"list",
"mean... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/libutils.py#L83-L114 |
228,382 | gwastro/pycbc | pycbc/libutils.py | get_libpath_from_dirlist | def get_libpath_from_dirlist(libname, dirs):
"""
This function tries to find the architecture-independent library given by libname in the first
available directory in the list dirs. 'Architecture-independent' means omitting any prefix such
as 'lib' or suffix such as 'so' or 'dylib' or version number. Within the first directory in which
a matching pattern can be found, the lexicographically first such file is returned, as a string
giving the full path name. The only supported OSes at the moment are posix and mac, and this
function does not attempt to determine which is being run. So if for some reason your directory
has both '.so' and '.dylib' libraries, who knows what will happen. If the library cannot be found,
None is returned.
"""
dirqueue = deque(dirs)
while (len(dirqueue) > 0):
nextdir = dirqueue.popleft()
possible = []
# Our directory might be no good, so try/except
try:
for libfile in os.listdir(nextdir):
if fnmatch.fnmatch(libfile,'lib'+libname+'.so*') or \
fnmatch.fnmatch(libfile,'lib'+libname+'.dylib*') or \
fnmatch.fnmatch(libfile,libname+'.dll') or \
fnmatch.fnmatch(libfile,'cyg'+libname+'-*.dll'):
possible.append(libfile)
except OSError:
pass
# There might be more than one library found, we want the highest-numbered
if (len(possible) > 0):
possible.sort()
return os.path.join(nextdir,possible[-1])
# If we get here, we didn't find it...
return None | python | def get_libpath_from_dirlist(libname, dirs):
dirqueue = deque(dirs)
while (len(dirqueue) > 0):
nextdir = dirqueue.popleft()
possible = []
# Our directory might be no good, so try/except
try:
for libfile in os.listdir(nextdir):
if fnmatch.fnmatch(libfile,'lib'+libname+'.so*') or \
fnmatch.fnmatch(libfile,'lib'+libname+'.dylib*') or \
fnmatch.fnmatch(libfile,libname+'.dll') or \
fnmatch.fnmatch(libfile,'cyg'+libname+'-*.dll'):
possible.append(libfile)
except OSError:
pass
# There might be more than one library found, we want the highest-numbered
if (len(possible) > 0):
possible.sort()
return os.path.join(nextdir,possible[-1])
# If we get here, we didn't find it...
return None | [
"def",
"get_libpath_from_dirlist",
"(",
"libname",
",",
"dirs",
")",
":",
"dirqueue",
"=",
"deque",
"(",
"dirs",
")",
"while",
"(",
"len",
"(",
"dirqueue",
")",
">",
"0",
")",
":",
"nextdir",
"=",
"dirqueue",
".",
"popleft",
"(",
")",
"possible",
"=",
... | This function tries to find the architecture-independent library given by libname in the first
available directory in the list dirs. 'Architecture-independent' means omitting any prefix such
as 'lib' or suffix such as 'so' or 'dylib' or version number. Within the first directory in which
a matching pattern can be found, the lexicographically first such file is returned, as a string
giving the full path name. The only supported OSes at the moment are posix and mac, and this
function does not attempt to determine which is being run. So if for some reason your directory
has both '.so' and '.dylib' libraries, who knows what will happen. If the library cannot be found,
None is returned. | [
"This",
"function",
"tries",
"to",
"find",
"the",
"architecture",
"-",
"independent",
"library",
"given",
"by",
"libname",
"in",
"the",
"first",
"available",
"directory",
"in",
"the",
"list",
"dirs",
".",
"Architecture",
"-",
"independent",
"means",
"omitting",
... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/libutils.py#L116-L146 |
228,383 | gwastro/pycbc | pycbc/inference/io/base_mcmc.py | thin_samples_for_writing | def thin_samples_for_writing(fp, samples, parameters, last_iteration):
"""Thins samples for writing to disk.
The thinning interval to use is determined by the given file handler's
``thinned_by`` attribute. If that attribute is 1, just returns the samples.
Parameters
----------
fp : MCMCMetadataIO instance
The file the sampels will be written to. Needed to determine the
thin interval used on disk.
samples : dict
Dictionary mapping parameter names to arrays of (unthinned) samples.
The arrays are thinned along their last dimension.
parameters : list of str
The parameters to thin in ``samples`` before writing. All listed
parameters must be in ``samples``.
last_iteration : int
The iteration that the last sample in ``samples`` occurred at. This is
needed to figure out where to start the thinning in ``samples``, such
that the interval between the last sample on disk and the first new
sample is the same as all of the other samples.
Returns
-------
dict :
Dictionary of the thinned samples to write.
"""
if fp.thinned_by > 1:
if last_iteration is None:
raise ValueError("File's thinned_by attribute is > 1 ({}), "
"but last_iteration not provided."
.format(fp.thinned_by))
thinned_samples = {}
for param in parameters:
data = samples[param]
nsamples = data.shape[-1]
# To figure out where to start:
# the last iteration in the file + the file's thinning interval
# gives the iteration of the next sample that should be written;
# last_iteration - nsamples gives the iteration of the first
# sample in samples. Subtracting the latter from the former - 1
# (-1 to convert from iteration to index) therefore gives the index
# in the samples data to start using samples.
thin_start = fp.last_iteration(param) + fp.thinned_by \
- (last_iteration - nsamples) - 1
thinned_samples[param] = data[..., thin_start::fp.thinned_by]
else:
thinned_samples = samples
return thinned_samples | python | def thin_samples_for_writing(fp, samples, parameters, last_iteration):
if fp.thinned_by > 1:
if last_iteration is None:
raise ValueError("File's thinned_by attribute is > 1 ({}), "
"but last_iteration not provided."
.format(fp.thinned_by))
thinned_samples = {}
for param in parameters:
data = samples[param]
nsamples = data.shape[-1]
# To figure out where to start:
# the last iteration in the file + the file's thinning interval
# gives the iteration of the next sample that should be written;
# last_iteration - nsamples gives the iteration of the first
# sample in samples. Subtracting the latter from the former - 1
# (-1 to convert from iteration to index) therefore gives the index
# in the samples data to start using samples.
thin_start = fp.last_iteration(param) + fp.thinned_by \
- (last_iteration - nsamples) - 1
thinned_samples[param] = data[..., thin_start::fp.thinned_by]
else:
thinned_samples = samples
return thinned_samples | [
"def",
"thin_samples_for_writing",
"(",
"fp",
",",
"samples",
",",
"parameters",
",",
"last_iteration",
")",
":",
"if",
"fp",
".",
"thinned_by",
">",
"1",
":",
"if",
"last_iteration",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"File's thinned_by attribute ... | Thins samples for writing to disk.
The thinning interval to use is determined by the given file handler's
``thinned_by`` attribute. If that attribute is 1, just returns the samples.
Parameters
----------
fp : MCMCMetadataIO instance
The file the sampels will be written to. Needed to determine the
thin interval used on disk.
samples : dict
Dictionary mapping parameter names to arrays of (unthinned) samples.
The arrays are thinned along their last dimension.
parameters : list of str
The parameters to thin in ``samples`` before writing. All listed
parameters must be in ``samples``.
last_iteration : int
The iteration that the last sample in ``samples`` occurred at. This is
needed to figure out where to start the thinning in ``samples``, such
that the interval between the last sample on disk and the first new
sample is the same as all of the other samples.
Returns
-------
dict :
Dictionary of the thinned samples to write. | [
"Thins",
"samples",
"for",
"writing",
"to",
"disk",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/io/base_mcmc.py#L425-L474 |
228,384 | gwastro/pycbc | pycbc/inference/io/base_mcmc.py | MCMCMetadataIO.write_resume_point | def write_resume_point(self):
"""Keeps a list of the number of iterations that were in a file when a
run was resumed from a checkpoint."""
try:
resume_pts = self.attrs["resume_points"].tolist()
except KeyError:
resume_pts = []
try:
niterations = self.niterations
except KeyError:
niterations = 0
resume_pts.append(niterations)
self.attrs["resume_points"] = resume_pts | python | def write_resume_point(self):
try:
resume_pts = self.attrs["resume_points"].tolist()
except KeyError:
resume_pts = []
try:
niterations = self.niterations
except KeyError:
niterations = 0
resume_pts.append(niterations)
self.attrs["resume_points"] = resume_pts | [
"def",
"write_resume_point",
"(",
"self",
")",
":",
"try",
":",
"resume_pts",
"=",
"self",
".",
"attrs",
"[",
"\"resume_points\"",
"]",
".",
"tolist",
"(",
")",
"except",
"KeyError",
":",
"resume_pts",
"=",
"[",
"]",
"try",
":",
"niterations",
"=",
"self... | Keeps a list of the number of iterations that were in a file when a
run was resumed from a checkpoint. | [
"Keeps",
"a",
"list",
"of",
"the",
"number",
"of",
"iterations",
"that",
"were",
"in",
"a",
"file",
"when",
"a",
"run",
"was",
"resumed",
"from",
"a",
"checkpoint",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/io/base_mcmc.py#L35-L47 |
228,385 | gwastro/pycbc | pycbc/inference/io/base_mcmc.py | MCMCMetadataIO.thin | def thin(self, thin_interval):
"""Thins the samples on disk using the given thinning interval.
Parameters
----------
thin_interval : int
The interval to thin by.
"""
# read thinned samples into memory
params = self[self.samples_group].keys()
samples = self.read_raw_samples(params, thin_start=0,
thin_interval=thin_interval,
thin_end=None,
flatten=False)
# now resize and write the data back to disk
group = self[self.samples_group]
for param in params:
data = samples[param]
# resize the arrays on disk
group[param].resize(data.shape)
# and write
group[param][:] = data
# store the interval that samples were thinned by
self.thinned_by *= thin_interval
# If a default thin interval and thin start exist, reduce them by the
# thinned interval. If the thin interval is not an integer multiple
# of the original, we'll round up, to avoid getting samples from
# before the burn in / at an interval less than the ACL.
self.thin_start = int(numpy.ceil(self.thin_start/thin_interval))
self.thin_interval = int(numpy.ceil(self.thin_interval/thin_interval)) | python | def thin(self, thin_interval):
# read thinned samples into memory
params = self[self.samples_group].keys()
samples = self.read_raw_samples(params, thin_start=0,
thin_interval=thin_interval,
thin_end=None,
flatten=False)
# now resize and write the data back to disk
group = self[self.samples_group]
for param in params:
data = samples[param]
# resize the arrays on disk
group[param].resize(data.shape)
# and write
group[param][:] = data
# store the interval that samples were thinned by
self.thinned_by *= thin_interval
# If a default thin interval and thin start exist, reduce them by the
# thinned interval. If the thin interval is not an integer multiple
# of the original, we'll round up, to avoid getting samples from
# before the burn in / at an interval less than the ACL.
self.thin_start = int(numpy.ceil(self.thin_start/thin_interval))
self.thin_interval = int(numpy.ceil(self.thin_interval/thin_interval)) | [
"def",
"thin",
"(",
"self",
",",
"thin_interval",
")",
":",
"# read thinned samples into memory",
"params",
"=",
"self",
"[",
"self",
".",
"samples_group",
"]",
".",
"keys",
"(",
")",
"samples",
"=",
"self",
".",
"read_raw_samples",
"(",
"params",
",",
"thin... | Thins the samples on disk using the given thinning interval.
Parameters
----------
thin_interval : int
The interval to thin by. | [
"Thins",
"the",
"samples",
"on",
"disk",
"using",
"the",
"given",
"thinning",
"interval",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/io/base_mcmc.py#L63-L92 |
228,386 | gwastro/pycbc | pycbc/inference/io/base_mcmc.py | MCMCMetadataIO.last_iteration | def last_iteration(self, parameter=None):
"""Returns the iteration of the last sample of the given parameter.
If parameter is ``None``, will just use the first parameter in the
samples group.
"""
if parameter is None:
try:
parameter = list(self[self.samples_group].keys())[0]
except (IndexError, KeyError):
# nothing has been written yet, just return 0
return 0
try:
lastiter = self[self.samples_group][parameter].shape[-1]
except KeyError:
# no samples have been written, just return 0
lastiter = 0
# account for thinning
return lastiter * self.thinned_by | python | def last_iteration(self, parameter=None):
if parameter is None:
try:
parameter = list(self[self.samples_group].keys())[0]
except (IndexError, KeyError):
# nothing has been written yet, just return 0
return 0
try:
lastiter = self[self.samples_group][parameter].shape[-1]
except KeyError:
# no samples have been written, just return 0
lastiter = 0
# account for thinning
return lastiter * self.thinned_by | [
"def",
"last_iteration",
"(",
"self",
",",
"parameter",
"=",
"None",
")",
":",
"if",
"parameter",
"is",
"None",
":",
"try",
":",
"parameter",
"=",
"list",
"(",
"self",
"[",
"self",
".",
"samples_group",
"]",
".",
"keys",
"(",
")",
")",
"[",
"0",
"]... | Returns the iteration of the last sample of the given parameter.
If parameter is ``None``, will just use the first parameter in the
samples group. | [
"Returns",
"the",
"iteration",
"of",
"the",
"last",
"sample",
"of",
"the",
"given",
"parameter",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/io/base_mcmc.py#L117-L135 |
228,387 | gwastro/pycbc | pycbc/inference/io/base_mcmc.py | MCMCMetadataIO.iterations | def iterations(self, parameter):
"""Returns the iteration each sample occurred at."""
return numpy.arange(0, self.last_iteration(parameter), self.thinned_by) | python | def iterations(self, parameter):
return numpy.arange(0, self.last_iteration(parameter), self.thinned_by) | [
"def",
"iterations",
"(",
"self",
",",
"parameter",
")",
":",
"return",
"numpy",
".",
"arange",
"(",
"0",
",",
"self",
".",
"last_iteration",
"(",
"parameter",
")",
",",
"self",
".",
"thinned_by",
")"
] | Returns the iteration each sample occurred at. | [
"Returns",
"the",
"iteration",
"each",
"sample",
"occurred",
"at",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/io/base_mcmc.py#L137-L139 |
228,388 | gwastro/pycbc | pycbc/inference/io/base_mcmc.py | MCMCMetadataIO.write_sampler_metadata | def write_sampler_metadata(self, sampler):
"""Writes the sampler's metadata."""
self.attrs['sampler'] = sampler.name
self[self.sampler_group].attrs['nwalkers'] = sampler.nwalkers
# write the model's metadata
sampler.model.write_metadata(self) | python | def write_sampler_metadata(self, sampler):
self.attrs['sampler'] = sampler.name
self[self.sampler_group].attrs['nwalkers'] = sampler.nwalkers
# write the model's metadata
sampler.model.write_metadata(self) | [
"def",
"write_sampler_metadata",
"(",
"self",
",",
"sampler",
")",
":",
"self",
".",
"attrs",
"[",
"'sampler'",
"]",
"=",
"sampler",
".",
"name",
"self",
"[",
"self",
".",
"sampler_group",
"]",
".",
"attrs",
"[",
"'nwalkers'",
"]",
"=",
"sampler",
".",
... | Writes the sampler's metadata. | [
"Writes",
"the",
"sampler",
"s",
"metadata",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/io/base_mcmc.py#L141-L146 |
228,389 | gwastro/pycbc | pycbc/inference/io/base_mcmc.py | MCMCMetadataIO.write_acls | def write_acls(self, acls):
"""Writes the given autocorrelation lengths.
The ACL of each parameter is saved to
``[sampler_group]/acls/{param}']``. The maximum over all the
parameters is saved to the file's 'acl' attribute.
Parameters
----------
acls : dict
A dictionary of ACLs keyed by the parameter.
Returns
-------
ACL
The maximum of the acls that was written to the file.
"""
group = self.sampler_group + '/acls/{}'
# write the individual acls
for param in acls:
try:
# we need to use the write_direct function because it's
# apparently the only way to update scalars in h5py
self[group.format(param)].write_direct(
numpy.array(acls[param]))
except KeyError:
# dataset doesn't exist yet
self[group.format(param)] = acls[param]
# write the maximum over all params
acl = numpy.array(acls.values()).max()
self[self.sampler_group].attrs['acl'] = acl
# set the default thin interval to be the acl (if it is finite)
if numpy.isfinite(acl):
self.thin_interval = int(numpy.ceil(acl)) | python | def write_acls(self, acls):
group = self.sampler_group + '/acls/{}'
# write the individual acls
for param in acls:
try:
# we need to use the write_direct function because it's
# apparently the only way to update scalars in h5py
self[group.format(param)].write_direct(
numpy.array(acls[param]))
except KeyError:
# dataset doesn't exist yet
self[group.format(param)] = acls[param]
# write the maximum over all params
acl = numpy.array(acls.values()).max()
self[self.sampler_group].attrs['acl'] = acl
# set the default thin interval to be the acl (if it is finite)
if numpy.isfinite(acl):
self.thin_interval = int(numpy.ceil(acl)) | [
"def",
"write_acls",
"(",
"self",
",",
"acls",
")",
":",
"group",
"=",
"self",
".",
"sampler_group",
"+",
"'/acls/{}'",
"# write the individual acls",
"for",
"param",
"in",
"acls",
":",
"try",
":",
"# we need to use the write_direct function because it's",
"# apparent... | Writes the given autocorrelation lengths.
The ACL of each parameter is saved to
``[sampler_group]/acls/{param}']``. The maximum over all the
parameters is saved to the file's 'acl' attribute.
Parameters
----------
acls : dict
A dictionary of ACLs keyed by the parameter.
Returns
-------
ACL
The maximum of the acls that was written to the file. | [
"Writes",
"the",
"given",
"autocorrelation",
"lengths",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/io/base_mcmc.py#L148-L181 |
228,390 | gwastro/pycbc | pycbc/inference/io/base_mcmc.py | MCMCMetadataIO.read_acls | def read_acls(self):
"""Reads the acls of all the parameters.
Returns
-------
dict
A dictionary of the ACLs, keyed by the parameter name.
"""
group = self[self.sampler_group]['acls']
return {param: group[param].value for param in group.keys()} | python | def read_acls(self):
group = self[self.sampler_group]['acls']
return {param: group[param].value for param in group.keys()} | [
"def",
"read_acls",
"(",
"self",
")",
":",
"group",
"=",
"self",
"[",
"self",
".",
"sampler_group",
"]",
"[",
"'acls'",
"]",
"return",
"{",
"param",
":",
"group",
"[",
"param",
"]",
".",
"value",
"for",
"param",
"in",
"group",
".",
"keys",
"(",
")"... | Reads the acls of all the parameters.
Returns
-------
dict
A dictionary of the ACLs, keyed by the parameter name. | [
"Reads",
"the",
"acls",
"of",
"all",
"the",
"parameters",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/io/base_mcmc.py#L183-L192 |
228,391 | gwastro/pycbc | pycbc/inference/io/base_mcmc.py | MCMCMetadataIO.write_burn_in | def write_burn_in(self, burn_in):
"""Write the given burn-in data to the given filename."""
group = self[self.sampler_group]
group.attrs['burn_in_test'] = burn_in.burn_in_test
group.attrs['is_burned_in'] = burn_in.is_burned_in
group.attrs['burn_in_iteration'] = burn_in.burn_in_iteration
# set the defaut thin_start to be the burn_in_index
self.thin_start = burn_in.burn_in_index
# write individual test data
for tst in burn_in.burn_in_data:
key = 'burn_in_tests/{}'.format(tst)
try:
attrs = group[key].attrs
except KeyError:
group.create_group(key)
attrs = group[key].attrs
self.write_kwargs_to_attrs(attrs, **burn_in.burn_in_data[tst]) | python | def write_burn_in(self, burn_in):
group = self[self.sampler_group]
group.attrs['burn_in_test'] = burn_in.burn_in_test
group.attrs['is_burned_in'] = burn_in.is_burned_in
group.attrs['burn_in_iteration'] = burn_in.burn_in_iteration
# set the defaut thin_start to be the burn_in_index
self.thin_start = burn_in.burn_in_index
# write individual test data
for tst in burn_in.burn_in_data:
key = 'burn_in_tests/{}'.format(tst)
try:
attrs = group[key].attrs
except KeyError:
group.create_group(key)
attrs = group[key].attrs
self.write_kwargs_to_attrs(attrs, **burn_in.burn_in_data[tst]) | [
"def",
"write_burn_in",
"(",
"self",
",",
"burn_in",
")",
":",
"group",
"=",
"self",
"[",
"self",
".",
"sampler_group",
"]",
"group",
".",
"attrs",
"[",
"'burn_in_test'",
"]",
"=",
"burn_in",
".",
"burn_in_test",
"group",
".",
"attrs",
"[",
"'is_burned_in'... | Write the given burn-in data to the given filename. | [
"Write",
"the",
"given",
"burn",
"-",
"in",
"data",
"to",
"the",
"given",
"filename",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/io/base_mcmc.py#L194-L210 |
228,392 | gwastro/pycbc | pycbc/inference/io/base_mcmc.py | MCMCMetadataIO.extra_args_parser | def extra_args_parser(parser=None, skip_args=None, **kwargs):
"""Create a parser to parse sampler-specific arguments for loading
samples.
Parameters
----------
parser : argparse.ArgumentParser, optional
Instead of creating a parser, add arguments to the given one. If
none provided, will create one.
skip_args : list, optional
Don't parse the given options. Options should be given as the
option string, minus the '--'. For example,
``skip_args=['iteration']`` would cause the ``--iteration``
argument not to be included.
\**kwargs :
All other keyword arguments are passed to the parser that is
created.
Returns
-------
parser : argparse.ArgumentParser
An argument parser with th extra arguments added.
actions : list of argparse.Action
A list of the actions that were added.
"""
if parser is None:
parser = argparse.ArgumentParser(**kwargs)
elif kwargs:
raise ValueError("No other keyword arguments should be provded if "
"a parser is provided.")
if skip_args is None:
skip_args = []
actions = []
if 'thin-start' not in skip_args:
act = parser.add_argument(
"--thin-start", type=int, default=None,
help="Sample number to start collecting samples to plot. If "
"none provided, will use the input file's `thin_start` "
"attribute.")
actions.append(act)
if 'thin-interval' not in skip_args:
act = parser.add_argument(
"--thin-interval", type=int, default=None,
help="Interval to use for thinning samples. If none provided, "
"will use the input file's `thin_interval` attribute.")
actions.append(act)
if 'thin-end' not in skip_args:
act = parser.add_argument(
"--thin-end", type=int, default=None,
help="Sample number to stop collecting samples to plot. If "
"none provided, will use the input file's `thin_end` "
"attribute.")
actions.append(act)
if 'iteration' not in skip_args:
act = parser.add_argument(
"--iteration", type=int, default=None,
help="Only retrieve the given iteration. To load "
"the last n-th sampe use -n, e.g., -1 will "
"load the last iteration. This overrides "
"the thin-start/interval/end options.")
actions.append(act)
if 'walkers' not in skip_args:
act = parser.add_argument(
"--walkers", type=int, nargs="+", default=None,
help="Only retrieve samples from the listed "
"walkers. Default is to retrieve from all "
"walkers.")
actions.append(act)
return parser, actions | python | def extra_args_parser(parser=None, skip_args=None, **kwargs):
if parser is None:
parser = argparse.ArgumentParser(**kwargs)
elif kwargs:
raise ValueError("No other keyword arguments should be provded if "
"a parser is provided.")
if skip_args is None:
skip_args = []
actions = []
if 'thin-start' not in skip_args:
act = parser.add_argument(
"--thin-start", type=int, default=None,
help="Sample number to start collecting samples to plot. If "
"none provided, will use the input file's `thin_start` "
"attribute.")
actions.append(act)
if 'thin-interval' not in skip_args:
act = parser.add_argument(
"--thin-interval", type=int, default=None,
help="Interval to use for thinning samples. If none provided, "
"will use the input file's `thin_interval` attribute.")
actions.append(act)
if 'thin-end' not in skip_args:
act = parser.add_argument(
"--thin-end", type=int, default=None,
help="Sample number to stop collecting samples to plot. If "
"none provided, will use the input file's `thin_end` "
"attribute.")
actions.append(act)
if 'iteration' not in skip_args:
act = parser.add_argument(
"--iteration", type=int, default=None,
help="Only retrieve the given iteration. To load "
"the last n-th sampe use -n, e.g., -1 will "
"load the last iteration. This overrides "
"the thin-start/interval/end options.")
actions.append(act)
if 'walkers' not in skip_args:
act = parser.add_argument(
"--walkers", type=int, nargs="+", default=None,
help="Only retrieve samples from the listed "
"walkers. Default is to retrieve from all "
"walkers.")
actions.append(act)
return parser, actions | [
"def",
"extra_args_parser",
"(",
"parser",
"=",
"None",
",",
"skip_args",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"parser",
"is",
"None",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"*",
"*",
"kwargs",
")",
"elif",
"kwargs... | Create a parser to parse sampler-specific arguments for loading
samples.
Parameters
----------
parser : argparse.ArgumentParser, optional
Instead of creating a parser, add arguments to the given one. If
none provided, will create one.
skip_args : list, optional
Don't parse the given options. Options should be given as the
option string, minus the '--'. For example,
``skip_args=['iteration']`` would cause the ``--iteration``
argument not to be included.
\**kwargs :
All other keyword arguments are passed to the parser that is
created.
Returns
-------
parser : argparse.ArgumentParser
An argument parser with th extra arguments added.
actions : list of argparse.Action
A list of the actions that were added. | [
"Create",
"a",
"parser",
"to",
"parse",
"sampler",
"-",
"specific",
"arguments",
"for",
"loading",
"samples",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/io/base_mcmc.py#L213-L281 |
228,393 | gwastro/pycbc | pycbc/inference/io/base_mcmc.py | SingleTempMCMCIO.write_samples | def write_samples(self, samples, parameters=None, last_iteration=None):
"""Writes samples to the given file.
Results are written to ``samples_group/{vararg}``, where ``{vararg}``
is the name of a model params. The samples are written as an
``nwalkers x niterations`` array. If samples already exist, the new
samples are appended to the current.
If the current samples on disk have been thinned (determined by the
``thinned_by`` attribute in the samples group), then the samples will
be thinned by the same amount before being written. The thinning is
started at the sample in ``samples`` that occured at the iteration
equal to the last iteration on disk plus the ``thinned_by`` interval.
If this iteration is larger than the iteration of the last given
sample, then none of the samples will be written.
Parameters
-----------
samples : dict
The samples to write. Each array in the dictionary should have
shape nwalkers x niterations.
parameters : list, optional
Only write the specified parameters to the file. If None, will
write all of the keys in the ``samples`` dict.
last_iteration : int, optional
The iteration of the last sample. If the file's ``thinned_by``
attribute is > 1, this is needed to determine where to start
thinning the samples such that the interval between the last sample
currently on disk and the first new sample is the same as all of
the other samples.
"""
nwalkers, nsamples = list(samples.values())[0].shape
assert all(p.shape == (nwalkers, nsamples)
for p in samples.values()), (
"all samples must have the same shape")
group = self.samples_group + '/{name}'
if parameters is None:
parameters = samples.keys()
# thin the samples
samples = thin_samples_for_writing(self, samples, parameters, last_iteration)
# loop over number of dimensions
for param in parameters:
dataset_name = group.format(name=param)
data = samples[param]
# check that there's something to write after thinning
if data.shape[1] == 0:
# nothing to write, move along
continue
try:
fp_nsamples = self[dataset_name].shape[-1]
istart = fp_nsamples
istop = istart + data.shape[1]
if istop > fp_nsamples:
# resize the dataset
self[dataset_name].resize(istop, axis=1)
except KeyError:
# dataset doesn't exist yet
istart = 0
istop = istart + data.shape[1]
self.create_dataset(dataset_name, (nwalkers, istop),
maxshape=(nwalkers, None),
dtype=data.dtype,
fletcher32=True)
self[dataset_name][:, istart:istop] = data | python | def write_samples(self, samples, parameters=None, last_iteration=None):
nwalkers, nsamples = list(samples.values())[0].shape
assert all(p.shape == (nwalkers, nsamples)
for p in samples.values()), (
"all samples must have the same shape")
group = self.samples_group + '/{name}'
if parameters is None:
parameters = samples.keys()
# thin the samples
samples = thin_samples_for_writing(self, samples, parameters, last_iteration)
# loop over number of dimensions
for param in parameters:
dataset_name = group.format(name=param)
data = samples[param]
# check that there's something to write after thinning
if data.shape[1] == 0:
# nothing to write, move along
continue
try:
fp_nsamples = self[dataset_name].shape[-1]
istart = fp_nsamples
istop = istart + data.shape[1]
if istop > fp_nsamples:
# resize the dataset
self[dataset_name].resize(istop, axis=1)
except KeyError:
# dataset doesn't exist yet
istart = 0
istop = istart + data.shape[1]
self.create_dataset(dataset_name, (nwalkers, istop),
maxshape=(nwalkers, None),
dtype=data.dtype,
fletcher32=True)
self[dataset_name][:, istart:istop] = data | [
"def",
"write_samples",
"(",
"self",
",",
"samples",
",",
"parameters",
"=",
"None",
",",
"last_iteration",
"=",
"None",
")",
":",
"nwalkers",
",",
"nsamples",
"=",
"list",
"(",
"samples",
".",
"values",
"(",
")",
")",
"[",
"0",
"]",
".",
"shape",
"a... | Writes samples to the given file.
Results are written to ``samples_group/{vararg}``, where ``{vararg}``
is the name of a model params. The samples are written as an
``nwalkers x niterations`` array. If samples already exist, the new
samples are appended to the current.
If the current samples on disk have been thinned (determined by the
``thinned_by`` attribute in the samples group), then the samples will
be thinned by the same amount before being written. The thinning is
started at the sample in ``samples`` that occured at the iteration
equal to the last iteration on disk plus the ``thinned_by`` interval.
If this iteration is larger than the iteration of the last given
sample, then none of the samples will be written.
Parameters
-----------
samples : dict
The samples to write. Each array in the dictionary should have
shape nwalkers x niterations.
parameters : list, optional
Only write the specified parameters to the file. If None, will
write all of the keys in the ``samples`` dict.
last_iteration : int, optional
The iteration of the last sample. If the file's ``thinned_by``
attribute is > 1, this is needed to determine where to start
thinning the samples such that the interval between the last sample
currently on disk and the first new sample is the same as all of
the other samples. | [
"Writes",
"samples",
"to",
"the",
"given",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/io/base_mcmc.py#L291-L354 |
228,394 | gwastro/pycbc | pycbc/inference/io/base_mcmc.py | SingleTempMCMCIO.read_raw_samples | def read_raw_samples(self, fields,
thin_start=None, thin_interval=None, thin_end=None,
iteration=None, walkers=None, flatten=True):
"""Base function for reading samples.
Parameters
-----------
fields : list
The list of field names to retrieve. Must be names of datasets in
the ``samples_group``.
thin_start : int, optional
Start reading from the given iteration. Default is to start from
the first iteration.
thin_interval : int, optional
Only read every ``thin_interval`` -th sample. Default is 1.
thin_end : int, optional
Stop reading at the given iteration. Default is to end at the last
iteration.
iteration : int, optional
Only read the given iteration. If this provided, it overrides
the ``thin_(start|interval|end)`` options.
walkers : int, optional
Only read from the given walkers. Default is to read all.
flatten : bool, optional
Flatten the samples to 1D arrays before returning. Otherwise, the
returned arrays will have shape (requested walkers x
requested iteration(s)). Default is True.
Returns
-------
dict
A dictionary of field name -> numpy array pairs.
"""
if isinstance(fields, (str, unicode)):
fields = [fields]
# walkers to load
if walkers is not None:
widx = numpy.zeros(self.nwalkers, dtype=bool)
widx[walkers] = True
nwalkers = widx.sum()
else:
widx = slice(0, None)
nwalkers = self.nwalkers
# get the slice to use
if iteration is not None:
get_index = int(iteration)
niterations = 1
else:
get_index = self.get_slice(thin_start=thin_start,
thin_end=thin_end,
thin_interval=thin_interval)
# we'll just get the number of iterations from the returned shape
niterations = None
# load
group = self.samples_group + '/{name}'
arrays = {}
for name in fields:
arr = self[group.format(name=name)][widx, get_index]
if niterations is None:
niterations = arr.shape[-1]
if flatten:
arr = arr.flatten()
else:
# ensure that the returned array is 2D
arr = arr.reshape((nwalkers, niterations))
arrays[name] = arr
return arrays | python | def read_raw_samples(self, fields,
thin_start=None, thin_interval=None, thin_end=None,
iteration=None, walkers=None, flatten=True):
if isinstance(fields, (str, unicode)):
fields = [fields]
# walkers to load
if walkers is not None:
widx = numpy.zeros(self.nwalkers, dtype=bool)
widx[walkers] = True
nwalkers = widx.sum()
else:
widx = slice(0, None)
nwalkers = self.nwalkers
# get the slice to use
if iteration is not None:
get_index = int(iteration)
niterations = 1
else:
get_index = self.get_slice(thin_start=thin_start,
thin_end=thin_end,
thin_interval=thin_interval)
# we'll just get the number of iterations from the returned shape
niterations = None
# load
group = self.samples_group + '/{name}'
arrays = {}
for name in fields:
arr = self[group.format(name=name)][widx, get_index]
if niterations is None:
niterations = arr.shape[-1]
if flatten:
arr = arr.flatten()
else:
# ensure that the returned array is 2D
arr = arr.reshape((nwalkers, niterations))
arrays[name] = arr
return arrays | [
"def",
"read_raw_samples",
"(",
"self",
",",
"fields",
",",
"thin_start",
"=",
"None",
",",
"thin_interval",
"=",
"None",
",",
"thin_end",
"=",
"None",
",",
"iteration",
"=",
"None",
",",
"walkers",
"=",
"None",
",",
"flatten",
"=",
"True",
")",
":",
"... | Base function for reading samples.
Parameters
-----------
fields : list
The list of field names to retrieve. Must be names of datasets in
the ``samples_group``.
thin_start : int, optional
Start reading from the given iteration. Default is to start from
the first iteration.
thin_interval : int, optional
Only read every ``thin_interval`` -th sample. Default is 1.
thin_end : int, optional
Stop reading at the given iteration. Default is to end at the last
iteration.
iteration : int, optional
Only read the given iteration. If this provided, it overrides
the ``thin_(start|interval|end)`` options.
walkers : int, optional
Only read from the given walkers. Default is to read all.
flatten : bool, optional
Flatten the samples to 1D arrays before returning. Otherwise, the
returned arrays will have shape (requested walkers x
requested iteration(s)). Default is True.
Returns
-------
dict
A dictionary of field name -> numpy array pairs. | [
"Base",
"function",
"for",
"reading",
"samples",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/io/base_mcmc.py#L356-L422 |
228,395 | gwastro/pycbc | pycbc/workflow/datafind.py | setup_datafind_runtime_frames_single_call_perifo | def setup_datafind_runtime_frames_single_call_perifo(cp, scienceSegs,
outputDir, tags=None):
"""
This function uses the glue.datafind library to obtain the location of all
the frame files that will be needed to cover the analysis of the data
given in scienceSegs. This function will not check if the returned frames
cover the whole time requested, such sanity checks are done in the
pycbc.workflow.setup_datafind_workflow entry function. As opposed to
setup_datafind_runtime_generated this call will only run one call to
datafind per ifo, spanning the whole time. This function will return a list
of files corresponding to the individual frames returned by the datafind
query. This will allow pegasus to more easily identify all the files used
as input, but may cause problems for codes that need to take frame cache
files as input.
Parameters
-----------
cp : ConfigParser.ConfigParser instance
This contains a representation of the information stored within the
workflow configuration files
scienceSegs : Dictionary of ifo keyed glue.segment.segmentlist instances
This contains the times that the workflow is expected to analyse.
outputDir : path
All output files written by datafind processes will be written to this
directory.
tags : list of strings, optional (default=None)
Use this to specify tags. This can be used if this module is being
called more than once to give call specific configuration (by setting
options in [workflow-datafind-${TAG}] rather than [workflow-datafind]).
This is also used to tag the Files returned by the class to uniqueify
the Files and uniqueify the actual filename.
FIXME: Filenames may not be unique with current codes!
Returns
--------
datafindcaches : list of glue.lal.Cache instances
The glue.lal.Cache representations of the various calls to the datafind
server and the returned frame files.
datafindOuts : pycbc.workflow.core.FileList
List of all the datafind output files for use later in the pipeline.
"""
datafindcaches, _ = \
setup_datafind_runtime_cache_single_call_perifo(cp, scienceSegs,
outputDir, tags=tags)
datafindouts = convert_cachelist_to_filelist(datafindcaches)
return datafindcaches, datafindouts | python | def setup_datafind_runtime_frames_single_call_perifo(cp, scienceSegs,
outputDir, tags=None):
datafindcaches, _ = \
setup_datafind_runtime_cache_single_call_perifo(cp, scienceSegs,
outputDir, tags=tags)
datafindouts = convert_cachelist_to_filelist(datafindcaches)
return datafindcaches, datafindouts | [
"def",
"setup_datafind_runtime_frames_single_call_perifo",
"(",
"cp",
",",
"scienceSegs",
",",
"outputDir",
",",
"tags",
"=",
"None",
")",
":",
"datafindcaches",
",",
"_",
"=",
"setup_datafind_runtime_cache_single_call_perifo",
"(",
"cp",
",",
"scienceSegs",
",",
"out... | This function uses the glue.datafind library to obtain the location of all
the frame files that will be needed to cover the analysis of the data
given in scienceSegs. This function will not check if the returned frames
cover the whole time requested, such sanity checks are done in the
pycbc.workflow.setup_datafind_workflow entry function. As opposed to
setup_datafind_runtime_generated this call will only run one call to
datafind per ifo, spanning the whole time. This function will return a list
of files corresponding to the individual frames returned by the datafind
query. This will allow pegasus to more easily identify all the files used
as input, but may cause problems for codes that need to take frame cache
files as input.
Parameters
-----------
cp : ConfigParser.ConfigParser instance
This contains a representation of the information stored within the
workflow configuration files
scienceSegs : Dictionary of ifo keyed glue.segment.segmentlist instances
This contains the times that the workflow is expected to analyse.
outputDir : path
All output files written by datafind processes will be written to this
directory.
tags : list of strings, optional (default=None)
Use this to specify tags. This can be used if this module is being
called more than once to give call specific configuration (by setting
options in [workflow-datafind-${TAG}] rather than [workflow-datafind]).
This is also used to tag the Files returned by the class to uniqueify
the Files and uniqueify the actual filename.
FIXME: Filenames may not be unique with current codes!
Returns
--------
datafindcaches : list of glue.lal.Cache instances
The glue.lal.Cache representations of the various calls to the datafind
server and the returned frame files.
datafindOuts : pycbc.workflow.core.FileList
List of all the datafind output files for use later in the pipeline. | [
"This",
"function",
"uses",
"the",
"glue",
".",
"datafind",
"library",
"to",
"obtain",
"the",
"location",
"of",
"all",
"the",
"frame",
"files",
"that",
"will",
"be",
"needed",
"to",
"cover",
"the",
"analysis",
"of",
"the",
"data",
"given",
"in",
"scienceSe... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/datafind.py#L519-L567 |
228,396 | gwastro/pycbc | pycbc/workflow/datafind.py | setup_datafind_runtime_frames_multi_calls_perifo | def setup_datafind_runtime_frames_multi_calls_perifo(cp, scienceSegs,
outputDir, tags=None):
"""
This function uses the glue.datafind library to obtain the location of all
the frame files that will be needed to cover the analysis of the data
given in scienceSegs. This function will not check if the returned frames
cover the whole time requested, such sanity checks are done in the
pycbc.workflow.setup_datafind_workflow entry function. As opposed to
setup_datafind_runtime_single_call_perifo this call will one call to the
datafind server for every science segment. This function will return a list
of files corresponding to the individual frames returned by the datafind
query. This will allow pegasus to more easily identify all the files used
as input, but may cause problems for codes that need to take frame cache
files as input.
Parameters
-----------
cp : ConfigParser.ConfigParser instance
This contains a representation of the information stored within the
workflow configuration files
scienceSegs : Dictionary of ifo keyed glue.segment.segmentlist instances
This contains the times that the workflow is expected to analyse.
outputDir : path
All output files written by datafind processes will be written to this
directory.
tags : list of strings, optional (default=None)
Use this to specify tags. This can be used if this module is being
called more than once to give call specific configuration (by setting
options in [workflow-datafind-${TAG}] rather than [workflow-datafind]).
This is also used to tag the Files returned by the class to uniqueify
the Files and uniqueify the actual filename.
FIXME: Filenames may not be unique with current codes!
Returns
--------
datafindcaches : list of glue.lal.Cache instances
The glue.lal.Cache representations of the various calls to the datafind
server and the returned frame files.
datafindOuts : pycbc.workflow.core.FileList
List of all the datafind output files for use later in the pipeline.
"""
datafindcaches, _ = \
setup_datafind_runtime_cache_multi_calls_perifo(cp, scienceSegs,
outputDir, tags=tags)
datafindouts = convert_cachelist_to_filelist(datafindcaches)
return datafindcaches, datafindouts | python | def setup_datafind_runtime_frames_multi_calls_perifo(cp, scienceSegs,
outputDir, tags=None):
datafindcaches, _ = \
setup_datafind_runtime_cache_multi_calls_perifo(cp, scienceSegs,
outputDir, tags=tags)
datafindouts = convert_cachelist_to_filelist(datafindcaches)
return datafindcaches, datafindouts | [
"def",
"setup_datafind_runtime_frames_multi_calls_perifo",
"(",
"cp",
",",
"scienceSegs",
",",
"outputDir",
",",
"tags",
"=",
"None",
")",
":",
"datafindcaches",
",",
"_",
"=",
"setup_datafind_runtime_cache_multi_calls_perifo",
"(",
"cp",
",",
"scienceSegs",
",",
"out... | This function uses the glue.datafind library to obtain the location of all
the frame files that will be needed to cover the analysis of the data
given in scienceSegs. This function will not check if the returned frames
cover the whole time requested, such sanity checks are done in the
pycbc.workflow.setup_datafind_workflow entry function. As opposed to
setup_datafind_runtime_single_call_perifo this call will one call to the
datafind server for every science segment. This function will return a list
of files corresponding to the individual frames returned by the datafind
query. This will allow pegasus to more easily identify all the files used
as input, but may cause problems for codes that need to take frame cache
files as input.
Parameters
-----------
cp : ConfigParser.ConfigParser instance
This contains a representation of the information stored within the
workflow configuration files
scienceSegs : Dictionary of ifo keyed glue.segment.segmentlist instances
This contains the times that the workflow is expected to analyse.
outputDir : path
All output files written by datafind processes will be written to this
directory.
tags : list of strings, optional (default=None)
Use this to specify tags. This can be used if this module is being
called more than once to give call specific configuration (by setting
options in [workflow-datafind-${TAG}] rather than [workflow-datafind]).
This is also used to tag the Files returned by the class to uniqueify
the Files and uniqueify the actual filename.
FIXME: Filenames may not be unique with current codes!
Returns
--------
datafindcaches : list of glue.lal.Cache instances
The glue.lal.Cache representations of the various calls to the datafind
server and the returned frame files.
datafindOuts : pycbc.workflow.core.FileList
List of all the datafind output files for use later in the pipeline. | [
"This",
"function",
"uses",
"the",
"glue",
".",
"datafind",
"library",
"to",
"obtain",
"the",
"location",
"of",
"all",
"the",
"frame",
"files",
"that",
"will",
"be",
"needed",
"to",
"cover",
"the",
"analysis",
"of",
"the",
"data",
"given",
"in",
"scienceSe... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/datafind.py#L569-L617 |
228,397 | gwastro/pycbc | pycbc/workflow/datafind.py | setup_datafind_from_pregenerated_lcf_files | def setup_datafind_from_pregenerated_lcf_files(cp, ifos, outputDir, tags=None):
"""
This function is used if you want to run with pregenerated lcf frame
cache files.
Parameters
-----------
cp : ConfigParser.ConfigParser instance
This contains a representation of the information stored within the
workflow configuration files
ifos : list of ifo strings
List of ifos to get pregenerated files for.
outputDir : path
All output files written by datafind processes will be written to this
directory. Currently this sub-module writes no output.
tags : list of strings, optional (default=None)
Use this to specify tags. This can be used if this module is being
called more than once to give call specific configuration (by setting
options in [workflow-datafind-${TAG}] rather than [workflow-datafind]).
This is also used to tag the Files returned by the class to uniqueify
the Files and uniqueify the actual filename.
Returns
--------
datafindcaches : list of glue.lal.Cache instances
The glue.lal.Cache representations of the various calls to the datafind
server and the returned frame files.
datafindOuts : pycbc.workflow.core.FileList
List of all the datafind output files for use later in the pipeline.
"""
if tags is None:
tags = []
datafindcaches = []
for ifo in ifos:
search_string = "datafind-pregenerated-cache-file-%s" %(ifo.lower(),)
frame_cache_file_name = cp.get_opt_tags("workflow-datafind",
search_string, tags=tags)
curr_cache = lal.Cache.fromfilenames([frame_cache_file_name],
coltype=lal.LIGOTimeGPS)
curr_cache.ifo = ifo
datafindcaches.append(curr_cache)
datafindouts = convert_cachelist_to_filelist(datafindcaches)
return datafindcaches, datafindouts | python | def setup_datafind_from_pregenerated_lcf_files(cp, ifos, outputDir, tags=None):
if tags is None:
tags = []
datafindcaches = []
for ifo in ifos:
search_string = "datafind-pregenerated-cache-file-%s" %(ifo.lower(),)
frame_cache_file_name = cp.get_opt_tags("workflow-datafind",
search_string, tags=tags)
curr_cache = lal.Cache.fromfilenames([frame_cache_file_name],
coltype=lal.LIGOTimeGPS)
curr_cache.ifo = ifo
datafindcaches.append(curr_cache)
datafindouts = convert_cachelist_to_filelist(datafindcaches)
return datafindcaches, datafindouts | [
"def",
"setup_datafind_from_pregenerated_lcf_files",
"(",
"cp",
",",
"ifos",
",",
"outputDir",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"datafindcaches",
"=",
"[",
"]",
"for",
"ifo",
"in",
"ifos",
":",
... | This function is used if you want to run with pregenerated lcf frame
cache files.
Parameters
-----------
cp : ConfigParser.ConfigParser instance
This contains a representation of the information stored within the
workflow configuration files
ifos : list of ifo strings
List of ifos to get pregenerated files for.
outputDir : path
All output files written by datafind processes will be written to this
directory. Currently this sub-module writes no output.
tags : list of strings, optional (default=None)
Use this to specify tags. This can be used if this module is being
called more than once to give call specific configuration (by setting
options in [workflow-datafind-${TAG}] rather than [workflow-datafind]).
This is also used to tag the Files returned by the class to uniqueify
the Files and uniqueify the actual filename.
Returns
--------
datafindcaches : list of glue.lal.Cache instances
The glue.lal.Cache representations of the various calls to the datafind
server and the returned frame files.
datafindOuts : pycbc.workflow.core.FileList
List of all the datafind output files for use later in the pipeline. | [
"This",
"function",
"is",
"used",
"if",
"you",
"want",
"to",
"run",
"with",
"pregenerated",
"lcf",
"frame",
"cache",
"files",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/datafind.py#L619-L663 |
228,398 | gwastro/pycbc | pycbc/workflow/datafind.py | convert_cachelist_to_filelist | def convert_cachelist_to_filelist(datafindcache_list):
"""
Take as input a list of glue.lal.Cache objects and return a pycbc FileList
containing all frames within those caches.
Parameters
-----------
datafindcache_list : list of glue.lal.Cache objects
The list of cache files to convert.
Returns
--------
datafind_filelist : FileList of frame File objects
The list of frame files.
"""
prev_file = None
prev_name = None
this_name = None
datafind_filelist = FileList([])
for cache in datafindcache_list:
# sort the cache into time sequential order
cache.sort()
curr_ifo = cache.ifo
for frame in cache:
# Pegasus doesn't like "localhost" in URLs.
frame.url = frame.url.replace('file://localhost','file://')
# Create one File() object for each unique frame file that we
# get back in the cache.
if prev_file:
prev_name = os.path.basename(prev_file.cache_entry.url)
this_name = os.path.basename(frame.url)
if (prev_file is None) or (prev_name != this_name):
currFile = File(curr_ifo, frame.description,
frame.segment, file_url=frame.url, use_tmp_subdirs=True)
datafind_filelist.append(currFile)
prev_file = currFile
# Populate the PFNs for the File() we just created
if frame.url.startswith('file://'):
currFile.PFN(frame.url, site='local')
if frame.url.startswith(
'file:///cvmfs/oasis.opensciencegrid.org/ligo/frames'):
# Datafind returned a URL valid on the osg as well
# so add the additional PFNs to allow OSG access.
currFile.PFN(frame.url, site='osg')
currFile.PFN(frame.url.replace(
'file:///cvmfs/oasis.opensciencegrid.org/',
'root://xrootd-local.unl.edu/user/'), site='osg')
currFile.PFN(frame.url.replace(
'file:///cvmfs/oasis.opensciencegrid.org/',
'gsiftp://red-gridftp.unl.edu/user/'), site='osg')
currFile.PFN(frame.url.replace(
'file:///cvmfs/oasis.opensciencegrid.org/',
'gsiftp://ldas-grid.ligo.caltech.edu/hdfs/'), site='osg')
elif frame.url.startswith(
'file:///cvmfs/gwosc.osgstorage.org/'):
# Datafind returned a URL valid on the osg as well
# so add the additional PFNs to allow OSG access.
for s in ['osg', 'orangegrid', 'osgconnect']:
currFile.PFN(frame.url, site=s)
currFile.PFN(frame.url, site="{}-scratch".format(s))
else:
currFile.PFN(frame.url, site='notlocal')
return datafind_filelist | python | def convert_cachelist_to_filelist(datafindcache_list):
prev_file = None
prev_name = None
this_name = None
datafind_filelist = FileList([])
for cache in datafindcache_list:
# sort the cache into time sequential order
cache.sort()
curr_ifo = cache.ifo
for frame in cache:
# Pegasus doesn't like "localhost" in URLs.
frame.url = frame.url.replace('file://localhost','file://')
# Create one File() object for each unique frame file that we
# get back in the cache.
if prev_file:
prev_name = os.path.basename(prev_file.cache_entry.url)
this_name = os.path.basename(frame.url)
if (prev_file is None) or (prev_name != this_name):
currFile = File(curr_ifo, frame.description,
frame.segment, file_url=frame.url, use_tmp_subdirs=True)
datafind_filelist.append(currFile)
prev_file = currFile
# Populate the PFNs for the File() we just created
if frame.url.startswith('file://'):
currFile.PFN(frame.url, site='local')
if frame.url.startswith(
'file:///cvmfs/oasis.opensciencegrid.org/ligo/frames'):
# Datafind returned a URL valid on the osg as well
# so add the additional PFNs to allow OSG access.
currFile.PFN(frame.url, site='osg')
currFile.PFN(frame.url.replace(
'file:///cvmfs/oasis.opensciencegrid.org/',
'root://xrootd-local.unl.edu/user/'), site='osg')
currFile.PFN(frame.url.replace(
'file:///cvmfs/oasis.opensciencegrid.org/',
'gsiftp://red-gridftp.unl.edu/user/'), site='osg')
currFile.PFN(frame.url.replace(
'file:///cvmfs/oasis.opensciencegrid.org/',
'gsiftp://ldas-grid.ligo.caltech.edu/hdfs/'), site='osg')
elif frame.url.startswith(
'file:///cvmfs/gwosc.osgstorage.org/'):
# Datafind returned a URL valid on the osg as well
# so add the additional PFNs to allow OSG access.
for s in ['osg', 'orangegrid', 'osgconnect']:
currFile.PFN(frame.url, site=s)
currFile.PFN(frame.url, site="{}-scratch".format(s))
else:
currFile.PFN(frame.url, site='notlocal')
return datafind_filelist | [
"def",
"convert_cachelist_to_filelist",
"(",
"datafindcache_list",
")",
":",
"prev_file",
"=",
"None",
"prev_name",
"=",
"None",
"this_name",
"=",
"None",
"datafind_filelist",
"=",
"FileList",
"(",
"[",
"]",
")",
"for",
"cache",
"in",
"datafindcache_list",
":",
... | Take as input a list of glue.lal.Cache objects and return a pycbc FileList
containing all frames within those caches.
Parameters
-----------
datafindcache_list : list of glue.lal.Cache objects
The list of cache files to convert.
Returns
--------
datafind_filelist : FileList of frame File objects
The list of frame files. | [
"Take",
"as",
"input",
"a",
"list",
"of",
"glue",
".",
"lal",
".",
"Cache",
"objects",
"and",
"return",
"a",
"pycbc",
"FileList",
"containing",
"all",
"frames",
"within",
"those",
"caches",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/datafind.py#L665-L733 |
228,399 | gwastro/pycbc | pycbc/workflow/datafind.py | get_science_segs_from_datafind_outs | def get_science_segs_from_datafind_outs(datafindcaches):
"""
This function will calculate the science segments that are covered in
the OutGroupList containing the frame files returned by various
calls to the datafind server. This can then be used to check whether this
list covers what it is expected to cover.
Parameters
----------
datafindcaches : OutGroupList
List of all the datafind output files.
Returns
--------
newScienceSegs : Dictionary of ifo keyed glue.segment.segmentlist instances
The times covered by the frames found in datafindOuts.
"""
newScienceSegs = {}
for cache in datafindcaches:
if len(cache) > 0:
groupSegs = segments.segmentlist(e.segment for e in cache).coalesce()
ifo = cache.ifo
if ifo not in newScienceSegs:
newScienceSegs[ifo] = groupSegs
else:
newScienceSegs[ifo].extend(groupSegs)
newScienceSegs[ifo].coalesce()
return newScienceSegs | python | def get_science_segs_from_datafind_outs(datafindcaches):
newScienceSegs = {}
for cache in datafindcaches:
if len(cache) > 0:
groupSegs = segments.segmentlist(e.segment for e in cache).coalesce()
ifo = cache.ifo
if ifo not in newScienceSegs:
newScienceSegs[ifo] = groupSegs
else:
newScienceSegs[ifo].extend(groupSegs)
newScienceSegs[ifo].coalesce()
return newScienceSegs | [
"def",
"get_science_segs_from_datafind_outs",
"(",
"datafindcaches",
")",
":",
"newScienceSegs",
"=",
"{",
"}",
"for",
"cache",
"in",
"datafindcaches",
":",
"if",
"len",
"(",
"cache",
")",
">",
"0",
":",
"groupSegs",
"=",
"segments",
".",
"segmentlist",
"(",
... | This function will calculate the science segments that are covered in
the OutGroupList containing the frame files returned by various
calls to the datafind server. This can then be used to check whether this
list covers what it is expected to cover.
Parameters
----------
datafindcaches : OutGroupList
List of all the datafind output files.
Returns
--------
newScienceSegs : Dictionary of ifo keyed glue.segment.segmentlist instances
The times covered by the frames found in datafindOuts. | [
"This",
"function",
"will",
"calculate",
"the",
"science",
"segments",
"that",
"are",
"covered",
"in",
"the",
"OutGroupList",
"containing",
"the",
"frame",
"files",
"returned",
"by",
"various",
"calls",
"to",
"the",
"datafind",
"server",
".",
"This",
"can",
"t... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/datafind.py#L736-L763 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.