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,100 | gwastro/pycbc | pycbc/workflow/core.py | FileList.dump | def dump(self, filename):
"""
Output this AhopeFileList to a pickle file
"""
f = open(filename, 'w')
cPickle.dump(self, f) | python | def dump(self, filename):
f = open(filename, 'w')
cPickle.dump(self, f) | [
"def",
"dump",
"(",
"self",
",",
"filename",
")",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"cPickle",
".",
"dump",
"(",
"self",
",",
"f",
")"
] | Output this AhopeFileList to a pickle file | [
"Output",
"this",
"AhopeFileList",
"to",
"a",
"pickle",
"file"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1542-L1547 |
228,101 | gwastro/pycbc | pycbc/workflow/core.py | FileList.to_file_object | def to_file_object(self, name, out_dir):
"""Dump to a pickle file and return an File object reference of this list
Parameters
----------
name : str
An identifier of this file. Needs to be unique.
out_dir : path
path to place this file
Returns
-------
file : AhopeFile
"""
make_analysis_dir(out_dir)
file_ref = File('ALL', name, self.get_times_covered_by_files(),
extension='.pkl', directory=out_dir)
self.dump(file_ref.storage_path)
return file_ref | python | def to_file_object(self, name, out_dir):
make_analysis_dir(out_dir)
file_ref = File('ALL', name, self.get_times_covered_by_files(),
extension='.pkl', directory=out_dir)
self.dump(file_ref.storage_path)
return file_ref | [
"def",
"to_file_object",
"(",
"self",
",",
"name",
",",
"out_dir",
")",
":",
"make_analysis_dir",
"(",
"out_dir",
")",
"file_ref",
"=",
"File",
"(",
"'ALL'",
",",
"name",
",",
"self",
".",
"get_times_covered_by_files",
"(",
")",
",",
"extension",
"=",
"'.p... | Dump to a pickle file and return an File object reference of this list
Parameters
----------
name : str
An identifier of this file. Needs to be unique.
out_dir : path
path to place this file
Returns
-------
file : AhopeFile | [
"Dump",
"to",
"a",
"pickle",
"file",
"and",
"return",
"an",
"File",
"object",
"reference",
"of",
"this",
"list"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1549-L1568 |
228,102 | gwastro/pycbc | pycbc/workflow/core.py | SegFile.from_segment_list | def from_segment_list(cls, description, segmentlist, name, ifo,
seg_summ_list=None, **kwargs):
""" Initialize a SegFile object from a segmentlist.
Parameters
------------
description : string (required)
See File.__init__
segmentlist : ligo.segments.segmentslist
The segment list that will be stored in this file.
name : str
The name of the segment lists to be stored in the file.
ifo : str
The ifo of the segment lists to be stored in this file.
seg_summ_list : ligo.segments.segmentslist (OPTIONAL)
Specify the segment_summary segmentlist that goes along with the
segmentlist. Default=None, in this case segment_summary is taken
from the valid_segment of the SegFile class.
"""
seglistdict = segments.segmentlistdict()
seglistdict[ifo + ':' + name] = segmentlist
if seg_summ_list is not None:
seg_summ_dict = segments.segmentlistdict()
seg_summ_dict[ifo + ':' + name] = seg_summ_list
else:
seg_summ_dict = None
return cls.from_segment_list_dict(description, seglistdict,
seg_summ_dict=None, **kwargs) | python | def from_segment_list(cls, description, segmentlist, name, ifo,
seg_summ_list=None, **kwargs):
seglistdict = segments.segmentlistdict()
seglistdict[ifo + ':' + name] = segmentlist
if seg_summ_list is not None:
seg_summ_dict = segments.segmentlistdict()
seg_summ_dict[ifo + ':' + name] = seg_summ_list
else:
seg_summ_dict = None
return cls.from_segment_list_dict(description, seglistdict,
seg_summ_dict=None, **kwargs) | [
"def",
"from_segment_list",
"(",
"cls",
",",
"description",
",",
"segmentlist",
",",
"name",
",",
"ifo",
",",
"seg_summ_list",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"seglistdict",
"=",
"segments",
".",
"segmentlistdict",
"(",
")",
"seglistdict",
... | Initialize a SegFile object from a segmentlist.
Parameters
------------
description : string (required)
See File.__init__
segmentlist : ligo.segments.segmentslist
The segment list that will be stored in this file.
name : str
The name of the segment lists to be stored in the file.
ifo : str
The ifo of the segment lists to be stored in this file.
seg_summ_list : ligo.segments.segmentslist (OPTIONAL)
Specify the segment_summary segmentlist that goes along with the
segmentlist. Default=None, in this case segment_summary is taken
from the valid_segment of the SegFile class. | [
"Initialize",
"a",
"SegFile",
"object",
"from",
"a",
"segmentlist",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1610-L1637 |
228,103 | gwastro/pycbc | pycbc/workflow/core.py | SegFile.from_multi_segment_list | def from_multi_segment_list(cls, description, segmentlists, names, ifos,
seg_summ_lists=None, **kwargs):
""" Initialize a SegFile object from a list of segmentlists.
Parameters
------------
description : string (required)
See File.__init__
segmentlists : List of ligo.segments.segmentslist
List of segment lists that will be stored in this file.
names : List of str
List of names of the segment lists to be stored in the file.
ifos : str
List of ifos of the segment lists to be stored in this file.
seg_summ_lists : ligo.segments.segmentslist (OPTIONAL)
Specify the segment_summary segmentlists that go along with the
segmentlists. Default=None, in this case segment_summary is taken
from the valid_segment of the SegFile class.
"""
seglistdict = segments.segmentlistdict()
for name, ifo, segmentlist in zip(names, ifos, segmentlists):
seglistdict[ifo + ':' + name] = segmentlist
if seg_summ_lists is not None:
seg_summ_dict = segments.segmentlistdict()
for name, ifo, seg_summ_list in zip(names, ifos, seg_summ_lists):
seg_summ_dict[ifo + ':' + name] = seg_summ_list
else:
seg_summ_dict = None
return cls.from_segment_list_dict(description, seglistdict,
seg_summ_dict=seg_summ_dict, **kwargs) | python | def from_multi_segment_list(cls, description, segmentlists, names, ifos,
seg_summ_lists=None, **kwargs):
seglistdict = segments.segmentlistdict()
for name, ifo, segmentlist in zip(names, ifos, segmentlists):
seglistdict[ifo + ':' + name] = segmentlist
if seg_summ_lists is not None:
seg_summ_dict = segments.segmentlistdict()
for name, ifo, seg_summ_list in zip(names, ifos, seg_summ_lists):
seg_summ_dict[ifo + ':' + name] = seg_summ_list
else:
seg_summ_dict = None
return cls.from_segment_list_dict(description, seglistdict,
seg_summ_dict=seg_summ_dict, **kwargs) | [
"def",
"from_multi_segment_list",
"(",
"cls",
",",
"description",
",",
"segmentlists",
",",
"names",
",",
"ifos",
",",
"seg_summ_lists",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"seglistdict",
"=",
"segments",
".",
"segmentlistdict",
"(",
")",
"for",
... | Initialize a SegFile object from a list of segmentlists.
Parameters
------------
description : string (required)
See File.__init__
segmentlists : List of ligo.segments.segmentslist
List of segment lists that will be stored in this file.
names : List of str
List of names of the segment lists to be stored in the file.
ifos : str
List of ifos of the segment lists to be stored in this file.
seg_summ_lists : ligo.segments.segmentslist (OPTIONAL)
Specify the segment_summary segmentlists that go along with the
segmentlists. Default=None, in this case segment_summary is taken
from the valid_segment of the SegFile class. | [
"Initialize",
"a",
"SegFile",
"object",
"from",
"a",
"list",
"of",
"segmentlists",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1640-L1670 |
228,104 | gwastro/pycbc | pycbc/workflow/core.py | SegFile.from_segment_list_dict | def from_segment_list_dict(cls, description, segmentlistdict,
ifo_list=None, valid_segment=None,
file_exists=False, seg_summ_dict=None,
**kwargs):
""" Initialize a SegFile object from a segmentlistdict.
Parameters
------------
description : string (required)
See File.__init__
segmentlistdict : ligo.segments.segmentslistdict
See SegFile.__init__
ifo_list : string or list (optional)
See File.__init__, if not given a list of all ifos in the
segmentlistdict object will be used
valid_segment : ligo.segments.segment or ligo.segments.segmentlist
See File.__init__, if not given the extent of all segments in the
segmentlistdict is used.
file_exists : boolean (default = False)
If provided and set to True it is assumed that this file already
exists on disk and so there is no need to write again.
seg_summ_dict : ligo.segments.segmentslistdict
Optional. See SegFile.__init__.
"""
if ifo_list is None:
ifo_set = set([i.split(':')[0] for i in segmentlistdict.keys()])
ifo_list = list(ifo_set)
ifo_list.sort()
if valid_segment is None:
if seg_summ_dict and \
numpy.any([len(v) for _, v in seg_summ_dict.items()]):
# Only come here if seg_summ_dict is supplied and it is
# not empty.
valid_segment = seg_summ_dict.extent_all()
else:
try:
valid_segment = segmentlistdict.extent_all()
except:
# Numpty probably didn't supply a glue.segmentlistdict
segmentlistdict=segments.segmentlistdict(segmentlistdict)
try:
valid_segment = segmentlistdict.extent_all()
except ValueError:
# No segment_summary and segment list is empty
# Setting valid segment now is hard!
warn_msg = "No information with which to set valid "
warn_msg += "segment."
logging.warn(warn_msg)
valid_segment = segments.segment([0,1])
instnc = cls(ifo_list, description, valid_segment,
segment_dict=segmentlistdict, seg_summ_dict=seg_summ_dict,
**kwargs)
if not file_exists:
instnc.to_segment_xml()
else:
instnc.PFN(urlparse.urljoin('file:',
urllib.pathname2url(
instnc.storage_path)), site='local')
return instnc | python | def from_segment_list_dict(cls, description, segmentlistdict,
ifo_list=None, valid_segment=None,
file_exists=False, seg_summ_dict=None,
**kwargs):
if ifo_list is None:
ifo_set = set([i.split(':')[0] for i in segmentlistdict.keys()])
ifo_list = list(ifo_set)
ifo_list.sort()
if valid_segment is None:
if seg_summ_dict and \
numpy.any([len(v) for _, v in seg_summ_dict.items()]):
# Only come here if seg_summ_dict is supplied and it is
# not empty.
valid_segment = seg_summ_dict.extent_all()
else:
try:
valid_segment = segmentlistdict.extent_all()
except:
# Numpty probably didn't supply a glue.segmentlistdict
segmentlistdict=segments.segmentlistdict(segmentlistdict)
try:
valid_segment = segmentlistdict.extent_all()
except ValueError:
# No segment_summary and segment list is empty
# Setting valid segment now is hard!
warn_msg = "No information with which to set valid "
warn_msg += "segment."
logging.warn(warn_msg)
valid_segment = segments.segment([0,1])
instnc = cls(ifo_list, description, valid_segment,
segment_dict=segmentlistdict, seg_summ_dict=seg_summ_dict,
**kwargs)
if not file_exists:
instnc.to_segment_xml()
else:
instnc.PFN(urlparse.urljoin('file:',
urllib.pathname2url(
instnc.storage_path)), site='local')
return instnc | [
"def",
"from_segment_list_dict",
"(",
"cls",
",",
"description",
",",
"segmentlistdict",
",",
"ifo_list",
"=",
"None",
",",
"valid_segment",
"=",
"None",
",",
"file_exists",
"=",
"False",
",",
"seg_summ_dict",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
... | Initialize a SegFile object from a segmentlistdict.
Parameters
------------
description : string (required)
See File.__init__
segmentlistdict : ligo.segments.segmentslistdict
See SegFile.__init__
ifo_list : string or list (optional)
See File.__init__, if not given a list of all ifos in the
segmentlistdict object will be used
valid_segment : ligo.segments.segment or ligo.segments.segmentlist
See File.__init__, if not given the extent of all segments in the
segmentlistdict is used.
file_exists : boolean (default = False)
If provided and set to True it is assumed that this file already
exists on disk and so there is no need to write again.
seg_summ_dict : ligo.segments.segmentslistdict
Optional. See SegFile.__init__. | [
"Initialize",
"a",
"SegFile",
"object",
"from",
"a",
"segmentlistdict",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1673-L1731 |
228,105 | gwastro/pycbc | pycbc/workflow/core.py | SegFile.from_segment_xml | def from_segment_xml(cls, xml_file, **kwargs):
"""
Read a ligo.segments.segmentlist from the file object file containing an
xml segment table.
Parameters
-----------
xml_file : file object
file object for segment xml file
"""
# load xmldocument and SegmentDefTable and SegmentTables
fp = open(xml_file, 'r')
xmldoc, _ = ligolw_utils.load_fileobj(fp,
gz=xml_file.endswith(".gz"),
contenthandler=ContentHandler)
seg_def_table = table.get_table(xmldoc,
lsctables.SegmentDefTable.tableName)
seg_table = table.get_table(xmldoc, lsctables.SegmentTable.tableName)
seg_sum_table = table.get_table(xmldoc,
lsctables.SegmentSumTable.tableName)
segs = segments.segmentlistdict()
seg_summ = segments.segmentlistdict()
seg_id = {}
for seg_def in seg_def_table:
# Here we want to encode ifo and segment name
full_channel_name = ':'.join([str(seg_def.ifos),
str(seg_def.name)])
seg_id[int(seg_def.segment_def_id)] = full_channel_name
segs[full_channel_name] = segments.segmentlist()
seg_summ[full_channel_name] = segments.segmentlist()
for seg in seg_table:
seg_obj = segments.segment(
lal.LIGOTimeGPS(seg.start_time, seg.start_time_ns),
lal.LIGOTimeGPS(seg.end_time, seg.end_time_ns))
segs[seg_id[int(seg.segment_def_id)]].append(seg_obj)
for seg in seg_sum_table:
seg_obj = segments.segment(
lal.LIGOTimeGPS(seg.start_time, seg.start_time_ns),
lal.LIGOTimeGPS(seg.end_time, seg.end_time_ns))
seg_summ[seg_id[int(seg.segment_def_id)]].append(seg_obj)
for seg_name in seg_id.values():
segs[seg_name] = segs[seg_name].coalesce()
xmldoc.unlink()
fp.close()
curr_url = urlparse.urlunparse(['file', 'localhost', xml_file, None,
None, None])
return cls.from_segment_list_dict('SEGMENTS', segs, file_url=curr_url,
file_exists=True,
seg_summ_dict=seg_summ, **kwargs) | python | def from_segment_xml(cls, xml_file, **kwargs):
# load xmldocument and SegmentDefTable and SegmentTables
fp = open(xml_file, 'r')
xmldoc, _ = ligolw_utils.load_fileobj(fp,
gz=xml_file.endswith(".gz"),
contenthandler=ContentHandler)
seg_def_table = table.get_table(xmldoc,
lsctables.SegmentDefTable.tableName)
seg_table = table.get_table(xmldoc, lsctables.SegmentTable.tableName)
seg_sum_table = table.get_table(xmldoc,
lsctables.SegmentSumTable.tableName)
segs = segments.segmentlistdict()
seg_summ = segments.segmentlistdict()
seg_id = {}
for seg_def in seg_def_table:
# Here we want to encode ifo and segment name
full_channel_name = ':'.join([str(seg_def.ifos),
str(seg_def.name)])
seg_id[int(seg_def.segment_def_id)] = full_channel_name
segs[full_channel_name] = segments.segmentlist()
seg_summ[full_channel_name] = segments.segmentlist()
for seg in seg_table:
seg_obj = segments.segment(
lal.LIGOTimeGPS(seg.start_time, seg.start_time_ns),
lal.LIGOTimeGPS(seg.end_time, seg.end_time_ns))
segs[seg_id[int(seg.segment_def_id)]].append(seg_obj)
for seg in seg_sum_table:
seg_obj = segments.segment(
lal.LIGOTimeGPS(seg.start_time, seg.start_time_ns),
lal.LIGOTimeGPS(seg.end_time, seg.end_time_ns))
seg_summ[seg_id[int(seg.segment_def_id)]].append(seg_obj)
for seg_name in seg_id.values():
segs[seg_name] = segs[seg_name].coalesce()
xmldoc.unlink()
fp.close()
curr_url = urlparse.urlunparse(['file', 'localhost', xml_file, None,
None, None])
return cls.from_segment_list_dict('SEGMENTS', segs, file_url=curr_url,
file_exists=True,
seg_summ_dict=seg_summ, **kwargs) | [
"def",
"from_segment_xml",
"(",
"cls",
",",
"xml_file",
",",
"*",
"*",
"kwargs",
")",
":",
"# load xmldocument and SegmentDefTable and SegmentTables",
"fp",
"=",
"open",
"(",
"xml_file",
",",
"'r'",
")",
"xmldoc",
",",
"_",
"=",
"ligolw_utils",
".",
"load_fileob... | Read a ligo.segments.segmentlist from the file object file containing an
xml segment table.
Parameters
-----------
xml_file : file object
file object for segment xml file | [
"Read",
"a",
"ligo",
".",
"segments",
".",
"segmentlist",
"from",
"the",
"file",
"object",
"file",
"containing",
"an",
"xml",
"segment",
"table",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1734-L1790 |
228,106 | gwastro/pycbc | pycbc/workflow/core.py | SegFile.remove_short_sci_segs | def remove_short_sci_segs(self, minSegLength):
"""
Function to remove all science segments
shorter than a specific length. Also updates the file on disk to remove
these segments.
Parameters
-----------
minSegLength : int
Maximum length of science segments. Segments shorter than this will
be removed.
"""
newsegment_list = segments.segmentlist()
for key, seglist in self.segment_dict.items():
newsegment_list = segments.segmentlist()
for seg in seglist:
if abs(seg) > minSegLength:
newsegment_list.append(seg)
newsegment_list.coalesce()
self.segment_dict[key] = newsegment_list
self.to_segment_xml(override_file_if_exists=True) | python | def remove_short_sci_segs(self, minSegLength):
newsegment_list = segments.segmentlist()
for key, seglist in self.segment_dict.items():
newsegment_list = segments.segmentlist()
for seg in seglist:
if abs(seg) > minSegLength:
newsegment_list.append(seg)
newsegment_list.coalesce()
self.segment_dict[key] = newsegment_list
self.to_segment_xml(override_file_if_exists=True) | [
"def",
"remove_short_sci_segs",
"(",
"self",
",",
"minSegLength",
")",
":",
"newsegment_list",
"=",
"segments",
".",
"segmentlist",
"(",
")",
"for",
"key",
",",
"seglist",
"in",
"self",
".",
"segment_dict",
".",
"items",
"(",
")",
":",
"newsegment_list",
"="... | Function to remove all science segments
shorter than a specific length. Also updates the file on disk to remove
these segments.
Parameters
-----------
minSegLength : int
Maximum length of science segments. Segments shorter than this will
be removed. | [
"Function",
"to",
"remove",
"all",
"science",
"segments",
"shorter",
"than",
"a",
"specific",
"length",
".",
"Also",
"updates",
"the",
"file",
"on",
"disk",
"to",
"remove",
"these",
"segments",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1792-L1812 |
228,107 | gwastro/pycbc | pycbc/workflow/core.py | SegFile.parse_segdict_key | def parse_segdict_key(self, key):
"""
Return ifo and name from the segdict key.
"""
splt = key.split(':')
if len(splt) == 2:
return splt[0], splt[1]
else:
err_msg = "Key should be of the format 'ifo:name', got %s." %(key,)
raise ValueError(err_msg) | python | def parse_segdict_key(self, key):
splt = key.split(':')
if len(splt) == 2:
return splt[0], splt[1]
else:
err_msg = "Key should be of the format 'ifo:name', got %s." %(key,)
raise ValueError(err_msg) | [
"def",
"parse_segdict_key",
"(",
"self",
",",
"key",
")",
":",
"splt",
"=",
"key",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"splt",
")",
"==",
"2",
":",
"return",
"splt",
"[",
"0",
"]",
",",
"splt",
"[",
"1",
"]",
"else",
":",
"err_msg"... | Return ifo and name from the segdict key. | [
"Return",
"ifo",
"and",
"name",
"from",
"the",
"segdict",
"key",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1817-L1826 |
228,108 | gwastro/pycbc | pycbc/workflow/core.py | SegFile.to_segment_xml | def to_segment_xml(self, override_file_if_exists=False):
"""
Write the segment list in self.segmentList to self.storage_path.
"""
# create XML doc and add process table
outdoc = ligolw.Document()
outdoc.appendChild(ligolw.LIGO_LW())
process = ligolw_process.register_to_xmldoc(outdoc, sys.argv[0], {})
for key, seglist in self.segment_dict.items():
ifo, name = self.parse_segdict_key(key)
# Ensure we have LIGOTimeGPS
fsegs = [(lal.LIGOTimeGPS(seg[0]),
lal.LIGOTimeGPS(seg[1])) for seg in seglist]
if self.seg_summ_dict is None:
vsegs = [(lal.LIGOTimeGPS(seg[0]),
lal.LIGOTimeGPS(seg[1])) \
for seg in self.valid_segments]
else:
vsegs = [(lal.LIGOTimeGPS(seg[0]),
lal.LIGOTimeGPS(seg[1])) \
for seg in self.seg_summ_dict[key]]
# Add using glue library to set all segment tables
with ligolw_segments.LigolwSegments(outdoc, process) as x:
x.add(ligolw_segments.LigolwSegmentList(active=fsegs,
instruments=set([ifo]), name=name,
version=1, valid=vsegs))
# write file
url = urlparse.urljoin('file:', urllib.pathname2url(self.storage_path))
if not override_file_if_exists or not self.has_pfn(url, site='local'):
self.PFN(url, site='local')
ligolw_utils.write_filename(outdoc, self.storage_path) | python | def to_segment_xml(self, override_file_if_exists=False):
# create XML doc and add process table
outdoc = ligolw.Document()
outdoc.appendChild(ligolw.LIGO_LW())
process = ligolw_process.register_to_xmldoc(outdoc, sys.argv[0], {})
for key, seglist in self.segment_dict.items():
ifo, name = self.parse_segdict_key(key)
# Ensure we have LIGOTimeGPS
fsegs = [(lal.LIGOTimeGPS(seg[0]),
lal.LIGOTimeGPS(seg[1])) for seg in seglist]
if self.seg_summ_dict is None:
vsegs = [(lal.LIGOTimeGPS(seg[0]),
lal.LIGOTimeGPS(seg[1])) \
for seg in self.valid_segments]
else:
vsegs = [(lal.LIGOTimeGPS(seg[0]),
lal.LIGOTimeGPS(seg[1])) \
for seg in self.seg_summ_dict[key]]
# Add using glue library to set all segment tables
with ligolw_segments.LigolwSegments(outdoc, process) as x:
x.add(ligolw_segments.LigolwSegmentList(active=fsegs,
instruments=set([ifo]), name=name,
version=1, valid=vsegs))
# write file
url = urlparse.urljoin('file:', urllib.pathname2url(self.storage_path))
if not override_file_if_exists or not self.has_pfn(url, site='local'):
self.PFN(url, site='local')
ligolw_utils.write_filename(outdoc, self.storage_path) | [
"def",
"to_segment_xml",
"(",
"self",
",",
"override_file_if_exists",
"=",
"False",
")",
":",
"# create XML doc and add process table",
"outdoc",
"=",
"ligolw",
".",
"Document",
"(",
")",
"outdoc",
".",
"appendChild",
"(",
"ligolw",
".",
"LIGO_LW",
"(",
")",
")"... | Write the segment list in self.segmentList to self.storage_path. | [
"Write",
"the",
"segment",
"list",
"in",
"self",
".",
"segmentList",
"to",
"self",
".",
"storage_path",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1828-L1862 |
228,109 | gwastro/pycbc | pycbc/strain/lines.py | complex_median | def complex_median(complex_list):
""" Get the median value of a list of complex numbers.
Parameters
----------
complex_list: list
List of complex numbers to calculate the median.
Returns
-------
a + 1.j*b: complex number
The median of the real and imaginary parts.
"""
median_real = numpy.median([complex_number.real
for complex_number in complex_list])
median_imag = numpy.median([complex_number.imag
for complex_number in complex_list])
return median_real + 1.j*median_imag | python | def complex_median(complex_list):
median_real = numpy.median([complex_number.real
for complex_number in complex_list])
median_imag = numpy.median([complex_number.imag
for complex_number in complex_list])
return median_real + 1.j*median_imag | [
"def",
"complex_median",
"(",
"complex_list",
")",
":",
"median_real",
"=",
"numpy",
".",
"median",
"(",
"[",
"complex_number",
".",
"real",
"for",
"complex_number",
"in",
"complex_list",
"]",
")",
"median_imag",
"=",
"numpy",
".",
"median",
"(",
"[",
"compl... | Get the median value of a list of complex numbers.
Parameters
----------
complex_list: list
List of complex numbers to calculate the median.
Returns
-------
a + 1.j*b: complex number
The median of the real and imaginary parts. | [
"Get",
"the",
"median",
"value",
"of",
"a",
"list",
"of",
"complex",
"numbers",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/strain/lines.py#L22-L39 |
228,110 | gwastro/pycbc | pycbc/strain/lines.py | avg_inner_product | def avg_inner_product(data1, data2, bin_size):
""" Calculate the time-domain inner product averaged over bins.
Parameters
----------
data1: pycbc.types.TimeSeries
First data set.
data2: pycbc.types.TimeSeries
Second data set, with same duration and sample rate as data1.
bin_size: float
Duration of the bins the data will be divided into to calculate
the inner product.
Returns
-------
inner_prod: list
The (complex) inner product of data1 and data2 obtained in each bin.
amp: float
The absolute value of the median of the inner product.
phi: float
The angle of the median of the inner product.
"""
assert data1.duration == data2.duration
assert data1.sample_rate == data2.sample_rate
seglen = int(bin_size * data1.sample_rate)
inner_prod = []
for idx in range(int(data1.duration / bin_size)):
start, end = idx * seglen, (idx+1) * seglen
norm = len(data1[start:end])
bin_prod = 2 * sum(data1.data[start:end].real *
numpy.conjugate(data2.data[start:end])) / norm
inner_prod.append(bin_prod)
# Get the median over all bins to avoid outliers due to the presence
# of a signal in a particular bin.
inner_median = complex_median(inner_prod)
return inner_prod, numpy.abs(inner_median), numpy.angle(inner_median) | python | def avg_inner_product(data1, data2, bin_size):
assert data1.duration == data2.duration
assert data1.sample_rate == data2.sample_rate
seglen = int(bin_size * data1.sample_rate)
inner_prod = []
for idx in range(int(data1.duration / bin_size)):
start, end = idx * seglen, (idx+1) * seglen
norm = len(data1[start:end])
bin_prod = 2 * sum(data1.data[start:end].real *
numpy.conjugate(data2.data[start:end])) / norm
inner_prod.append(bin_prod)
# Get the median over all bins to avoid outliers due to the presence
# of a signal in a particular bin.
inner_median = complex_median(inner_prod)
return inner_prod, numpy.abs(inner_median), numpy.angle(inner_median) | [
"def",
"avg_inner_product",
"(",
"data1",
",",
"data2",
",",
"bin_size",
")",
":",
"assert",
"data1",
".",
"duration",
"==",
"data2",
".",
"duration",
"assert",
"data1",
".",
"sample_rate",
"==",
"data2",
".",
"sample_rate",
"seglen",
"=",
"int",
"(",
"bin... | Calculate the time-domain inner product averaged over bins.
Parameters
----------
data1: pycbc.types.TimeSeries
First data set.
data2: pycbc.types.TimeSeries
Second data set, with same duration and sample rate as data1.
bin_size: float
Duration of the bins the data will be divided into to calculate
the inner product.
Returns
-------
inner_prod: list
The (complex) inner product of data1 and data2 obtained in each bin.
amp: float
The absolute value of the median of the inner product.
phi: float
The angle of the median of the inner product. | [
"Calculate",
"the",
"time",
"-",
"domain",
"inner",
"product",
"averaged",
"over",
"bins",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/strain/lines.py#L41-L77 |
228,111 | gwastro/pycbc | pycbc/strain/lines.py | line_model | def line_model(freq, data, tref, amp=1, phi=0):
""" Simple time-domain model for a frequency line.
Parameters
----------
freq: float
Frequency of the line.
data: pycbc.types.TimeSeries
Reference data, to get delta_t, start_time, duration and sample_times.
tref: float
Reference time for the line model.
amp: {1., float}, optional
Amplitude of the frequency line.
phi: {0. float}, optional
Phase of the frequency line (radians).
Returns
-------
freq_line: pycbc.types.TimeSeries
A timeseries of the line model with frequency 'freq'. The returned
data are complex to allow measuring the amplitude and phase of the
corresponding frequency line in the strain data. For extraction, use
only the real part of the data.
"""
freq_line = TimeSeries(zeros(len(data)), delta_t=data.delta_t,
epoch=data.start_time)
times = data.sample_times - float(tref)
alpha = 2 * numpy.pi * freq * times + phi
freq_line.data = amp * numpy.exp(1.j * alpha)
return freq_line | python | def line_model(freq, data, tref, amp=1, phi=0):
freq_line = TimeSeries(zeros(len(data)), delta_t=data.delta_t,
epoch=data.start_time)
times = data.sample_times - float(tref)
alpha = 2 * numpy.pi * freq * times + phi
freq_line.data = amp * numpy.exp(1.j * alpha)
return freq_line | [
"def",
"line_model",
"(",
"freq",
",",
"data",
",",
"tref",
",",
"amp",
"=",
"1",
",",
"phi",
"=",
"0",
")",
":",
"freq_line",
"=",
"TimeSeries",
"(",
"zeros",
"(",
"len",
"(",
"data",
")",
")",
",",
"delta_t",
"=",
"data",
".",
"delta_t",
",",
... | Simple time-domain model for a frequency line.
Parameters
----------
freq: float
Frequency of the line.
data: pycbc.types.TimeSeries
Reference data, to get delta_t, start_time, duration and sample_times.
tref: float
Reference time for the line model.
amp: {1., float}, optional
Amplitude of the frequency line.
phi: {0. float}, optional
Phase of the frequency line (radians).
Returns
-------
freq_line: pycbc.types.TimeSeries
A timeseries of the line model with frequency 'freq'. The returned
data are complex to allow measuring the amplitude and phase of the
corresponding frequency line in the strain data. For extraction, use
only the real part of the data. | [
"Simple",
"time",
"-",
"domain",
"model",
"for",
"a",
"frequency",
"line",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/strain/lines.py#L79-L110 |
228,112 | gwastro/pycbc | pycbc/strain/lines.py | matching_line | def matching_line(freq, data, tref, bin_size=1):
""" Find the parameter of the line with frequency 'freq' in the data.
Parameters
----------
freq: float
Frequency of the line to find in the data.
data: pycbc.types.TimeSeries
Data from which the line wants to be measured.
tref: float
Reference time for the frequency line.
bin_size: {1, float}, optional
Duration of the bins the data will be divided into for averaging.
Returns
-------
line_model: pycbc.types.TimeSeries
A timeseries containing the frequency line with the amplitude
and phase measured from the data.
"""
template_line = line_model(freq, data, tref=tref)
# Measure amplitude and phase of the line in the data
_, amp, phi = avg_inner_product(data, template_line,
bin_size=bin_size)
return line_model(freq, data, tref=tref, amp=amp, phi=phi) | python | def matching_line(freq, data, tref, bin_size=1):
template_line = line_model(freq, data, tref=tref)
# Measure amplitude and phase of the line in the data
_, amp, phi = avg_inner_product(data, template_line,
bin_size=bin_size)
return line_model(freq, data, tref=tref, amp=amp, phi=phi) | [
"def",
"matching_line",
"(",
"freq",
",",
"data",
",",
"tref",
",",
"bin_size",
"=",
"1",
")",
":",
"template_line",
"=",
"line_model",
"(",
"freq",
",",
"data",
",",
"tref",
"=",
"tref",
")",
"# Measure amplitude and phase of the line in the data",
"_",
",",
... | Find the parameter of the line with frequency 'freq' in the data.
Parameters
----------
freq: float
Frequency of the line to find in the data.
data: pycbc.types.TimeSeries
Data from which the line wants to be measured.
tref: float
Reference time for the frequency line.
bin_size: {1, float}, optional
Duration of the bins the data will be divided into for averaging.
Returns
-------
line_model: pycbc.types.TimeSeries
A timeseries containing the frequency line with the amplitude
and phase measured from the data. | [
"Find",
"the",
"parameter",
"of",
"the",
"line",
"with",
"frequency",
"freq",
"in",
"the",
"data",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/strain/lines.py#L112-L136 |
228,113 | gwastro/pycbc | pycbc/strain/lines.py | calibration_lines | def calibration_lines(freqs, data, tref=None):
""" Extract the calibration lines from strain data.
Parameters
----------
freqs: list
List containing the frequencies of the calibration lines.
data: pycbc.types.TimeSeries
Strain data to extract the calibration lines from.
tref: {None, float}, optional
Reference time for the line. If None, will use data.start_time.
Returns
-------
data: pycbc.types.TimeSeries
The strain data with the calibration lines removed.
"""
if tref is None:
tref = float(data.start_time)
for freq in freqs:
measured_line = matching_line(freq, data, tref,
bin_size=data.duration)
data -= measured_line.data.real
return data | python | def calibration_lines(freqs, data, tref=None):
if tref is None:
tref = float(data.start_time)
for freq in freqs:
measured_line = matching_line(freq, data, tref,
bin_size=data.duration)
data -= measured_line.data.real
return data | [
"def",
"calibration_lines",
"(",
"freqs",
",",
"data",
",",
"tref",
"=",
"None",
")",
":",
"if",
"tref",
"is",
"None",
":",
"tref",
"=",
"float",
"(",
"data",
".",
"start_time",
")",
"for",
"freq",
"in",
"freqs",
":",
"measured_line",
"=",
"matching_li... | Extract the calibration lines from strain data.
Parameters
----------
freqs: list
List containing the frequencies of the calibration lines.
data: pycbc.types.TimeSeries
Strain data to extract the calibration lines from.
tref: {None, float}, optional
Reference time for the line. If None, will use data.start_time.
Returns
-------
data: pycbc.types.TimeSeries
The strain data with the calibration lines removed. | [
"Extract",
"the",
"calibration",
"lines",
"from",
"strain",
"data",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/strain/lines.py#L138-L162 |
228,114 | gwastro/pycbc | pycbc/workflow/injection.py | compute_inj_optimal_snr | def compute_inj_optimal_snr(workflow, inj_file, precalc_psd_files, out_dir,
tags=None):
"Set up a job for computing optimal SNRs of a sim_inspiral file."
if tags is None:
tags = []
node = Executable(workflow.cp, 'optimal_snr', ifos=workflow.ifos,
out_dir=out_dir, tags=tags).create_node()
node.add_input_opt('--input-file', inj_file)
node.add_input_list_opt('--time-varying-psds', precalc_psd_files)
node.new_output_file_opt(workflow.analysis_time, '.xml', '--output-file')
workflow += node
return node.output_files[0] | python | def compute_inj_optimal_snr(workflow, inj_file, precalc_psd_files, out_dir,
tags=None):
"Set up a job for computing optimal SNRs of a sim_inspiral file."
if tags is None:
tags = []
node = Executable(workflow.cp, 'optimal_snr', ifos=workflow.ifos,
out_dir=out_dir, tags=tags).create_node()
node.add_input_opt('--input-file', inj_file)
node.add_input_list_opt('--time-varying-psds', precalc_psd_files)
node.new_output_file_opt(workflow.analysis_time, '.xml', '--output-file')
workflow += node
return node.output_files[0] | [
"def",
"compute_inj_optimal_snr",
"(",
"workflow",
",",
"inj_file",
",",
"precalc_psd_files",
",",
"out_dir",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"node",
"=",
"Executable",
"(",
"workflow",
".",
"cp... | Set up a job for computing optimal SNRs of a sim_inspiral file. | [
"Set",
"up",
"a",
"job",
"for",
"computing",
"optimal",
"SNRs",
"of",
"a",
"sim_inspiral",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/injection.py#L52-L64 |
228,115 | gwastro/pycbc | pycbc/workflow/injection.py | cut_distant_injections | def cut_distant_injections(workflow, inj_file, out_dir, tags=None):
"Set up a job for removing injections that are too distant to be seen"
if tags is None:
tags = []
node = Executable(workflow.cp, 'inj_cut', ifos=workflow.ifos,
out_dir=out_dir, tags=tags).create_node()
node.add_input_opt('--input', inj_file)
node.new_output_file_opt(workflow.analysis_time, '.xml', '--output-file')
workflow += node
return node.output_files[0] | python | def cut_distant_injections(workflow, inj_file, out_dir, tags=None):
"Set up a job for removing injections that are too distant to be seen"
if tags is None:
tags = []
node = Executable(workflow.cp, 'inj_cut', ifos=workflow.ifos,
out_dir=out_dir, tags=tags).create_node()
node.add_input_opt('--input', inj_file)
node.new_output_file_opt(workflow.analysis_time, '.xml', '--output-file')
workflow += node
return node.output_files[0] | [
"def",
"cut_distant_injections",
"(",
"workflow",
",",
"inj_file",
",",
"out_dir",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"node",
"=",
"Executable",
"(",
"workflow",
".",
"cp",
",",
"'inj_cut'",
",",... | Set up a job for removing injections that are too distant to be seen | [
"Set",
"up",
"a",
"job",
"for",
"removing",
"injections",
"that",
"are",
"too",
"distant",
"to",
"be",
"seen"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/injection.py#L66-L76 |
228,116 | gwastro/pycbc | pycbc/inference/models/base.py | read_sampling_params_from_config | def read_sampling_params_from_config(cp, section_group=None,
section='sampling_params'):
"""Reads sampling parameters from the given config file.
Parameters are read from the `[({section_group}_){section}]` section.
The options should list the variable args to transform; the parameters they
point to should list the parameters they are to be transformed to for
sampling. If a multiple parameters are transformed together, they should
be comma separated. Example:
.. code-block:: ini
[sampling_params]
mass1, mass2 = mchirp, logitq
spin1_a = logitspin1_a
Note that only the final sampling parameters should be listed, even if
multiple intermediate transforms are needed. (In the above example, a
transform is needed to go from mass1, mass2 to mchirp, q, then another one
needed to go from q to logitq.) These transforms should be specified
in separate sections; see ``transforms.read_transforms_from_config`` for
details.
Parameters
----------
cp : WorkflowConfigParser
An open config parser to read from.
section_group : str, optional
Append `{section_group}_` to the section name. Default is None.
section : str, optional
The name of the section. Default is 'sampling_params'.
Returns
-------
sampling_params : list
The list of sampling parameters to use instead.
replaced_params : list
The list of variable args to replace in the sampler.
"""
if section_group is not None:
section_prefix = '{}_'.format(section_group)
else:
section_prefix = ''
section = section_prefix + section
replaced_params = set()
sampling_params = set()
for args in cp.options(section):
map_args = cp.get(section, args)
sampling_params.update(set(map(str.strip, map_args.split(','))))
replaced_params.update(set(map(str.strip, args.split(','))))
return list(sampling_params), list(replaced_params) | python | def read_sampling_params_from_config(cp, section_group=None,
section='sampling_params'):
if section_group is not None:
section_prefix = '{}_'.format(section_group)
else:
section_prefix = ''
section = section_prefix + section
replaced_params = set()
sampling_params = set()
for args in cp.options(section):
map_args = cp.get(section, args)
sampling_params.update(set(map(str.strip, map_args.split(','))))
replaced_params.update(set(map(str.strip, args.split(','))))
return list(sampling_params), list(replaced_params) | [
"def",
"read_sampling_params_from_config",
"(",
"cp",
",",
"section_group",
"=",
"None",
",",
"section",
"=",
"'sampling_params'",
")",
":",
"if",
"section_group",
"is",
"not",
"None",
":",
"section_prefix",
"=",
"'{}_'",
".",
"format",
"(",
"section_group",
")"... | Reads sampling parameters from the given config file.
Parameters are read from the `[({section_group}_){section}]` section.
The options should list the variable args to transform; the parameters they
point to should list the parameters they are to be transformed to for
sampling. If a multiple parameters are transformed together, they should
be comma separated. Example:
.. code-block:: ini
[sampling_params]
mass1, mass2 = mchirp, logitq
spin1_a = logitspin1_a
Note that only the final sampling parameters should be listed, even if
multiple intermediate transforms are needed. (In the above example, a
transform is needed to go from mass1, mass2 to mchirp, q, then another one
needed to go from q to logitq.) These transforms should be specified
in separate sections; see ``transforms.read_transforms_from_config`` for
details.
Parameters
----------
cp : WorkflowConfigParser
An open config parser to read from.
section_group : str, optional
Append `{section_group}_` to the section name. Default is None.
section : str, optional
The name of the section. Default is 'sampling_params'.
Returns
-------
sampling_params : list
The list of sampling parameters to use instead.
replaced_params : list
The list of variable args to replace in the sampler. | [
"Reads",
"sampling",
"parameters",
"from",
"the",
"given",
"config",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L222-L272 |
228,117 | gwastro/pycbc | pycbc/inference/models/base.py | ModelStats.getstats | def getstats(self, names, default=numpy.nan):
"""Get the requested stats as a tuple.
If a requested stat is not an attribute (implying it hasn't been
stored), then the default value is returned for that stat.
Parameters
----------
names : list of str
The names of the stats to get.
default : float, optional
What to return if a requested stat is not an attribute of self.
Default is ``numpy.nan``.
Returns
-------
tuple
A tuple of the requested stats.
"""
return tuple(getattr(self, n, default) for n in names) | python | def getstats(self, names, default=numpy.nan):
return tuple(getattr(self, n, default) for n in names) | [
"def",
"getstats",
"(",
"self",
",",
"names",
",",
"default",
"=",
"numpy",
".",
"nan",
")",
":",
"return",
"tuple",
"(",
"getattr",
"(",
"self",
",",
"n",
",",
"default",
")",
"for",
"n",
"in",
"names",
")"
] | Get the requested stats as a tuple.
If a requested stat is not an attribute (implying it hasn't been
stored), then the default value is returned for that stat.
Parameters
----------
names : list of str
The names of the stats to get.
default : float, optional
What to return if a requested stat is not an attribute of self.
Default is ``numpy.nan``.
Returns
-------
tuple
A tuple of the requested stats. | [
"Get",
"the",
"requested",
"stats",
"as",
"a",
"tuple",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L65-L84 |
228,118 | gwastro/pycbc | pycbc/inference/models/base.py | ModelStats.getstatsdict | def getstatsdict(self, names, default=numpy.nan):
"""Get the requested stats as a dictionary.
If a requested stat is not an attribute (implying it hasn't been
stored), then the default value is returned for that stat.
Parameters
----------
names : list of str
The names of the stats to get.
default : float, optional
What to return if a requested stat is not an attribute of self.
Default is ``numpy.nan``.
Returns
-------
dict
A dictionary of the requested stats.
"""
return dict(zip(names, self.getstats(names, default=default))) | python | def getstatsdict(self, names, default=numpy.nan):
return dict(zip(names, self.getstats(names, default=default))) | [
"def",
"getstatsdict",
"(",
"self",
",",
"names",
",",
"default",
"=",
"numpy",
".",
"nan",
")",
":",
"return",
"dict",
"(",
"zip",
"(",
"names",
",",
"self",
".",
"getstats",
"(",
"names",
",",
"default",
"=",
"default",
")",
")",
")"
] | Get the requested stats as a dictionary.
If a requested stat is not an attribute (implying it hasn't been
stored), then the default value is returned for that stat.
Parameters
----------
names : list of str
The names of the stats to get.
default : float, optional
What to return if a requested stat is not an attribute of self.
Default is ``numpy.nan``.
Returns
-------
dict
A dictionary of the requested stats. | [
"Get",
"the",
"requested",
"stats",
"as",
"a",
"dictionary",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L86-L105 |
228,119 | gwastro/pycbc | pycbc/inference/models/base.py | SamplingTransforms.logjacobian | def logjacobian(self, **params):
r"""Returns the log of the jacobian needed to transform pdfs in the
``variable_params`` parameter space to the ``sampling_params``
parameter space.
Let :math:`\mathbf{x}` be the set of variable parameters,
:math:`\mathbf{y} = f(\mathbf{x})` the set of sampling parameters, and
:math:`p_x(\mathbf{x})` a probability density function defined over
:math:`\mathbf{x}`.
The corresponding pdf in :math:`\mathbf{y}` is then:
.. math::
p_y(\mathbf{y}) =
p_x(\mathbf{x})\left|\mathrm{det}\,\mathbf{J}_{ij}\right|,
where :math:`\mathbf{J}_{ij}` is the Jacobian of the inverse transform
:math:`\mathbf{x} = g(\mathbf{y})`. This has elements:
.. math::
\mathbf{J}_{ij} = \frac{\partial g_i}{\partial{y_j}}
This function returns
:math:`\log \left|\mathrm{det}\,\mathbf{J}_{ij}\right|`.
Parameters
----------
\**params :
The keyword arguments should specify values for all of the variable
args and all of the sampling args.
Returns
-------
float :
The value of the jacobian.
"""
return numpy.log(abs(transforms.compute_jacobian(
params, self.sampling_transforms, inverse=True))) | python | def logjacobian(self, **params):
r"""Returns the log of the jacobian needed to transform pdfs in the
``variable_params`` parameter space to the ``sampling_params``
parameter space.
Let :math:`\mathbf{x}` be the set of variable parameters,
:math:`\mathbf{y} = f(\mathbf{x})` the set of sampling parameters, and
:math:`p_x(\mathbf{x})` a probability density function defined over
:math:`\mathbf{x}`.
The corresponding pdf in :math:`\mathbf{y}` is then:
.. math::
p_y(\mathbf{y}) =
p_x(\mathbf{x})\left|\mathrm{det}\,\mathbf{J}_{ij}\right|,
where :math:`\mathbf{J}_{ij}` is the Jacobian of the inverse transform
:math:`\mathbf{x} = g(\mathbf{y})`. This has elements:
.. math::
\mathbf{J}_{ij} = \frac{\partial g_i}{\partial{y_j}}
This function returns
:math:`\log \left|\mathrm{det}\,\mathbf{J}_{ij}\right|`.
Parameters
----------
\**params :
The keyword arguments should specify values for all of the variable
args and all of the sampling args.
Returns
-------
float :
The value of the jacobian.
"""
return numpy.log(abs(transforms.compute_jacobian(
params, self.sampling_transforms, inverse=True))) | [
"def",
"logjacobian",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"return",
"numpy",
".",
"log",
"(",
"abs",
"(",
"transforms",
".",
"compute_jacobian",
"(",
"params",
",",
"self",
".",
"sampling_transforms",
",",
"inverse",
"=",
"True",
")",
")",
... | r"""Returns the log of the jacobian needed to transform pdfs in the
``variable_params`` parameter space to the ``sampling_params``
parameter space.
Let :math:`\mathbf{x}` be the set of variable parameters,
:math:`\mathbf{y} = f(\mathbf{x})` the set of sampling parameters, and
:math:`p_x(\mathbf{x})` a probability density function defined over
:math:`\mathbf{x}`.
The corresponding pdf in :math:`\mathbf{y}` is then:
.. math::
p_y(\mathbf{y}) =
p_x(\mathbf{x})\left|\mathrm{det}\,\mathbf{J}_{ij}\right|,
where :math:`\mathbf{J}_{ij}` is the Jacobian of the inverse transform
:math:`\mathbf{x} = g(\mathbf{y})`. This has elements:
.. math::
\mathbf{J}_{ij} = \frac{\partial g_i}{\partial{y_j}}
This function returns
:math:`\log \left|\mathrm{det}\,\mathbf{J}_{ij}\right|`.
Parameters
----------
\**params :
The keyword arguments should specify values for all of the variable
args and all of the sampling args.
Returns
-------
float :
The value of the jacobian. | [
"r",
"Returns",
"the",
"log",
"of",
"the",
"jacobian",
"needed",
"to",
"transform",
"pdfs",
"in",
"the",
"variable_params",
"parameter",
"space",
"to",
"the",
"sampling_params",
"parameter",
"space",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L125-L164 |
228,120 | gwastro/pycbc | pycbc/inference/models/base.py | SamplingTransforms.apply | def apply(self, samples, inverse=False):
"""Applies the sampling transforms to the given samples.
Parameters
----------
samples : dict or FieldArray
The samples to apply the transforms to.
inverse : bool, optional
Whether to apply the inverse transforms (i.e., go from the sampling
args to the ``variable_params``). Default is False.
Returns
-------
dict or FieldArray
The transformed samples, along with the original samples.
"""
return transforms.apply_transforms(samples, self.sampling_transforms,
inverse=inverse) | python | def apply(self, samples, inverse=False):
return transforms.apply_transforms(samples, self.sampling_transforms,
inverse=inverse) | [
"def",
"apply",
"(",
"self",
",",
"samples",
",",
"inverse",
"=",
"False",
")",
":",
"return",
"transforms",
".",
"apply_transforms",
"(",
"samples",
",",
"self",
".",
"sampling_transforms",
",",
"inverse",
"=",
"inverse",
")"
] | Applies the sampling transforms to the given samples.
Parameters
----------
samples : dict or FieldArray
The samples to apply the transforms to.
inverse : bool, optional
Whether to apply the inverse transforms (i.e., go from the sampling
args to the ``variable_params``). Default is False.
Returns
-------
dict or FieldArray
The transformed samples, along with the original samples. | [
"Applies",
"the",
"sampling",
"transforms",
"to",
"the",
"given",
"samples",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L166-L183 |
228,121 | gwastro/pycbc | pycbc/inference/models/base.py | SamplingTransforms.from_config | def from_config(cls, cp, variable_params):
"""Gets sampling transforms specified in a config file.
Sampling parameters and the parameters they replace are read from the
``sampling_params`` section, if it exists. Sampling transforms are
read from the ``sampling_transforms`` section(s), using
``transforms.read_transforms_from_config``.
An ``AssertionError`` is raised if no ``sampling_params`` section
exists in the config file.
Parameters
----------
cp : WorkflowConfigParser
Config file parser to read.
variable_params : list
List of parameter names of the original variable params.
Returns
-------
SamplingTransforms
A sampling transforms class.
"""
if not cp.has_section('sampling_params'):
raise ValueError("no sampling_params section found in config file")
# get sampling transformations
sampling_params, replace_parameters = \
read_sampling_params_from_config(cp)
sampling_transforms = transforms.read_transforms_from_config(
cp, 'sampling_transforms')
logging.info("Sampling in {} in place of {}".format(
', '.join(sampling_params), ', '.join(replace_parameters)))
return cls(variable_params, sampling_params,
replace_parameters, sampling_transforms) | python | def from_config(cls, cp, variable_params):
if not cp.has_section('sampling_params'):
raise ValueError("no sampling_params section found in config file")
# get sampling transformations
sampling_params, replace_parameters = \
read_sampling_params_from_config(cp)
sampling_transforms = transforms.read_transforms_from_config(
cp, 'sampling_transforms')
logging.info("Sampling in {} in place of {}".format(
', '.join(sampling_params), ', '.join(replace_parameters)))
return cls(variable_params, sampling_params,
replace_parameters, sampling_transforms) | [
"def",
"from_config",
"(",
"cls",
",",
"cp",
",",
"variable_params",
")",
":",
"if",
"not",
"cp",
".",
"has_section",
"(",
"'sampling_params'",
")",
":",
"raise",
"ValueError",
"(",
"\"no sampling_params section found in config file\"",
")",
"# get sampling transforma... | Gets sampling transforms specified in a config file.
Sampling parameters and the parameters they replace are read from the
``sampling_params`` section, if it exists. Sampling transforms are
read from the ``sampling_transforms`` section(s), using
``transforms.read_transforms_from_config``.
An ``AssertionError`` is raised if no ``sampling_params`` section
exists in the config file.
Parameters
----------
cp : WorkflowConfigParser
Config file parser to read.
variable_params : list
List of parameter names of the original variable params.
Returns
-------
SamplingTransforms
A sampling transforms class. | [
"Gets",
"sampling",
"transforms",
"specified",
"in",
"a",
"config",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L186-L219 |
228,122 | gwastro/pycbc | pycbc/inference/models/base.py | BaseModel.sampling_params | def sampling_params(self):
"""Returns the sampling parameters.
If ``sampling_transforms`` is None, this is the same as the
``variable_params``.
"""
if self.sampling_transforms is None:
sampling_params = self.variable_params
else:
sampling_params = self.sampling_transforms.sampling_params
return sampling_params | python | def sampling_params(self):
if self.sampling_transforms is None:
sampling_params = self.variable_params
else:
sampling_params = self.sampling_transforms.sampling_params
return sampling_params | [
"def",
"sampling_params",
"(",
"self",
")",
":",
"if",
"self",
".",
"sampling_transforms",
"is",
"None",
":",
"sampling_params",
"=",
"self",
".",
"variable_params",
"else",
":",
"sampling_params",
"=",
"self",
".",
"sampling_transforms",
".",
"sampling_params",
... | Returns the sampling parameters.
If ``sampling_transforms`` is None, this is the same as the
``variable_params``. | [
"Returns",
"the",
"sampling",
"parameters",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L397-L407 |
228,123 | gwastro/pycbc | pycbc/inference/models/base.py | BaseModel.update | def update(self, **params):
"""Updates the current parameter positions and resets stats.
If any sampling transforms are specified, they are applied to the
params before being stored.
"""
self._current_params = self._transform_params(**params)
self._current_stats = ModelStats() | python | def update(self, **params):
self._current_params = self._transform_params(**params)
self._current_stats = ModelStats() | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"self",
".",
"_current_params",
"=",
"self",
".",
"_transform_params",
"(",
"*",
"*",
"params",
")",
"self",
".",
"_current_stats",
"=",
"ModelStats",
"(",
")"
] | Updates the current parameter positions and resets stats.
If any sampling transforms are specified, they are applied to the
params before being stored. | [
"Updates",
"the",
"current",
"parameter",
"positions",
"and",
"resets",
"stats",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L409-L416 |
228,124 | gwastro/pycbc | pycbc/inference/models/base.py | BaseModel.get_current_stats | def get_current_stats(self, names=None):
"""Return one or more of the current stats as a tuple.
This function does no computation. It only returns what has already
been calculated. If a stat hasn't been calculated, it will be returned
as ``numpy.nan``.
Parameters
----------
names : list of str, optional
Specify the names of the stats to retrieve. If ``None`` (the
default), will return ``default_stats``.
Returns
-------
tuple :
The current values of the requested stats, as a tuple. The order
of the stats is the same as the names.
"""
if names is None:
names = self.default_stats
return self._current_stats.getstats(names) | python | def get_current_stats(self, names=None):
if names is None:
names = self.default_stats
return self._current_stats.getstats(names) | [
"def",
"get_current_stats",
"(",
"self",
",",
"names",
"=",
"None",
")",
":",
"if",
"names",
"is",
"None",
":",
"names",
"=",
"self",
".",
"default_stats",
"return",
"self",
".",
"_current_stats",
".",
"getstats",
"(",
"names",
")"
] | Return one or more of the current stats as a tuple.
This function does no computation. It only returns what has already
been calculated. If a stat hasn't been calculated, it will be returned
as ``numpy.nan``.
Parameters
----------
names : list of str, optional
Specify the names of the stats to retrieve. If ``None`` (the
default), will return ``default_stats``.
Returns
-------
tuple :
The current values of the requested stats, as a tuple. The order
of the stats is the same as the names. | [
"Return",
"one",
"or",
"more",
"of",
"the",
"current",
"stats",
"as",
"a",
"tuple",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L439-L460 |
228,125 | gwastro/pycbc | pycbc/inference/models/base.py | BaseModel._trytoget | def _trytoget(self, statname, fallback, **kwargs):
"""Helper function to get a stat from ``_current_stats``.
If the statistic hasn't been calculated, ``_current_stats`` will raise
an ``AttributeError``. In that case, the ``fallback`` function will
be called. If that call is successful, the ``statname`` will be added
to ``_current_stats`` with the returned value.
Parameters
----------
statname : str
The stat to get from ``current_stats``.
fallback : method of self
The function to call if the property call fails.
\**kwargs :
Any other keyword arguments are passed through to the function.
Returns
-------
float :
The value of the property.
"""
try:
return getattr(self._current_stats, statname)
except AttributeError:
val = fallback(**kwargs)
setattr(self._current_stats, statname, val)
return val | python | def _trytoget(self, statname, fallback, **kwargs):
try:
return getattr(self._current_stats, statname)
except AttributeError:
val = fallback(**kwargs)
setattr(self._current_stats, statname, val)
return val | [
"def",
"_trytoget",
"(",
"self",
",",
"statname",
",",
"fallback",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"getattr",
"(",
"self",
".",
"_current_stats",
",",
"statname",
")",
"except",
"AttributeError",
":",
"val",
"=",
"fallback",
"(",... | Helper function to get a stat from ``_current_stats``.
If the statistic hasn't been calculated, ``_current_stats`` will raise
an ``AttributeError``. In that case, the ``fallback`` function will
be called. If that call is successful, the ``statname`` will be added
to ``_current_stats`` with the returned value.
Parameters
----------
statname : str
The stat to get from ``current_stats``.
fallback : method of self
The function to call if the property call fails.
\**kwargs :
Any other keyword arguments are passed through to the function.
Returns
-------
float :
The value of the property. | [
"Helper",
"function",
"to",
"get",
"a",
"stat",
"from",
"_current_stats",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L477-L504 |
228,126 | gwastro/pycbc | pycbc/inference/models/base.py | BaseModel._logjacobian | def _logjacobian(self):
"""Calculates the logjacobian of the current parameters."""
if self.sampling_transforms is None:
logj = 0.
else:
logj = self.sampling_transforms.logjacobian(
**self.current_params)
return logj | python | def _logjacobian(self):
if self.sampling_transforms is None:
logj = 0.
else:
logj = self.sampling_transforms.logjacobian(
**self.current_params)
return logj | [
"def",
"_logjacobian",
"(",
"self",
")",
":",
"if",
"self",
".",
"sampling_transforms",
"is",
"None",
":",
"logj",
"=",
"0.",
"else",
":",
"logj",
"=",
"self",
".",
"sampling_transforms",
".",
"logjacobian",
"(",
"*",
"*",
"self",
".",
"current_params",
... | Calculates the logjacobian of the current parameters. | [
"Calculates",
"the",
"logjacobian",
"of",
"the",
"current",
"parameters",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L541-L548 |
228,127 | gwastro/pycbc | pycbc/inference/models/base.py | BaseModel._logprior | def _logprior(self):
"""Calculates the log prior at the current parameters."""
logj = self.logjacobian
logp = self.prior_distribution(**self.current_params) + logj
if numpy.isnan(logp):
logp = -numpy.inf
return logp | python | def _logprior(self):
logj = self.logjacobian
logp = self.prior_distribution(**self.current_params) + logj
if numpy.isnan(logp):
logp = -numpy.inf
return logp | [
"def",
"_logprior",
"(",
"self",
")",
":",
"logj",
"=",
"self",
".",
"logjacobian",
"logp",
"=",
"self",
".",
"prior_distribution",
"(",
"*",
"*",
"self",
".",
"current_params",
")",
"+",
"logj",
"if",
"numpy",
".",
"isnan",
"(",
"logp",
")",
":",
"l... | Calculates the log prior at the current parameters. | [
"Calculates",
"the",
"log",
"prior",
"at",
"the",
"current",
"parameters",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L555-L561 |
228,128 | gwastro/pycbc | pycbc/inference/models/base.py | BaseModel.logposterior | def logposterior(self):
"""Returns the log of the posterior of the current parameter values.
The logprior is calculated first. If the logprior returns ``-inf``
(possibly indicating a non-physical point), then the ``loglikelihood``
is not called.
"""
logp = self.logprior
if logp == -numpy.inf:
return logp
else:
return logp + self.loglikelihood | python | def logposterior(self):
logp = self.logprior
if logp == -numpy.inf:
return logp
else:
return logp + self.loglikelihood | [
"def",
"logposterior",
"(",
"self",
")",
":",
"logp",
"=",
"self",
".",
"logprior",
"if",
"logp",
"==",
"-",
"numpy",
".",
"inf",
":",
"return",
"logp",
"else",
":",
"return",
"logp",
"+",
"self",
".",
"loglikelihood"
] | Returns the log of the posterior of the current parameter values.
The logprior is calculated first. If the logprior returns ``-inf``
(possibly indicating a non-physical point), then the ``loglikelihood``
is not called. | [
"Returns",
"the",
"log",
"of",
"the",
"posterior",
"of",
"the",
"current",
"parameter",
"values",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L564-L575 |
228,129 | gwastro/pycbc | pycbc/inference/models/base.py | BaseModel.prior_rvs | def prior_rvs(self, size=1, prior=None):
"""Returns random variates drawn from the prior.
If the ``sampling_params`` are different from the ``variable_params``,
the variates are transformed to the `sampling_params` parameter space
before being returned.
Parameters
----------
size : int, optional
Number of random values to return for each parameter. Default is 1.
prior : JointDistribution, optional
Use the given prior to draw values rather than the saved prior.
Returns
-------
FieldArray
A field array of the random values.
"""
# draw values from the prior
if prior is None:
prior = self.prior_distribution
p0 = prior.rvs(size=size)
# transform if necessary
if self.sampling_transforms is not None:
ptrans = self.sampling_transforms.apply(p0)
# pull out the sampling args
p0 = FieldArray.from_arrays([ptrans[arg]
for arg in self.sampling_params],
names=self.sampling_params)
return p0 | python | def prior_rvs(self, size=1, prior=None):
# draw values from the prior
if prior is None:
prior = self.prior_distribution
p0 = prior.rvs(size=size)
# transform if necessary
if self.sampling_transforms is not None:
ptrans = self.sampling_transforms.apply(p0)
# pull out the sampling args
p0 = FieldArray.from_arrays([ptrans[arg]
for arg in self.sampling_params],
names=self.sampling_params)
return p0 | [
"def",
"prior_rvs",
"(",
"self",
",",
"size",
"=",
"1",
",",
"prior",
"=",
"None",
")",
":",
"# draw values from the prior",
"if",
"prior",
"is",
"None",
":",
"prior",
"=",
"self",
".",
"prior_distribution",
"p0",
"=",
"prior",
".",
"rvs",
"(",
"size",
... | Returns random variates drawn from the prior.
If the ``sampling_params`` are different from the ``variable_params``,
the variates are transformed to the `sampling_params` parameter space
before being returned.
Parameters
----------
size : int, optional
Number of random values to return for each parameter. Default is 1.
prior : JointDistribution, optional
Use the given prior to draw values rather than the saved prior.
Returns
-------
FieldArray
A field array of the random values. | [
"Returns",
"random",
"variates",
"drawn",
"from",
"the",
"prior",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L577-L607 |
228,130 | gwastro/pycbc | pycbc/inference/models/base.py | BaseModel._transform_params | def _transform_params(self, **params):
"""Applies all transforms to the given params.
Parameters
----------
\**params :
Key, value pairs of parameters to apply the transforms to.
Returns
-------
dict
A dictionary of the transformed parameters.
"""
# apply inverse transforms to go from sampling parameters to
# variable args
if self.sampling_transforms is not None:
params = self.sampling_transforms.apply(params, inverse=True)
# apply waveform transforms
if self.waveform_transforms is not None:
params = transforms.apply_transforms(params,
self.waveform_transforms,
inverse=False)
# apply boundary conditions
params = self.prior_distribution.apply_boundary_conditions(**params)
return params | python | def _transform_params(self, **params):
# apply inverse transforms to go from sampling parameters to
# variable args
if self.sampling_transforms is not None:
params = self.sampling_transforms.apply(params, inverse=True)
# apply waveform transforms
if self.waveform_transforms is not None:
params = transforms.apply_transforms(params,
self.waveform_transforms,
inverse=False)
# apply boundary conditions
params = self.prior_distribution.apply_boundary_conditions(**params)
return params | [
"def",
"_transform_params",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"# apply inverse transforms to go from sampling parameters to",
"# variable args",
"if",
"self",
".",
"sampling_transforms",
"is",
"not",
"None",
":",
"params",
"=",
"self",
".",
"sampling_tra... | Applies all transforms to the given params.
Parameters
----------
\**params :
Key, value pairs of parameters to apply the transforms to.
Returns
-------
dict
A dictionary of the transformed parameters. | [
"Applies",
"all",
"transforms",
"to",
"the",
"given",
"params",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L609-L633 |
228,131 | gwastro/pycbc | pycbc/inference/models/base.py | BaseModel.extra_args_from_config | def extra_args_from_config(cp, section, skip_args=None, dtypes=None):
"""Gets any additional keyword in the given config file.
Parameters
----------
cp : WorkflowConfigParser
Config file parser to read.
section : str
The name of the section to read.
skip_args : list of str, optional
Names of arguments to skip.
dtypes : dict, optional
A dictionary of arguments -> data types. If an argument is found
in the dict, it will be cast to the given datatype. Otherwise, the
argument's value will just be read from the config file (and thus
be a string).
Returns
-------
dict
Dictionary of keyword arguments read from the config file.
"""
kwargs = {}
if dtypes is None:
dtypes = {}
if skip_args is None:
skip_args = []
read_args = [opt for opt in cp.options(section)
if opt not in skip_args]
for opt in read_args:
val = cp.get(section, opt)
# try to cast the value if a datatype was specified for this opt
try:
val = dtypes[opt](val)
except KeyError:
pass
kwargs[opt] = val
return kwargs | python | def extra_args_from_config(cp, section, skip_args=None, dtypes=None):
kwargs = {}
if dtypes is None:
dtypes = {}
if skip_args is None:
skip_args = []
read_args = [opt for opt in cp.options(section)
if opt not in skip_args]
for opt in read_args:
val = cp.get(section, opt)
# try to cast the value if a datatype was specified for this opt
try:
val = dtypes[opt](val)
except KeyError:
pass
kwargs[opt] = val
return kwargs | [
"def",
"extra_args_from_config",
"(",
"cp",
",",
"section",
",",
"skip_args",
"=",
"None",
",",
"dtypes",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"}",
"if",
"dtypes",
"is",
"None",
":",
"dtypes",
"=",
"{",
"}",
"if",
"skip_args",
"is",
"None",
":"... | Gets any additional keyword in the given config file.
Parameters
----------
cp : WorkflowConfigParser
Config file parser to read.
section : str
The name of the section to read.
skip_args : list of str, optional
Names of arguments to skip.
dtypes : dict, optional
A dictionary of arguments -> data types. If an argument is found
in the dict, it will be cast to the given datatype. Otherwise, the
argument's value will just be read from the config file (and thus
be a string).
Returns
-------
dict
Dictionary of keyword arguments read from the config file. | [
"Gets",
"any",
"additional",
"keyword",
"in",
"the",
"given",
"config",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L639-L676 |
228,132 | gwastro/pycbc | pycbc/inference/models/base.py | BaseModel.prior_from_config | def prior_from_config(cp, variable_params, prior_section,
constraint_section):
"""Gets arguments and keyword arguments from a config file.
Parameters
----------
cp : WorkflowConfigParser
Config file parser to read.
variable_params : list
List of of model parameter names.
prior_section : str
Section to read prior(s) from.
constraint_section : str
Section to read constraint(s) from.
Returns
-------
pycbc.distributions.JointDistribution
The prior.
"""
# get prior distribution for each variable parameter
logging.info("Setting up priors for each parameter")
dists = distributions.read_distributions_from_config(cp, prior_section)
constraints = distributions.read_constraints_from_config(
cp, constraint_section)
return distributions.JointDistribution(variable_params, *dists,
constraints=constraints) | python | def prior_from_config(cp, variable_params, prior_section,
constraint_section):
# get prior distribution for each variable parameter
logging.info("Setting up priors for each parameter")
dists = distributions.read_distributions_from_config(cp, prior_section)
constraints = distributions.read_constraints_from_config(
cp, constraint_section)
return distributions.JointDistribution(variable_params, *dists,
constraints=constraints) | [
"def",
"prior_from_config",
"(",
"cp",
",",
"variable_params",
",",
"prior_section",
",",
"constraint_section",
")",
":",
"# get prior distribution for each variable parameter",
"logging",
".",
"info",
"(",
"\"Setting up priors for each parameter\"",
")",
"dists",
"=",
"dis... | Gets arguments and keyword arguments from a config file.
Parameters
----------
cp : WorkflowConfigParser
Config file parser to read.
variable_params : list
List of of model parameter names.
prior_section : str
Section to read prior(s) from.
constraint_section : str
Section to read constraint(s) from.
Returns
-------
pycbc.distributions.JointDistribution
The prior. | [
"Gets",
"arguments",
"and",
"keyword",
"arguments",
"from",
"a",
"config",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L679-L705 |
228,133 | gwastro/pycbc | pycbc/inference/models/base.py | BaseModel._init_args_from_config | def _init_args_from_config(cls, cp):
"""Helper function for loading parameters.
This retrieves the prior, variable parameters, static parameterss,
constraints, sampling transforms, and waveform transforms
(if provided).
Parameters
----------
cp : ConfigParser
Config parser to read.
Returns
-------
dict :
Dictionary of the arguments. Has keys ``variable_params``,
``static_params``, ``prior``, and ``sampling_transforms``. If
waveform transforms are in the config file, will also have
``waveform_transforms``.
"""
section = "model"
prior_section = "prior"
vparams_section = 'variable_params'
sparams_section = 'static_params'
constraint_section = 'constraint'
# check that the name exists and matches
name = cp.get(section, 'name')
if name != cls.name:
raise ValueError("section's {} name does not match mine {}".format(
name, cls.name))
# get model parameters
variable_params, static_params = distributions.read_params_from_config(
cp, prior_section=prior_section, vargs_section=vparams_section,
sargs_section=sparams_section)
# get prior
prior = cls.prior_from_config(cp, variable_params, prior_section,
constraint_section)
args = {'variable_params': variable_params,
'static_params': static_params,
'prior': prior}
# try to load sampling transforms
try:
sampling_transforms = SamplingTransforms.from_config(
cp, variable_params)
except ValueError:
sampling_transforms = None
args['sampling_transforms'] = sampling_transforms
# get any waveform transforms
if any(cp.get_subsections('waveform_transforms')):
logging.info("Loading waveform transforms")
args['waveform_transforms'] = \
transforms.read_transforms_from_config(
cp, 'waveform_transforms')
return args | python | def _init_args_from_config(cls, cp):
section = "model"
prior_section = "prior"
vparams_section = 'variable_params'
sparams_section = 'static_params'
constraint_section = 'constraint'
# check that the name exists and matches
name = cp.get(section, 'name')
if name != cls.name:
raise ValueError("section's {} name does not match mine {}".format(
name, cls.name))
# get model parameters
variable_params, static_params = distributions.read_params_from_config(
cp, prior_section=prior_section, vargs_section=vparams_section,
sargs_section=sparams_section)
# get prior
prior = cls.prior_from_config(cp, variable_params, prior_section,
constraint_section)
args = {'variable_params': variable_params,
'static_params': static_params,
'prior': prior}
# try to load sampling transforms
try:
sampling_transforms = SamplingTransforms.from_config(
cp, variable_params)
except ValueError:
sampling_transforms = None
args['sampling_transforms'] = sampling_transforms
# get any waveform transforms
if any(cp.get_subsections('waveform_transforms')):
logging.info("Loading waveform transforms")
args['waveform_transforms'] = \
transforms.read_transforms_from_config(
cp, 'waveform_transforms')
return args | [
"def",
"_init_args_from_config",
"(",
"cls",
",",
"cp",
")",
":",
"section",
"=",
"\"model\"",
"prior_section",
"=",
"\"prior\"",
"vparams_section",
"=",
"'variable_params'",
"sparams_section",
"=",
"'static_params'",
"constraint_section",
"=",
"'constraint'",
"# check ... | Helper function for loading parameters.
This retrieves the prior, variable parameters, static parameterss,
constraints, sampling transforms, and waveform transforms
(if provided).
Parameters
----------
cp : ConfigParser
Config parser to read.
Returns
-------
dict :
Dictionary of the arguments. Has keys ``variable_params``,
``static_params``, ``prior``, and ``sampling_transforms``. If
waveform transforms are in the config file, will also have
``waveform_transforms``. | [
"Helper",
"function",
"for",
"loading",
"parameters",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L708-L761 |
228,134 | gwastro/pycbc | pycbc/inference/models/base.py | BaseModel.write_metadata | def write_metadata(self, fp):
"""Writes metadata to the given file handler.
Parameters
----------
fp : pycbc.inference.io.BaseInferenceFile instance
The inference file to write to.
"""
fp.attrs['model'] = self.name
fp.attrs['variable_params'] = list(self.variable_params)
fp.attrs['sampling_params'] = list(self.sampling_params)
fp.write_kwargs_to_attrs(fp.attrs, static_params=self.static_params) | python | def write_metadata(self, fp):
fp.attrs['model'] = self.name
fp.attrs['variable_params'] = list(self.variable_params)
fp.attrs['sampling_params'] = list(self.sampling_params)
fp.write_kwargs_to_attrs(fp.attrs, static_params=self.static_params) | [
"def",
"write_metadata",
"(",
"self",
",",
"fp",
")",
":",
"fp",
".",
"attrs",
"[",
"'model'",
"]",
"=",
"self",
".",
"name",
"fp",
".",
"attrs",
"[",
"'variable_params'",
"]",
"=",
"list",
"(",
"self",
".",
"variable_params",
")",
"fp",
".",
"attrs"... | Writes metadata to the given file handler.
Parameters
----------
fp : pycbc.inference.io.BaseInferenceFile instance
The inference file to write to. | [
"Writes",
"metadata",
"to",
"the",
"given",
"file",
"handler",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L782-L793 |
228,135 | gwastro/pycbc | pycbc/tmpltbank/coord_utils.py | get_cov_params | def get_cov_params(mass1, mass2, spin1z, spin2z, metricParams, fUpper,
lambda1=None, lambda2=None, quadparam1=None,
quadparam2=None):
"""
Function to convert between masses and spins and locations in the xi
parameter space. Xi = Cartesian metric and rotated to principal components.
Parameters
-----------
mass1 : float
Mass of heavier body.
mass2 : float
Mass of lighter body.
spin1z : float
Spin of body 1.
spin2z : float
Spin of body 2.
metricParams : metricParameters instance
Structure holding all the options for construction of the metric
and the eigenvalues, eigenvectors and covariance matrix
needed to manipulate the space.
fUpper : float
The value of fUpper to use when getting the mu coordinates from the
lambda coordinates. This must be a key in metricParams.evals,
metricParams.evecs and metricParams.evecsCV
(ie. we must know how to do the transformation for
the given value of fUpper)
Returns
--------
xis : list of floats or numpy.arrays
Position of the system(s) in the xi coordinate system
"""
# Do this by doing masses - > lambdas -> mus
mus = get_conv_params(mass1, mass2, spin1z, spin2z, metricParams, fUpper,
lambda1=lambda1, lambda2=lambda2,
quadparam1=quadparam1, quadparam2=quadparam2)
# and then mus -> xis
xis = get_covaried_params(mus, metricParams.evecsCV[fUpper])
return xis | python | def get_cov_params(mass1, mass2, spin1z, spin2z, metricParams, fUpper,
lambda1=None, lambda2=None, quadparam1=None,
quadparam2=None):
# Do this by doing masses - > lambdas -> mus
mus = get_conv_params(mass1, mass2, spin1z, spin2z, metricParams, fUpper,
lambda1=lambda1, lambda2=lambda2,
quadparam1=quadparam1, quadparam2=quadparam2)
# and then mus -> xis
xis = get_covaried_params(mus, metricParams.evecsCV[fUpper])
return xis | [
"def",
"get_cov_params",
"(",
"mass1",
",",
"mass2",
",",
"spin1z",
",",
"spin2z",
",",
"metricParams",
",",
"fUpper",
",",
"lambda1",
"=",
"None",
",",
"lambda2",
"=",
"None",
",",
"quadparam1",
"=",
"None",
",",
"quadparam2",
"=",
"None",
")",
":",
"... | Function to convert between masses and spins and locations in the xi
parameter space. Xi = Cartesian metric and rotated to principal components.
Parameters
-----------
mass1 : float
Mass of heavier body.
mass2 : float
Mass of lighter body.
spin1z : float
Spin of body 1.
spin2z : float
Spin of body 2.
metricParams : metricParameters instance
Structure holding all the options for construction of the metric
and the eigenvalues, eigenvectors and covariance matrix
needed to manipulate the space.
fUpper : float
The value of fUpper to use when getting the mu coordinates from the
lambda coordinates. This must be a key in metricParams.evals,
metricParams.evecs and metricParams.evecsCV
(ie. we must know how to do the transformation for
the given value of fUpper)
Returns
--------
xis : list of floats or numpy.arrays
Position of the system(s) in the xi coordinate system | [
"Function",
"to",
"convert",
"between",
"masses",
"and",
"spins",
"and",
"locations",
"in",
"the",
"xi",
"parameter",
"space",
".",
"Xi",
"=",
"Cartesian",
"metric",
"and",
"rotated",
"to",
"principal",
"components",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/coord_utils.py#L295-L335 |
228,136 | gwastro/pycbc | pycbc/tmpltbank/coord_utils.py | get_conv_params | def get_conv_params(mass1, mass2, spin1z, spin2z, metricParams, fUpper,
lambda1=None, lambda2=None, quadparam1=None,
quadparam2=None):
"""
Function to convert between masses and spins and locations in the mu
parameter space. Mu = Cartesian metric, but not principal components.
Parameters
-----------
mass1 : float
Mass of heavier body.
mass2 : float
Mass of lighter body.
spin1z : float
Spin of body 1.
spin2z : float
Spin of body 2.
metricParams : metricParameters instance
Structure holding all the options for construction of the metric
and the eigenvalues, eigenvectors and covariance matrix
needed to manipulate the space.
fUpper : float
The value of fUpper to use when getting the mu coordinates from the
lambda coordinates. This must be a key in metricParams.evals and
metricParams.evecs (ie. we must know how to do the transformation for
the given value of fUpper)
Returns
--------
mus : list of floats or numpy.arrays
Position of the system(s) in the mu coordinate system
"""
# Do this by masses -> lambdas
lambdas = get_chirp_params(mass1, mass2, spin1z, spin2z,
metricParams.f0, metricParams.pnOrder,
lambda1=lambda1, lambda2=lambda2,
quadparam1=quadparam1, quadparam2=quadparam2)
# and lambdas -> mus
mus = get_mu_params(lambdas, metricParams, fUpper)
return mus | python | def get_conv_params(mass1, mass2, spin1z, spin2z, metricParams, fUpper,
lambda1=None, lambda2=None, quadparam1=None,
quadparam2=None):
# Do this by masses -> lambdas
lambdas = get_chirp_params(mass1, mass2, spin1z, spin2z,
metricParams.f0, metricParams.pnOrder,
lambda1=lambda1, lambda2=lambda2,
quadparam1=quadparam1, quadparam2=quadparam2)
# and lambdas -> mus
mus = get_mu_params(lambdas, metricParams, fUpper)
return mus | [
"def",
"get_conv_params",
"(",
"mass1",
",",
"mass2",
",",
"spin1z",
",",
"spin2z",
",",
"metricParams",
",",
"fUpper",
",",
"lambda1",
"=",
"None",
",",
"lambda2",
"=",
"None",
",",
"quadparam1",
"=",
"None",
",",
"quadparam2",
"=",
"None",
")",
":",
... | Function to convert between masses and spins and locations in the mu
parameter space. Mu = Cartesian metric, but not principal components.
Parameters
-----------
mass1 : float
Mass of heavier body.
mass2 : float
Mass of lighter body.
spin1z : float
Spin of body 1.
spin2z : float
Spin of body 2.
metricParams : metricParameters instance
Structure holding all the options for construction of the metric
and the eigenvalues, eigenvectors and covariance matrix
needed to manipulate the space.
fUpper : float
The value of fUpper to use when getting the mu coordinates from the
lambda coordinates. This must be a key in metricParams.evals and
metricParams.evecs (ie. we must know how to do the transformation for
the given value of fUpper)
Returns
--------
mus : list of floats or numpy.arrays
Position of the system(s) in the mu coordinate system | [
"Function",
"to",
"convert",
"between",
"masses",
"and",
"spins",
"and",
"locations",
"in",
"the",
"mu",
"parameter",
"space",
".",
"Mu",
"=",
"Cartesian",
"metric",
"but",
"not",
"principal",
"components",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/coord_utils.py#L337-L377 |
228,137 | gwastro/pycbc | pycbc/tmpltbank/coord_utils.py | get_mu_params | def get_mu_params(lambdas, metricParams, fUpper):
"""
Function to rotate from the lambda coefficients into position in the mu
coordinate system. Mu = Cartesian metric, but not principal components.
Parameters
-----------
lambdas : list of floats or numpy.arrays
Position of the system(s) in the lambda coefficients
metricParams : metricParameters instance
Structure holding all the options for construction of the metric
and the eigenvalues, eigenvectors and covariance matrix
needed to manipulate the space.
fUpper : float
The value of fUpper to use when getting the mu coordinates from the
lambda coordinates. This must be a key in metricParams.evals and
metricParams.evecs (ie. we must know how to do the transformation for
the given value of fUpper)
Returns
--------
mus : list of floats or numpy.arrays
Position of the system(s) in the mu coordinate system
"""
lambdas = numpy.array(lambdas, copy=False)
# If original inputs were floats we need to make this a 2D array
if len(lambdas.shape) == 1:
resize_needed = True
lambdas = lambdas[:,None]
else:
resize_needed = False
evecs = metricParams.evecs[fUpper]
evals = metricParams.evals[fUpper]
evecs = numpy.array(evecs, copy=False)
mus = ((lambdas.T).dot(evecs)).T
mus = mus * numpy.sqrt(evals)[:,None]
if resize_needed:
mus = numpy.ndarray.flatten(mus)
return mus | python | def get_mu_params(lambdas, metricParams, fUpper):
lambdas = numpy.array(lambdas, copy=False)
# If original inputs were floats we need to make this a 2D array
if len(lambdas.shape) == 1:
resize_needed = True
lambdas = lambdas[:,None]
else:
resize_needed = False
evecs = metricParams.evecs[fUpper]
evals = metricParams.evals[fUpper]
evecs = numpy.array(evecs, copy=False)
mus = ((lambdas.T).dot(evecs)).T
mus = mus * numpy.sqrt(evals)[:,None]
if resize_needed:
mus = numpy.ndarray.flatten(mus)
return mus | [
"def",
"get_mu_params",
"(",
"lambdas",
",",
"metricParams",
",",
"fUpper",
")",
":",
"lambdas",
"=",
"numpy",
".",
"array",
"(",
"lambdas",
",",
"copy",
"=",
"False",
")",
"# If original inputs were floats we need to make this a 2D array",
"if",
"len",
"(",
"lamb... | Function to rotate from the lambda coefficients into position in the mu
coordinate system. Mu = Cartesian metric, but not principal components.
Parameters
-----------
lambdas : list of floats or numpy.arrays
Position of the system(s) in the lambda coefficients
metricParams : metricParameters instance
Structure holding all the options for construction of the metric
and the eigenvalues, eigenvectors and covariance matrix
needed to manipulate the space.
fUpper : float
The value of fUpper to use when getting the mu coordinates from the
lambda coordinates. This must be a key in metricParams.evals and
metricParams.evecs (ie. we must know how to do the transformation for
the given value of fUpper)
Returns
--------
mus : list of floats or numpy.arrays
Position of the system(s) in the mu coordinate system | [
"Function",
"to",
"rotate",
"from",
"the",
"lambda",
"coefficients",
"into",
"position",
"in",
"the",
"mu",
"coordinate",
"system",
".",
"Mu",
"=",
"Cartesian",
"metric",
"but",
"not",
"principal",
"components",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/coord_utils.py#L379-L422 |
228,138 | gwastro/pycbc | pycbc/tmpltbank/coord_utils.py | calc_point_dist | def calc_point_dist(vsA, entryA):
"""
This function is used to determine the distance between two points.
Parameters
----------
vsA : list or numpy.array or similar
An array of point 1's position in the \chi_i coordinate system
entryA : list or numpy.array or similar
An array of point 2's position in the \chi_i coordinate system
MMdistA : float
The minimal mismatch allowed between the points
Returns
--------
val : float
The metric distance between the two points.
"""
chi_diffs = vsA - entryA
val = ((chi_diffs)*(chi_diffs)).sum()
return val | python | def calc_point_dist(vsA, entryA):
chi_diffs = vsA - entryA
val = ((chi_diffs)*(chi_diffs)).sum()
return val | [
"def",
"calc_point_dist",
"(",
"vsA",
",",
"entryA",
")",
":",
"chi_diffs",
"=",
"vsA",
"-",
"entryA",
"val",
"=",
"(",
"(",
"chi_diffs",
")",
"*",
"(",
"chi_diffs",
")",
")",
".",
"sum",
"(",
")",
"return",
"val"
] | This function is used to determine the distance between two points.
Parameters
----------
vsA : list or numpy.array or similar
An array of point 1's position in the \chi_i coordinate system
entryA : list or numpy.array or similar
An array of point 2's position in the \chi_i coordinate system
MMdistA : float
The minimal mismatch allowed between the points
Returns
--------
val : float
The metric distance between the two points. | [
"This",
"function",
"is",
"used",
"to",
"determine",
"the",
"distance",
"between",
"two",
"points",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/coord_utils.py#L543-L563 |
228,139 | gwastro/pycbc | pycbc/population/scale_injections.py | read_injections | def read_injections(sim_files, m_dist, s_dist, d_dist):
''' Read all the injections from the files in the provided folder.
The files must belong to individual set i.e. no files that combine
all the injections in a run.
Identify injection strategies and finds parameter boundaries.
Collect injection according to GPS.
Parameters
----------
sim_files: list
List containign names of the simulation files
m_dist: list
The mass distribution used in the simulation runs
s_dist: list
The spin distribution used in the simulation runs
d_dist: list
The distance distribution used in the simulation runs
Returns
-------
injections: dictionary
Contains the organized information about the injections
'''
injections = {}
min_d, max_d = 1e12, 0
nf = len(sim_files)
for i in range(nf):
key = str(i)
injections[key] = process_injections(sim_files[i])
injections[key]['file_name'] = sim_files[i]
injections[key]['m_dist'] = m_dist[i]
injections[key]['s_dist'] = s_dist[i]
injections[key]['d_dist'] = d_dist[i]
mass1, mass2 = injections[key]['mass1'], injections[key]['mass2']
distance = injections[key]['distance']
mchirp = m1m2tomch(mass1, mass2)
injections[key]['chirp_mass'] = mchirp
injections[key]['total_mass'] = mass1 + mass2
injections[key]['mtot_range'] = [min(mass1 + mass2), max(mass1 + mass2)]
injections[key]['m1_range'] = [min(mass1), max(mass1)]
injections[key]['m2_range'] = [min(mass2), max(mass2)]
injections[key]['d_range'] = [min(distance), max(distance)]
min_d, max_d = min(min_d, min(distance)), max(max_d, max(distance))
injections['z_range'] = [dlum_to_z(min_d), dlum_to_z(max_d)]
return injections | python | def read_injections(sim_files, m_dist, s_dist, d_dist):
''' Read all the injections from the files in the provided folder.
The files must belong to individual set i.e. no files that combine
all the injections in a run.
Identify injection strategies and finds parameter boundaries.
Collect injection according to GPS.
Parameters
----------
sim_files: list
List containign names of the simulation files
m_dist: list
The mass distribution used in the simulation runs
s_dist: list
The spin distribution used in the simulation runs
d_dist: list
The distance distribution used in the simulation runs
Returns
-------
injections: dictionary
Contains the organized information about the injections
'''
injections = {}
min_d, max_d = 1e12, 0
nf = len(sim_files)
for i in range(nf):
key = str(i)
injections[key] = process_injections(sim_files[i])
injections[key]['file_name'] = sim_files[i]
injections[key]['m_dist'] = m_dist[i]
injections[key]['s_dist'] = s_dist[i]
injections[key]['d_dist'] = d_dist[i]
mass1, mass2 = injections[key]['mass1'], injections[key]['mass2']
distance = injections[key]['distance']
mchirp = m1m2tomch(mass1, mass2)
injections[key]['chirp_mass'] = mchirp
injections[key]['total_mass'] = mass1 + mass2
injections[key]['mtot_range'] = [min(mass1 + mass2), max(mass1 + mass2)]
injections[key]['m1_range'] = [min(mass1), max(mass1)]
injections[key]['m2_range'] = [min(mass2), max(mass2)]
injections[key]['d_range'] = [min(distance), max(distance)]
min_d, max_d = min(min_d, min(distance)), max(max_d, max(distance))
injections['z_range'] = [dlum_to_z(min_d), dlum_to_z(max_d)]
return injections | [
"def",
"read_injections",
"(",
"sim_files",
",",
"m_dist",
",",
"s_dist",
",",
"d_dist",
")",
":",
"injections",
"=",
"{",
"}",
"min_d",
",",
"max_d",
"=",
"1e12",
",",
"0",
"nf",
"=",
"len",
"(",
"sim_files",
")",
"for",
"i",
"in",
"range",
"(",
"... | Read all the injections from the files in the provided folder.
The files must belong to individual set i.e. no files that combine
all the injections in a run.
Identify injection strategies and finds parameter boundaries.
Collect injection according to GPS.
Parameters
----------
sim_files: list
List containign names of the simulation files
m_dist: list
The mass distribution used in the simulation runs
s_dist: list
The spin distribution used in the simulation runs
d_dist: list
The distance distribution used in the simulation runs
Returns
-------
injections: dictionary
Contains the organized information about the injections | [
"Read",
"all",
"the",
"injections",
"from",
"the",
"files",
"in",
"the",
"provided",
"folder",
".",
"The",
"files",
"must",
"belong",
"to",
"individual",
"set",
"i",
".",
"e",
".",
"no",
"files",
"that",
"combine",
"all",
"the",
"injections",
"in",
"a",
... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/population/scale_injections.py#L19-L71 |
228,140 | gwastro/pycbc | pycbc/population/scale_injections.py | process_injections | def process_injections(hdffile):
"""Function to read in the injection file and
extract the found injections and all injections
Parameters
----------
hdffile: hdf file
File for which injections are to be processed
Returns
-------
data: dictionary
Dictionary containing injection read from the input file
"""
data = {}
with h5py.File(hdffile, 'r') as inp:
found_index = inp['found_after_vetoes/injection_index'][:]
for param in _save_params:
data[param] = inp['injections/'+param][:]
ifar = np.zeros_like(data[_save_params[0]])
ifar[found_index] = inp['found_after_vetoes/ifar'][:]
data['ifar'] = ifar
stat = np.zeros_like(data[_save_params[0]])
stat[found_index] = inp['found_after_vetoes/stat'][:]
data['stat'] = stat
return data | python | def process_injections(hdffile):
data = {}
with h5py.File(hdffile, 'r') as inp:
found_index = inp['found_after_vetoes/injection_index'][:]
for param in _save_params:
data[param] = inp['injections/'+param][:]
ifar = np.zeros_like(data[_save_params[0]])
ifar[found_index] = inp['found_after_vetoes/ifar'][:]
data['ifar'] = ifar
stat = np.zeros_like(data[_save_params[0]])
stat[found_index] = inp['found_after_vetoes/stat'][:]
data['stat'] = stat
return data | [
"def",
"process_injections",
"(",
"hdffile",
")",
":",
"data",
"=",
"{",
"}",
"with",
"h5py",
".",
"File",
"(",
"hdffile",
",",
"'r'",
")",
"as",
"inp",
":",
"found_index",
"=",
"inp",
"[",
"'found_after_vetoes/injection_index'",
"]",
"[",
":",
"]",
"for... | Function to read in the injection file and
extract the found injections and all injections
Parameters
----------
hdffile: hdf file
File for which injections are to be processed
Returns
-------
data: dictionary
Dictionary containing injection read from the input file | [
"Function",
"to",
"read",
"in",
"the",
"injection",
"file",
"and",
"extract",
"the",
"found",
"injections",
"and",
"all",
"injections"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/population/scale_injections.py#L238-L270 |
228,141 | gwastro/pycbc | pycbc/population/scale_injections.py | astro_redshifts | def astro_redshifts(min_z, max_z, nsamples):
'''Sample the redshifts for sources, with redshift
independent rate, using standard cosmology
Parameters
----------
min_z: float
Minimum redshift
max_z: float
Maximum redshift
nsamples: int
Number of samples
Returns
-------
z_astro: array
nsamples of redshift, between min_z, max_z, by standard cosmology
'''
dz, fac = 0.001, 3.0
# use interpolation instead of directly estimating all the pdfz for rndz
V = quad(contracted_dVdc, 0., max_z)[0]
zbins = np.arange(min_z, max_z + dz/2., dz)
zcenter = (zbins[:-1] + zbins[1:]) / 2
pdfz = cosmo.differential_comoving_volume(zcenter).value/(1+zcenter)/V
int_pdf = interp1d(zcenter, pdfz, bounds_error=False, fill_value=0)
rndz = np.random.uniform(min_z, max_z, int(fac*nsamples))
pdf_zs = int_pdf(rndz)
maxpdf = max(pdf_zs)
rndn = np.random.uniform(0, 1, int(fac*nsamples)) * maxpdf
diff = pdf_zs - rndn
idx = np.where(diff > 0)
z_astro = rndz[idx]
np.random.shuffle(z_astro)
z_astro.resize(nsamples)
return z_astro | python | def astro_redshifts(min_z, max_z, nsamples):
'''Sample the redshifts for sources, with redshift
independent rate, using standard cosmology
Parameters
----------
min_z: float
Minimum redshift
max_z: float
Maximum redshift
nsamples: int
Number of samples
Returns
-------
z_astro: array
nsamples of redshift, between min_z, max_z, by standard cosmology
'''
dz, fac = 0.001, 3.0
# use interpolation instead of directly estimating all the pdfz for rndz
V = quad(contracted_dVdc, 0., max_z)[0]
zbins = np.arange(min_z, max_z + dz/2., dz)
zcenter = (zbins[:-1] + zbins[1:]) / 2
pdfz = cosmo.differential_comoving_volume(zcenter).value/(1+zcenter)/V
int_pdf = interp1d(zcenter, pdfz, bounds_error=False, fill_value=0)
rndz = np.random.uniform(min_z, max_z, int(fac*nsamples))
pdf_zs = int_pdf(rndz)
maxpdf = max(pdf_zs)
rndn = np.random.uniform(0, 1, int(fac*nsamples)) * maxpdf
diff = pdf_zs - rndn
idx = np.where(diff > 0)
z_astro = rndz[idx]
np.random.shuffle(z_astro)
z_astro.resize(nsamples)
return z_astro | [
"def",
"astro_redshifts",
"(",
"min_z",
",",
"max_z",
",",
"nsamples",
")",
":",
"dz",
",",
"fac",
"=",
"0.001",
",",
"3.0",
"# use interpolation instead of directly estimating all the pdfz for rndz",
"V",
"=",
"quad",
"(",
"contracted_dVdc",
",",
"0.",
",",
"max_... | Sample the redshifts for sources, with redshift
independent rate, using standard cosmology
Parameters
----------
min_z: float
Minimum redshift
max_z: float
Maximum redshift
nsamples: int
Number of samples
Returns
-------
z_astro: array
nsamples of redshift, between min_z, max_z, by standard cosmology | [
"Sample",
"the",
"redshifts",
"for",
"sources",
"with",
"redshift",
"independent",
"rate",
"using",
"standard",
"cosmology"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/population/scale_injections.py#L288-L327 |
228,142 | gwastro/pycbc | pycbc/population/scale_injections.py | inj_mass_pdf | def inj_mass_pdf(key, mass1, mass2, lomass, himass, lomass_2 = 0, himass_2 = 0):
'''Estimate the probability density based on the injection strategy
Parameters
----------
key: string
Injection strategy
mass1: array
First mass of the injections
mass2: array
Second mass of the injections
lomass: float
Lower value of the mass distributions
himass: float
higher value of the mass distribution
Returns
-------
pdf: array
Probability density of the injections
'''
mass1, mass2 = np.array(mass1), np.array(mass2)
if key == 'totalMass':
# Returns the PDF of mass when total mass is uniformly distributed.
# Both the component masses have the same distribution for this case.
# Parameters
# ----------
# lomass: lower component mass
# himass: higher component mass
bound = np.sign((lomass + himass) - (mass1 + mass2))
bound += np.sign((himass - mass1)*(mass1 - lomass))
bound += np.sign((himass - mass2)*(mass2 - lomass))
idx = np.where(bound != 3)
pdf = 1./(himass - lomass)/(mass1 + mass2 - 2 * lomass)
pdf[idx] = 0
return pdf
if key == 'componentMass':
# Returns the PDF of mass when component mass is uniformly
# distributed. Component masses are independent for this case.
# Parameters
# ----------
# lomass: lower component mass
# himass: higher component mass
bound = np.sign((himass - mass1)*(mass1 - lomass))
bound += np.sign((himass_2 - mass2)*(mass2 - lomass_2))
idx = np.where(bound != 2)
pdf = np.ones_like(mass1) / (himass - lomass) / (himass_2 - lomass_2)
pdf[idx] = 0
return pdf
if key == 'log':
# Returns the PDF of mass when component mass is uniform in log.
# Component masses are independent for this case.
# Parameters
# ----------
# lomass: lower component mass
# himass: higher component mass
bound = np.sign((himass - mass1)*(mass1 - lomass))
bound += np.sign((himass_2 - mass2)*(mass2 - lomass_2))
idx = np.where(bound != 2)
pdf = 1 / (log(himass) - log(lomass)) / (log(himass_2) - log(lomass_2))
pdf /= (mass1 * mass2)
pdf[idx] = 0
return pdf | python | def inj_mass_pdf(key, mass1, mass2, lomass, himass, lomass_2 = 0, himass_2 = 0):
'''Estimate the probability density based on the injection strategy
Parameters
----------
key: string
Injection strategy
mass1: array
First mass of the injections
mass2: array
Second mass of the injections
lomass: float
Lower value of the mass distributions
himass: float
higher value of the mass distribution
Returns
-------
pdf: array
Probability density of the injections
'''
mass1, mass2 = np.array(mass1), np.array(mass2)
if key == 'totalMass':
# Returns the PDF of mass when total mass is uniformly distributed.
# Both the component masses have the same distribution for this case.
# Parameters
# ----------
# lomass: lower component mass
# himass: higher component mass
bound = np.sign((lomass + himass) - (mass1 + mass2))
bound += np.sign((himass - mass1)*(mass1 - lomass))
bound += np.sign((himass - mass2)*(mass2 - lomass))
idx = np.where(bound != 3)
pdf = 1./(himass - lomass)/(mass1 + mass2 - 2 * lomass)
pdf[idx] = 0
return pdf
if key == 'componentMass':
# Returns the PDF of mass when component mass is uniformly
# distributed. Component masses are independent for this case.
# Parameters
# ----------
# lomass: lower component mass
# himass: higher component mass
bound = np.sign((himass - mass1)*(mass1 - lomass))
bound += np.sign((himass_2 - mass2)*(mass2 - lomass_2))
idx = np.where(bound != 2)
pdf = np.ones_like(mass1) / (himass - lomass) / (himass_2 - lomass_2)
pdf[idx] = 0
return pdf
if key == 'log':
# Returns the PDF of mass when component mass is uniform in log.
# Component masses are independent for this case.
# Parameters
# ----------
# lomass: lower component mass
# himass: higher component mass
bound = np.sign((himass - mass1)*(mass1 - lomass))
bound += np.sign((himass_2 - mass2)*(mass2 - lomass_2))
idx = np.where(bound != 2)
pdf = 1 / (log(himass) - log(lomass)) / (log(himass_2) - log(lomass_2))
pdf /= (mass1 * mass2)
pdf[idx] = 0
return pdf | [
"def",
"inj_mass_pdf",
"(",
"key",
",",
"mass1",
",",
"mass2",
",",
"lomass",
",",
"himass",
",",
"lomass_2",
"=",
"0",
",",
"himass_2",
"=",
"0",
")",
":",
"mass1",
",",
"mass2",
"=",
"np",
".",
"array",
"(",
"mass1",
")",
",",
"np",
".",
"array... | Estimate the probability density based on the injection strategy
Parameters
----------
key: string
Injection strategy
mass1: array
First mass of the injections
mass2: array
Second mass of the injections
lomass: float
Lower value of the mass distributions
himass: float
higher value of the mass distribution
Returns
-------
pdf: array
Probability density of the injections | [
"Estimate",
"the",
"probability",
"density",
"based",
"on",
"the",
"injection",
"strategy"
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/population/scale_injections.py#L341-L417 |
228,143 | gwastro/pycbc | pycbc/population/scale_injections.py | inj_spin_pdf | def inj_spin_pdf(key, high_spin, spinz):
''' Estimate the probability density of the
injections for the spin distribution.
Parameters
----------
key: string
Injections strategy
high_spin: float
Maximum spin used in the strategy
spinz: array
Spin of the injections (for one component)
'''
# If the data comes from disable_spin simulation
if spinz[0] == 0:
return np.ones_like(spinz)
spinz = np.array(spinz)
bound = np.sign(np.absolute(high_spin) - np.absolute(spinz))
bound += np.sign(1 - np.absolute(spinz))
if key == 'precessing':
# Returns the PDF of spins when total spin is
# isotropically distributed. Both the component
# masses have the same distribution for this case.
pdf = (np.log(high_spin - np.log(abs(spinz)))/high_spin/2)
idx = np.where(bound != 2)
pdf[idx] = 0
return pdf
if key == 'aligned':
# Returns the PDF of mass when spins are aligned and uniformly
# distributed. Component spins are independent for this case.
pdf = (np.ones_like(spinz) / 2 / high_spin)
idx = np.where(bound != 2)
pdf[idx] = 0
return pdf
if key == 'disable_spin':
# Returns unit array
pdf = np.ones_like(spinz)
return pdf | python | def inj_spin_pdf(key, high_spin, spinz):
''' Estimate the probability density of the
injections for the spin distribution.
Parameters
----------
key: string
Injections strategy
high_spin: float
Maximum spin used in the strategy
spinz: array
Spin of the injections (for one component)
'''
# If the data comes from disable_spin simulation
if spinz[0] == 0:
return np.ones_like(spinz)
spinz = np.array(spinz)
bound = np.sign(np.absolute(high_spin) - np.absolute(spinz))
bound += np.sign(1 - np.absolute(spinz))
if key == 'precessing':
# Returns the PDF of spins when total spin is
# isotropically distributed. Both the component
# masses have the same distribution for this case.
pdf = (np.log(high_spin - np.log(abs(spinz)))/high_spin/2)
idx = np.where(bound != 2)
pdf[idx] = 0
return pdf
if key == 'aligned':
# Returns the PDF of mass when spins are aligned and uniformly
# distributed. Component spins are independent for this case.
pdf = (np.ones_like(spinz) / 2 / high_spin)
idx = np.where(bound != 2)
pdf[idx] = 0
return pdf
if key == 'disable_spin':
# Returns unit array
pdf = np.ones_like(spinz)
return pdf | [
"def",
"inj_spin_pdf",
"(",
"key",
",",
"high_spin",
",",
"spinz",
")",
":",
"# If the data comes from disable_spin simulation",
"if",
"spinz",
"[",
"0",
"]",
"==",
"0",
":",
"return",
"np",
".",
"ones_like",
"(",
"spinz",
")",
"spinz",
"=",
"np",
".",
"ar... | Estimate the probability density of the
injections for the spin distribution.
Parameters
----------
key: string
Injections strategy
high_spin: float
Maximum spin used in the strategy
spinz: array
Spin of the injections (for one component) | [
"Estimate",
"the",
"probability",
"density",
"of",
"the",
"injections",
"for",
"the",
"spin",
"distribution",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/population/scale_injections.py#L419-L468 |
228,144 | gwastro/pycbc | pycbc/population/scale_injections.py | inj_distance_pdf | def inj_distance_pdf(key, distance, low_dist, high_dist, mchirp = 1):
''' Estimate the probability density of the
injections for the distance distribution.
Parameters
----------
key: string
Injections strategy
distance: array
Array of distances
low_dist: float
Lower value of distance used in the injection strategy
high_dist: float
Higher value of distance used in the injection strategy
'''
distance = np.array(distance)
if key == 'uniform':
# Returns the PDF at a distance when
# distance is uniformly distributed.
pdf = np.ones_like(distance)/(high_dist - low_dist)
bound = np.sign((high_dist - distance)*(distance - low_dist))
idx = np.where(bound != 1)
pdf[idx] = 0
return pdf
if key == 'dchirp':
# Returns the PDF at a distance when distance is uniformly
# distributed but scaled by the chirp mass
weight = (mchirp/_mch_BNS)**(5./6)
pdf = np.ones_like(distance) / weight / (high_dist - low_dist)
bound = np.sign((weight*high_dist - distance)*(distance - weight*low_dist))
idx = np.where(bound != 1)
pdf[idx] = 0
return pdf | python | def inj_distance_pdf(key, distance, low_dist, high_dist, mchirp = 1):
''' Estimate the probability density of the
injections for the distance distribution.
Parameters
----------
key: string
Injections strategy
distance: array
Array of distances
low_dist: float
Lower value of distance used in the injection strategy
high_dist: float
Higher value of distance used in the injection strategy
'''
distance = np.array(distance)
if key == 'uniform':
# Returns the PDF at a distance when
# distance is uniformly distributed.
pdf = np.ones_like(distance)/(high_dist - low_dist)
bound = np.sign((high_dist - distance)*(distance - low_dist))
idx = np.where(bound != 1)
pdf[idx] = 0
return pdf
if key == 'dchirp':
# Returns the PDF at a distance when distance is uniformly
# distributed but scaled by the chirp mass
weight = (mchirp/_mch_BNS)**(5./6)
pdf = np.ones_like(distance) / weight / (high_dist - low_dist)
bound = np.sign((weight*high_dist - distance)*(distance - weight*low_dist))
idx = np.where(bound != 1)
pdf[idx] = 0
return pdf | [
"def",
"inj_distance_pdf",
"(",
"key",
",",
"distance",
",",
"low_dist",
",",
"high_dist",
",",
"mchirp",
"=",
"1",
")",
":",
"distance",
"=",
"np",
".",
"array",
"(",
"distance",
")",
"if",
"key",
"==",
"'uniform'",
":",
"# Returns the PDF at a distance whe... | Estimate the probability density of the
injections for the distance distribution.
Parameters
----------
key: string
Injections strategy
distance: array
Array of distances
low_dist: float
Lower value of distance used in the injection strategy
high_dist: float
Higher value of distance used in the injection strategy | [
"Estimate",
"the",
"probability",
"density",
"of",
"the",
"injections",
"for",
"the",
"distance",
"distribution",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/population/scale_injections.py#L470-L507 |
228,145 | gwastro/pycbc | pycbc/transforms.py | get_common_cbc_transforms | def get_common_cbc_transforms(requested_params, variable_args,
valid_params=None):
"""Determines if any additional parameters from the InferenceFile are
needed to get derived parameters that user has asked for.
First it will try to add any base parameters that are required to calculate
the derived parameters. Then it will add any sampling parameters that are
required to calculate the base parameters needed.
Parameters
----------
requested_params : list
List of parameters that user wants.
variable_args : list
List of parameters that InferenceFile has.
valid_params : list
List of parameters that can be accepted.
Returns
-------
requested_params : list
Updated list of parameters that user wants.
all_c : list
List of BaseTransforms to apply.
"""
variable_args = set(variable_args) if not isinstance(variable_args, set) \
else variable_args
# try to parse any equations by putting all strings together
# this will get some garbage but ensures all alphanumeric/underscored
# parameter names are added
new_params = []
for opt in requested_params:
s = ""
for ch in opt:
s += ch if ch.isalnum() or ch == "_" else " "
new_params += s.split(" ")
requested_params = set(list(requested_params) + list(new_params))
# can pass a list of valid parameters to remove garbage from parsing above
if valid_params:
valid_params = set(valid_params)
requested_params = requested_params.intersection(valid_params)
# find all the transforms for the requested derived parameters
# calculated from base parameters
from_base_c = []
for converter in common_cbc_inverse_transforms:
if (converter.outputs.issubset(variable_args) or
converter.outputs.isdisjoint(requested_params)):
continue
intersect = converter.outputs.intersection(requested_params)
if (not intersect or intersect.issubset(converter.inputs) or
intersect.issubset(variable_args)):
continue
requested_params.update(converter.inputs)
from_base_c.append(converter)
# find all the tranforms for the required base parameters
# calculated from sampling parameters
to_base_c = []
for converter in common_cbc_forward_transforms:
if (converter.inputs.issubset(variable_args) and
len(converter.outputs.intersection(requested_params)) > 0):
requested_params.update(converter.inputs)
to_base_c.append(converter)
variable_args.update(converter.outputs)
# get list of transforms that converts sampling parameters to the base
# parameters and then converts base parameters to the derived parameters
all_c = to_base_c + from_base_c
return list(requested_params), all_c | python | def get_common_cbc_transforms(requested_params, variable_args,
valid_params=None):
variable_args = set(variable_args) if not isinstance(variable_args, set) \
else variable_args
# try to parse any equations by putting all strings together
# this will get some garbage but ensures all alphanumeric/underscored
# parameter names are added
new_params = []
for opt in requested_params:
s = ""
for ch in opt:
s += ch if ch.isalnum() or ch == "_" else " "
new_params += s.split(" ")
requested_params = set(list(requested_params) + list(new_params))
# can pass a list of valid parameters to remove garbage from parsing above
if valid_params:
valid_params = set(valid_params)
requested_params = requested_params.intersection(valid_params)
# find all the transforms for the requested derived parameters
# calculated from base parameters
from_base_c = []
for converter in common_cbc_inverse_transforms:
if (converter.outputs.issubset(variable_args) or
converter.outputs.isdisjoint(requested_params)):
continue
intersect = converter.outputs.intersection(requested_params)
if (not intersect or intersect.issubset(converter.inputs) or
intersect.issubset(variable_args)):
continue
requested_params.update(converter.inputs)
from_base_c.append(converter)
# find all the tranforms for the required base parameters
# calculated from sampling parameters
to_base_c = []
for converter in common_cbc_forward_transforms:
if (converter.inputs.issubset(variable_args) and
len(converter.outputs.intersection(requested_params)) > 0):
requested_params.update(converter.inputs)
to_base_c.append(converter)
variable_args.update(converter.outputs)
# get list of transforms that converts sampling parameters to the base
# parameters and then converts base parameters to the derived parameters
all_c = to_base_c + from_base_c
return list(requested_params), all_c | [
"def",
"get_common_cbc_transforms",
"(",
"requested_params",
",",
"variable_args",
",",
"valid_params",
"=",
"None",
")",
":",
"variable_args",
"=",
"set",
"(",
"variable_args",
")",
"if",
"not",
"isinstance",
"(",
"variable_args",
",",
"set",
")",
"else",
"vari... | Determines if any additional parameters from the InferenceFile are
needed to get derived parameters that user has asked for.
First it will try to add any base parameters that are required to calculate
the derived parameters. Then it will add any sampling parameters that are
required to calculate the base parameters needed.
Parameters
----------
requested_params : list
List of parameters that user wants.
variable_args : list
List of parameters that InferenceFile has.
valid_params : list
List of parameters that can be accepted.
Returns
-------
requested_params : list
Updated list of parameters that user wants.
all_c : list
List of BaseTransforms to apply. | [
"Determines",
"if",
"any",
"additional",
"parameters",
"from",
"the",
"InferenceFile",
"are",
"needed",
"to",
"get",
"derived",
"parameters",
"that",
"user",
"has",
"asked",
"for",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L1517-L1589 |
228,146 | gwastro/pycbc | pycbc/transforms.py | apply_transforms | def apply_transforms(samples, transforms, inverse=False):
"""Applies a list of BaseTransform instances on a mapping object.
Parameters
----------
samples : {FieldArray, dict}
Mapping object to apply transforms to.
transforms : list
List of BaseTransform instances to apply. Nested transforms are assumed
to be in order for forward transforms.
inverse : bool, optional
Apply inverse transforms. In this case transforms will be applied in
the opposite order. Default is False.
Returns
-------
samples : {FieldArray, dict}
Mapping object with transforms applied. Same type as input.
"""
if inverse:
transforms = transforms[::-1]
for t in transforms:
try:
if inverse:
samples = t.inverse_transform(samples)
else:
samples = t.transform(samples)
except NotImplementedError:
continue
return samples | python | def apply_transforms(samples, transforms, inverse=False):
if inverse:
transforms = transforms[::-1]
for t in transforms:
try:
if inverse:
samples = t.inverse_transform(samples)
else:
samples = t.transform(samples)
except NotImplementedError:
continue
return samples | [
"def",
"apply_transforms",
"(",
"samples",
",",
"transforms",
",",
"inverse",
"=",
"False",
")",
":",
"if",
"inverse",
":",
"transforms",
"=",
"transforms",
"[",
":",
":",
"-",
"1",
"]",
"for",
"t",
"in",
"transforms",
":",
"try",
":",
"if",
"inverse",... | Applies a list of BaseTransform instances on a mapping object.
Parameters
----------
samples : {FieldArray, dict}
Mapping object to apply transforms to.
transforms : list
List of BaseTransform instances to apply. Nested transforms are assumed
to be in order for forward transforms.
inverse : bool, optional
Apply inverse transforms. In this case transforms will be applied in
the opposite order. Default is False.
Returns
-------
samples : {FieldArray, dict}
Mapping object with transforms applied. Same type as input. | [
"Applies",
"a",
"list",
"of",
"BaseTransform",
"instances",
"on",
"a",
"mapping",
"object",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L1592-L1621 |
228,147 | gwastro/pycbc | pycbc/transforms.py | compute_jacobian | def compute_jacobian(samples, transforms, inverse=False):
"""Computes the jacobian of the list of transforms at the given sample
points.
Parameters
----------
samples : {FieldArray, dict}
Mapping object specifying points at which to compute jacobians.
transforms : list
List of BaseTransform instances to apply. Nested transforms are assumed
to be in order for forward transforms.
inverse : bool, optional
Compute inverse jacobians. Default is False.
Returns
-------
float :
The product of the jacobians of all fo the transforms.
"""
j = 1.
if inverse:
for t in transforms:
j *= t.inverse_jacobian(samples)
else:
for t in transforms:
j *= t.jacobian(samples)
return j | python | def compute_jacobian(samples, transforms, inverse=False):
j = 1.
if inverse:
for t in transforms:
j *= t.inverse_jacobian(samples)
else:
for t in transforms:
j *= t.jacobian(samples)
return j | [
"def",
"compute_jacobian",
"(",
"samples",
",",
"transforms",
",",
"inverse",
"=",
"False",
")",
":",
"j",
"=",
"1.",
"if",
"inverse",
":",
"for",
"t",
"in",
"transforms",
":",
"j",
"*=",
"t",
".",
"inverse_jacobian",
"(",
"samples",
")",
"else",
":",
... | Computes the jacobian of the list of transforms at the given sample
points.
Parameters
----------
samples : {FieldArray, dict}
Mapping object specifying points at which to compute jacobians.
transforms : list
List of BaseTransform instances to apply. Nested transforms are assumed
to be in order for forward transforms.
inverse : bool, optional
Compute inverse jacobians. Default is False.
Returns
-------
float :
The product of the jacobians of all fo the transforms. | [
"Computes",
"the",
"jacobian",
"of",
"the",
"list",
"of",
"transforms",
"at",
"the",
"given",
"sample",
"points",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L1624-L1650 |
228,148 | gwastro/pycbc | pycbc/transforms.py | order_transforms | def order_transforms(transforms):
"""Orders transforms to ensure proper chaining.
For example, if `transforms = [B, A, C]`, and `A` produces outputs needed
by `B`, the transforms will be re-rorderd to `[A, B, C]`.
Parameters
----------
transforms : list
List of transform instances to order.
Outputs
-------
list :
List of transformed ordered such that forward transforms can be carried
out without error.
"""
# get a set of all inputs and all outputs
outputs = set().union(*[t.outputs for t in transforms])
out = []
remaining = [t for t in transforms]
while remaining:
# pull out transforms that have no inputs in the set of outputs
leftover = []
for t in remaining:
if t.inputs.isdisjoint(outputs):
out.append(t)
outputs -= t.outputs
else:
leftover.append(t)
remaining = leftover
return out | python | def order_transforms(transforms):
# get a set of all inputs and all outputs
outputs = set().union(*[t.outputs for t in transforms])
out = []
remaining = [t for t in transforms]
while remaining:
# pull out transforms that have no inputs in the set of outputs
leftover = []
for t in remaining:
if t.inputs.isdisjoint(outputs):
out.append(t)
outputs -= t.outputs
else:
leftover.append(t)
remaining = leftover
return out | [
"def",
"order_transforms",
"(",
"transforms",
")",
":",
"# get a set of all inputs and all outputs",
"outputs",
"=",
"set",
"(",
")",
".",
"union",
"(",
"*",
"[",
"t",
".",
"outputs",
"for",
"t",
"in",
"transforms",
"]",
")",
"out",
"=",
"[",
"]",
"remaini... | Orders transforms to ensure proper chaining.
For example, if `transforms = [B, A, C]`, and `A` produces outputs needed
by `B`, the transforms will be re-rorderd to `[A, B, C]`.
Parameters
----------
transforms : list
List of transform instances to order.
Outputs
-------
list :
List of transformed ordered such that forward transforms can be carried
out without error. | [
"Orders",
"transforms",
"to",
"ensure",
"proper",
"chaining",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L1653-L1684 |
228,149 | gwastro/pycbc | pycbc/transforms.py | read_transforms_from_config | def read_transforms_from_config(cp, section="transforms"):
"""Returns a list of PyCBC transform instances for a section in the
given configuration file.
If the transforms are nested (i.e., the output of one transform is the
input of another), the returned list will be sorted by the order of the
nests.
Parameters
----------
cp : WorflowConfigParser
An open config file to read.
section : {"transforms", string}
Prefix on section names from which to retrieve the transforms.
Returns
-------
list
A list of the parsed transforms.
"""
trans = []
for subsection in cp.get_subsections(section):
name = cp.get_opt_tag(section, "name", subsection)
t = transforms[name].from_config(cp, section, subsection)
trans.append(t)
return order_transforms(trans) | python | def read_transforms_from_config(cp, section="transforms"):
trans = []
for subsection in cp.get_subsections(section):
name = cp.get_opt_tag(section, "name", subsection)
t = transforms[name].from_config(cp, section, subsection)
trans.append(t)
return order_transforms(trans) | [
"def",
"read_transforms_from_config",
"(",
"cp",
",",
"section",
"=",
"\"transforms\"",
")",
":",
"trans",
"=",
"[",
"]",
"for",
"subsection",
"in",
"cp",
".",
"get_subsections",
"(",
"section",
")",
":",
"name",
"=",
"cp",
".",
"get_opt_tag",
"(",
"sectio... | Returns a list of PyCBC transform instances for a section in the
given configuration file.
If the transforms are nested (i.e., the output of one transform is the
input of another), the returned list will be sorted by the order of the
nests.
Parameters
----------
cp : WorflowConfigParser
An open config file to read.
section : {"transforms", string}
Prefix on section names from which to retrieve the transforms.
Returns
-------
list
A list of the parsed transforms. | [
"Returns",
"a",
"list",
"of",
"PyCBC",
"transform",
"instances",
"for",
"a",
"section",
"in",
"the",
"given",
"configuration",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L1686-L1711 |
228,150 | gwastro/pycbc | pycbc/transforms.py | BaseTransform.format_output | def format_output(old_maps, new_maps):
""" This function takes the returned dict from `transform` and converts
it to the same datatype as the input.
Parameters
----------
old_maps : {FieldArray, dict}
The mapping object to add new maps to.
new_maps : dict
A dict with key as parameter name and value is numpy.array.
Returns
-------
{FieldArray, dict}
The old_maps object with new keys from new_maps.
"""
# if input is FieldArray then return FieldArray
if isinstance(old_maps, record.FieldArray):
keys = new_maps.keys()
values = [new_maps[key] for key in keys]
for key, vals in zip(keys, values):
try:
old_maps = old_maps.add_fields([vals], [key])
except ValueError:
old_maps[key] = vals
return old_maps
# if input is dict then return dict
elif isinstance(old_maps, dict):
out = old_maps.copy()
out.update(new_maps)
return out
# else error
else:
raise TypeError("Input type must be FieldArray or dict.") | python | def format_output(old_maps, new_maps):
# if input is FieldArray then return FieldArray
if isinstance(old_maps, record.FieldArray):
keys = new_maps.keys()
values = [new_maps[key] for key in keys]
for key, vals in zip(keys, values):
try:
old_maps = old_maps.add_fields([vals], [key])
except ValueError:
old_maps[key] = vals
return old_maps
# if input is dict then return dict
elif isinstance(old_maps, dict):
out = old_maps.copy()
out.update(new_maps)
return out
# else error
else:
raise TypeError("Input type must be FieldArray or dict.") | [
"def",
"format_output",
"(",
"old_maps",
",",
"new_maps",
")",
":",
"# if input is FieldArray then return FieldArray",
"if",
"isinstance",
"(",
"old_maps",
",",
"record",
".",
"FieldArray",
")",
":",
"keys",
"=",
"new_maps",
".",
"keys",
"(",
")",
"values",
"=",... | This function takes the returned dict from `transform` and converts
it to the same datatype as the input.
Parameters
----------
old_maps : {FieldArray, dict}
The mapping object to add new maps to.
new_maps : dict
A dict with key as parameter name and value is numpy.array.
Returns
-------
{FieldArray, dict}
The old_maps object with new keys from new_maps. | [
"This",
"function",
"takes",
"the",
"returned",
"dict",
"from",
"transform",
"and",
"converts",
"it",
"to",
"the",
"same",
"datatype",
"as",
"the",
"input",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L68-L104 |
228,151 | gwastro/pycbc | pycbc/transforms.py | BaseTransform.from_config | def from_config(cls, cp, section, outputs, skip_opts=None,
additional_opts=None):
"""Initializes a transform from the given section.
Parameters
----------
cp : pycbc.workflow.WorkflowConfigParser
A parsed configuration file that contains the transform options.
section : str
Name of the section in the configuration file.
outputs : str
The names of the parameters that are output by this transformation,
separated by `VARARGS_DELIM`. These must appear in the "tag" part
of the section header.
skip_opts : list, optional
Do not read options in the given list.
additional_opts : dict, optional
Any additional arguments to pass to the class. If an option is
provided that also exists in the config file, the value provided
will be used instead of being read from the file.
Returns
-------
cls
An instance of the class.
"""
tag = outputs
if skip_opts is None:
skip_opts = []
if additional_opts is None:
additional_opts = {}
else:
additional_opts = additional_opts.copy()
outputs = set(outputs.split(VARARGS_DELIM))
special_args = ['name'] + skip_opts + additional_opts.keys()
# get any extra arguments to pass to init
extra_args = {}
for opt in cp.options("-".join([section, tag])):
if opt in special_args:
continue
# check if option can be cast as a float
val = cp.get_opt_tag(section, opt, tag)
try:
val = float(val)
except ValueError:
pass
# add option
extra_args.update({opt:val})
extra_args.update(additional_opts)
out = cls(**extra_args)
# check that the outputs matches
if outputs-out.outputs != set() or out.outputs-outputs != set():
raise ValueError("outputs of class do not match outputs specified "
"in section")
return out | python | def from_config(cls, cp, section, outputs, skip_opts=None,
additional_opts=None):
tag = outputs
if skip_opts is None:
skip_opts = []
if additional_opts is None:
additional_opts = {}
else:
additional_opts = additional_opts.copy()
outputs = set(outputs.split(VARARGS_DELIM))
special_args = ['name'] + skip_opts + additional_opts.keys()
# get any extra arguments to pass to init
extra_args = {}
for opt in cp.options("-".join([section, tag])):
if opt in special_args:
continue
# check if option can be cast as a float
val = cp.get_opt_tag(section, opt, tag)
try:
val = float(val)
except ValueError:
pass
# add option
extra_args.update({opt:val})
extra_args.update(additional_opts)
out = cls(**extra_args)
# check that the outputs matches
if outputs-out.outputs != set() or out.outputs-outputs != set():
raise ValueError("outputs of class do not match outputs specified "
"in section")
return out | [
"def",
"from_config",
"(",
"cls",
",",
"cp",
",",
"section",
",",
"outputs",
",",
"skip_opts",
"=",
"None",
",",
"additional_opts",
"=",
"None",
")",
":",
"tag",
"=",
"outputs",
"if",
"skip_opts",
"is",
"None",
":",
"skip_opts",
"=",
"[",
"]",
"if",
... | Initializes a transform from the given section.
Parameters
----------
cp : pycbc.workflow.WorkflowConfigParser
A parsed configuration file that contains the transform options.
section : str
Name of the section in the configuration file.
outputs : str
The names of the parameters that are output by this transformation,
separated by `VARARGS_DELIM`. These must appear in the "tag" part
of the section header.
skip_opts : list, optional
Do not read options in the given list.
additional_opts : dict, optional
Any additional arguments to pass to the class. If an option is
provided that also exists in the config file, the value provided
will be used instead of being read from the file.
Returns
-------
cls
An instance of the class. | [
"Initializes",
"a",
"transform",
"from",
"the",
"given",
"section",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L107-L161 |
228,152 | gwastro/pycbc | pycbc/transforms.py | CustomTransform._createscratch | def _createscratch(self, shape=1):
"""Creates a scratch FieldArray to use for transforms."""
self._scratch = record.FieldArray(shape, dtype=[(p, float)
for p in self.inputs]) | python | def _createscratch(self, shape=1):
self._scratch = record.FieldArray(shape, dtype=[(p, float)
for p in self.inputs]) | [
"def",
"_createscratch",
"(",
"self",
",",
"shape",
"=",
"1",
")",
":",
"self",
".",
"_scratch",
"=",
"record",
".",
"FieldArray",
"(",
"shape",
",",
"dtype",
"=",
"[",
"(",
"p",
",",
"float",
")",
"for",
"p",
"in",
"self",
".",
"inputs",
"]",
")... | Creates a scratch FieldArray to use for transforms. | [
"Creates",
"a",
"scratch",
"FieldArray",
"to",
"use",
"for",
"transforms",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L214-L217 |
228,153 | gwastro/pycbc | pycbc/transforms.py | CustomTransform._copytoscratch | def _copytoscratch(self, maps):
"""Copies the data in maps to the scratch space.
If the maps contain arrays that are not the same shape as the scratch
space, a new scratch space will be created.
"""
try:
for p in self.inputs:
self._scratch[p][:] = maps[p]
except ValueError:
# we'll get a ValueError if the scratch space isn't the same size
# as the maps; in that case, re-create the scratch space with the
# appropriate size and try again
invals = maps[list(self.inputs)[0]]
if isinstance(invals, numpy.ndarray):
shape = invals.shape
else:
shape = len(invals)
self._createscratch(shape)
for p in self.inputs:
self._scratch[p][:] = maps[p] | python | def _copytoscratch(self, maps):
try:
for p in self.inputs:
self._scratch[p][:] = maps[p]
except ValueError:
# we'll get a ValueError if the scratch space isn't the same size
# as the maps; in that case, re-create the scratch space with the
# appropriate size and try again
invals = maps[list(self.inputs)[0]]
if isinstance(invals, numpy.ndarray):
shape = invals.shape
else:
shape = len(invals)
self._createscratch(shape)
for p in self.inputs:
self._scratch[p][:] = maps[p] | [
"def",
"_copytoscratch",
"(",
"self",
",",
"maps",
")",
":",
"try",
":",
"for",
"p",
"in",
"self",
".",
"inputs",
":",
"self",
".",
"_scratch",
"[",
"p",
"]",
"[",
":",
"]",
"=",
"maps",
"[",
"p",
"]",
"except",
"ValueError",
":",
"# we'll get a Va... | Copies the data in maps to the scratch space.
If the maps contain arrays that are not the same shape as the scratch
space, a new scratch space will be created. | [
"Copies",
"the",
"data",
"in",
"maps",
"to",
"the",
"scratch",
"space",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L219-L239 |
228,154 | gwastro/pycbc | pycbc/transforms.py | CustomTransform._getslice | def _getslice(self, maps):
"""Determines how to slice the scratch for returning values."""
invals = maps[list(self.inputs)[0]]
if not isinstance(invals, (numpy.ndarray, list)):
getslice = 0
else:
getslice = slice(None, None)
return getslice | python | def _getslice(self, maps):
invals = maps[list(self.inputs)[0]]
if not isinstance(invals, (numpy.ndarray, list)):
getslice = 0
else:
getslice = slice(None, None)
return getslice | [
"def",
"_getslice",
"(",
"self",
",",
"maps",
")",
":",
"invals",
"=",
"maps",
"[",
"list",
"(",
"self",
".",
"inputs",
")",
"[",
"0",
"]",
"]",
"if",
"not",
"isinstance",
"(",
"invals",
",",
"(",
"numpy",
".",
"ndarray",
",",
"list",
")",
")",
... | Determines how to slice the scratch for returning values. | [
"Determines",
"how",
"to",
"slice",
"the",
"scratch",
"for",
"returning",
"values",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L241-L248 |
228,155 | gwastro/pycbc | pycbc/transforms.py | CustomTransform.transform | def transform(self, maps):
"""Applies the transform functions to the given maps object.
Parameters
----------
maps : dict, or FieldArray
Returns
-------
dict or FieldArray
A map object containing the transformed variables, along with the
original variables. The type of the output will be the same as the
input.
"""
if self.transform_functions is None:
raise NotImplementedError("no transform function(s) provided")
# copy values to scratch
self._copytoscratch(maps)
# ensure that we return the same data type in each dict
getslice = self._getslice(maps)
# evaluate the functions
out = {p: self._scratch[func][getslice]
for p,func in self.transform_functions.items()}
return self.format_output(maps, out) | python | def transform(self, maps):
if self.transform_functions is None:
raise NotImplementedError("no transform function(s) provided")
# copy values to scratch
self._copytoscratch(maps)
# ensure that we return the same data type in each dict
getslice = self._getslice(maps)
# evaluate the functions
out = {p: self._scratch[func][getslice]
for p,func in self.transform_functions.items()}
return self.format_output(maps, out) | [
"def",
"transform",
"(",
"self",
",",
"maps",
")",
":",
"if",
"self",
".",
"transform_functions",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"\"no transform function(s) provided\"",
")",
"# copy values to scratch",
"self",
".",
"_copytoscratch",
"(",
"m... | Applies the transform functions to the given maps object.
Parameters
----------
maps : dict, or FieldArray
Returns
-------
dict or FieldArray
A map object containing the transformed variables, along with the
original variables. The type of the output will be the same as the
input. | [
"Applies",
"the",
"transform",
"functions",
"to",
"the",
"given",
"maps",
"object",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L250-L273 |
228,156 | gwastro/pycbc | pycbc/transforms.py | CustomTransform.from_config | def from_config(cls, cp, section, outputs):
"""Loads a CustomTransform from the given config file.
Example section:
.. code-block:: ini
[{section}-outvar1+outvar2]
name = custom
inputs = inputvar1, inputvar2
outvar1 = func1(inputs)
outvar2 = func2(inputs)
jacobian = func(inputs)
"""
tag = outputs
outputs = set(outputs.split(VARARGS_DELIM))
inputs = map(str.strip,
cp.get_opt_tag(section, 'inputs', tag).split(','))
# get the functions for each output
transform_functions = {}
for var in outputs:
# check if option can be cast as a float
func = cp.get_opt_tag(section, var, tag)
transform_functions[var] = func
s = '-'.join([section, tag])
if cp.has_option(s, 'jacobian'):
jacobian = cp.get_opt_tag(section, 'jacobian', tag)
else:
jacobian = None
return cls(inputs, outputs, transform_functions, jacobian=jacobian) | python | def from_config(cls, cp, section, outputs):
tag = outputs
outputs = set(outputs.split(VARARGS_DELIM))
inputs = map(str.strip,
cp.get_opt_tag(section, 'inputs', tag).split(','))
# get the functions for each output
transform_functions = {}
for var in outputs:
# check if option can be cast as a float
func = cp.get_opt_tag(section, var, tag)
transform_functions[var] = func
s = '-'.join([section, tag])
if cp.has_option(s, 'jacobian'):
jacobian = cp.get_opt_tag(section, 'jacobian', tag)
else:
jacobian = None
return cls(inputs, outputs, transform_functions, jacobian=jacobian) | [
"def",
"from_config",
"(",
"cls",
",",
"cp",
",",
"section",
",",
"outputs",
")",
":",
"tag",
"=",
"outputs",
"outputs",
"=",
"set",
"(",
"outputs",
".",
"split",
"(",
"VARARGS_DELIM",
")",
")",
"inputs",
"=",
"map",
"(",
"str",
".",
"strip",
",",
... | Loads a CustomTransform from the given config file.
Example section:
.. code-block:: ini
[{section}-outvar1+outvar2]
name = custom
inputs = inputvar1, inputvar2
outvar1 = func1(inputs)
outvar2 = func2(inputs)
jacobian = func(inputs) | [
"Loads",
"a",
"CustomTransform",
"from",
"the",
"given",
"config",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L286-L315 |
228,157 | gwastro/pycbc | pycbc/transforms.py | MchirpQToMass1Mass2.transform | def transform(self, maps):
"""This function transforms from chirp mass and mass ratio to component
masses.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.MchirpQToMass1Mass2()
>>> t.transform({'mchirp': numpy.array([10.]), 'q': numpy.array([2.])})
{'mass1': array([ 16.4375183]), 'mass2': array([ 8.21875915]),
'mchirp': array([ 10.]), 'q': array([ 2.])}
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values.
"""
out = {}
out[parameters.mass1] = conversions.mass1_from_mchirp_q(
maps[parameters.mchirp],
maps[parameters.q])
out[parameters.mass2] = conversions.mass2_from_mchirp_q(
maps[parameters.mchirp],
maps[parameters.q])
return self.format_output(maps, out) | python | def transform(self, maps):
out = {}
out[parameters.mass1] = conversions.mass1_from_mchirp_q(
maps[parameters.mchirp],
maps[parameters.q])
out[parameters.mass2] = conversions.mass2_from_mchirp_q(
maps[parameters.mchirp],
maps[parameters.q])
return self.format_output(maps, out) | [
"def",
"transform",
"(",
"self",
",",
"maps",
")",
":",
"out",
"=",
"{",
"}",
"out",
"[",
"parameters",
".",
"mass1",
"]",
"=",
"conversions",
".",
"mass1_from_mchirp_q",
"(",
"maps",
"[",
"parameters",
".",
"mchirp",
"]",
",",
"maps",
"[",
"parameters... | This function transforms from chirp mass and mass ratio to component
masses.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.MchirpQToMass1Mass2()
>>> t.transform({'mchirp': numpy.array([10.]), 'q': numpy.array([2.])})
{'mass1': array([ 16.4375183]), 'mass2': array([ 8.21875915]),
'mchirp': array([ 10.]), 'q': array([ 2.])}
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values. | [
"This",
"function",
"transforms",
"from",
"chirp",
"mass",
"and",
"mass",
"ratio",
"to",
"component",
"masses",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L333-L365 |
228,158 | gwastro/pycbc | pycbc/transforms.py | MchirpQToMass1Mass2.inverse_transform | def inverse_transform(self, maps):
"""This function transforms from component masses to chirp mass and
mass ratio.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.MchirpQToMass1Mass2()
>>> t.inverse_transform({'mass1': numpy.array([16.4]), 'mass2': numpy.array([8.2])})
{'mass1': array([ 16.4]), 'mass2': array([ 8.2]),
'mchirp': array([ 9.97717521]), 'q': 2.0}
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values.
"""
out = {}
m1 = maps[parameters.mass1]
m2 = maps[parameters.mass2]
out[parameters.mchirp] = conversions.mchirp_from_mass1_mass2(m1, m2)
out[parameters.q] = m1 / m2
return self.format_output(maps, out) | python | def inverse_transform(self, maps):
out = {}
m1 = maps[parameters.mass1]
m2 = maps[parameters.mass2]
out[parameters.mchirp] = conversions.mchirp_from_mass1_mass2(m1, m2)
out[parameters.q] = m1 / m2
return self.format_output(maps, out) | [
"def",
"inverse_transform",
"(",
"self",
",",
"maps",
")",
":",
"out",
"=",
"{",
"}",
"m1",
"=",
"maps",
"[",
"parameters",
".",
"mass1",
"]",
"m2",
"=",
"maps",
"[",
"parameters",
".",
"mass2",
"]",
"out",
"[",
"parameters",
".",
"mchirp",
"]",
"=... | This function transforms from component masses to chirp mass and
mass ratio.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.MchirpQToMass1Mass2()
>>> t.inverse_transform({'mass1': numpy.array([16.4]), 'mass2': numpy.array([8.2])})
{'mass1': array([ 16.4]), 'mass2': array([ 8.2]),
'mchirp': array([ 9.97717521]), 'q': 2.0}
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values. | [
"This",
"function",
"transforms",
"from",
"component",
"masses",
"to",
"chirp",
"mass",
"and",
"mass",
"ratio",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L367-L397 |
228,159 | gwastro/pycbc | pycbc/transforms.py | MchirpQToMass1Mass2.jacobian | def jacobian(self, maps):
"""Returns the Jacobian for transforming mchirp and q to mass1 and
mass2.
"""
mchirp = maps[parameters.mchirp]
q = maps[parameters.q]
return mchirp * ((1.+q)/q**3.)**(2./5) | python | def jacobian(self, maps):
mchirp = maps[parameters.mchirp]
q = maps[parameters.q]
return mchirp * ((1.+q)/q**3.)**(2./5) | [
"def",
"jacobian",
"(",
"self",
",",
"maps",
")",
":",
"mchirp",
"=",
"maps",
"[",
"parameters",
".",
"mchirp",
"]",
"q",
"=",
"maps",
"[",
"parameters",
".",
"q",
"]",
"return",
"mchirp",
"*",
"(",
"(",
"1.",
"+",
"q",
")",
"/",
"q",
"**",
"3.... | Returns the Jacobian for transforming mchirp and q to mass1 and
mass2. | [
"Returns",
"the",
"Jacobian",
"for",
"transforming",
"mchirp",
"and",
"q",
"to",
"mass1",
"and",
"mass2",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L399-L405 |
228,160 | gwastro/pycbc | pycbc/transforms.py | MchirpQToMass1Mass2.inverse_jacobian | def inverse_jacobian(self, maps):
"""Returns the Jacobian for transforming mass1 and mass2 to
mchirp and q.
"""
m1 = maps[parameters.mass1]
m2 = maps[parameters.mass2]
return conversions.mchirp_from_mass1_mass2(m1, m2)/m2**2. | python | def inverse_jacobian(self, maps):
m1 = maps[parameters.mass1]
m2 = maps[parameters.mass2]
return conversions.mchirp_from_mass1_mass2(m1, m2)/m2**2. | [
"def",
"inverse_jacobian",
"(",
"self",
",",
"maps",
")",
":",
"m1",
"=",
"maps",
"[",
"parameters",
".",
"mass1",
"]",
"m2",
"=",
"maps",
"[",
"parameters",
".",
"mass2",
"]",
"return",
"conversions",
".",
"mchirp_from_mass1_mass2",
"(",
"m1",
",",
"m2"... | Returns the Jacobian for transforming mass1 and mass2 to
mchirp and q. | [
"Returns",
"the",
"Jacobian",
"for",
"transforming",
"mass1",
"and",
"mass2",
"to",
"mchirp",
"and",
"q",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L407-L413 |
228,161 | gwastro/pycbc | pycbc/transforms.py | MchirpEtaToMass1Mass2.transform | def transform(self, maps):
"""This function transforms from chirp mass and symmetric mass ratio to
component masses.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.MchirpEtaToMass1Mass2()
>>> t.transform({'mchirp': numpy.array([10.]), 'eta': numpy.array([0.25])})
{'mass1': array([ 16.4375183]), 'mass2': array([ 8.21875915]),
'mchirp': array([ 10.]), 'eta': array([ 0.25])}
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values.
"""
out = {}
out[parameters.mass1] = conversions.mass1_from_mchirp_eta(
maps[parameters.mchirp],
maps[parameters.eta])
out[parameters.mass2] = conversions.mass2_from_mchirp_eta(
maps[parameters.mchirp],
maps[parameters.eta])
return self.format_output(maps, out) | python | def transform(self, maps):
out = {}
out[parameters.mass1] = conversions.mass1_from_mchirp_eta(
maps[parameters.mchirp],
maps[parameters.eta])
out[parameters.mass2] = conversions.mass2_from_mchirp_eta(
maps[parameters.mchirp],
maps[parameters.eta])
return self.format_output(maps, out) | [
"def",
"transform",
"(",
"self",
",",
"maps",
")",
":",
"out",
"=",
"{",
"}",
"out",
"[",
"parameters",
".",
"mass1",
"]",
"=",
"conversions",
".",
"mass1_from_mchirp_eta",
"(",
"maps",
"[",
"parameters",
".",
"mchirp",
"]",
",",
"maps",
"[",
"paramete... | This function transforms from chirp mass and symmetric mass ratio to
component masses.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.MchirpEtaToMass1Mass2()
>>> t.transform({'mchirp': numpy.array([10.]), 'eta': numpy.array([0.25])})
{'mass1': array([ 16.4375183]), 'mass2': array([ 8.21875915]),
'mchirp': array([ 10.]), 'eta': array([ 0.25])}
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values. | [
"This",
"function",
"transforms",
"from",
"chirp",
"mass",
"and",
"symmetric",
"mass",
"ratio",
"to",
"component",
"masses",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L422-L454 |
228,162 | gwastro/pycbc | pycbc/transforms.py | MchirpEtaToMass1Mass2.jacobian | def jacobian(self, maps):
"""Returns the Jacobian for transforming mchirp and eta to mass1 and
mass2.
"""
mchirp = maps[parameters.mchirp]
eta = maps[parameters.eta]
m1 = conversions.mass1_from_mchirp_eta(mchirp, eta)
m2 = conversions.mass2_from_mchirp_eta(mchirp, eta)
return mchirp * (m1 - m2) / (m1 + m2)**3 | python | def jacobian(self, maps):
mchirp = maps[parameters.mchirp]
eta = maps[parameters.eta]
m1 = conversions.mass1_from_mchirp_eta(mchirp, eta)
m2 = conversions.mass2_from_mchirp_eta(mchirp, eta)
return mchirp * (m1 - m2) / (m1 + m2)**3 | [
"def",
"jacobian",
"(",
"self",
",",
"maps",
")",
":",
"mchirp",
"=",
"maps",
"[",
"parameters",
".",
"mchirp",
"]",
"eta",
"=",
"maps",
"[",
"parameters",
".",
"eta",
"]",
"m1",
"=",
"conversions",
".",
"mass1_from_mchirp_eta",
"(",
"mchirp",
",",
"et... | Returns the Jacobian for transforming mchirp and eta to mass1 and
mass2. | [
"Returns",
"the",
"Jacobian",
"for",
"transforming",
"mchirp",
"and",
"eta",
"to",
"mass1",
"and",
"mass2",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L488-L496 |
228,163 | gwastro/pycbc | pycbc/transforms.py | MchirpEtaToMass1Mass2.inverse_jacobian | def inverse_jacobian(self, maps):
"""Returns the Jacobian for transforming mass1 and mass2 to
mchirp and eta.
"""
m1 = maps[parameters.mass1]
m2 = maps[parameters.mass2]
mchirp = conversions.mchirp_from_mass1_mass2(m1, m2)
eta = conversions.eta_from_mass1_mass2(m1, m2)
return -1. * mchirp / eta**(6./5) | python | def inverse_jacobian(self, maps):
m1 = maps[parameters.mass1]
m2 = maps[parameters.mass2]
mchirp = conversions.mchirp_from_mass1_mass2(m1, m2)
eta = conversions.eta_from_mass1_mass2(m1, m2)
return -1. * mchirp / eta**(6./5) | [
"def",
"inverse_jacobian",
"(",
"self",
",",
"maps",
")",
":",
"m1",
"=",
"maps",
"[",
"parameters",
".",
"mass1",
"]",
"m2",
"=",
"maps",
"[",
"parameters",
".",
"mass2",
"]",
"mchirp",
"=",
"conversions",
".",
"mchirp_from_mass1_mass2",
"(",
"m1",
",",... | Returns the Jacobian for transforming mass1 and mass2 to
mchirp and eta. | [
"Returns",
"the",
"Jacobian",
"for",
"transforming",
"mass1",
"and",
"mass2",
"to",
"mchirp",
"and",
"eta",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L498-L506 |
228,164 | gwastro/pycbc | pycbc/transforms.py | ChirpDistanceToDistance.transform | def transform(self, maps):
"""This function transforms from chirp distance to luminosity distance,
given the chirp mass.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> import numpy as np
>>> from pycbc import transforms
>>> t = transforms.ChirpDistanceToDistance()
>>> t.transform({'chirp_distance': np.array([40.]), 'mchirp': np.array([1.2])})
{'mchirp': array([ 1.2]), 'chirp_distance': array([ 40.]), 'distance': array([ 39.48595679])}
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values.
"""
out = {}
out[parameters.distance] = \
conversions.distance_from_chirp_distance_mchirp(
maps[parameters.chirp_distance],
maps[parameters.mchirp],
ref_mass=self.ref_mass)
return self.format_output(maps, out) | python | def transform(self, maps):
out = {}
out[parameters.distance] = \
conversions.distance_from_chirp_distance_mchirp(
maps[parameters.chirp_distance],
maps[parameters.mchirp],
ref_mass=self.ref_mass)
return self.format_output(maps, out) | [
"def",
"transform",
"(",
"self",
",",
"maps",
")",
":",
"out",
"=",
"{",
"}",
"out",
"[",
"parameters",
".",
"distance",
"]",
"=",
"conversions",
".",
"distance_from_chirp_distance_mchirp",
"(",
"maps",
"[",
"parameters",
".",
"chirp_distance",
"]",
",",
"... | This function transforms from chirp distance to luminosity distance,
given the chirp mass.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> import numpy as np
>>> from pycbc import transforms
>>> t = transforms.ChirpDistanceToDistance()
>>> t.transform({'chirp_distance': np.array([40.]), 'mchirp': np.array([1.2])})
{'mchirp': array([ 1.2]), 'chirp_distance': array([ 40.]), 'distance': array([ 39.48595679])}
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values. | [
"This",
"function",
"transforms",
"from",
"chirp",
"distance",
"to",
"luminosity",
"distance",
"given",
"the",
"chirp",
"mass",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L520-L550 |
228,165 | gwastro/pycbc | pycbc/transforms.py | ChirpDistanceToDistance.inverse_transform | def inverse_transform(self, maps):
"""This function transforms from luminosity distance to chirp distance,
given the chirp mass.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> import numpy as np
>>> from pycbc import transforms
>>> t = transforms.ChirpDistanceToDistance()
>>> t.inverse_transform({'distance': np.array([40.]), 'mchirp': np.array([1.2])})
{'distance': array([ 40.]), 'chirp_distance': array([ 40.52073522]), 'mchirp': array([ 1.2])}
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values.
"""
out = {}
out[parameters.chirp_distance] = \
conversions.chirp_distance(maps[parameters.distance],
maps[parameters.mchirp], ref_mass=self.ref_mass)
return self.format_output(maps, out) | python | def inverse_transform(self, maps):
out = {}
out[parameters.chirp_distance] = \
conversions.chirp_distance(maps[parameters.distance],
maps[parameters.mchirp], ref_mass=self.ref_mass)
return self.format_output(maps, out) | [
"def",
"inverse_transform",
"(",
"self",
",",
"maps",
")",
":",
"out",
"=",
"{",
"}",
"out",
"[",
"parameters",
".",
"chirp_distance",
"]",
"=",
"conversions",
".",
"chirp_distance",
"(",
"maps",
"[",
"parameters",
".",
"distance",
"]",
",",
"maps",
"[",... | This function transforms from luminosity distance to chirp distance,
given the chirp mass.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> import numpy as np
>>> from pycbc import transforms
>>> t = transforms.ChirpDistanceToDistance()
>>> t.inverse_transform({'distance': np.array([40.]), 'mchirp': np.array([1.2])})
{'distance': array([ 40.]), 'chirp_distance': array([ 40.52073522]), 'mchirp': array([ 1.2])}
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values. | [
"This",
"function",
"transforms",
"from",
"luminosity",
"distance",
"to",
"chirp",
"distance",
"given",
"the",
"chirp",
"mass",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L552-L580 |
228,166 | gwastro/pycbc | pycbc/transforms.py | SphericalSpin1ToCartesianSpin1.transform | def transform(self, maps):
""" This function transforms from spherical to cartesian spins.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.SphericalSpin1ToCartesianSpin1()
>>> t.transform({'spin1_a': numpy.array([0.1]), 'spin1_azimuthal': numpy.array([0.1]), 'spin1_polar': numpy.array([0.1])})
{'spin1_a': array([ 0.1]), 'spin1_azimuthal': array([ 0.1]), 'spin1_polar': array([ 0.1]),
'spin2x': array([ 0.00993347]), 'spin2y': array([ 0.00099667]), 'spin2z': array([ 0.09950042])}
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values.
"""
a, az, po = self._inputs
data = coordinates.spherical_to_cartesian(maps[a], maps[az], maps[po])
out = {param : val for param, val in zip(self._outputs, data)}
return self.format_output(maps, out) | python | def transform(self, maps):
a, az, po = self._inputs
data = coordinates.spherical_to_cartesian(maps[a], maps[az], maps[po])
out = {param : val for param, val in zip(self._outputs, data)}
return self.format_output(maps, out) | [
"def",
"transform",
"(",
"self",
",",
"maps",
")",
":",
"a",
",",
"az",
",",
"po",
"=",
"self",
".",
"_inputs",
"data",
"=",
"coordinates",
".",
"spherical_to_cartesian",
"(",
"maps",
"[",
"a",
"]",
",",
"maps",
"[",
"az",
"]",
",",
"maps",
"[",
... | This function transforms from spherical to cartesian spins.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.SphericalSpin1ToCartesianSpin1()
>>> t.transform({'spin1_a': numpy.array([0.1]), 'spin1_azimuthal': numpy.array([0.1]), 'spin1_polar': numpy.array([0.1])})
{'spin1_a': array([ 0.1]), 'spin1_azimuthal': array([ 0.1]), 'spin1_polar': array([ 0.1]),
'spin2x': array([ 0.00993347]), 'spin2y': array([ 0.00099667]), 'spin2z': array([ 0.09950042])}
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values. | [
"This",
"function",
"transforms",
"from",
"spherical",
"to",
"cartesian",
"spins",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L609-L636 |
228,167 | gwastro/pycbc | pycbc/transforms.py | SphericalSpin1ToCartesianSpin1.inverse_transform | def inverse_transform(self, maps):
""" This function transforms from cartesian to spherical spins.
Parameters
----------
maps : a mapping object
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values.
"""
sx, sy, sz = self._outputs
data = coordinates.cartesian_to_spherical(maps[sx], maps[sy], maps[sz])
out = {param : val for param, val in zip(self._outputs, data)}
return self.format_output(maps, out) | python | def inverse_transform(self, maps):
sx, sy, sz = self._outputs
data = coordinates.cartesian_to_spherical(maps[sx], maps[sy], maps[sz])
out = {param : val for param, val in zip(self._outputs, data)}
return self.format_output(maps, out) | [
"def",
"inverse_transform",
"(",
"self",
",",
"maps",
")",
":",
"sx",
",",
"sy",
",",
"sz",
"=",
"self",
".",
"_outputs",
"data",
"=",
"coordinates",
".",
"cartesian_to_spherical",
"(",
"maps",
"[",
"sx",
"]",
",",
"maps",
"[",
"sy",
"]",
",",
"maps"... | This function transforms from cartesian to spherical spins.
Parameters
----------
maps : a mapping object
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values. | [
"This",
"function",
"transforms",
"from",
"cartesian",
"to",
"spherical",
"spins",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L638-L654 |
228,168 | gwastro/pycbc | pycbc/transforms.py | DistanceToRedshift.transform | def transform(self, maps):
""" This function transforms from distance to redshift.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.DistanceToRedshift()
>>> t.transform({'distance': numpy.array([1000])})
{'distance': array([1000]), 'redshift': 0.19650987609144363}
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values.
"""
out = {parameters.redshift : cosmology.redshift(
maps[parameters.distance])}
return self.format_output(maps, out) | python | def transform(self, maps):
out = {parameters.redshift : cosmology.redshift(
maps[parameters.distance])}
return self.format_output(maps, out) | [
"def",
"transform",
"(",
"self",
",",
"maps",
")",
":",
"out",
"=",
"{",
"parameters",
".",
"redshift",
":",
"cosmology",
".",
"redshift",
"(",
"maps",
"[",
"parameters",
".",
"distance",
"]",
")",
"}",
"return",
"self",
".",
"format_output",
"(",
"map... | This function transforms from distance to redshift.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.DistanceToRedshift()
>>> t.transform({'distance': numpy.array([1000])})
{'distance': array([1000]), 'redshift': 0.19650987609144363}
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values. | [
"This",
"function",
"transforms",
"from",
"distance",
"to",
"redshift",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L676-L701 |
228,169 | gwastro/pycbc | pycbc/transforms.py | AlignedMassSpinToCartesianSpin.transform | def transform(self, maps):
""" This function transforms from aligned mass-weighted spins to
cartesian spins aligned along the z-axis.
Parameters
----------
maps : a mapping object
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values.
"""
mass1 = maps[parameters.mass1]
mass2 = maps[parameters.mass2]
out = {}
out[parameters.spin1z] = \
conversions.spin1z_from_mass1_mass2_chi_eff_chi_a(
mass1, mass2,
maps[parameters.chi_eff], maps["chi_a"])
out[parameters.spin2z] = \
conversions.spin2z_from_mass1_mass2_chi_eff_chi_a(
mass1, mass2,
maps[parameters.chi_eff], maps["chi_a"])
return self.format_output(maps, out) | python | def transform(self, maps):
mass1 = maps[parameters.mass1]
mass2 = maps[parameters.mass2]
out = {}
out[parameters.spin1z] = \
conversions.spin1z_from_mass1_mass2_chi_eff_chi_a(
mass1, mass2,
maps[parameters.chi_eff], maps["chi_a"])
out[parameters.spin2z] = \
conversions.spin2z_from_mass1_mass2_chi_eff_chi_a(
mass1, mass2,
maps[parameters.chi_eff], maps["chi_a"])
return self.format_output(maps, out) | [
"def",
"transform",
"(",
"self",
",",
"maps",
")",
":",
"mass1",
"=",
"maps",
"[",
"parameters",
".",
"mass1",
"]",
"mass2",
"=",
"maps",
"[",
"parameters",
".",
"mass2",
"]",
"out",
"=",
"{",
"}",
"out",
"[",
"parameters",
".",
"spin1z",
"]",
"=",... | This function transforms from aligned mass-weighted spins to
cartesian spins aligned along the z-axis.
Parameters
----------
maps : a mapping object
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values. | [
"This",
"function",
"transforms",
"from",
"aligned",
"mass",
"-",
"weighted",
"spins",
"to",
"cartesian",
"spins",
"aligned",
"along",
"the",
"z",
"-",
"axis",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L712-L737 |
228,170 | gwastro/pycbc | pycbc/transforms.py | AlignedMassSpinToCartesianSpin.inverse_transform | def inverse_transform(self, maps):
""" This function transforms from component masses and cartesian spins
to mass-weighted spin parameters aligned with the angular momentum.
Parameters
----------
maps : a mapping object
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values.
"""
mass1 = maps[parameters.mass1]
spin1z = maps[parameters.spin1z]
mass2 = maps[parameters.mass2]
spin2z = maps[parameters.spin2z]
out = {
parameters.chi_eff : conversions.chi_eff(mass1, mass2,
spin1z, spin2z),
"chi_a" : conversions.chi_a(mass1, mass2, spin1z, spin2z),
}
return self.format_output(maps, out) | python | def inverse_transform(self, maps):
mass1 = maps[parameters.mass1]
spin1z = maps[parameters.spin1z]
mass2 = maps[parameters.mass2]
spin2z = maps[parameters.spin2z]
out = {
parameters.chi_eff : conversions.chi_eff(mass1, mass2,
spin1z, spin2z),
"chi_a" : conversions.chi_a(mass1, mass2, spin1z, spin2z),
}
return self.format_output(maps, out) | [
"def",
"inverse_transform",
"(",
"self",
",",
"maps",
")",
":",
"mass1",
"=",
"maps",
"[",
"parameters",
".",
"mass1",
"]",
"spin1z",
"=",
"maps",
"[",
"parameters",
".",
"spin1z",
"]",
"mass2",
"=",
"maps",
"[",
"parameters",
".",
"mass2",
"]",
"spin2... | This function transforms from component masses and cartesian spins
to mass-weighted spin parameters aligned with the angular momentum.
Parameters
----------
maps : a mapping object
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values. | [
"This",
"function",
"transforms",
"from",
"component",
"masses",
"and",
"cartesian",
"spins",
"to",
"mass",
"-",
"weighted",
"spin",
"parameters",
"aligned",
"with",
"the",
"angular",
"momentum",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L739-L762 |
228,171 | gwastro/pycbc | pycbc/transforms.py | PrecessionMassSpinToCartesianSpin.transform | def transform(self, maps):
""" This function transforms from mass-weighted spins to caretsian spins
in the x-y plane.
Parameters
----------
maps : a mapping object
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values.
"""
# find primary and secondary masses
# since functions in conversions.py map to primary/secondary masses
m_p = conversions.primary_mass(maps["mass1"], maps["mass2"])
m_s = conversions.secondary_mass(maps["mass1"], maps["mass2"])
# find primary and secondary xi
# can re-purpose spin functions for just a generic variable
xi_p = conversions.primary_spin(maps["mass1"], maps["mass2"],
maps["xi1"], maps["xi2"])
xi_s = conversions.secondary_spin(maps["mass1"], maps["mass2"],
maps["xi1"], maps["xi2"])
# convert using convention of conversions.py that is mass1 > mass2
spinx_p = conversions.spin1x_from_xi1_phi_a_phi_s(
xi_p, maps["phi_a"], maps["phi_s"])
spiny_p = conversions.spin1y_from_xi1_phi_a_phi_s(
xi_p, maps["phi_a"], maps["phi_s"])
spinx_s = conversions.spin2x_from_mass1_mass2_xi2_phi_a_phi_s(
m_p, m_s, xi_s, maps["phi_a"], maps["phi_s"])
spiny_s = conversions.spin2y_from_mass1_mass2_xi2_phi_a_phi_s(
m_p, m_s, xi_s, maps["phi_a"], maps["phi_s"])
# map parameters from primary/secondary to indices
out = {}
if isinstance(m_p, numpy.ndarray):
mass1, mass2 = map(numpy.array, [maps["mass1"], maps["mass2"]])
mask_mass1_gte_mass2 = mass1 >= mass2
mask_mass1_lt_mass2 = mass1 < mass2
out[parameters.spin1x] = numpy.concatenate((
spinx_p[mask_mass1_gte_mass2],
spinx_s[mask_mass1_lt_mass2]))
out[parameters.spin1y] = numpy.concatenate((
spiny_p[mask_mass1_gte_mass2],
spiny_s[mask_mass1_lt_mass2]))
out[parameters.spin2x] = numpy.concatenate((
spinx_p[mask_mass1_lt_mass2],
spinx_s[mask_mass1_gte_mass2]))
out[parameters.spin2y] = numpy.concatenate((
spinx_p[mask_mass1_lt_mass2],
spinx_s[mask_mass1_gte_mass2]))
elif maps["mass1"] > maps["mass2"]:
out[parameters.spin1x] = spinx_p
out[parameters.spin1y] = spiny_p
out[parameters.spin2x] = spinx_s
out[parameters.spin2y] = spiny_s
else:
out[parameters.spin1x] = spinx_s
out[parameters.spin1y] = spiny_s
out[parameters.spin2x] = spinx_p
out[parameters.spin2y] = spiny_p
return self.format_output(maps, out) | python | def transform(self, maps):
# find primary and secondary masses
# since functions in conversions.py map to primary/secondary masses
m_p = conversions.primary_mass(maps["mass1"], maps["mass2"])
m_s = conversions.secondary_mass(maps["mass1"], maps["mass2"])
# find primary and secondary xi
# can re-purpose spin functions for just a generic variable
xi_p = conversions.primary_spin(maps["mass1"], maps["mass2"],
maps["xi1"], maps["xi2"])
xi_s = conversions.secondary_spin(maps["mass1"], maps["mass2"],
maps["xi1"], maps["xi2"])
# convert using convention of conversions.py that is mass1 > mass2
spinx_p = conversions.spin1x_from_xi1_phi_a_phi_s(
xi_p, maps["phi_a"], maps["phi_s"])
spiny_p = conversions.spin1y_from_xi1_phi_a_phi_s(
xi_p, maps["phi_a"], maps["phi_s"])
spinx_s = conversions.spin2x_from_mass1_mass2_xi2_phi_a_phi_s(
m_p, m_s, xi_s, maps["phi_a"], maps["phi_s"])
spiny_s = conversions.spin2y_from_mass1_mass2_xi2_phi_a_phi_s(
m_p, m_s, xi_s, maps["phi_a"], maps["phi_s"])
# map parameters from primary/secondary to indices
out = {}
if isinstance(m_p, numpy.ndarray):
mass1, mass2 = map(numpy.array, [maps["mass1"], maps["mass2"]])
mask_mass1_gte_mass2 = mass1 >= mass2
mask_mass1_lt_mass2 = mass1 < mass2
out[parameters.spin1x] = numpy.concatenate((
spinx_p[mask_mass1_gte_mass2],
spinx_s[mask_mass1_lt_mass2]))
out[parameters.spin1y] = numpy.concatenate((
spiny_p[mask_mass1_gte_mass2],
spiny_s[mask_mass1_lt_mass2]))
out[parameters.spin2x] = numpy.concatenate((
spinx_p[mask_mass1_lt_mass2],
spinx_s[mask_mass1_gte_mass2]))
out[parameters.spin2y] = numpy.concatenate((
spinx_p[mask_mass1_lt_mass2],
spinx_s[mask_mass1_gte_mass2]))
elif maps["mass1"] > maps["mass2"]:
out[parameters.spin1x] = spinx_p
out[parameters.spin1y] = spiny_p
out[parameters.spin2x] = spinx_s
out[parameters.spin2y] = spiny_s
else:
out[parameters.spin1x] = spinx_s
out[parameters.spin1y] = spiny_s
out[parameters.spin2x] = spinx_p
out[parameters.spin2y] = spiny_p
return self.format_output(maps, out) | [
"def",
"transform",
"(",
"self",
",",
"maps",
")",
":",
"# find primary and secondary masses",
"# since functions in conversions.py map to primary/secondary masses",
"m_p",
"=",
"conversions",
".",
"primary_mass",
"(",
"maps",
"[",
"\"mass1\"",
"]",
",",
"maps",
"[",
"\... | This function transforms from mass-weighted spins to caretsian spins
in the x-y plane.
Parameters
----------
maps : a mapping object
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values. | [
"This",
"function",
"transforms",
"from",
"mass",
"-",
"weighted",
"spins",
"to",
"caretsian",
"spins",
"in",
"the",
"x",
"-",
"y",
"plane",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L775-L841 |
228,172 | gwastro/pycbc | pycbc/transforms.py | PrecessionMassSpinToCartesianSpin.inverse_transform | def inverse_transform(self, maps):
""" This function transforms from component masses and cartesian spins to
mass-weighted spin parameters perpendicular with the angular momentum.
Parameters
----------
maps : a mapping object
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values.
"""
# convert
out = {}
xi1 = conversions.primary_xi(
maps[parameters.mass1], maps[parameters.mass2],
maps[parameters.spin1x], maps[parameters.spin1y],
maps[parameters.spin2x], maps[parameters.spin2y])
xi2 = conversions.secondary_xi(
maps[parameters.mass1], maps[parameters.mass2],
maps[parameters.spin1x], maps[parameters.spin1y],
maps[parameters.spin2x], maps[parameters.spin2y])
out["phi_a"] = conversions.phi_a(
maps[parameters.mass1], maps[parameters.mass2],
maps[parameters.spin1x], maps[parameters.spin1y],
maps[parameters.spin2x], maps[parameters.spin2y])
out["phi_s"] = conversions.phi_s(
maps[parameters.spin1x], maps[parameters.spin1y],
maps[parameters.spin2x], maps[parameters.spin2y])
# map parameters from primary/secondary to indices
if isinstance(xi1, numpy.ndarray):
mass1, mass2 = map(numpy.array, [maps[parameters.mass1],
maps[parameters.mass2]])
mask_mass1_gte_mass2 = mass1 >= mass2
mask_mass1_lt_mass2 = mass1 < mass2
out["xi1"] = numpy.concatenate((
xi1[mask_mass1_gte_mass2],
xi2[mask_mass1_lt_mass2]))
out["xi2"] = numpy.concatenate((
xi1[mask_mass1_gte_mass2],
xi2[mask_mass1_lt_mass2]))
elif maps["mass1"] > maps["mass2"]:
out["xi1"] = xi1
out["xi2"] = xi2
else:
out["xi1"] = xi2
out["xi2"] = xi1
return self.format_output(maps, out) | python | def inverse_transform(self, maps):
# convert
out = {}
xi1 = conversions.primary_xi(
maps[parameters.mass1], maps[parameters.mass2],
maps[parameters.spin1x], maps[parameters.spin1y],
maps[parameters.spin2x], maps[parameters.spin2y])
xi2 = conversions.secondary_xi(
maps[parameters.mass1], maps[parameters.mass2],
maps[parameters.spin1x], maps[parameters.spin1y],
maps[parameters.spin2x], maps[parameters.spin2y])
out["phi_a"] = conversions.phi_a(
maps[parameters.mass1], maps[parameters.mass2],
maps[parameters.spin1x], maps[parameters.spin1y],
maps[parameters.spin2x], maps[parameters.spin2y])
out["phi_s"] = conversions.phi_s(
maps[parameters.spin1x], maps[parameters.spin1y],
maps[parameters.spin2x], maps[parameters.spin2y])
# map parameters from primary/secondary to indices
if isinstance(xi1, numpy.ndarray):
mass1, mass2 = map(numpy.array, [maps[parameters.mass1],
maps[parameters.mass2]])
mask_mass1_gte_mass2 = mass1 >= mass2
mask_mass1_lt_mass2 = mass1 < mass2
out["xi1"] = numpy.concatenate((
xi1[mask_mass1_gte_mass2],
xi2[mask_mass1_lt_mass2]))
out["xi2"] = numpy.concatenate((
xi1[mask_mass1_gte_mass2],
xi2[mask_mass1_lt_mass2]))
elif maps["mass1"] > maps["mass2"]:
out["xi1"] = xi1
out["xi2"] = xi2
else:
out["xi1"] = xi2
out["xi2"] = xi1
return self.format_output(maps, out) | [
"def",
"inverse_transform",
"(",
"self",
",",
"maps",
")",
":",
"# convert",
"out",
"=",
"{",
"}",
"xi1",
"=",
"conversions",
".",
"primary_xi",
"(",
"maps",
"[",
"parameters",
".",
"mass1",
"]",
",",
"maps",
"[",
"parameters",
".",
"mass2",
"]",
",",
... | This function transforms from component masses and cartesian spins to
mass-weighted spin parameters perpendicular with the angular momentum.
Parameters
----------
maps : a mapping object
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values. | [
"This",
"function",
"transforms",
"from",
"component",
"masses",
"and",
"cartesian",
"spins",
"to",
"mass",
"-",
"weighted",
"spin",
"parameters",
"perpendicular",
"with",
"the",
"angular",
"momentum",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L844-L896 |
228,173 | gwastro/pycbc | pycbc/transforms.py | CartesianSpinToChiP.transform | def transform(self, maps):
""" This function transforms from component masses and caretsian spins
to chi_p.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values.
"""
out = {}
out["chi_p"] = conversions.chi_p(
maps[parameters.mass1], maps[parameters.mass2],
maps[parameters.spin1x], maps[parameters.spin1y],
maps[parameters.spin2x], maps[parameters.spin2y])
return self.format_output(maps, out) | python | def transform(self, maps):
out = {}
out["chi_p"] = conversions.chi_p(
maps[parameters.mass1], maps[parameters.mass2],
maps[parameters.spin1x], maps[parameters.spin1y],
maps[parameters.spin2x], maps[parameters.spin2y])
return self.format_output(maps, out) | [
"def",
"transform",
"(",
"self",
",",
"maps",
")",
":",
"out",
"=",
"{",
"}",
"out",
"[",
"\"chi_p\"",
"]",
"=",
"conversions",
".",
"chi_p",
"(",
"maps",
"[",
"parameters",
".",
"mass1",
"]",
",",
"maps",
"[",
"parameters",
".",
"mass2",
"]",
",",... | This function transforms from component masses and caretsian spins
to chi_p.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
Returns
-------
out : dict
A dict with key as parameter name and value as numpy.array or float
of transformed values. | [
"This",
"function",
"transforms",
"from",
"component",
"masses",
"and",
"caretsian",
"spins",
"to",
"chi_p",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L908-L931 |
228,174 | gwastro/pycbc | pycbc/transforms.py | Logistic.from_config | def from_config(cls, cp, section, outputs, skip_opts=None,
additional_opts=None):
"""Initializes a Logistic transform from the given section.
The section must specify an input and output variable name. The
codomain of the output may be specified using `min-{output}`,
`max-{output}`. Example:
.. code-block:: ini
[{section}-q]
name = logistic
inputvar = logitq
outputvar = q
min-q = 1
max-q = 8
Parameters
----------
cp : pycbc.workflow.WorkflowConfigParser
A parsed configuration file that contains the transform options.
section : str
Name of the section in the configuration file.
outputs : str
The names of the parameters that are output by this transformation,
separated by `VARARGS_DELIM`. These must appear in the "tag" part
of the section header.
skip_opts : list, optional
Do not read options in the given list.
additional_opts : dict, optional
Any additional arguments to pass to the class. If an option is
provided that also exists in the config file, the value provided
will be used instead of being read from the file.
Returns
-------
cls
An instance of the class.
"""
# pull out the minimum, maximum values of the output variable
outputvar = cp.get_opt_tag(section, 'output', outputs)
if skip_opts is None:
skip_opts = []
if additional_opts is None:
additional_opts = {}
else:
additional_opts = additional_opts.copy()
s = '-'.join([section, outputs])
opt = 'min-{}'.format(outputvar)
if cp.has_option(s, opt):
a = cp.get_opt_tag(section, opt, outputs)
skip_opts.append(opt)
else:
a = None
opt = 'max-{}'.format(outputvar)
if cp.has_option(s, opt):
b = cp.get_opt_tag(section, opt, outputs)
skip_opts.append(opt)
else:
b = None
if a is None and b is not None or b is None and a is not None:
raise ValueError("if providing a min(max)-{}, must also provide "
"a max(min)-{}".format(outputvar, outputvar))
elif a is not None:
additional_opts.update({'codomain': (float(a), float(b))})
return super(Logistic, cls).from_config(cp, section, outputs,
skip_opts, additional_opts) | python | def from_config(cls, cp, section, outputs, skip_opts=None,
additional_opts=None):
# pull out the minimum, maximum values of the output variable
outputvar = cp.get_opt_tag(section, 'output', outputs)
if skip_opts is None:
skip_opts = []
if additional_opts is None:
additional_opts = {}
else:
additional_opts = additional_opts.copy()
s = '-'.join([section, outputs])
opt = 'min-{}'.format(outputvar)
if cp.has_option(s, opt):
a = cp.get_opt_tag(section, opt, outputs)
skip_opts.append(opt)
else:
a = None
opt = 'max-{}'.format(outputvar)
if cp.has_option(s, opt):
b = cp.get_opt_tag(section, opt, outputs)
skip_opts.append(opt)
else:
b = None
if a is None and b is not None or b is None and a is not None:
raise ValueError("if providing a min(max)-{}, must also provide "
"a max(min)-{}".format(outputvar, outputvar))
elif a is not None:
additional_opts.update({'codomain': (float(a), float(b))})
return super(Logistic, cls).from_config(cp, section, outputs,
skip_opts, additional_opts) | [
"def",
"from_config",
"(",
"cls",
",",
"cp",
",",
"section",
",",
"outputs",
",",
"skip_opts",
"=",
"None",
",",
"additional_opts",
"=",
"None",
")",
":",
"# pull out the minimum, maximum values of the output variable",
"outputvar",
"=",
"cp",
".",
"get_opt_tag",
... | Initializes a Logistic transform from the given section.
The section must specify an input and output variable name. The
codomain of the output may be specified using `min-{output}`,
`max-{output}`. Example:
.. code-block:: ini
[{section}-q]
name = logistic
inputvar = logitq
outputvar = q
min-q = 1
max-q = 8
Parameters
----------
cp : pycbc.workflow.WorkflowConfigParser
A parsed configuration file that contains the transform options.
section : str
Name of the section in the configuration file.
outputs : str
The names of the parameters that are output by this transformation,
separated by `VARARGS_DELIM`. These must appear in the "tag" part
of the section header.
skip_opts : list, optional
Do not read options in the given list.
additional_opts : dict, optional
Any additional arguments to pass to the class. If an option is
provided that also exists in the config file, the value provided
will be used instead of being read from the file.
Returns
-------
cls
An instance of the class. | [
"Initializes",
"a",
"Logistic",
"transform",
"from",
"the",
"given",
"section",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L1390-L1456 |
228,175 | gwastro/pycbc | pycbc/tmpltbank/option_utils.py | get_options_from_group | def get_options_from_group(option_group):
"""
Take an option group and return all the options that are defined in that
group.
"""
option_list = option_group._group_actions
command_lines = []
for option in option_list:
option_strings = option.option_strings
for string in option_strings:
if string.startswith('--'):
command_lines.append(string)
return command_lines | python | def get_options_from_group(option_group):
option_list = option_group._group_actions
command_lines = []
for option in option_list:
option_strings = option.option_strings
for string in option_strings:
if string.startswith('--'):
command_lines.append(string)
return command_lines | [
"def",
"get_options_from_group",
"(",
"option_group",
")",
":",
"option_list",
"=",
"option_group",
".",
"_group_actions",
"command_lines",
"=",
"[",
"]",
"for",
"option",
"in",
"option_list",
":",
"option_strings",
"=",
"option",
".",
"option_strings",
"for",
"st... | Take an option group and return all the options that are defined in that
group. | [
"Take",
"an",
"option",
"group",
"and",
"return",
"all",
"the",
"options",
"that",
"are",
"defined",
"in",
"that",
"group",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/option_utils.py#L96-L108 |
228,176 | gwastro/pycbc | pycbc/tmpltbank/option_utils.py | insert_base_bank_options | def insert_base_bank_options(parser):
"""
Adds essential common options for template bank generation to an
ArgumentParser instance.
"""
def match_type(s):
err_msg = "must be a number between 0 and 1 excluded, not %r" % s
try:
value = float(s)
except ValueError:
raise argparse.ArgumentTypeError(err_msg)
if value <= 0 or value >= 1:
raise argparse.ArgumentTypeError(err_msg)
return value
parser.add_argument(
'-m', '--min-match', type=match_type, required=True,
help="Generate bank with specified minimum match. Required.")
parser.add_argument(
'-O', '--output-file', required=True,
help="Output file name. Required.")
parser.add_argument('--f-low-column', type=str, metavar='NAME',
help='If given, store the lower frequency cutoff into '
'column NAME of the single-inspiral table.') | python | def insert_base_bank_options(parser):
def match_type(s):
err_msg = "must be a number between 0 and 1 excluded, not %r" % s
try:
value = float(s)
except ValueError:
raise argparse.ArgumentTypeError(err_msg)
if value <= 0 or value >= 1:
raise argparse.ArgumentTypeError(err_msg)
return value
parser.add_argument(
'-m', '--min-match', type=match_type, required=True,
help="Generate bank with specified minimum match. Required.")
parser.add_argument(
'-O', '--output-file', required=True,
help="Output file name. Required.")
parser.add_argument('--f-low-column', type=str, metavar='NAME',
help='If given, store the lower frequency cutoff into '
'column NAME of the single-inspiral table.') | [
"def",
"insert_base_bank_options",
"(",
"parser",
")",
":",
"def",
"match_type",
"(",
"s",
")",
":",
"err_msg",
"=",
"\"must be a number between 0 and 1 excluded, not %r\"",
"%",
"s",
"try",
":",
"value",
"=",
"float",
"(",
"s",
")",
"except",
"ValueError",
":",... | Adds essential common options for template bank generation to an
ArgumentParser instance. | [
"Adds",
"essential",
"common",
"options",
"for",
"template",
"bank",
"generation",
"to",
"an",
"ArgumentParser",
"instance",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/option_utils.py#L110-L134 |
228,177 | gwastro/pycbc | pycbc/tmpltbank/option_utils.py | insert_metric_calculation_options | def insert_metric_calculation_options(parser):
"""
Adds the options used to obtain a metric in the bank generation codes to an
argparser as an OptionGroup. This should be used if you want to use these
options in your code.
"""
metricOpts = parser.add_argument_group(
"Options related to calculating the parameter space metric")
metricOpts.add_argument("--pn-order", action="store", type=str,
required=True,
help="Determines the PN order to use. For a bank of "
"non-spinning templates, spin-related terms in the "
"metric will be zero. REQUIRED. "
"Choices: %s" %(pycbcValidOrdersHelpDescriptions))
metricOpts.add_argument("--f0", action="store", type=positive_float,
default=70.,\
help="f0 is used as a dynamic scaling factor when "
"calculating integrals used in metric construction. "
"I.e. instead of integrating F(f) we integrate F(f/f0) "
"then rescale by powers of f0. The default value 70Hz "
"should be fine for most applications. OPTIONAL. "
"UNITS=Hz. **WARNING: If the ethinca metric is to be "
"calculated, f0 must be set equal to f-low**")
metricOpts.add_argument("--f-low", action="store", type=positive_float,
required=True,
help="Lower frequency cutoff used in computing the "
"parameter space metric. REQUIRED. UNITS=Hz")
metricOpts.add_argument("--f-upper", action="store", type=positive_float,
required=True,
help="Upper frequency cutoff used in computing the "
"parameter space metric. REQUIRED. UNITS=Hz")
metricOpts.add_argument("--delta-f", action="store", type=positive_float,
required=True,
help="Frequency spacing used in computing the parameter "
"space metric: integrals of the form \int F(f) df "
"are approximated as \sum F(f) delta_f. REQUIRED. "
"UNITS=Hz")
metricOpts.add_argument("--write-metric", action="store_true",
default=False, help="If given write the metric components "
"to disk as they are calculated.")
return metricOpts | python | def insert_metric_calculation_options(parser):
metricOpts = parser.add_argument_group(
"Options related to calculating the parameter space metric")
metricOpts.add_argument("--pn-order", action="store", type=str,
required=True,
help="Determines the PN order to use. For a bank of "
"non-spinning templates, spin-related terms in the "
"metric will be zero. REQUIRED. "
"Choices: %s" %(pycbcValidOrdersHelpDescriptions))
metricOpts.add_argument("--f0", action="store", type=positive_float,
default=70.,\
help="f0 is used as a dynamic scaling factor when "
"calculating integrals used in metric construction. "
"I.e. instead of integrating F(f) we integrate F(f/f0) "
"then rescale by powers of f0. The default value 70Hz "
"should be fine for most applications. OPTIONAL. "
"UNITS=Hz. **WARNING: If the ethinca metric is to be "
"calculated, f0 must be set equal to f-low**")
metricOpts.add_argument("--f-low", action="store", type=positive_float,
required=True,
help="Lower frequency cutoff used in computing the "
"parameter space metric. REQUIRED. UNITS=Hz")
metricOpts.add_argument("--f-upper", action="store", type=positive_float,
required=True,
help="Upper frequency cutoff used in computing the "
"parameter space metric. REQUIRED. UNITS=Hz")
metricOpts.add_argument("--delta-f", action="store", type=positive_float,
required=True,
help="Frequency spacing used in computing the parameter "
"space metric: integrals of the form \int F(f) df "
"are approximated as \sum F(f) delta_f. REQUIRED. "
"UNITS=Hz")
metricOpts.add_argument("--write-metric", action="store_true",
default=False, help="If given write the metric components "
"to disk as they are calculated.")
return metricOpts | [
"def",
"insert_metric_calculation_options",
"(",
"parser",
")",
":",
"metricOpts",
"=",
"parser",
".",
"add_argument_group",
"(",
"\"Options related to calculating the parameter space metric\"",
")",
"metricOpts",
".",
"add_argument",
"(",
"\"--pn-order\"",
",",
"action",
"... | Adds the options used to obtain a metric in the bank generation codes to an
argparser as an OptionGroup. This should be used if you want to use these
options in your code. | [
"Adds",
"the",
"options",
"used",
"to",
"obtain",
"a",
"metric",
"in",
"the",
"bank",
"generation",
"codes",
"to",
"an",
"argparser",
"as",
"an",
"OptionGroup",
".",
"This",
"should",
"be",
"used",
"if",
"you",
"want",
"to",
"use",
"these",
"options",
"i... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/option_utils.py#L136-L176 |
228,178 | gwastro/pycbc | pycbc/tmpltbank/option_utils.py | verify_ethinca_metric_options | def verify_ethinca_metric_options(opts, parser):
"""
Checks that the necessary options are given for the ethinca metric
calculation.
Parameters
----------
opts : argparse.Values instance
Result of parsing the input options with OptionParser
parser : object
The OptionParser instance.
"""
if opts.filter_cutoff is not None and not (opts.filter_cutoff in
pnutils.named_frequency_cutoffs.keys()):
parser.error("Need a valid cutoff formula to calculate ethinca or "
"assign filter f_final values! Possible values are "
+str(pnutils.named_frequency_cutoffs.keys()))
if (opts.calculate_ethinca_metric or opts.calculate_time_metric_components)\
and not opts.ethinca_frequency_step:
parser.error("Need to specify a cutoff frequency step to calculate "
"ethinca!")
if not (opts.calculate_ethinca_metric or\
opts.calculate_time_metric_components) and opts.ethinca_pn_order:
parser.error("Can't specify an ethinca PN order if not "
"calculating ethinca metric!") | python | def verify_ethinca_metric_options(opts, parser):
if opts.filter_cutoff is not None and not (opts.filter_cutoff in
pnutils.named_frequency_cutoffs.keys()):
parser.error("Need a valid cutoff formula to calculate ethinca or "
"assign filter f_final values! Possible values are "
+str(pnutils.named_frequency_cutoffs.keys()))
if (opts.calculate_ethinca_metric or opts.calculate_time_metric_components)\
and not opts.ethinca_frequency_step:
parser.error("Need to specify a cutoff frequency step to calculate "
"ethinca!")
if not (opts.calculate_ethinca_metric or\
opts.calculate_time_metric_components) and opts.ethinca_pn_order:
parser.error("Can't specify an ethinca PN order if not "
"calculating ethinca metric!") | [
"def",
"verify_ethinca_metric_options",
"(",
"opts",
",",
"parser",
")",
":",
"if",
"opts",
".",
"filter_cutoff",
"is",
"not",
"None",
"and",
"not",
"(",
"opts",
".",
"filter_cutoff",
"in",
"pnutils",
".",
"named_frequency_cutoffs",
".",
"keys",
"(",
")",
")... | Checks that the necessary options are given for the ethinca metric
calculation.
Parameters
----------
opts : argparse.Values instance
Result of parsing the input options with OptionParser
parser : object
The OptionParser instance. | [
"Checks",
"that",
"the",
"necessary",
"options",
"are",
"given",
"for",
"the",
"ethinca",
"metric",
"calculation",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/option_utils.py#L1158-L1182 |
228,179 | gwastro/pycbc | pycbc/tmpltbank/option_utils.py | check_ethinca_against_bank_params | def check_ethinca_against_bank_params(ethincaParams, metricParams):
"""
Cross-check the ethinca and bank layout metric calculation parameters
and set the ethinca metric PN order equal to the bank PN order if not
previously set.
Parameters
----------
ethincaParams: instance of ethincaParameters
metricParams: instance of metricParameters
"""
if ethincaParams.doEthinca:
if metricParams.f0 != metricParams.fLow:
raise ValueError("If calculating ethinca metric, f0 and f-low "
"must be equal!")
if ethincaParams.fLow is not None and (
ethincaParams.fLow != metricParams.fLow):
raise ValueError("Ethinca metric calculation does not currently "
"support a f-low value different from the bank "
"metric!")
if ethincaParams.pnOrder is None:
ethincaParams.pnOrder = metricParams.pnOrder
else: pass | python | def check_ethinca_against_bank_params(ethincaParams, metricParams):
if ethincaParams.doEthinca:
if metricParams.f0 != metricParams.fLow:
raise ValueError("If calculating ethinca metric, f0 and f-low "
"must be equal!")
if ethincaParams.fLow is not None and (
ethincaParams.fLow != metricParams.fLow):
raise ValueError("Ethinca metric calculation does not currently "
"support a f-low value different from the bank "
"metric!")
if ethincaParams.pnOrder is None:
ethincaParams.pnOrder = metricParams.pnOrder
else: pass | [
"def",
"check_ethinca_against_bank_params",
"(",
"ethincaParams",
",",
"metricParams",
")",
":",
"if",
"ethincaParams",
".",
"doEthinca",
":",
"if",
"metricParams",
".",
"f0",
"!=",
"metricParams",
".",
"fLow",
":",
"raise",
"ValueError",
"(",
"\"If calculating ethi... | Cross-check the ethinca and bank layout metric calculation parameters
and set the ethinca metric PN order equal to the bank PN order if not
previously set.
Parameters
----------
ethincaParams: instance of ethincaParameters
metricParams: instance of metricParameters | [
"Cross",
"-",
"check",
"the",
"ethinca",
"and",
"bank",
"layout",
"metric",
"calculation",
"parameters",
"and",
"set",
"the",
"ethinca",
"metric",
"PN",
"order",
"equal",
"to",
"the",
"bank",
"PN",
"order",
"if",
"not",
"previously",
"set",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/option_utils.py#L1184-L1206 |
228,180 | gwastro/pycbc | pycbc/tmpltbank/option_utils.py | metricParameters.from_argparse | def from_argparse(cls, opts):
"""
Initialize an instance of the metricParameters class from an
argparse.OptionParser instance. This assumes that
insert_metric_calculation_options
and
verify_metric_calculation_options
have already been called before initializing the class.
"""
return cls(opts.pn_order, opts.f_low, opts.f_upper, opts.delta_f,\
f0=opts.f0, write_metric=opts.write_metric) | python | def from_argparse(cls, opts):
return cls(opts.pn_order, opts.f_low, opts.f_upper, opts.delta_f,\
f0=opts.f0, write_metric=opts.write_metric) | [
"def",
"from_argparse",
"(",
"cls",
",",
"opts",
")",
":",
"return",
"cls",
"(",
"opts",
".",
"pn_order",
",",
"opts",
".",
"f_low",
",",
"opts",
".",
"f_upper",
",",
"opts",
".",
"delta_f",
",",
"f0",
"=",
"opts",
".",
"f0",
",",
"write_metric",
"... | Initialize an instance of the metricParameters class from an
argparse.OptionParser instance. This assumes that
insert_metric_calculation_options
and
verify_metric_calculation_options
have already been called before initializing the class. | [
"Initialize",
"an",
"instance",
"of",
"the",
"metricParameters",
"class",
"from",
"an",
"argparse",
".",
"OptionParser",
"instance",
".",
"This",
"assumes",
"that",
"insert_metric_calculation_options",
"and",
"verify_metric_calculation_options",
"have",
"already",
"been",... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/option_utils.py#L223-L233 |
228,181 | gwastro/pycbc | pycbc/tmpltbank/option_utils.py | metricParameters.psd | def psd(self):
"""
A pyCBC FrequencySeries holding the appropriate PSD.
Return the PSD used in the metric calculation.
"""
if not self._psd:
errMsg = "The PSD has not been set in the metricParameters "
errMsg += "instance."
raise ValueError(errMsg)
return self._psd | python | def psd(self):
if not self._psd:
errMsg = "The PSD has not been set in the metricParameters "
errMsg += "instance."
raise ValueError(errMsg)
return self._psd | [
"def",
"psd",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_psd",
":",
"errMsg",
"=",
"\"The PSD has not been set in the metricParameters \"",
"errMsg",
"+=",
"\"instance.\"",
"raise",
"ValueError",
"(",
"errMsg",
")",
"return",
"self",
".",
"_psd"
] | A pyCBC FrequencySeries holding the appropriate PSD.
Return the PSD used in the metric calculation. | [
"A",
"pyCBC",
"FrequencySeries",
"holding",
"the",
"appropriate",
"PSD",
".",
"Return",
"the",
"PSD",
"used",
"in",
"the",
"metric",
"calculation",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/option_utils.py#L236-L245 |
228,182 | gwastro/pycbc | pycbc/tmpltbank/option_utils.py | metricParameters.evals | def evals(self):
"""
The eigenvalues of the parameter space.
This is a Dictionary of numpy.array
Each entry in the dictionary corresponds to the different frequency
ranges described in vary_fmax. If vary_fmax = False, the only entry
will be f_upper, this corresponds to integrals in [f_low,f_upper). This
entry is always present. Each other entry will use floats as keys to
the dictionary. These floats give the upper frequency cutoff when it is
varying.
Each numpy.array contains the eigenvalues which, with the eigenvectors
in evecs, are needed to rotate the
coordinate system to one in which the metric is the identity matrix.
"""
if self._evals is None:
errMsg = "The metric eigenvalues have not been set in the "
errMsg += "metricParameters instance."
raise ValueError(errMsg)
return self._evals | python | def evals(self):
if self._evals is None:
errMsg = "The metric eigenvalues have not been set in the "
errMsg += "metricParameters instance."
raise ValueError(errMsg)
return self._evals | [
"def",
"evals",
"(",
"self",
")",
":",
"if",
"self",
".",
"_evals",
"is",
"None",
":",
"errMsg",
"=",
"\"The metric eigenvalues have not been set in the \"",
"errMsg",
"+=",
"\"metricParameters instance.\"",
"raise",
"ValueError",
"(",
"errMsg",
")",
"return",
"self... | The eigenvalues of the parameter space.
This is a Dictionary of numpy.array
Each entry in the dictionary corresponds to the different frequency
ranges described in vary_fmax. If vary_fmax = False, the only entry
will be f_upper, this corresponds to integrals in [f_low,f_upper). This
entry is always present. Each other entry will use floats as keys to
the dictionary. These floats give the upper frequency cutoff when it is
varying.
Each numpy.array contains the eigenvalues which, with the eigenvectors
in evecs, are needed to rotate the
coordinate system to one in which the metric is the identity matrix. | [
"The",
"eigenvalues",
"of",
"the",
"parameter",
"space",
".",
"This",
"is",
"a",
"Dictionary",
"of",
"numpy",
".",
"array",
"Each",
"entry",
"in",
"the",
"dictionary",
"corresponds",
"to",
"the",
"different",
"frequency",
"ranges",
"described",
"in",
"vary_fma... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/option_utils.py#L296-L314 |
228,183 | gwastro/pycbc | pycbc/tmpltbank/option_utils.py | metricParameters.evecs | def evecs(self):
"""
The eigenvectors of the parameter space.
This is a Dictionary of numpy.matrix
Each entry in the dictionary is as described under evals.
Each numpy.matrix contains the eigenvectors which, with the eigenvalues
in evals, are needed to rotate the
coordinate system to one in which the metric is the identity matrix.
"""
if self._evecs is None:
errMsg = "The metric eigenvectors have not been set in the "
errMsg += "metricParameters instance."
raise ValueError(errMsg)
return self._evecs | python | def evecs(self):
if self._evecs is None:
errMsg = "The metric eigenvectors have not been set in the "
errMsg += "metricParameters instance."
raise ValueError(errMsg)
return self._evecs | [
"def",
"evecs",
"(",
"self",
")",
":",
"if",
"self",
".",
"_evecs",
"is",
"None",
":",
"errMsg",
"=",
"\"The metric eigenvectors have not been set in the \"",
"errMsg",
"+=",
"\"metricParameters instance.\"",
"raise",
"ValueError",
"(",
"errMsg",
")",
"return",
"sel... | The eigenvectors of the parameter space.
This is a Dictionary of numpy.matrix
Each entry in the dictionary is as described under evals.
Each numpy.matrix contains the eigenvectors which, with the eigenvalues
in evals, are needed to rotate the
coordinate system to one in which the metric is the identity matrix. | [
"The",
"eigenvectors",
"of",
"the",
"parameter",
"space",
".",
"This",
"is",
"a",
"Dictionary",
"of",
"numpy",
".",
"matrix",
"Each",
"entry",
"in",
"the",
"dictionary",
"is",
"as",
"described",
"under",
"evals",
".",
"Each",
"numpy",
".",
"matrix",
"conta... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/option_utils.py#L325-L338 |
228,184 | gwastro/pycbc | pycbc/tmpltbank/option_utils.py | metricParameters.metric | def metric(self):
"""
The metric of the parameter space.
This is a Dictionary of numpy.matrix
Each entry in the dictionary is as described under evals.
Each numpy.matrix contains the metric of the parameter space in the
Lambda_i coordinate system.
"""
if self._metric is None:
errMsg = "The metric eigenvectors have not been set in the "
errMsg += "metricParameters instance."
raise ValueError(errMsg)
return self._metric | python | def metric(self):
if self._metric is None:
errMsg = "The metric eigenvectors have not been set in the "
errMsg += "metricParameters instance."
raise ValueError(errMsg)
return self._metric | [
"def",
"metric",
"(",
"self",
")",
":",
"if",
"self",
".",
"_metric",
"is",
"None",
":",
"errMsg",
"=",
"\"The metric eigenvectors have not been set in the \"",
"errMsg",
"+=",
"\"metricParameters instance.\"",
"raise",
"ValueError",
"(",
"errMsg",
")",
"return",
"s... | The metric of the parameter space.
This is a Dictionary of numpy.matrix
Each entry in the dictionary is as described under evals.
Each numpy.matrix contains the metric of the parameter space in the
Lambda_i coordinate system. | [
"The",
"metric",
"of",
"the",
"parameter",
"space",
".",
"This",
"is",
"a",
"Dictionary",
"of",
"numpy",
".",
"matrix",
"Each",
"entry",
"in",
"the",
"dictionary",
"is",
"as",
"described",
"under",
"evals",
".",
"Each",
"numpy",
".",
"matrix",
"contains",
... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/option_utils.py#L349-L361 |
228,185 | gwastro/pycbc | pycbc/tmpltbank/option_utils.py | metricParameters.evecsCV | def evecsCV(self):
"""
The eigenvectors of the principal directions of the mu space.
This is a Dictionary of numpy.matrix
Each entry in the dictionary is as described under evals.
Each numpy.matrix contains the eigenvectors which, with the eigenvalues
in evals, are needed to rotate the
coordinate system to one in which the metric is the identity matrix.
"""
if self._evecsCV is None:
errMsg = "The covariance eigenvectors have not been set in the "
errMsg += "metricParameters instance."
raise ValueError(errMsg)
return self._evecsCV | python | def evecsCV(self):
if self._evecsCV is None:
errMsg = "The covariance eigenvectors have not been set in the "
errMsg += "metricParameters instance."
raise ValueError(errMsg)
return self._evecsCV | [
"def",
"evecsCV",
"(",
"self",
")",
":",
"if",
"self",
".",
"_evecsCV",
"is",
"None",
":",
"errMsg",
"=",
"\"The covariance eigenvectors have not been set in the \"",
"errMsg",
"+=",
"\"metricParameters instance.\"",
"raise",
"ValueError",
"(",
"errMsg",
")",
"return"... | The eigenvectors of the principal directions of the mu space.
This is a Dictionary of numpy.matrix
Each entry in the dictionary is as described under evals.
Each numpy.matrix contains the eigenvectors which, with the eigenvalues
in evals, are needed to rotate the
coordinate system to one in which the metric is the identity matrix. | [
"The",
"eigenvectors",
"of",
"the",
"principal",
"directions",
"of",
"the",
"mu",
"space",
".",
"This",
"is",
"a",
"Dictionary",
"of",
"numpy",
".",
"matrix",
"Each",
"entry",
"in",
"the",
"dictionary",
"is",
"as",
"described",
"under",
"evals",
".",
"Each... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/option_utils.py#L396-L409 |
228,186 | gwastro/pycbc | pycbc/tmpltbank/option_utils.py | massRangeParameters.from_argparse | def from_argparse(cls, opts, nonSpin=False):
"""
Initialize an instance of the massRangeParameters class from an
argparse.OptionParser instance. This assumes that
insert_mass_range_option_group
and
verify_mass_range_options
have already been called before initializing the class.
"""
if nonSpin:
return cls(opts.min_mass1, opts.max_mass1, opts.min_mass2,
opts.max_mass2, maxTotMass=opts.max_total_mass,
minTotMass=opts.min_total_mass, maxEta=opts.max_eta,
minEta=opts.min_eta, max_chirp_mass=opts.max_chirp_mass,
min_chirp_mass=opts.min_chirp_mass,
remnant_mass_threshold=opts.remnant_mass_threshold,
ns_eos=opts.ns_eos, use_eos_max_ns_mass=opts.use_eos_max_ns_mass,
delta_bh_spin=opts.delta_bh_spin, delta_ns_mass=opts.delta_ns_mass)
else:
return cls(opts.min_mass1, opts.max_mass1, opts.min_mass2,
opts.max_mass2, maxTotMass=opts.max_total_mass,
minTotMass=opts.min_total_mass, maxEta=opts.max_eta,
minEta=opts.min_eta, maxNSSpinMag=opts.max_ns_spin_mag,
maxBHSpinMag=opts.max_bh_spin_mag,
nsbhFlag=opts.nsbh_flag,
max_chirp_mass=opts.max_chirp_mass,
min_chirp_mass=opts.min_chirp_mass,
ns_bh_boundary_mass=opts.ns_bh_boundary_mass,
remnant_mass_threshold=opts.remnant_mass_threshold,
ns_eos=opts.ns_eos, use_eos_max_ns_mass=opts.use_eos_max_ns_mass,
delta_bh_spin=opts.delta_bh_spin, delta_ns_mass=opts.delta_ns_mass) | python | def from_argparse(cls, opts, nonSpin=False):
if nonSpin:
return cls(opts.min_mass1, opts.max_mass1, opts.min_mass2,
opts.max_mass2, maxTotMass=opts.max_total_mass,
minTotMass=opts.min_total_mass, maxEta=opts.max_eta,
minEta=opts.min_eta, max_chirp_mass=opts.max_chirp_mass,
min_chirp_mass=opts.min_chirp_mass,
remnant_mass_threshold=opts.remnant_mass_threshold,
ns_eos=opts.ns_eos, use_eos_max_ns_mass=opts.use_eos_max_ns_mass,
delta_bh_spin=opts.delta_bh_spin, delta_ns_mass=opts.delta_ns_mass)
else:
return cls(opts.min_mass1, opts.max_mass1, opts.min_mass2,
opts.max_mass2, maxTotMass=opts.max_total_mass,
minTotMass=opts.min_total_mass, maxEta=opts.max_eta,
minEta=opts.min_eta, maxNSSpinMag=opts.max_ns_spin_mag,
maxBHSpinMag=opts.max_bh_spin_mag,
nsbhFlag=opts.nsbh_flag,
max_chirp_mass=opts.max_chirp_mass,
min_chirp_mass=opts.min_chirp_mass,
ns_bh_boundary_mass=opts.ns_bh_boundary_mass,
remnant_mass_threshold=opts.remnant_mass_threshold,
ns_eos=opts.ns_eos, use_eos_max_ns_mass=opts.use_eos_max_ns_mass,
delta_bh_spin=opts.delta_bh_spin, delta_ns_mass=opts.delta_ns_mass) | [
"def",
"from_argparse",
"(",
"cls",
",",
"opts",
",",
"nonSpin",
"=",
"False",
")",
":",
"if",
"nonSpin",
":",
"return",
"cls",
"(",
"opts",
".",
"min_mass1",
",",
"opts",
".",
"max_mass1",
",",
"opts",
".",
"min_mass2",
",",
"opts",
".",
"max_mass2",
... | Initialize an instance of the massRangeParameters class from an
argparse.OptionParser instance. This assumes that
insert_mass_range_option_group
and
verify_mass_range_options
have already been called before initializing the class. | [
"Initialize",
"an",
"instance",
"of",
"the",
"massRangeParameters",
"class",
"from",
"an",
"argparse",
".",
"OptionParser",
"instance",
".",
"This",
"assumes",
"that",
"insert_mass_range_option_group",
"and",
"verify_mass_range_options",
"have",
"already",
"been",
"call... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/option_utils.py#L965-L995 |
228,187 | gwastro/pycbc | pycbc/tmpltbank/option_utils.py | massRangeParameters.is_outside_range | def is_outside_range(self, mass1, mass2, spin1z, spin2z):
"""
Test if a given location in mass1, mass2, spin1z, spin2z is within the
range of parameters allowed by the massParams object.
"""
# Mass1 test
if mass1 * 1.001 < self.minMass1:
return 1
if mass1 > self.maxMass1 * 1.001:
return 1
# Mass2 test
if mass2 * 1.001 < self.minMass2:
return 1
if mass2 > self.maxMass2 * 1.001:
return 1
# Spin1 test
if self.nsbhFlag:
if (abs(spin1z) > self.maxBHSpinMag * 1.001):
return 1
else:
spin1zM = abs(spin1z)
if not( (mass1 * 1.001 > self.ns_bh_boundary_mass \
and spin1zM <= self.maxBHSpinMag * 1.001) \
or (mass1 < self.ns_bh_boundary_mass * 1.001 \
and spin1zM <= self.maxNSSpinMag * 1.001)):
return 1
# Spin2 test
if self.nsbhFlag:
if (abs(spin2z) > self.maxNSSpinMag * 1.001):
return 1
else:
spin2zM = abs(spin2z)
if not( (mass2 * 1.001 > self.ns_bh_boundary_mass \
and spin2zM <= self.maxBHSpinMag * 1.001) \
or (mass2 < self.ns_bh_boundary_mass * 1.001 and \
spin2zM <= self.maxNSSpinMag * 1.001)):
return 1
# Total mass test
mTot = mass1 + mass2
if mTot > self.maxTotMass * 1.001:
return 1
if mTot * 1.001 < self.minTotMass:
return 1
# Eta test
eta = mass1 * mass2 / (mTot * mTot)
if eta > self.maxEta * 1.001:
return 1
if eta * 1.001 < self.minEta:
return 1
# Chirp mass test
chirp_mass = mTot * eta**(3./5.)
if self.min_chirp_mass is not None \
and chirp_mass * 1.001 < self.min_chirp_mass:
return 1
if self.max_chirp_mass is not None \
and chirp_mass > self.max_chirp_mass * 1.001:
return 1
return 0 | python | def is_outside_range(self, mass1, mass2, spin1z, spin2z):
# Mass1 test
if mass1 * 1.001 < self.minMass1:
return 1
if mass1 > self.maxMass1 * 1.001:
return 1
# Mass2 test
if mass2 * 1.001 < self.minMass2:
return 1
if mass2 > self.maxMass2 * 1.001:
return 1
# Spin1 test
if self.nsbhFlag:
if (abs(spin1z) > self.maxBHSpinMag * 1.001):
return 1
else:
spin1zM = abs(spin1z)
if not( (mass1 * 1.001 > self.ns_bh_boundary_mass \
and spin1zM <= self.maxBHSpinMag * 1.001) \
or (mass1 < self.ns_bh_boundary_mass * 1.001 \
and spin1zM <= self.maxNSSpinMag * 1.001)):
return 1
# Spin2 test
if self.nsbhFlag:
if (abs(spin2z) > self.maxNSSpinMag * 1.001):
return 1
else:
spin2zM = abs(spin2z)
if not( (mass2 * 1.001 > self.ns_bh_boundary_mass \
and spin2zM <= self.maxBHSpinMag * 1.001) \
or (mass2 < self.ns_bh_boundary_mass * 1.001 and \
spin2zM <= self.maxNSSpinMag * 1.001)):
return 1
# Total mass test
mTot = mass1 + mass2
if mTot > self.maxTotMass * 1.001:
return 1
if mTot * 1.001 < self.minTotMass:
return 1
# Eta test
eta = mass1 * mass2 / (mTot * mTot)
if eta > self.maxEta * 1.001:
return 1
if eta * 1.001 < self.minEta:
return 1
# Chirp mass test
chirp_mass = mTot * eta**(3./5.)
if self.min_chirp_mass is not None \
and chirp_mass * 1.001 < self.min_chirp_mass:
return 1
if self.max_chirp_mass is not None \
and chirp_mass > self.max_chirp_mass * 1.001:
return 1
return 0 | [
"def",
"is_outside_range",
"(",
"self",
",",
"mass1",
",",
"mass2",
",",
"spin1z",
",",
"spin2z",
")",
":",
"# Mass1 test",
"if",
"mass1",
"*",
"1.001",
"<",
"self",
".",
"minMass1",
":",
"return",
"1",
"if",
"mass1",
">",
"self",
".",
"maxMass1",
"*",... | Test if a given location in mass1, mass2, spin1z, spin2z is within the
range of parameters allowed by the massParams object. | [
"Test",
"if",
"a",
"given",
"location",
"in",
"mass1",
"mass2",
"spin1z",
"spin2z",
"is",
"within",
"the",
"range",
"of",
"parameters",
"allowed",
"by",
"the",
"massParams",
"object",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/option_utils.py#L997-L1057 |
228,188 | gwastro/pycbc | pycbc/tmpltbank/option_utils.py | ethincaParameters.from_argparse | def from_argparse(cls, opts):
"""
Initialize an instance of the ethincaParameters class from an
argparse.OptionParser instance. This assumes that
insert_ethinca_metric_options
and
verify_ethinca_metric_options
have already been called before initializing the class.
"""
return cls(opts.ethinca_pn_order, opts.filter_cutoff,
opts.ethinca_frequency_step, fLow=None,
full_ethinca=opts.calculate_ethinca_metric,
time_ethinca=opts.calculate_time_metric_components) | python | def from_argparse(cls, opts):
return cls(opts.ethinca_pn_order, opts.filter_cutoff,
opts.ethinca_frequency_step, fLow=None,
full_ethinca=opts.calculate_ethinca_metric,
time_ethinca=opts.calculate_time_metric_components) | [
"def",
"from_argparse",
"(",
"cls",
",",
"opts",
")",
":",
"return",
"cls",
"(",
"opts",
".",
"ethinca_pn_order",
",",
"opts",
".",
"filter_cutoff",
",",
"opts",
".",
"ethinca_frequency_step",
",",
"fLow",
"=",
"None",
",",
"full_ethinca",
"=",
"opts",
"."... | Initialize an instance of the ethincaParameters class from an
argparse.OptionParser instance. This assumes that
insert_ethinca_metric_options
and
verify_ethinca_metric_options
have already been called before initializing the class. | [
"Initialize",
"an",
"instance",
"of",
"the",
"ethincaParameters",
"class",
"from",
"an",
"argparse",
".",
"OptionParser",
"instance",
".",
"This",
"assumes",
"that",
"insert_ethinca_metric_options",
"and",
"verify_ethinca_metric_options",
"have",
"already",
"been",
"cal... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/option_utils.py#L1097-L1109 |
228,189 | gwastro/pycbc | pycbc/inject/inject.py | set_sim_data | def set_sim_data(inj, field, data):
"""Sets data of a SimInspiral instance."""
try:
sim_field = sim_inspiral_map[field]
except KeyError:
sim_field = field
# for tc, map to geocentric times
if sim_field == 'tc':
inj.geocent_end_time = int(data)
inj.geocent_end_time_ns = int(1e9*(data % 1))
else:
setattr(inj, sim_field, data) | python | def set_sim_data(inj, field, data):
try:
sim_field = sim_inspiral_map[field]
except KeyError:
sim_field = field
# for tc, map to geocentric times
if sim_field == 'tc':
inj.geocent_end_time = int(data)
inj.geocent_end_time_ns = int(1e9*(data % 1))
else:
setattr(inj, sim_field, data) | [
"def",
"set_sim_data",
"(",
"inj",
",",
"field",
",",
"data",
")",
":",
"try",
":",
"sim_field",
"=",
"sim_inspiral_map",
"[",
"field",
"]",
"except",
"KeyError",
":",
"sim_field",
"=",
"field",
"# for tc, map to geocentric times",
"if",
"sim_field",
"==",
"'t... | Sets data of a SimInspiral instance. | [
"Sets",
"data",
"of",
"a",
"SimInspiral",
"instance",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inject/inject.py#L69-L80 |
228,190 | gwastro/pycbc | pycbc/inject/inject.py | get_hdf_injtype | def get_hdf_injtype(sim_file):
"""Gets the HDFInjectionSet class to use with the given file.
This looks for the ``injtype`` in the given file's top level ``attrs``. If
that attribute isn't set, will default to :py:class:`CBCHDFInjectionSet`.
Parameters
----------
sim_file : str
Name of the file. The file must already exist.
Returns
-------
HDFInjectionSet :
The type of HDFInjectionSet to use.
"""
with h5py.File(sim_file, 'r') as fp:
try:
ftype = fp.attrs['injtype']
except KeyError:
ftype = CBCHDFInjectionSet.injtype
return hdfinjtypes[ftype] | python | def get_hdf_injtype(sim_file):
with h5py.File(sim_file, 'r') as fp:
try:
ftype = fp.attrs['injtype']
except KeyError:
ftype = CBCHDFInjectionSet.injtype
return hdfinjtypes[ftype] | [
"def",
"get_hdf_injtype",
"(",
"sim_file",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"sim_file",
",",
"'r'",
")",
"as",
"fp",
":",
"try",
":",
"ftype",
"=",
"fp",
".",
"attrs",
"[",
"'injtype'",
"]",
"except",
"KeyError",
":",
"ftype",
"=",
"CBCHDF... | Gets the HDFInjectionSet class to use with the given file.
This looks for the ``injtype`` in the given file's top level ``attrs``. If
that attribute isn't set, will default to :py:class:`CBCHDFInjectionSet`.
Parameters
----------
sim_file : str
Name of the file. The file must already exist.
Returns
-------
HDFInjectionSet :
The type of HDFInjectionSet to use. | [
"Gets",
"the",
"HDFInjectionSet",
"class",
"to",
"use",
"with",
"the",
"given",
"file",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inject/inject.py#L722-L743 |
228,191 | gwastro/pycbc | pycbc/inject/inject.py | hdf_injtype_from_approximant | def hdf_injtype_from_approximant(approximant):
"""Gets the HDFInjectionSet class to use with the given approximant.
Parameters
----------
approximant : str
Name of the approximant.
Returns
-------
HDFInjectionSet :
The type of HDFInjectionSet to use.
"""
retcls = None
for cls in hdfinjtypes.values():
if approximant in cls.supported_approximants():
retcls = cls
if retcls is None:
# none were found, raise an error
raise ValueError("Injection file type unknown for approximant {}"
.format(approximant))
return retcls | python | def hdf_injtype_from_approximant(approximant):
retcls = None
for cls in hdfinjtypes.values():
if approximant in cls.supported_approximants():
retcls = cls
if retcls is None:
# none were found, raise an error
raise ValueError("Injection file type unknown for approximant {}"
.format(approximant))
return retcls | [
"def",
"hdf_injtype_from_approximant",
"(",
"approximant",
")",
":",
"retcls",
"=",
"None",
"for",
"cls",
"in",
"hdfinjtypes",
".",
"values",
"(",
")",
":",
"if",
"approximant",
"in",
"cls",
".",
"supported_approximants",
"(",
")",
":",
"retcls",
"=",
"cls",... | Gets the HDFInjectionSet class to use with the given approximant.
Parameters
----------
approximant : str
Name of the approximant.
Returns
-------
HDFInjectionSet :
The type of HDFInjectionSet to use. | [
"Gets",
"the",
"HDFInjectionSet",
"class",
"to",
"use",
"with",
"the",
"given",
"approximant",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inject/inject.py#L746-L767 |
228,192 | gwastro/pycbc | pycbc/inject/inject.py | _XMLInjectionSet.write | def write(filename, samples, write_params=None, static_args=None):
"""Writes the injection samples to the given xml.
Parameters
----------
filename : str
The name of the file to write to.
samples : io.FieldArray
FieldArray of parameters.
write_params : list, optional
Only write the given parameter names. All given names must be keys
in ``samples``. Default is to write all parameters in ``samples``.
static_args : dict, optional
Dictionary mapping static parameter names to values. These are
written to the ``attrs``.
"""
xmldoc = ligolw.Document()
xmldoc.appendChild(ligolw.LIGO_LW())
simtable = lsctables.New(lsctables.SimInspiralTable)
xmldoc.childNodes[0].appendChild(simtable)
if static_args is None:
static_args = {}
if write_params is None:
write_params = samples.fieldnames
for ii in range(samples.size):
sim = lsctables.SimInspiral()
# initialize all elements to None
for col in sim.__slots__:
setattr(sim, col, None)
for field in write_params:
data = samples[ii][field]
set_sim_data(sim, field, data)
# set any static args
for (field, value) in static_args.items():
set_sim_data(sim, field, value)
simtable.append(sim)
ligolw_utils.write_filename(xmldoc, filename,
gz=filename.endswith('gz')) | python | def write(filename, samples, write_params=None, static_args=None):
xmldoc = ligolw.Document()
xmldoc.appendChild(ligolw.LIGO_LW())
simtable = lsctables.New(lsctables.SimInspiralTable)
xmldoc.childNodes[0].appendChild(simtable)
if static_args is None:
static_args = {}
if write_params is None:
write_params = samples.fieldnames
for ii in range(samples.size):
sim = lsctables.SimInspiral()
# initialize all elements to None
for col in sim.__slots__:
setattr(sim, col, None)
for field in write_params:
data = samples[ii][field]
set_sim_data(sim, field, data)
# set any static args
for (field, value) in static_args.items():
set_sim_data(sim, field, value)
simtable.append(sim)
ligolw_utils.write_filename(xmldoc, filename,
gz=filename.endswith('gz')) | [
"def",
"write",
"(",
"filename",
",",
"samples",
",",
"write_params",
"=",
"None",
",",
"static_args",
"=",
"None",
")",
":",
"xmldoc",
"=",
"ligolw",
".",
"Document",
"(",
")",
"xmldoc",
".",
"appendChild",
"(",
"ligolw",
".",
"LIGO_LW",
"(",
")",
")"... | Writes the injection samples to the given xml.
Parameters
----------
filename : str
The name of the file to write to.
samples : io.FieldArray
FieldArray of parameters.
write_params : list, optional
Only write the given parameter names. All given names must be keys
in ``samples``. Default is to write all parameters in ``samples``.
static_args : dict, optional
Dictionary mapping static parameter names to values. These are
written to the ``attrs``. | [
"Writes",
"the",
"injection",
"samples",
"to",
"the",
"given",
"xml",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inject/inject.py#L269-L306 |
228,193 | gwastro/pycbc | pycbc/tmpltbank/partitioned_bank.py | PartitionedTmpltbank.get_point_from_bins_and_idx | def get_point_from_bins_and_idx(self, chi1_bin, chi2_bin, idx):
"""Find masses and spins given bin numbers and index.
Given the chi1 bin, chi2 bin and an index, return the masses and spins
of the point at that index. Will fail if no point exists there.
Parameters
-----------
chi1_bin : int
The bin number for chi1.
chi2_bin : int
The bin number for chi2.
idx : int
The index within the chi1, chi2 bin.
Returns
--------
mass1 : float
Mass of heavier body.
mass2 : float
Mass of lighter body.
spin1z : float
Spin of heavier body.
spin2z : float
Spin of lighter body.
"""
mass1 = self.massbank[chi1_bin][chi2_bin]['mass1s'][idx]
mass2 = self.massbank[chi1_bin][chi2_bin]['mass2s'][idx]
spin1z = self.massbank[chi1_bin][chi2_bin]['spin1s'][idx]
spin2z = self.massbank[chi1_bin][chi2_bin]['spin2s'][idx]
return mass1, mass2, spin1z, spin2z | python | def get_point_from_bins_and_idx(self, chi1_bin, chi2_bin, idx):
mass1 = self.massbank[chi1_bin][chi2_bin]['mass1s'][idx]
mass2 = self.massbank[chi1_bin][chi2_bin]['mass2s'][idx]
spin1z = self.massbank[chi1_bin][chi2_bin]['spin1s'][idx]
spin2z = self.massbank[chi1_bin][chi2_bin]['spin2s'][idx]
return mass1, mass2, spin1z, spin2z | [
"def",
"get_point_from_bins_and_idx",
"(",
"self",
",",
"chi1_bin",
",",
"chi2_bin",
",",
"idx",
")",
":",
"mass1",
"=",
"self",
".",
"massbank",
"[",
"chi1_bin",
"]",
"[",
"chi2_bin",
"]",
"[",
"'mass1s'",
"]",
"[",
"idx",
"]",
"mass2",
"=",
"self",
"... | Find masses and spins given bin numbers and index.
Given the chi1 bin, chi2 bin and an index, return the masses and spins
of the point at that index. Will fail if no point exists there.
Parameters
-----------
chi1_bin : int
The bin number for chi1.
chi2_bin : int
The bin number for chi2.
idx : int
The index within the chi1, chi2 bin.
Returns
--------
mass1 : float
Mass of heavier body.
mass2 : float
Mass of lighter body.
spin1z : float
Spin of heavier body.
spin2z : float
Spin of lighter body. | [
"Find",
"masses",
"and",
"spins",
"given",
"bin",
"numbers",
"and",
"index",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/partitioned_bank.py#L119-L149 |
228,194 | gwastro/pycbc | pycbc/tmpltbank/partitioned_bank.py | PartitionedTmpltbank.find_point_bin | def find_point_bin(self, chi_coords):
"""
Given a set of coordinates in the chi parameter space, identify the
indices of the chi1 and chi2 bins that the point occurs in. Returns
these indices.
Parameters
-----------
chi_coords : numpy.array
The position of the point in the chi coordinates.
Returns
--------
chi1_bin : int
Index of the chi_1 bin.
chi2_bin : int
Index of the chi_2 bin.
"""
# Identify bin
chi1_bin = int((chi_coords[0] - self.chi1_min) // self.bin_spacing)
chi2_bin = int((chi_coords[1] - self.chi2_min) // self.bin_spacing)
self.check_bin_existence(chi1_bin, chi2_bin)
return chi1_bin, chi2_bin | python | def find_point_bin(self, chi_coords):
# Identify bin
chi1_bin = int((chi_coords[0] - self.chi1_min) // self.bin_spacing)
chi2_bin = int((chi_coords[1] - self.chi2_min) // self.bin_spacing)
self.check_bin_existence(chi1_bin, chi2_bin)
return chi1_bin, chi2_bin | [
"def",
"find_point_bin",
"(",
"self",
",",
"chi_coords",
")",
":",
"# Identify bin",
"chi1_bin",
"=",
"int",
"(",
"(",
"chi_coords",
"[",
"0",
"]",
"-",
"self",
".",
"chi1_min",
")",
"//",
"self",
".",
"bin_spacing",
")",
"chi2_bin",
"=",
"int",
"(",
"... | Given a set of coordinates in the chi parameter space, identify the
indices of the chi1 and chi2 bins that the point occurs in. Returns
these indices.
Parameters
-----------
chi_coords : numpy.array
The position of the point in the chi coordinates.
Returns
--------
chi1_bin : int
Index of the chi_1 bin.
chi2_bin : int
Index of the chi_2 bin. | [
"Given",
"a",
"set",
"of",
"coordinates",
"in",
"the",
"chi",
"parameter",
"space",
"identify",
"the",
"indices",
"of",
"the",
"chi1",
"and",
"chi2",
"bins",
"that",
"the",
"point",
"occurs",
"in",
".",
"Returns",
"these",
"indices",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/partitioned_bank.py#L177-L199 |
228,195 | gwastro/pycbc | pycbc/tmpltbank/partitioned_bank.py | PartitionedTmpltbank.calc_point_distance | def calc_point_distance(self, chi_coords):
"""
Calculate distance between point and the bank. Return the closest
distance.
Parameters
-----------
chi_coords : numpy.array
The position of the point in the chi coordinates.
Returns
--------
min_dist : float
The smallest **SQUARED** metric distance between the test point and
the bank.
indexes : The chi1_bin, chi2_bin and position within that bin at which
the closest matching point lies.
"""
chi1_bin, chi2_bin = self.find_point_bin(chi_coords)
min_dist = 1000000000
indexes = None
for chi1_bin_offset, chi2_bin_offset in self.bin_loop_order:
curr_chi1_bin = chi1_bin + chi1_bin_offset
curr_chi2_bin = chi2_bin + chi2_bin_offset
for idx, bank_chis in \
enumerate(self.bank[curr_chi1_bin][curr_chi2_bin]):
dist = coord_utils.calc_point_dist(chi_coords, bank_chis)
if dist < min_dist:
min_dist = dist
indexes = (curr_chi1_bin, curr_chi2_bin, idx)
return min_dist, indexes | python | def calc_point_distance(self, chi_coords):
chi1_bin, chi2_bin = self.find_point_bin(chi_coords)
min_dist = 1000000000
indexes = None
for chi1_bin_offset, chi2_bin_offset in self.bin_loop_order:
curr_chi1_bin = chi1_bin + chi1_bin_offset
curr_chi2_bin = chi2_bin + chi2_bin_offset
for idx, bank_chis in \
enumerate(self.bank[curr_chi1_bin][curr_chi2_bin]):
dist = coord_utils.calc_point_dist(chi_coords, bank_chis)
if dist < min_dist:
min_dist = dist
indexes = (curr_chi1_bin, curr_chi2_bin, idx)
return min_dist, indexes | [
"def",
"calc_point_distance",
"(",
"self",
",",
"chi_coords",
")",
":",
"chi1_bin",
",",
"chi2_bin",
"=",
"self",
".",
"find_point_bin",
"(",
"chi_coords",
")",
"min_dist",
"=",
"1000000000",
"indexes",
"=",
"None",
"for",
"chi1_bin_offset",
",",
"chi2_bin_offse... | Calculate distance between point and the bank. Return the closest
distance.
Parameters
-----------
chi_coords : numpy.array
The position of the point in the chi coordinates.
Returns
--------
min_dist : float
The smallest **SQUARED** metric distance between the test point and
the bank.
indexes : The chi1_bin, chi2_bin and position within that bin at which
the closest matching point lies. | [
"Calculate",
"distance",
"between",
"point",
"and",
"the",
"bank",
".",
"Return",
"the",
"closest",
"distance",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/partitioned_bank.py#L234-L264 |
228,196 | gwastro/pycbc | pycbc/tmpltbank/partitioned_bank.py | PartitionedTmpltbank.calc_point_distance_vary | def calc_point_distance_vary(self, chi_coords, point_fupper, mus):
"""
Calculate distance between point and the bank allowing the metric to
vary based on varying upper frequency cutoff. Slower than
calc_point_distance, but more reliable when upper frequency cutoff can
change a lot.
Parameters
-----------
chi_coords : numpy.array
The position of the point in the chi coordinates.
point_fupper : float
The upper frequency cutoff to use for this point. This value must
be one of the ones already calculated in the metric.
mus : numpy.array
A 2D array where idx 0 holds the upper frequency cutoff and idx 1
holds the coordinates in the [not covaried] mu parameter space for
each value of the upper frequency cutoff.
Returns
--------
min_dist : float
The smallest **SQUARED** metric distance between the test point and
the bank.
indexes : The chi1_bin, chi2_bin and position within that bin at which
the closest matching point lies.
"""
chi1_bin, chi2_bin = self.find_point_bin(chi_coords)
min_dist = 1000000000
indexes = None
for chi1_bin_offset, chi2_bin_offset in self.bin_loop_order:
curr_chi1_bin = chi1_bin + chi1_bin_offset
curr_chi2_bin = chi2_bin + chi2_bin_offset
# No points = Next iteration
curr_bank = self.massbank[curr_chi1_bin][curr_chi2_bin]
if not curr_bank['mass1s'].size:
continue
# *NOT* the same of .min and .max
f_upper = numpy.minimum(point_fupper, curr_bank['freqcuts'])
f_other = numpy.maximum(point_fupper, curr_bank['freqcuts'])
# NOTE: freq_idxes is a vector!
freq_idxes = numpy.array([self.frequency_map[f] for f in f_upper])
# vecs1 gives a 2x2 vector: idx0 = stored index, idx1 = mu index
vecs1 = mus[freq_idxes, :]
# vecs2 gives a 2x2 vector: idx0 = stored index, idx1 = mu index
range_idxes = numpy.arange(len(freq_idxes))
vecs2 = curr_bank['mus'][range_idxes, freq_idxes, :]
# Now do the sums
dists = (vecs1 - vecs2)*(vecs1 - vecs2)
# This reduces to 1D: idx = stored index
dists = numpy.sum(dists, axis=1)
norm_upper = numpy.array([self.normalization_map[f] \
for f in f_upper])
norm_other = numpy.array([self.normalization_map[f] \
for f in f_other])
norm_fac = norm_upper / norm_other
renormed_dists = 1 - (1 - dists)*norm_fac
curr_min_dist = renormed_dists.min()
if curr_min_dist < min_dist:
min_dist = curr_min_dist
indexes = curr_chi1_bin, curr_chi2_bin, renormed_dists.argmin()
return min_dist, indexes | python | def calc_point_distance_vary(self, chi_coords, point_fupper, mus):
chi1_bin, chi2_bin = self.find_point_bin(chi_coords)
min_dist = 1000000000
indexes = None
for chi1_bin_offset, chi2_bin_offset in self.bin_loop_order:
curr_chi1_bin = chi1_bin + chi1_bin_offset
curr_chi2_bin = chi2_bin + chi2_bin_offset
# No points = Next iteration
curr_bank = self.massbank[curr_chi1_bin][curr_chi2_bin]
if not curr_bank['mass1s'].size:
continue
# *NOT* the same of .min and .max
f_upper = numpy.minimum(point_fupper, curr_bank['freqcuts'])
f_other = numpy.maximum(point_fupper, curr_bank['freqcuts'])
# NOTE: freq_idxes is a vector!
freq_idxes = numpy.array([self.frequency_map[f] for f in f_upper])
# vecs1 gives a 2x2 vector: idx0 = stored index, idx1 = mu index
vecs1 = mus[freq_idxes, :]
# vecs2 gives a 2x2 vector: idx0 = stored index, idx1 = mu index
range_idxes = numpy.arange(len(freq_idxes))
vecs2 = curr_bank['mus'][range_idxes, freq_idxes, :]
# Now do the sums
dists = (vecs1 - vecs2)*(vecs1 - vecs2)
# This reduces to 1D: idx = stored index
dists = numpy.sum(dists, axis=1)
norm_upper = numpy.array([self.normalization_map[f] \
for f in f_upper])
norm_other = numpy.array([self.normalization_map[f] \
for f in f_other])
norm_fac = norm_upper / norm_other
renormed_dists = 1 - (1 - dists)*norm_fac
curr_min_dist = renormed_dists.min()
if curr_min_dist < min_dist:
min_dist = curr_min_dist
indexes = curr_chi1_bin, curr_chi2_bin, renormed_dists.argmin()
return min_dist, indexes | [
"def",
"calc_point_distance_vary",
"(",
"self",
",",
"chi_coords",
",",
"point_fupper",
",",
"mus",
")",
":",
"chi1_bin",
",",
"chi2_bin",
"=",
"self",
".",
"find_point_bin",
"(",
"chi_coords",
")",
"min_dist",
"=",
"1000000000",
"indexes",
"=",
"None",
"for",... | Calculate distance between point and the bank allowing the metric to
vary based on varying upper frequency cutoff. Slower than
calc_point_distance, but more reliable when upper frequency cutoff can
change a lot.
Parameters
-----------
chi_coords : numpy.array
The position of the point in the chi coordinates.
point_fupper : float
The upper frequency cutoff to use for this point. This value must
be one of the ones already calculated in the metric.
mus : numpy.array
A 2D array where idx 0 holds the upper frequency cutoff and idx 1
holds the coordinates in the [not covaried] mu parameter space for
each value of the upper frequency cutoff.
Returns
--------
min_dist : float
The smallest **SQUARED** metric distance between the test point and
the bank.
indexes : The chi1_bin, chi2_bin and position within that bin at which
the closest matching point lies. | [
"Calculate",
"distance",
"between",
"point",
"and",
"the",
"bank",
"allowing",
"the",
"metric",
"to",
"vary",
"based",
"on",
"varying",
"upper",
"frequency",
"cutoff",
".",
"Slower",
"than",
"calc_point_distance",
"but",
"more",
"reliable",
"when",
"upper",
"fre... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/partitioned_bank.py#L297-L361 |
228,197 | gwastro/pycbc | pycbc/tmpltbank/partitioned_bank.py | PartitionedTmpltbank.add_point_by_chi_coords | def add_point_by_chi_coords(self, chi_coords, mass1, mass2, spin1z, spin2z,
point_fupper=None, mus=None):
"""
Add a point to the partitioned template bank. The point_fupper and mus
kwargs must be provided for all templates if the vary fupper capability
is desired. This requires that the chi_coords, as well as mus and
point_fupper if needed, to be precalculated. If you just have the
masses and don't want to worry about translations see
add_point_by_masses, which will do translations and then call this.
Parameters
-----------
chi_coords : numpy.array
The position of the point in the chi coordinates.
mass1 : float
The heavier mass of the point to add.
mass2 : float
The lighter mass of the point to add.
spin1z: float
The [aligned] spin on the heavier body.
spin2z: float
The [aligned] spin on the lighter body.
The upper frequency cutoff to use for this point. This value must
be one of the ones already calculated in the metric.
mus : numpy.array
A 2D array where idx 0 holds the upper frequency cutoff and idx 1
holds the coordinates in the [not covaried] mu parameter space for
each value of the upper frequency cutoff.
"""
chi1_bin, chi2_bin = self.find_point_bin(chi_coords)
self.bank[chi1_bin][chi2_bin].append(copy.deepcopy(chi_coords))
curr_bank = self.massbank[chi1_bin][chi2_bin]
if curr_bank['mass1s'].size:
curr_bank['mass1s'] = numpy.append(curr_bank['mass1s'],
numpy.array([mass1]))
curr_bank['mass2s'] = numpy.append(curr_bank['mass2s'],
numpy.array([mass2]))
curr_bank['spin1s'] = numpy.append(curr_bank['spin1s'],
numpy.array([spin1z]))
curr_bank['spin2s'] = numpy.append(curr_bank['spin2s'],
numpy.array([spin2z]))
if point_fupper is not None:
curr_bank['freqcuts'] = numpy.append(curr_bank['freqcuts'],
numpy.array([point_fupper]))
# Mus needs to append onto axis 0. See below for contents of
# the mus variable
if mus is not None:
curr_bank['mus'] = numpy.append(curr_bank['mus'],
numpy.array([mus[:,:]]), axis=0)
else:
curr_bank['mass1s'] = numpy.array([mass1])
curr_bank['mass2s'] = numpy.array([mass2])
curr_bank['spin1s'] = numpy.array([spin1z])
curr_bank['spin2s'] = numpy.array([spin2z])
if point_fupper is not None:
curr_bank['freqcuts'] = numpy.array([point_fupper])
# curr_bank['mus'] is a 3D array
# NOTE: mu relates to the non-covaried Cartesian coordinate system
# Axis 0: Template index
# Axis 1: Frequency cutoff index
# Axis 2: Mu coordinate index
if mus is not None:
curr_bank['mus'] = numpy.array([mus[:,:]]) | python | def add_point_by_chi_coords(self, chi_coords, mass1, mass2, spin1z, spin2z,
point_fupper=None, mus=None):
chi1_bin, chi2_bin = self.find_point_bin(chi_coords)
self.bank[chi1_bin][chi2_bin].append(copy.deepcopy(chi_coords))
curr_bank = self.massbank[chi1_bin][chi2_bin]
if curr_bank['mass1s'].size:
curr_bank['mass1s'] = numpy.append(curr_bank['mass1s'],
numpy.array([mass1]))
curr_bank['mass2s'] = numpy.append(curr_bank['mass2s'],
numpy.array([mass2]))
curr_bank['spin1s'] = numpy.append(curr_bank['spin1s'],
numpy.array([spin1z]))
curr_bank['spin2s'] = numpy.append(curr_bank['spin2s'],
numpy.array([spin2z]))
if point_fupper is not None:
curr_bank['freqcuts'] = numpy.append(curr_bank['freqcuts'],
numpy.array([point_fupper]))
# Mus needs to append onto axis 0. See below for contents of
# the mus variable
if mus is not None:
curr_bank['mus'] = numpy.append(curr_bank['mus'],
numpy.array([mus[:,:]]), axis=0)
else:
curr_bank['mass1s'] = numpy.array([mass1])
curr_bank['mass2s'] = numpy.array([mass2])
curr_bank['spin1s'] = numpy.array([spin1z])
curr_bank['spin2s'] = numpy.array([spin2z])
if point_fupper is not None:
curr_bank['freqcuts'] = numpy.array([point_fupper])
# curr_bank['mus'] is a 3D array
# NOTE: mu relates to the non-covaried Cartesian coordinate system
# Axis 0: Template index
# Axis 1: Frequency cutoff index
# Axis 2: Mu coordinate index
if mus is not None:
curr_bank['mus'] = numpy.array([mus[:,:]]) | [
"def",
"add_point_by_chi_coords",
"(",
"self",
",",
"chi_coords",
",",
"mass1",
",",
"mass2",
",",
"spin1z",
",",
"spin2z",
",",
"point_fupper",
"=",
"None",
",",
"mus",
"=",
"None",
")",
":",
"chi1_bin",
",",
"chi2_bin",
"=",
"self",
".",
"find_point_bin"... | Add a point to the partitioned template bank. The point_fupper and mus
kwargs must be provided for all templates if the vary fupper capability
is desired. This requires that the chi_coords, as well as mus and
point_fupper if needed, to be precalculated. If you just have the
masses and don't want to worry about translations see
add_point_by_masses, which will do translations and then call this.
Parameters
-----------
chi_coords : numpy.array
The position of the point in the chi coordinates.
mass1 : float
The heavier mass of the point to add.
mass2 : float
The lighter mass of the point to add.
spin1z: float
The [aligned] spin on the heavier body.
spin2z: float
The [aligned] spin on the lighter body.
The upper frequency cutoff to use for this point. This value must
be one of the ones already calculated in the metric.
mus : numpy.array
A 2D array where idx 0 holds the upper frequency cutoff and idx 1
holds the coordinates in the [not covaried] mu parameter space for
each value of the upper frequency cutoff. | [
"Add",
"a",
"point",
"to",
"the",
"partitioned",
"template",
"bank",
".",
"The",
"point_fupper",
"and",
"mus",
"kwargs",
"must",
"be",
"provided",
"for",
"all",
"templates",
"if",
"the",
"vary",
"fupper",
"capability",
"is",
"desired",
".",
"This",
"requires... | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/partitioned_bank.py#L432-L495 |
228,198 | gwastro/pycbc | pycbc/tmpltbank/partitioned_bank.py | PartitionedTmpltbank.add_tmpltbank_from_xml_table | def add_tmpltbank_from_xml_table(self, sngl_table, vary_fupper=False):
"""
This function will take a sngl_inspiral_table of templates and add them
into the partitioned template bank object.
Parameters
-----------
sngl_table : sngl_inspiral_table
List of sngl_inspiral templates.
vary_fupper : False
If given also include the additional information needed to compute
distances with a varying upper frequency cutoff.
"""
for sngl in sngl_table:
self.add_point_by_masses(sngl.mass1, sngl.mass2, sngl.spin1z,
sngl.spin2z, vary_fupper=vary_fupper) | python | def add_tmpltbank_from_xml_table(self, sngl_table, vary_fupper=False):
for sngl in sngl_table:
self.add_point_by_masses(sngl.mass1, sngl.mass2, sngl.spin1z,
sngl.spin2z, vary_fupper=vary_fupper) | [
"def",
"add_tmpltbank_from_xml_table",
"(",
"self",
",",
"sngl_table",
",",
"vary_fupper",
"=",
"False",
")",
":",
"for",
"sngl",
"in",
"sngl_table",
":",
"self",
".",
"add_point_by_masses",
"(",
"sngl",
".",
"mass1",
",",
"sngl",
".",
"mass2",
",",
"sngl",
... | This function will take a sngl_inspiral_table of templates and add them
into the partitioned template bank object.
Parameters
-----------
sngl_table : sngl_inspiral_table
List of sngl_inspiral templates.
vary_fupper : False
If given also include the additional information needed to compute
distances with a varying upper frequency cutoff. | [
"This",
"function",
"will",
"take",
"a",
"sngl_inspiral_table",
"of",
"templates",
"and",
"add",
"them",
"into",
"the",
"partitioned",
"template",
"bank",
"object",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/partitioned_bank.py#L572-L587 |
228,199 | gwastro/pycbc | pycbc/tmpltbank/partitioned_bank.py | PartitionedTmpltbank.add_tmpltbank_from_hdf_file | def add_tmpltbank_from_hdf_file(self, hdf_fp, vary_fupper=False):
"""
This function will take a pointer to an open HDF File object containing
a list of templates and add them into the partitioned template bank
object.
Parameters
-----------
hdf_fp : h5py.File object
The template bank in HDF5 format.
vary_fupper : False
If given also include the additional information needed to compute
distances with a varying upper frequency cutoff.
"""
mass1s = hdf_fp['mass1'][:]
mass2s = hdf_fp['mass2'][:]
spin1zs = hdf_fp['spin1z'][:]
spin2zs = hdf_fp['spin2z'][:]
for idx in xrange(len(mass1s)):
self.add_point_by_masses(mass1s[idx], mass2s[idx], spin1zs[idx],
spin2zs[idx], vary_fupper=vary_fupper) | python | def add_tmpltbank_from_hdf_file(self, hdf_fp, vary_fupper=False):
mass1s = hdf_fp['mass1'][:]
mass2s = hdf_fp['mass2'][:]
spin1zs = hdf_fp['spin1z'][:]
spin2zs = hdf_fp['spin2z'][:]
for idx in xrange(len(mass1s)):
self.add_point_by_masses(mass1s[idx], mass2s[idx], spin1zs[idx],
spin2zs[idx], vary_fupper=vary_fupper) | [
"def",
"add_tmpltbank_from_hdf_file",
"(",
"self",
",",
"hdf_fp",
",",
"vary_fupper",
"=",
"False",
")",
":",
"mass1s",
"=",
"hdf_fp",
"[",
"'mass1'",
"]",
"[",
":",
"]",
"mass2s",
"=",
"hdf_fp",
"[",
"'mass2'",
"]",
"[",
":",
"]",
"spin1zs",
"=",
"hdf... | This function will take a pointer to an open HDF File object containing
a list of templates and add them into the partitioned template bank
object.
Parameters
-----------
hdf_fp : h5py.File object
The template bank in HDF5 format.
vary_fupper : False
If given also include the additional information needed to compute
distances with a varying upper frequency cutoff. | [
"This",
"function",
"will",
"take",
"a",
"pointer",
"to",
"an",
"open",
"HDF",
"File",
"object",
"containing",
"a",
"list",
"of",
"templates",
"and",
"add",
"them",
"into",
"the",
"partitioned",
"template",
"bank",
"object",
"."
] | 7a64cdd104d263f1b6ea0b01e6841837d05a4cb3 | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/partitioned_bank.py#L589-L609 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.