signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def add_node(self, node): | node._finalize()<EOL>node.in_workflow = self<EOL>self._adag.addJob(node._dax_node)<EOL>added_nodes = []<EOL>for inp in node._inputs:<EOL><INDENT>if inp.node is not None and inp.node.in_workflow == self:<EOL><INDENT>if inp.node not in added_nodes:<EOL><INDENT>parent = inp.node._dax_node<EOL>child = node._dax_node<EOL>de... | Add a node to this workflow
This function adds nodes to the workflow. It also determines
parent/child relations from the DataStorage inputs to this job.
Parameters
----------
node : pycbc.workflow.pegasus_workflow.Node
A node that should be executed as part of this ... | f16006:c3:m3 |
def save(self, filename=None, tc=None): | if filename is None:<EOL><INDENT>filename = self.filename<EOL><DEDENT>for sub in self.sub_workflows:<EOL><INDENT>sub.save()<EOL><DEDENT>if tc is None:<EOL><INDENT>tc = '<STR_LIT>'.format(filename)<EOL><DEDENT>p = os.path.dirname(tc)<EOL>f = os.path.basename(tc)<EOL>if not p:<EOL><INDENT>p = '<STR_LIT:.>'<EOL><DEDENT>tc... | Write this workflow to DAX file | f16006:c3:m5 |
@property<EOL><INDENT>def dax_repr(self):<DEDENT> | return self._dax_repr()<EOL> | Return the dax representation of a File. | f16006:c5:m2 |
def has_pfn(self, url, site=None): | curr_pfn = dax.PFN(url, site)<EOL>return self.hasPFN(curr_pfn)<EOL> | Wrapper of the pegasus hasPFN function, that allows it to be called
outside of specific pegasus functions. | f16006:c5:m6 |
@classmethod<EOL><INDENT>def from_path(cls, path):<DEDENT> | urlparts = urlparse.urlsplit(path)<EOL>site = '<STR_LIT>'<EOL>if (urlparts.scheme == '<STR_LIT>' or urlparts.scheme == '<STR_LIT:file>'):<EOL><INDENT>if os.path.isfile(urlparts.path):<EOL><INDENT>path = os.path.abspath(urlparts.path)<EOL>path = urlparse.urljoin('<STR_LIT>',<EOL>urllib.pathname2url(path)) <EOL>site = '<... | Takes a path and returns a File object with the path as the PFN. | f16006:c5:m8 |
def get_science_segments(workflow, out_dir, tags=None): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>logging.info('<STR_LIT>')<EOL>make_analysis_dir(out_dir)<EOL>start_time = workflow.analysis_time[<NUM_LIT:0>]<EOL>end_time = workflow.analysis_time[<NUM_LIT:1>]<EOL>sci_seg_name = "<STR_LIT>"<EOL>sci_segs = {}<EOL>sci_seg_dict = segments.segmentlistdict()<EOL>sci_seg_s... | Get the analyzable segments after applying ini specified vetoes.
Parameters
-----------
workflow : Workflow object
Instance of the workflow object
out_dir : path
Location to store output files
tags : list of strings
Used to retrieve subsections of the ini file for
configuration options.
Returns
------... | f16007:m0 |
def get_files_for_vetoes(workflow, out_dir,<EOL>runtime_names=None, in_workflow_names=None, tags=None): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>if runtime_names is None:<EOL><INDENT>runtime_names = []<EOL><DEDENT>if in_workflow_names is None:<EOL><INDENT>in_workflow_names = []<EOL><DEDENT>logging.info('<STR_LIT>')<EOL>make_analysis_dir(out_dir)<EOL>start_time = workflow.analysis_time[<NUM_LIT:0>]<EOL>end_time ... | Get the various sets of veto segments that will be used in this analysis.
Parameters
-----------
workflow : Workflow object
Instance of the workflow object
out_dir : path
Location to store output files
runtime_names : list
Veto category groups with these names in the [workflow-segment] section
of the i... | f16007:m1 |
def get_analyzable_segments(workflow, sci_segs, cat_files, out_dir, tags=None): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>logging.info('<STR_LIT>')<EOL>make_analysis_dir(out_dir)<EOL>sci_ok_seg_name = "<STR_LIT>"<EOL>sci_ok_seg_dict = segments.segmentlistdict()<EOL>sci_ok_segs = {}<EOL>cat_sets = parse_cat_ini_opt(workflow.cp.get_opt_tags('<STR_LIT>',<EOL>'<STR_LIT>', tags))<EOL>if len(ca... | Get the analyzable segments after applying ini specified vetoes and any
other restrictions on the science segs, e.g. a minimum segment length, or
demanding that only coincident segments are analysed.
Parameters
-----------
workflow : Workflow object
Instance of the workflow object
sci_segs : Ifo-keyed dictionary o... | f16007:m2 |
def get_cumulative_veto_group_files(workflow, option, cat_files,<EOL>out_dir, execute_now=True, tags=None): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>logging.info("<STR_LIT>" %(option))<EOL>make_analysis_dir(out_dir)<EOL>cat_sets = parse_cat_ini_opt(workflow.cp.get_opt_tags('<STR_LIT>',<EOL>option, tags))<EOL>cum_seg_files = FileList()<EOL>names = []<EOL>for cat_set in cat_sets:<EOL><INDENT>segment_name = "<STR_LIT>... | Get the cumulative veto files that define the different backgrounds
we want to analyze, defined by groups of vetos.
Parameters
-----------
workflow : Workflow object
Instance of the workflow object
option : str
ini file option to use to get the veto groups
cat_files : FileList of SegFiles
The category veto... | f16007:m3 |
def setup_segment_generation(workflow, out_dir, tag=None): | logging.info("<STR_LIT>")<EOL>make_analysis_dir(out_dir)<EOL>cp = workflow.cp<EOL>segmentsMethod = cp.get_opt_tags("<STR_LIT>",<EOL>"<STR_LIT>", [tag])<EOL>if segmentsMethod in ['<STR_LIT>','<STR_LIT>','<STR_LIT>',<EOL>'<STR_LIT>']:<EOL><INDENT>veto_cats = cp.get_opt_tags("<STR_LIT>",<EOL>"<STR_LIT>", [tag])<EOL>max_ve... | This function is the gateway for setting up the segment generation steps in a
workflow. It is designed to be able to support multiple ways of obtaining
these segments and to combine/edit such files as necessary for analysis.
The current modules have the capability to generate files at runtime or to
generate files that ... | f16007:m4 |
def setup_segment_gen_mixed(workflow, veto_categories, out_dir,<EOL>maxVetoAtRunTime, tag=None,<EOL>generate_coincident_segs=True): | cp = workflow.cp<EOL>segFilesList = FileList([])<EOL>start_time = workflow.analysis_time[<NUM_LIT:0>]<EOL>end_time = workflow.analysis_time[<NUM_LIT:1>]<EOL>segValidSeg = workflow.analysis_time<EOL>vetoGenJob = create_segs_from_cats_job(cp, out_dir, workflow.ifo_string)<EOL>for ifo in workflow.ifos:<EOL><INDENT>logging... | This function will generate veto files for each ifo and for each veto
category.
It can generate these vetoes at run-time or in the workflow (or do some at
run-time and some in the workflow). However, the CAT_1 vetoes and science
time must be generated at run time as they are needed to plan the workflow.
CATs 2 and high... | f16007:m5 |
def get_sci_segs_for_ifo(ifo, cp, start_time, end_time, out_dir, tags=None): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>seg_valid_seg = segments.segment([start_time,end_time])<EOL>sci_seg_name = cp.get_opt_tags(<EOL>"<STR_LIT>", "<STR_LIT>" %(ifo.lower()), tags)<EOL>sci_seg_url = cp.get_opt_tags(<EOL>"<STR_LIT>", "<STR_LIT>", tags)<EOL>out_sci_seg_name = "<STR_LIT>"<EOL>if tags:<EOL><IN... | Obtain science segments for the selected ifo
Parameters
-----------
ifo : string
The string describing the ifo to obtain science times for.
start_time : gps time (either int/LIGOTimeGPS)
The time at which to begin searching for segments.
end_time : gps time (either int/LIGOTimeGPS)
The time at which to sto... | f16007:m6 |
def get_veto_segs(workflow, ifo, category, start_time, end_time, out_dir,<EOL>veto_gen_job, tags=None, execute_now=False): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>seg_valid_seg = segments.segment([start_time,end_time])<EOL>node = Node(veto_gen_job)<EOL>node.add_opt('<STR_LIT>', str(category))<EOL>node.add_opt('<STR_LIT>', ifo)<EOL>node.add_opt('<STR_LIT>', str(start_time))<EOL>node.add_opt('<STR_LIT>', str(end_time))<EOL>if tags... | Obtain veto segments for the selected ifo and veto category and add the job
to generate this to the workflow.
Parameters
-----------
workflow: pycbc.workflow.core.Workflow
An instance of the Workflow class that manages the workflow.
ifo : string
The string describing the ifo to generate vetoes for.
category : ... | f16007:m7 |
def create_segs_from_cats_job(cp, out_dir, ifo_string, tags=None): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>seg_server_url = cp.get_opt_tags("<STR_LIT>",<EOL>"<STR_LIT>", tags)<EOL>veto_def_file = cp.get_opt_tags("<STR_LIT>",<EOL>"<STR_LIT>", tags)<EOL>job = Executable(cp, '<STR_LIT>', universe='<STR_LIT>',<EOL>ifos=ifo_string, out_dir=out_dir, tags=tags)<EOL>job.add_opt('<S... | This function creates the CondorDAGJob that will be used to run
ligolw_segments_from_cats as part of the workflow
Parameters
-----------
cp : pycbc.workflow.configuration.WorkflowConfigParser
The in-memory representation of the configuration (.ini) files
out_dir : path
Directory in which to put output files
if... | f16007:m8 |
def get_cumulative_segs(workflow, categories, seg_files_list, out_dir,<EOL>tags=None, execute_now=False, segment_name=None): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>add_inputs = FileList([])<EOL>valid_segment = workflow.analysis_time<EOL>if segment_name is None:<EOL><INDENT>segment_name = '<STR_LIT>' % (categories[-<NUM_LIT:1>])<EOL><DEDENT>cp = workflow.cp<EOL>for ifo in workflow.ifos:<EOL><INDENT>cum_job = LigoLWCombineSegsExecu... | Function to generate one of the cumulative, multi-detector segment files
as part of the workflow.
Parameters
-----------
workflow: pycbc.workflow.core.Workflow
An instance of the Workflow class that manages the workflow.
categories : int
The veto categories to include in this cumulative veto.
seg_files_list : ... | f16007:m9 |
def add_cumulative_files(workflow, output_file, input_files, out_dir,<EOL>execute_now=False, tags=None): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>llwadd_job = LigolwAddExecutable(workflow.cp, '<STR_LIT>',<EOL>ifo=output_file.ifo_list, out_dir=out_dir, tags=tags)<EOL>add_node = llwadd_job.create_node(output_file.segment, input_files,<EOL>output=output_file)<EOL>if file_needs_generating(add_node.output_files[<NUM_... | Function to combine a set of segment files into a single one. This function
will not merge the segment lists but keep each separate.
Parameters
-----------
workflow: pycbc.workflow.core.Workflow
An instance of the Workflow class that manages the workflow.
output_file: pycbc.workflow.core.File
The output file o... | f16007:m10 |
def find_playground_segments(segs): | <EOL>start_s2 = <NUM_LIT><EOL>playground_stride = <NUM_LIT><EOL>playground_length = <NUM_LIT><EOL>outlist = segments.segmentlist()<EOL>for seg in segs:<EOL><INDENT>start = seg[<NUM_LIT:0>]<EOL>end = seg[<NUM_LIT:1>]<EOL>playground_start = start_s2 + playground_stride * ( <NUM_LIT:1> +int(start-start_s2-playground_lengt... | Finds playground time in a list of segments.
Playground segments include the first 600s of every 6370s stride starting
at GPS time 729273613.
Parameters
----------
segs : segmentfilelist
A segmentfilelist to find playground segments.
Returns
-------
outlist :... | f16007:m11 |
def get_triggered_coherent_segment(workflow, sciencesegs): | <EOL>cp = workflow.cp<EOL>triggertime = int(os.path.basename(cp.get('<STR_LIT>', '<STR_LIT>')))<EOL>minduration = int(os.path.basename(cp.get('<STR_LIT>',<EOL>'<STR_LIT>')))<EOL>maxduration = int(os.path.basename(cp.get('<STR_LIT>',<EOL>'<STR_LIT>')))<EOL>onbefore = int(os.path.basename(cp.get('<STR_LIT>',<EOL>'<STR_LI... | Construct the coherent network on and off source segments. Can switch to
construction of segments for a single IFO search when coherent segments
are insufficient for a search.
Parameters
-----------
workflow : pycbc.workflow.core.Workflow
The workflow instance that the calculated segments belong to.
sciencesegs : ... | f16007:m12 |
def save_veto_definer(cp, out_dir, tags=None): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>make_analysis_dir(out_dir)<EOL>veto_def_url = cp.get_opt_tags("<STR_LIT>",<EOL>"<STR_LIT>", tags)<EOL>veto_def_base_name = os.path.basename(veto_def_url)<EOL>veto_def_new_path = os.path.abspath(os.path.join(out_dir,<EOL>veto_def_base_name))<EOL>resolve_url(veto_def_url... | Retrieve the veto definer file and save it locally
Parameters
-----------
cp : ConfigParser instance
out_dir : path
tags : list of strings
Used to retrieve subsections of the ini file for
configuration options. | f16007:m14 |
def parse_cat_ini_opt(cat_str): | if cat_str == "<STR_LIT>":<EOL><INDENT>return []<EOL><DEDENT>cat_groups = cat_str.split('<STR_LIT:U+002C>')<EOL>cat_sets = []<EOL>for group in cat_groups:<EOL><INDENT>group = group.strip()<EOL>cat_sets += [set(c for c in group)]<EOL><DEDENT>return cat_sets<EOL> | Parse a cat str from the ini file into a list of sets | f16007:m15 |
def cat_to_veto_def_cat(val): | if val == '<STR_LIT:1>':<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>if val == '<STR_LIT:2>':<EOL><INDENT>return <NUM_LIT:2><EOL><DEDENT>if val == '<STR_LIT:3>':<EOL><INDENT>return <NUM_LIT:4><EOL><DEDENT>if val == '<STR_LIT:H>':<EOL><INDENT>return <NUM_LIT:3><EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<... | Convert a category character to the corresponding value in the veto
definer file.
Parameters
----------
str : single character string
The input category character
Returns
-------
pipedown_str : str
The pipedown equivelant notation that can be passed to programs
that exp... | f16007:m16 |
def file_needs_generating(file_path, cp, tags=None): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>if cp.has_option_tags("<STR_LIT>",<EOL>"<STR_LIT>", tags):<EOL><INDENT>value = cp.get_opt_tags("<STR_LIT>",<EOL>"<STR_LIT>", tags)<EOL>generate_segment_files = value<EOL><DEDENT>else:<EOL><INDENT>generate_segment_files = '<STR_LIT>'<EOL><DEDENT>if os.path.isfile(file_p... | This job tests the file location and determines if the file should be
generated now or if an error should be raised. This uses the
generate_segment_files variable, global to this module, which is described
above and in the documentation.
Parameters
-----------
file_path : path
Location of file to check
cp : Config... | f16007:m17 |
def get_segments_file(workflow, name, option_name, out_dir): | from pycbc.dq import query_str<EOL>make_analysis_dir(out_dir)<EOL>cp = workflow.cp<EOL>start = workflow.analysis_time[<NUM_LIT:0>]<EOL>end = workflow.analysis_time[<NUM_LIT:1>]<EOL>veto_definer = None<EOL>if cp.has_option("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>veto_definer = save_veto_definer(workflow.cp, out_dir, [])<... | Get cumulative segments from option name syntax for each ifo.
Use syntax of configparser string to define the resulting segment_file
e.x. option_name = +up_flag1,+up_flag2,+up_flag3,-down_flag1,-down_flag2
Each ifo may have a different string and is stored separately in the file.
Flags which add time m... | f16007:m18 |
def setup_foreground_inference(workflow, coinc_file, single_triggers,<EOL>tmpltbank_file, insp_segs, insp_data_name,<EOL>insp_anal_name, dax_output, out_dir, tags=None): | logging.info("<STR_LIT>")<EOL>if not workflow.cp.has_section("<STR_LIT>"):<EOL><INDENT>logging.info("<STR_LIT>")<EOL>logging.info("<STR_LIT>")<EOL>return<EOL><DEDENT>tags = [] if tags is None else tags<EOL>makedir(dax_output)<EOL>config_path = os.path.abspath(dax_output + "<STR_LIT:/>" + "<STR_LIT:_>".join(tags)+ "<STR... | Creates workflow node that will run the inference workflow.
Parameters
----------
workflow: pycbc.workflow.Workflow
The core workflow instance we are populating
coinc_file: pycbc.workflow.File
The file associated with coincident triggers.
single_triggers: list of pycbc.workflow.File... | f16008:m0 |
def make_inference_prior_plot(workflow, config_file, output_dir,<EOL>sections=None, name="<STR_LIT>",<EOL>analysis_seg=None, tags=None): | <EOL>tags = [] if tags is None else tags<EOL>analysis_seg = workflow.analysis_timeif analysis_seg is None else analysis_seg<EOL>makedir(output_dir)<EOL>node = PlotExecutable(workflow.cp, name, ifos=workflow.ifos,<EOL>out_dir=output_dir, universe="<STR_LIT>",<EOL>tags=tags).create_node()<EOL>node.add_input_opt("<STR_LIT... | Sets up the corner plot of the priors in the workflow.
Parameters
----------
workflow: pycbc.workflow.Workflow
The core workflow instance we are populating
config_file: pycbc.workflow.File
The WorkflowConfigParser parasable inference configuration file..
output_dir: str
The ... | f16008:m1 |
def make_inference_summary_table(workflow, inference_file, output_dir,<EOL>variable_args=None, name="<STR_LIT>",<EOL>analysis_seg=None, tags=None): | <EOL>tags = [] if tags is None else tags<EOL>analysis_seg = workflow.analysis_timeif analysis_seg is None else analysis_seg<EOL>makedir(output_dir)<EOL>node = PlotExecutable(workflow.cp, name, ifos=workflow.ifos,<EOL>out_dir=output_dir, tags=tags).create_node()<EOL>node.add_input_opt("<STR_LIT>", inference_file)<EOL>no... | Sets up the corner plot of the posteriors in the workflow.
Parameters
----------
workflow: pycbc.workflow.Workflow
The core workflow instance we are populating
inference_file: pycbc.workflow.File
The file with posterior samples.
output_dir: str
The directory to store result ... | f16008:m2 |
def make_inference_posterior_plot(<EOL>workflow, inference_file, output_dir, parameters=None,<EOL>name="<STR_LIT>", analysis_seg=None, tags=None): | <EOL>tags = [] if tags is None else tags<EOL>analysis_seg = workflow.analysis_timeif analysis_seg is None else analysis_seg<EOL>makedir(output_dir)<EOL>node = PlotExecutable(workflow.cp, name, ifos=workflow.ifos,<EOL>out_dir=output_dir, universe="<STR_LIT>",<EOL>tags=tags).create_node()<EOL>node.add_input_opt("<STR_LIT... | Sets up the corner plot of the posteriors in the workflow.
Parameters
----------
workflow: pycbc.workflow.Workflow
The core workflow instance we are populating
inference_file: pycbc.workflow.File
The file with posterior samples.
output_dir: str
The directory to store result ... | f16008:m3 |
def make_inference_acceptance_rate_plot(workflow, inference_file, output_dir,<EOL>name="<STR_LIT>", analysis_seg=None, tags=None): | <EOL>tags = [] if tags is None else tags<EOL>analysis_seg = workflow.analysis_timeif analysis_seg is None else analysis_seg<EOL>makedir(output_dir)<EOL>node = PlotExecutable(workflow.cp, name, ifos=workflow.ifos,<EOL>out_dir=output_dir, tags=tags).create_node()<EOL>node.add_input_opt("<STR_LIT>", inference_file)<EOL>no... | Sets up the acceptance rate plot in the workflow.
Parameters
----------
workflow: pycbc.workflow.Workflow
The core workflow instance we are populating
inference_file: pycbc.workflow.File
The file with posterior samples.
output_dir: str
The directory to store result plots and... | f16008:m6 |
def make_inference_inj_plots(workflow, inference_files, output_dir,<EOL>parameters, name="<STR_LIT>",<EOL>analysis_seg=None, tags=None): | <EOL>tags = [] if tags is None else tags<EOL>analysis_seg = workflow.analysis_timeif analysis_seg is None else analysis_seg<EOL>output_files = FileList([])<EOL>makedir(output_dir)<EOL>for (ii, param) in enumerate(parameters):<EOL><INDENT>plot_exe = PlotExecutable(workflow.cp, name, ifos=workflow.ifos,<EOL>out_dir=outpu... | Sets up the recovered versus injected parameter plot in the workflow.
Parameters
----------
workflow: pycbc.workflow.Workflow
The core workflow instance we are populating
inference_files: pycbc.workflow.FileList
The files with posterior samples.
output_dir: str
The directory... | f16008:m7 |
def setup_matchedfltr_workflow(workflow, science_segs, datafind_outs,<EOL>tmplt_banks, output_dir=None,<EOL>injection_file=None, tags=None): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>logging.info("<STR_LIT>")<EOL>make_analysis_dir(output_dir)<EOL>cp = workflow.cp<EOL>mfltrMethod = cp.get_opt_tags("<STR_LIT>", "<STR_LIT>",<EOL>tags)<EOL>if mfltrMethod == "<STR_LIT>":<EOL><INDENT>logging.info("<STR_LIT>")<EOL>if cp.has_option_tags("<STR_LIT>",<EOL>"<... | This function aims to be the gateway for setting up a set of matched-filter
jobs in a workflow. This function is intended to support multiple
different ways/codes that could be used for doing this. For now the only
supported sub-module is one that runs the matched-filtering by setting up
a serious of matched-filtering ... | f16009:m0 |
def setup_matchedfltr_dax_generated(workflow, science_segs, datafind_outs,<EOL>tmplt_banks, output_dir,<EOL>injection_file=None,<EOL>tags=None, link_to_tmpltbank=False,<EOL>compatibility_mode=False): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>cp = workflow.cp<EOL>ifos = science_segs.keys()<EOL>match_fltr_exe = os.path.basename(cp.get('<STR_LIT>','<STR_LIT>'))<EOL>exe_class = select_matchedfilter_class(match_fltr_exe)<EOL>if link_to_tmpltbank:<EOL><INDENT>tmpltbank_exe = os.path.basename(cp.get('<STR_LIT>', ... | Setup matched-filter jobs that are generated as part of the workflow.
This
module can support any matched-filter code that is similar in principle to
lalapps_inspiral, but for new codes some additions are needed to define
Executable and Job sub-classes (see jobutils.py).
Parameters
-----------
workflow : pycbc.workflo... | f16009:m1 |
def setup_matchedfltr_dax_generated_multi(workflow, science_segs, datafind_outs,<EOL>tmplt_banks, output_dir,<EOL>injection_file=None,<EOL>tags=None, link_to_tmpltbank=False,<EOL>compatibility_mode=False): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>cp = workflow.cp<EOL>ifos = sorted(science_segs.keys())<EOL>match_fltr_exe = os.path.basename(cp.get('<STR_LIT>','<STR_LIT>'))<EOL>inspiral_outs = FileList([])<EOL>logging.info("<STR_LIT>" %('<STR_LIT:U+0020>'.join(ifos),))<EOL>if match_fltr_exe == '<STR_LIT>':<EOL><IN... | Setup matched-filter jobs that are generated as part of the workflow in
which a single job reads in and generates triggers over multiple ifos.
This
module can support any matched-filter code that is similar in principle to
pycbc_multi_inspiral or lalapps_coh_PTF_inspiral, but for new codes some
additions are needed to ... | f16009:m2 |
def convert_bank_to_hdf(workflow, xmlbank, out_dir, tags=None): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>if len(xmlbank) > <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>logging.info('<STR_LIT>')<EOL>make_analysis_dir(out_dir)<EOL>bank2hdf_exe = PyCBCBank2HDFExecutable(workflow.cp, '<STR_LIT>',<EOL>ifos=workflow.ifos,<EOL>out_dir=out_dir, tags=tags)<EO... | Return the template bank in hdf format | f16010:m4 |
def convert_trig_to_hdf(workflow, hdfbank, xml_trigger_files, out_dir, tags=None): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>logging.info('<STR_LIT>')<EOL>make_analysis_dir(out_dir)<EOL>trig_files = FileList()<EOL>for ifo, insp_group in zip(*xml_trigger_files.categorize_by_attr('<STR_LIT>')):<EOL><INDENT>trig2hdf_exe = PyCBCTrig2HDFExecutable(workflow.cp, '<STR_LIT>',<EOL>ifos=ifo, out_dir=o... | Return the list of hdf5 trigger files outputs | f16010:m5 |
def setup_interval_coinc_inj(workflow, hdfbank, full_data_trig_files, inj_trig_files,<EOL>stat_files, background_file, veto_file, veto_name, out_dir, tags=None): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>make_analysis_dir(out_dir)<EOL>logging.info('<STR_LIT>')<EOL>if len(hdfbank) > <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>hdfbank = hdfbank[<NUM_LIT:0>]<EOL>if len(workflow.ifos) > <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_... | This function sets up exact match coincidence and background estimation
using a folded interval technique. | f16010:m14 |
def setup_interval_coinc(workflow, hdfbank, trig_files, stat_files,<EOL>veto_files, veto_names, out_dir, tags=None): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>make_analysis_dir(out_dir)<EOL>logging.info('<STR_LIT>')<EOL>if len(hdfbank) != <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>' % len(hdfbank))<EOL><DEDENT>hdfbank = hdfbank[<NUM_LIT:0>]<EOL>if len(workflow.ifos) > <NUM_LIT:2>:<EOL><INDENT>raise V... | This function sets up exact match coincidence and background estimation
using a folded interval technique. | f16010:m15 |
def setup_multiifo_interval_coinc_inj(workflow, hdfbank, full_data_trig_files, inj_trig_files,<EOL>stat_files, background_file, veto_file, veto_name,<EOL>out_dir, pivot_ifo, fixed_ifo, tags=None): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>make_analysis_dir(out_dir)<EOL>logging.info('<STR_LIT>')<EOL>if len(hdfbank) != <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>' % len(hdfbank))<EOL><DEDENT>hdfbank = hdfbank[<NUM_LIT:0>]<EOL>factor = int(workflow.cp.get_opt_tags('<STR_LIT>', '<STR... | This function sets up exact match multiifo coincidence for injections | f16010:m16 |
def setup_multiifo_interval_coinc(workflow, hdfbank, trig_files, stat_files,<EOL>veto_files, veto_names, out_dir, pivot_ifo, fixed_ifo, tags=None): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>make_analysis_dir(out_dir)<EOL>logging.info('<STR_LIT>')<EOL>if len(hdfbank) != <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>' % len(hdfbank))<EOL><DEDENT>hdfbank = hdfbank[<NUM_LIT:0>]<EOL>ifos, _ = trig_files.categorize_by_attr('<STR_LIT>')<EOL... | This function sets up exact match multiifo coincidence | f16010:m17 |
def select_files_by_ifo_combination(ifocomb, insps): | inspcomb = FileList()<EOL>for ifo, ifile in zip(*insps.categorize_by_attr('<STR_LIT>')):<EOL><INDENT>if ifo in ifocomb:<EOL><INDENT>inspcomb += ifile<EOL><DEDENT><DEDENT>return inspcomb<EOL> | This function selects single-detector files ('insps') for a given ifo combination | f16010:m18 |
def get_ordered_ifo_list(ifocomb, ifo_ids): | <EOL>combination_prec = {ifo: ifo_ids[ifo] for ifo in ifocomb}<EOL>ordered_ifo_list = sorted(combination_prec, key = combination_prec.get)<EOL>pivot_ifo = ordered_ifo_list[<NUM_LIT:0>]<EOL>fixed_ifo = ordered_ifo_list[<NUM_LIT:1>]<EOL>return pivot_ifo, fixed_ifo, '<STR_LIT>'.join(ordered_ifo_list)<EOL> | This function sorts the combination of ifos (ifocomb) based on the given
precedence list (ifo_ids dictionary) and returns the first ifo as pivot
the second ifo as fixed, and the ordered list joined as a string. | f16010:m19 |
def setup_multiifo_combine_statmap(workflow, final_bg_file_list, out_dir, tags): | if tags is None:<EOL><INDENT>tags = []<EOL><DEDENT>make_analysis_dir(out_dir)<EOL>logging.info('<STR_LIT>')<EOL>cstat_exe = PyCBCMultiifoCombineStatmap(workflow.cp,<EOL>'<STR_LIT>',<EOL>ifos=workflow.ifos,<EOL>tags=tags,<EOL>out_dir=out_dir)<EOL>ifolist = '<STR_LIT:U+0020>'.join(workflow.ifos)<EOL>cluster_window = floa... | Combine the multiifo statmap files into one background file | f16010:m20 |
def frequency_noise_from_psd(psd, seed=None): | sigma = <NUM_LIT:0.5> * (psd / psd.delta_f) ** (<NUM_LIT:0.5>)<EOL>if seed is not None:<EOL><INDENT>numpy.random.seed(seed)<EOL><DEDENT>sigma = sigma.numpy()<EOL>dtype = complex_same_precision_as(psd)<EOL>not_zero = (sigma != <NUM_LIT:0>)<EOL>sigma_red = sigma[not_zero]<EOL>noise_re = numpy.random.normal(<NUM_LIT:0>, s... | Create noise with a given psd.
Return noise coloured with the given psd. The returned noise
FrequencySeries has the same length and frequency step as the given psd.
Note that if unique noise is desired a unique seed should be provided.
Parameters
----------
psd : FrequencySeries
The no... | f16012:m0 |
def noise_from_psd(length, delta_t, psd, seed=None): | noise_ts = TimeSeries(zeros(length), delta_t=delta_t)<EOL>if seed is None:<EOL><INDENT>seed = numpy.random.randint(<NUM_LIT:2>**<NUM_LIT:32>)<EOL><DEDENT>randomness = lal.gsl_rng("<STR_LIT>", seed)<EOL>N = int (<NUM_LIT:1.0> / delta_t / psd.delta_f)<EOL>n = N//<NUM_LIT:2>+<NUM_LIT:1><EOL>stride = N//<NUM_LIT:2><EOL>if ... | Create noise with a given psd.
Return noise with a given psd. Note that if unique noise is desired
a unique seed should be provided.
Parameters
----------
length : int
The length of noise to generate in samples.
delta_t : float
The time step of the noise.
psd : FrequencySer... | f16012:m1 |
def noise_from_string(psd_name, length, delta_t, seed=None, low_frequency_cutoff=<NUM_LIT>): | import pycbc.psd<EOL>delta_f = <NUM_LIT:1.0> / <NUM_LIT:8><EOL>flen = int(<NUM_LIT> / delta_t / delta_f) + <NUM_LIT:1><EOL>psd = pycbc.psd.from_string(psd_name, flen, delta_f, low_frequency_cutoff)<EOL>return noise_from_psd(int(length), delta_t, psd, seed=seed)<EOL> | Create noise from an analytic PSD
Return noise from the chosen PSD. Note that if unique noise is desired
a unique seed should be provided.
Parameters
----------
psd_name : str
Name of the analytic PSD to use.
low_fr
length : int
The length of noise to generate in samples.
... | f16012:m2 |
def block(seed): | num = SAMPLE_RATE * BLOCK_SIZE<EOL>rng = RandomState(seed % <NUM_LIT:2>**<NUM_LIT:32>)<EOL>variance = SAMPLE_RATE / <NUM_LIT:2><EOL>return rng.normal(size=num, scale=variance**<NUM_LIT:0.5>)<EOL> | Return block of normal random numbers
Parameters
----------
seed : {None, int}
The seed to generate the noise.sd
Returns
--------
noise : numpy.ndarray
Array of random numbers | f16013:m0 |
def normal(start, end, seed=<NUM_LIT:0>): | <EOL>s = int(start / BLOCK_SIZE)<EOL>e = int(end / BLOCK_SIZE)<EOL>if end % BLOCK_SIZE == <NUM_LIT:0>:<EOL><INDENT>e -= <NUM_LIT:1><EOL><DEDENT>sv = RandomState(seed).randint(-<NUM_LIT:2>**<NUM_LIT:50>, <NUM_LIT:2>**<NUM_LIT:50>)<EOL>data = numpy.concatenate([block(i + sv) for i in numpy.arange(s, e + <NUM_LIT:1>, <NUM... | Generate data with a white Gaussian (normal) distribution
Parameters
----------
start_time : int
Start time in GPS seconds to generate noise
end_time : int
End time in GPS seconds to generate nosie
seed : {None, int}
The seed to generate the noise.
Returns
--------
... | f16013:m1 |
def colored_noise(psd, start_time, end_time, seed=<NUM_LIT:0>, low_frequency_cutoff=<NUM_LIT:1.0>): | psd = psd.copy()<EOL>flen = int(SAMPLE_RATE / psd.delta_f) / <NUM_LIT:2> + <NUM_LIT:1><EOL>oldlen = len(psd)<EOL>psd.resize(flen)<EOL>max_val = psd.max()<EOL>for i in xrange(len(psd)):<EOL><INDENT>if i >= (oldlen-<NUM_LIT:1>):<EOL><INDENT>psd.data[i] = psd[oldlen - <NUM_LIT:2>]<EOL><DEDENT>if psd[i] == <NUM_LIT:0>:<EOL... | Create noise from a PSD
Return noise from the chosen PSD. Note that if unique noise is desired
a unique seed should be provided.
Parameters
----------
psd : pycbc.types.FrequencySeries
PSD to color the noise
start_time : int
Start time in GPS seconds to generate noise
end_t... | f16013:m2 |
def noise_from_string(psd_name, start_time, end_time, seed=<NUM_LIT:0>, low_frequency_cutoff=<NUM_LIT:1.0>): | delta_f = <NUM_LIT:1.0> / FILTER_LENGTH<EOL>flen = int(SAMPLE_RATE / delta_f) / <NUM_LIT:2> + <NUM_LIT:1><EOL>psd = pycbc.psd.from_string(psd_name, flen, delta_f, low_frequency_cutoff)<EOL>return colored_noise(psd, start_time, end_time,<EOL>seed=seed,<EOL>low_frequency_cutoff=low_frequency_cutoff)<EOL> | Create noise from an analytic PSD
Return noise from the chosen PSD. Note that if unique noise is desired
a unique seed should be provided.
Parameters
----------
psd_name : str
Name of the analytic PSD to use.
start_time : int
Start time in GPS seconds to generate noise
end_... | f16013:m3 |
def integral_element(mu, pdf): | dmu = mu[<NUM_LIT:1>:] - mu[:-<NUM_LIT:1>]<EOL>bin_mean = (pdf[<NUM_LIT:1>:] + pdf[:-<NUM_LIT:1>]) / <NUM_LIT><EOL>return dmu * bin_mean<EOL> | Returns an array of elements of the integrand dP = p(mu) dmu
for a density p(mu) defined at sample values mu ; samples need
not be equally spaced. Uses a simple trapezium rule.
Number of dP elements is 1 - (number of mu samples). | f16014:m0 |
def normalize_pdf(mu, pofmu): | if min(pofmu) < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if min(mu) < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>dp = integral_element(mu, pofmu)<EOL>return mu, pofmu/sum(dp)<EOL> | Takes a function pofmu defined at rate sample values mu and
normalizes it to be a suitable pdf. Both mu and pofmu must be
arrays or lists of the same length. | f16014:m1 |
def compute_upper_limit(mu_in, post, alpha=<NUM_LIT>): | if <NUM_LIT:0> < alpha < <NUM_LIT:1>:<EOL><INDENT>dp = integral_element(mu_in, post)<EOL>high_idx = bisect.bisect_left(dp.cumsum() / dp.sum(), alpha)<EOL>mu_high = mu_in[high_idx]<EOL><DEDENT>elif alpha == <NUM_LIT:1>:<EOL><INDENT>mu_high = numpy.max(mu_in[post > <NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>raise ValueE... | Returns the upper limit mu_high of confidence level alpha for a
posterior distribution post on the given parameter mu.
The posterior need not be normalized. | f16014:m2 |
def compute_lower_limit(mu_in, post, alpha=<NUM_LIT>): | if <NUM_LIT:0> < alpha < <NUM_LIT:1>:<EOL><INDENT>dp = integral_element(mu_in, post)<EOL>low_idx = bisect.bisect_right(dp.cumsum() / dp.sum(), <NUM_LIT:1> - alpha)<EOL>mu_low = mu_in[low_idx]<EOL><DEDENT>elif alpha == <NUM_LIT:1>:<EOL><INDENT>mu_low = numpy.min(mu_in[post > <NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>r... | Returns the lower limit mu_low of confidence level alpha for a
posterior distribution post on the given parameter mu.
The posterior need not be normalized. | f16014:m3 |
def confidence_interval_min_width(mu, post, alpha=<NUM_LIT>): | if not <NUM_LIT:0> < alpha < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>alpha_step = <NUM_LIT><EOL>mu_low = numpy.min(mu)<EOL>mu_high = numpy.max(mu)<EOL>for ai in numpy.arange(<NUM_LIT:0>, <NUM_LIT:1> - alpha, alpha_step):<EOL><INDENT>ml = compute_lower_limit(mu, post, <NUM_LIT:1> - ai)<EOL>mh ... | Returns the minimal-width confidence interval [mu_low, mu_high] of
confidence level alpha for a posterior distribution post on the parameter mu. | f16014:m4 |
def hpd_coverage(mu, pdf, thresh): | dp = integral_element(mu, pdf)<EOL>bin_mean = (pdf[<NUM_LIT:1>:] + pdf[:-<NUM_LIT:1>]) / <NUM_LIT><EOL>return dp[bin_mean > thresh].sum()<EOL> | Integrates a pdf over mu taking only bins where
the mean over the bin is above a given threshold
This gives the coverage of the HPD interval for
the given threshold. | f16014:m5 |
def hpd_threshold(mu_in, post, alpha, tol): | norm_post = normalize_pdf(mu_in, post)<EOL>p_minus = <NUM_LIT:0.0><EOL>p_plus = max(post)<EOL>while abs(hpd_coverage(mu_in, norm_post, p_minus) -<EOL>hpd_coverage(mu_in, norm_post, p_plus)) >= tol:<EOL><INDENT>p_test = (p_minus + p_plus) / <NUM_LIT><EOL>if hpd_coverage(mu_in, post, p_test) >= alpha:<EOL><INDENT>p_minus... | For a PDF post over samples mu_in, find a density
threshold such that the region having higher density
has coverage of at least alpha, and less than alpha
plus a given tolerance. | f16014:m6 |
def hpd_credible_interval(mu_in, post, alpha=<NUM_LIT>, tolerance=<NUM_LIT>): | if alpha == <NUM_LIT:1>:<EOL><INDENT>nonzero_samples = mu_in[post > <NUM_LIT:0>]<EOL>mu_low = numpy.min(nonzero_samples)<EOL>mu_high = numpy.max(nonzero_samples)<EOL><DEDENT>elif <NUM_LIT:0> < alpha < <NUM_LIT:1>:<EOL><INDENT>pthresh = hpd_threshold(mu_in, post, alpha, tol=tolerance)<EOL>samples_over_threshold = mu_in[... | Returns the minimum and maximum rate values of the HPD
(Highest Posterior Density) credible interval for a posterior
post defined at the sample values mu_in. Samples need not be
uniformly spaced and posterior need not be normalized.
Will not return a correct credible interval if the posterior
is multimodal and the co... | f16014:m7 |
def compute_efficiency(f_dist, m_dist, dbins): | efficiency = numpy.zeros(len(dbins) - <NUM_LIT:1>)<EOL>error = numpy.zeros(len(dbins) - <NUM_LIT:1>)<EOL>for j, dlow in enumerate(dbins[:-<NUM_LIT:1>]):<EOL><INDENT>dhigh = dbins[j + <NUM_LIT:1>]<EOL>found = numpy.sum((dlow <= f_dist) * (f_dist < dhigh))<EOL>missed = numpy.sum((dlow <= m_dist) * (m_dist < dhigh))<EOL>i... | Compute the efficiency as a function of distance for the given sets of found
and missed injection distances.
Note that injections that do not fit into any dbin get lost :( | f16014:m9 |
def filter_injections_by_mass(injs, mbins, bin_num, bin_type, bin_num2=None): | if bin_type == "<STR_LIT>":<EOL><INDENT>m1bins = numpy.concatenate((mbins.lower()[<NUM_LIT:0>],<EOL>numpy.array([mbins.upper()[<NUM_LIT:0>][-<NUM_LIT:1>]])))<EOL>m1lo = m1bins[bin_num]<EOL>m1hi = m1bins[bin_num + <NUM_LIT:1>]<EOL>m2bins = numpy.concatenate((mbins.lower()[<NUM_LIT:1>],<EOL>numpy.array([mbins.upper()[<NU... | For a given set of injections (sim_inspiral rows), return the subset
of injections that fall within the given mass range. | f16014:m11 |
def compute_volume_vs_mass(found, missed, mass_bins, bin_type, dbins=None): | <EOL>volArray = bin_utils.BinnedArray(mass_bins)<EOL>vol2Array = bin_utils.BinnedArray(mass_bins)<EOL>foundArray = bin_utils.BinnedArray(mass_bins)<EOL>missedArray = bin_utils.BinnedArray(mass_bins)<EOL>effvmass = []<EOL>errvmass = []<EOL>if bin_type == "<STR_LIT>":<EOL><INDENT>for j, mc1 in enumerate(mass_bins.centres... | Compute the average luminosity an experiment was sensitive to
Assumes that luminosity is uniformly distributed in space.
Input is the sets of found and missed injections. | f16014:m12 |
def get_cosmology(cosmology=None, **kwargs): | if kwargs and cosmology is not None:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if isinstance(cosmology, astropy.cosmology.FlatLambdaCDM):<EOL><INDENT>return cosmology<EOL><DEDENT>if kwargs:<EOL><INDENT>cosmology = astropy.cosmology.FlatLambdaCDM(**kwargs)<EOL><DEDENT>else:<EOL><INDENT>if cos... | r"""Gets an astropy cosmology class.
Parameters
----------
cosmology : str or astropy.cosmology.FlatLambdaCDM, optional
The name of the cosmology to use. For the list of options, see
:py:attr:`astropy.cosmology.parameters.available`. If None, and no
other keyword arguments are provi... | f16015:m0 |
def z_at_value(func, fval, unit, zmax=<NUM_LIT>, **kwargs): | fval, input_is_array = ensurearray(fval)<EOL>if fval.size == <NUM_LIT:1> and fval.ndim == <NUM_LIT:0>:<EOL><INDENT>fval = fval.reshape(<NUM_LIT:1>)<EOL><DEDENT>zs = numpy.zeros(fval.shape, dtype=float) <EOL>for (ii, val) in enumerate(fval):<EOL><INDENT>try:<EOL><INDENT>zs[ii] = astropy.cosmology.z_at_value(func, val*u... | r"""Wrapper around astropy.cosmology.z_at_value to handle numpy arrays.
Getting a z for a cosmological quantity involves numerically inverting
``func``. The ``zmax`` argument sets how large of a z to guess (see
:py:func:`astropy.cosmology.z_at_value` for details). If a z is larger than
``zmax``, this w... | f16015:m1 |
def _redshift(distance, **kwargs): | cosmology = get_cosmology(**kwargs)<EOL>return z_at_value(cosmology.luminosity_distance, distance, units.Mpc)<EOL> | r"""Uses astropy to get redshift from the given luminosity distance.
Parameters
----------
distance : float
The luminosity distance, in Mpc.
\**kwargs :
All other keyword args are passed to :py:func:`get_cosmology` to
select a cosmology. If none provided, will use
:py:at... | f16015:m2 |
def redshift(distance, **kwargs): | cosmology = get_cosmology(**kwargs)<EOL>try:<EOL><INDENT>z = _d2zs[cosmology.name](distance)<EOL><DEDENT>except KeyError:<EOL><INDENT>z = _redshift(distance, cosmology=cosmology)<EOL><DEDENT>return z<EOL> | r"""Returns the redshift associated with the given luminosity distance.
If the requested cosmology is one of the pre-defined ones in
:py:attr:`astropy.cosmology.parameters.available`, :py:class:`DistToZ` is
used to provide a fast interpolation. This takes a few seconds to setup
on the first call.
... | f16015:m3 |
def redshift_from_comoving_volume(vc, **kwargs): | cosmology = get_cosmology(**kwargs)<EOL>return z_at_value(cosmology.comoving_volume, vc, units.Mpc**<NUM_LIT:3>)<EOL> | r"""Returns the redshift from the given comoving volume.
Parameters
----------
vc : float
The comoving volume, in units of cubed Mpc.
\**kwargs :
All other keyword args are passed to :py:func:`get_cosmology` to
select a cosmology. If none provided, will use
:py:attr:`DEF... | f16015:m4 |
def distance_from_comoving_volume(vc, **kwargs): | cosmology = get_cosmology(**kwargs)<EOL>z = redshift_from_comoving_volume(vc, cosmology=cosmology)<EOL>return cosmology.luminosity_distance(z).value<EOL> | r"""Returns the luminosity distance from the given comoving volume.
Parameters
----------
vc : float
The comoving volume, in units of cubed Mpc.
\**kwargs :
All other keyword args are passed to :py:func:`get_cosmology` to
select a cosmology. If none provided, will use
:p... | f16015:m5 |
def cosmological_quantity_from_redshift(z, quantity, strip_unit=True,<EOL>**kwargs): | cosmology = get_cosmology(**kwargs)<EOL>val = getattr(cosmology, quantity)(z)<EOL>if strip_unit:<EOL><INDENT>val = val.value<EOL><DEDENT>return val<EOL> | r"""Returns the value of a cosmological quantity (e.g., age) at a redshift.
Parameters
----------
z : float
The redshift.
quantity : str
The name of the quantity to get. The name may be any attribute of
:py:class:`astropy.cosmology.FlatLambdaCDM`.
strip_unit : bool, optional... | f16015:m6 |
def setup_interpolant(self): | <EOL>zs = numpy.linspace(<NUM_LIT:0.>, <NUM_LIT:1.>, num=self.numpoints)<EOL>ds = self.cosmology.luminosity_distance(zs).value<EOL>self.nearby_d2z = interpolate.interp1d(ds, zs, kind='<STR_LIT>',<EOL>bounds_error=False)<EOL>zs = numpy.logspace(<NUM_LIT:0>, numpy.log10(self.default_maxz),<EOL>num=self.numpoints)<EOL>ds ... | Initializes the z(d) interpolation. | f16015:c0:m1 |
def get_redshift(self, dist): | dist, input_is_array = ensurearray(dist)<EOL>try:<EOL><INDENT>zs = self.nearby_d2z(dist)<EOL><DEDENT>except TypeError:<EOL><INDENT>self.setup_interpolant()<EOL>zs = self.nearby_d2z(dist)<EOL><DEDENT>replacemask = numpy.isnan(zs)<EOL>if replacemask.any():<EOL><INDENT>zs[replacemask] = self.faraway_d2z(dist[replacemask])... | Returns the redshift for the given distance. | f16015:c0:m2 |
def process_full_data(fname, rhomin, mass1, mass2, lo_mchirp, hi_mchirp): | with h5py.File(fname, '<STR_LIT:r>') as bulk:<EOL><INDENT>id_bkg = bulk['<STR_LIT>'][:]<EOL>id_fg = bulk['<STR_LIT>'][:]<EOL>mchirp_bkg = mchirp_from_mass1_mass2(mass1[id_bkg], mass2[id_bkg])<EOL>bound = np.sign((mchirp_bkg - lo_mchirp) * (hi_mchirp - mchirp_bkg))<EOL>idx_bkg = np.where(bound == <NUM_LIT:1>)<EOL>mchirp... | Read the zero-lag and time-lag triggers identified by templates in
a specified range of chirp mass.
Parameters
----------
hdfile:
File that stores all the triggers
rhomin: float
Minimum value of SNR threhold (will need including ifar)
mass1: array
... | f16017:m0 |
def save_bkg_falloff(fname_statmap, fname_bank, path, rhomin, lo_mchirp, hi_mchirp): | with h5py.File(fname_bank, '<STR_LIT:r>') as bulk:<EOL><INDENT>mass1_bank = bulk['<STR_LIT>'][:]<EOL>mass2_bank = bulk['<STR_LIT>'][:]<EOL>full_data = process_full_data(fname_statmap, rhomin,<EOL>mass1_bank, mass2_bank, lo_mchirp, hi_mchirp)<EOL><DEDENT>max_bg_stat = np.max(full_data['<STR_LIT>'])<EOL>bg_bins = np.lins... | Read the STATMAP files to derive snr falloff for the background events.
Save the output to a txt file
Bank file is also provided to restrict triggers to BBH templates.
Parameters
----------
fname_statmap: string
STATMAP file containing trigger information
... | f16017:m1 |
def log_rho_bg(trigs, bins, counts): | trigs = np.atleast_1d(trigs)<EOL>N = sum(counts)<EOL>assert np.all(trigs >= np.min(bins)),'<STR_LIT>'<EOL>if np.any(trigs >= np.max(bins)):<EOL><INDENT>N = N + <NUM_LIT:1><EOL><DEDENT>log_rhos = []<EOL>for t in trigs:<EOL><INDENT>if t >= np.max(bins):<EOL><INDENT>log_rhos.append(-log(N)-log(np.max(trigs) - bins[-<NUM_L... | Calculate the log of background fall-off
Parameters
----------
trigs: array
SNR values of all the triggers
bins: string
bins for histogrammed triggers
path: string
counts for histogrammed triggers
Returns
-------
... | f16017:m2 |
def fgmc(log_fg_ratios, mu_log_vt, sigma_log_vt, Rf, maxfg): | Lb = np.random.uniform(<NUM_LIT:0.>, maxfg, len(Rf))<EOL>pquit = <NUM_LIT:0><EOL>while pquit < <NUM_LIT:0.1>:<EOL><INDENT>nsamp = len(Lb)<EOL>Rf_sel = np.random.choice(Rf, nsamp)<EOL>vt = np.random.lognormal(mu_log_vt, sigma_log_vt, len(Rf_sel))<EOL>Lf = Rf_sel * vt<EOL>log_Lf, log_Lb = log(Lf), log(Lb)<EOL>plR = <NUM_... | Function to fit the likelihood Fixme | f16017:m4 |
def _optm(x, alpha, mu, sigma): | return ss.skewnorm.pdf(x, alpha, mu, sigma)<EOL> | Return probability density of skew-lognormal
See scipy.optimize.curve_fit | f16017:m5 |
def fit(R): | lR = np.log(R)<EOL>mu_norm, sigma_norm = np.mean(lR), np.std(lR)<EOL>xs = np.linspace(min(lR), max(lR), <NUM_LIT:200>)<EOL>kde = ss.gaussian_kde(lR)<EOL>pxs = kde(xs)<EOL>ff = optimize.curve_fit(_optm, xs, pxs, p0 = [<NUM_LIT:0.1>, mu_norm, sigma_norm])[<NUM_LIT:0>]<EOL>return ff[<NUM_LIT:0>], ff[<NUM_LIT:1>], ff[<NUM_... | Fit skew - lognormal to the rate samples achived from a prior analysis
Parameters
----------
R: array
Rate samples
Returns
-------
ff[0]: float
The skewness
ff[1]: float
The mean
ff[2]: float
The standard devi... | f16017:m6 |
def skew_lognormal_samples(alpha, mu, sigma, minrp, maxrp): | nsamp = <NUM_LIT><EOL>lRu = np.random.uniform(minrp, maxrp, nsamp)<EOL>plRu = ss.skewnorm.pdf(lRu, alpha, mu, sigma)<EOL>rndn = np.random.random(nsamp)<EOL>maxp = max(plRu)<EOL>idx = np.where(plRu/maxp > rndn)<EOL>log_Rf = lRu[idx]<EOL>Rfs = np.exp(log_Rf)<EOL>return Rfs<EOL> | Returns a large number of Skew lognormal samples
Parameters
----------
alpha: float
Skewness of the distribution
mu: float
Mean of the distribution
sigma: float
Scale of the distribution
minrp: float
Minimum value for the sample... | f16017:m7 |
def prob_lnm(m1, m2, s1z, s2z, **kwargs): | min_mass = kwargs.get('<STR_LIT>', <NUM_LIT>)<EOL>max_mass = kwargs.get('<STR_LIT>', <NUM_LIT>)<EOL>max_mtotal = min_mass + max_mass<EOL>m1, m2 = np.array(m1), np.array(m2)<EOL>C_lnm = integrate.quad(lambda x: (log(max_mtotal - x) - log(min_mass))/x, min_mass, max_mass)[<NUM_LIT:0>]<EOL>xx = np.minimum(m1, m2)<EOL>m1 =... | Return probability density for uniform in log
Parameters
----------
m1: array
Component masses 1
m2: array
Component masses 2
s1z: array
Aligned spin 1(Not in use currently)
s2z:
Aligned spin 2(Not in use currently)
... | f16017:m8 |
def prob_imf(m1, m2, s1z, s2z, **kwargs): | min_mass = kwargs.get('<STR_LIT>', <NUM_LIT>)<EOL>max_mass = kwargs.get('<STR_LIT>', <NUM_LIT>)<EOL>alpha = kwargs.get('<STR_LIT>', -<NUM_LIT>)<EOL>max_mtotal = min_mass + max_mass<EOL>m1, m2 = np.array(m1), np.array(m2)<EOL>C_imf = max_mass**(alpha + <NUM_LIT:1>)/(alpha + <NUM_LIT:1>)<EOL>C_imf -= min_mass**(alpha + <... | Return probability density for power-law
Parameters
----------
m1: array
Component masses 1
m2: array
Component masses 2
s1z: array
Aligned spin 1(Not in use currently)
s2z:
Aligned spin 2(Not in use currently)
**kwa... | f16017:m9 |
def prob_flat(m1, m2, s1z, s2z, **kwargs): | min_mass = kwargs.get('<STR_LIT>', <NUM_LIT:1.>)<EOL>max_mass = kwargs.get('<STR_LIT>', <NUM_LIT>)<EOL>bound = np.sign(m1 - m2)<EOL>bound += np.sign(max_mass - m1) * np.sign(m2 - min_mass)<EOL>idx = np.where(bound != <NUM_LIT:2>)<EOL>p_m1_m2 = <NUM_LIT> / (max_mass - min_mass)**<NUM_LIT:2><EOL>p_m1_m2[idx] = <NUM_LIT:0... | Return probability density for uniform in component mass
Parameters
----------
m1: array
Component masses 1
m2: array
Component masses 2
s1z: array
Aligned spin 1 (not in use currently)
s2z:
Aligned spin 2 (not in use curren... | f16017:m10 |
def draw_imf_samples(**kwargs): | alpha_salpeter = kwargs.get('<STR_LIT>', -<NUM_LIT>)<EOL>nsamples = kwargs.get('<STR_LIT>', <NUM_LIT:1>)<EOL>min_mass = kwargs.get('<STR_LIT>', <NUM_LIT>)<EOL>max_mass = kwargs.get('<STR_LIT>', <NUM_LIT>)<EOL>max_mtotal = min_mass + max_mass<EOL>a = (max_mass/min_mass)**(alpha_salpeter + <NUM_LIT:1.0>) - <NUM_LIT:1.0><... | Draw samples for power-law model
Parameters
----------
**kwargs: string
Keyword arguments as model parameters and number of samples
Returns
-------
array
The first mass
array
The second mass | f16017:m11 |
def draw_lnm_samples(**kwargs): | <EOL>nsamples = kwargs.get('<STR_LIT>', <NUM_LIT:1>)<EOL>min_mass = kwargs.get('<STR_LIT>', <NUM_LIT>)<EOL>max_mass = kwargs.get('<STR_LIT>', <NUM_LIT>)<EOL>max_mtotal = min_mass + max_mass<EOL>lnmmin = log(min_mass)<EOL>lnmmax = log(max_mass)<EOL>k = nsamples * int(<NUM_LIT> + log(<NUM_LIT:1> + <NUM_LIT>/nsamples))<EO... | Draw samples for uniform-in-log model
Parameters
----------
**kwargs: string
Keyword arguments as model parameters and number of samples
Returns
-------
array
The first mass
array
The second mass | f16017:m12 |
def draw_flat_samples(**kwargs): | <EOL>nsamples = kwargs.get('<STR_LIT>', <NUM_LIT:1>)<EOL>min_mass = kwargs.get('<STR_LIT>', <NUM_LIT:1.>)<EOL>max_mass = kwargs.get('<STR_LIT>', <NUM_LIT>)<EOL>m1 = np.random.uniform(min_mass, max_mass, nsamples)<EOL>m2 = np.random.uniform(min_mass, max_mass, nsamples)<EOL>return np.maximum(m1, m2), np.minimum(m1, m2)<... | Draw samples for uniform in mass
Parameters
----------
**kwargs: string
Keyword arguments as model parameters and number of samples
Returns
-------
array
The first mass
array
The second mass | f16017:m13 |
def mchirp_sampler_lnm(**kwargs): | m1, m2 = draw_lnm_samples(**kwargs)<EOL>mchirp_astro = mchirp_from_mass1_mass2(m1, m2)<EOL>return mchirp_astro<EOL> | Draw chirp mass samples for uniform-in-log model
Parameters
----------
**kwargs: string
Keyword arguments as model parameters and number of samples
Returns
-------
mchirp-astro: array
The chirp mass samples for the population | f16017:m14 |
def mchirp_sampler_imf(**kwargs): | m1, m2 = draw_imf_samples(**kwargs)<EOL>mchirp_astro = mchirp_from_mass1_mass2(m1, m2)<EOL>return mchirp_astro<EOL> | Draw chirp mass samples for power-law model
Parameters
----------
**kwargs: string
Keyword arguments as model parameters and number of samples
Returns
-------
mchirp-astro: array
The chirp mass samples for the population | f16017:m15 |
def mchirp_sampler_flat(**kwargs): | m1, m2 = draw_flat_samples(**kwargs)<EOL>mchirp_astro = mchirp_from_mass1_mass2(m1, m2)<EOL>return mchirp_astro<EOL> | Draw chirp mass samples for flat in mass model
Parameters
----------
**kwargs: string
Keyword arguments as model parameters and number of samples
Returns
-------
mchirp-astro: array
The chirp mass samples for the population | f16017:m16 |
def read_injections(sim_files, m_dist, s_dist, d_dist): | injections = {}<EOL>min_d, max_d = <NUM_LIT>, <NUM_LIT:0><EOL>nf = len(sim_files)<EOL>for i in range(nf):<EOL><INDENT>key = str(i)<EOL>injections[key] = process_injections(sim_files[i])<EOL>injections[key]['<STR_LIT>'] = sim_files[i]<EOL>injections[key]['<STR_LIT>'] = m_dist[i]<EOL>injections[key]['<STR_LIT>'] = s_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
---... | f16018:m0 |
def estimate_vt(injections, mchirp_sampler, model_pdf, **kwargs):<EOL> | thr_var = kwargs.get('<STR_LIT>')<EOL>thr_val = kwargs.get('<STR_LIT>')<EOL>nsamples = <NUM_LIT> <EOL>injections = copy.deepcopy(injections)<EOL>min_z, max_z = injections['<STR_LIT>']<EOL>V = quad(contracted_dVdc, <NUM_LIT:0.>, max_z)[<NUM_LIT:0>]<EOL>z_astro = astro_redshifts(min_z, max_z, nsamples)<EOL>astro_lum_dist... | Based on injection strategy and the desired astro model estimate the injected volume.
Scale injections and estimate sensitive volume.
Parameters
----------
injections: dictionary
Dictionary obtained after reading injections from read_injections
mchirp_sampler: function
... | f16018:m1 |
def process_injections(hdffile): | data = {}<EOL>with h5py.File(hdffile, '<STR_LIT:r>') as inp:<EOL><INDENT>found_index = inp['<STR_LIT>'][:]<EOL>for param in _save_params:<EOL><INDENT>data[param] = inp['<STR_LIT>'+param][:]<EOL><DEDENT>ifar = np.zeros_like(data[_save_params[<NUM_LIT:0>]])<EOL>ifar[found_index] = inp['<STR_LIT>'][:]<EOL>data['<STR_LIT>'... | 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 ... | f16018:m2 |
def dlum_to_z(dl): | return _dlum_interp(dl)<EOL> | Get the redshift for a luminosity distance
Parameters
----------
dl: array
The array of luminosity distances
Returns
-------
array
The redshift values corresponding to the luminosity distances | f16018:m3 |
def astro_redshifts(min_z, max_z, nsamples): | dz, fac = <NUM_LIT>, <NUM_LIT><EOL>V = quad(contracted_dVdc, <NUM_LIT:0.>, max_z)[<NUM_LIT:0>]<EOL>zbins = np.arange(min_z, max_z + dz/<NUM_LIT>, dz)<EOL>zcenter = (zbins[:-<NUM_LIT:1>] + zbins[<NUM_LIT:1>:]) / <NUM_LIT:2><EOL>pdfz = cosmo.differential_comoving_volume(zcenter).value/(<NUM_LIT:1>+zcenter)/V<EOL>int_pdf ... | 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
-------
... | f16018:m4 |
def pdf_z_astro(z, V_min, V_max): | return contracted_dVdc(z)/(V_max - V_min)<EOL> | Get the probability density for the rate of events
at a redshift assuming standard cosmology | f16018:m5 |
def inj_mass_pdf(key, mass1, mass2, lomass, himass, lomass_2 = <NUM_LIT:0>, himass_2 = <NUM_LIT:0>): | mass1, mass2 = np.array(mass1), np.array(mass2)<EOL>if key == '<STR_LIT>':<EOL><INDENT>bound = np.sign((lomass + himass) - (mass1 + mass2))<EOL>bound += np.sign((himass - mass1)*(mass1 - lomass))<EOL>bound += np.sign((himass - mass2)*(mass2 - lomass))<EOL>idx = np.where(bound != <NUM_LIT:3>)<EOL>pdf = <NUM_LIT:1.>/(him... | 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 m... | f16018:m7 |
def inj_spin_pdf(key, high_spin, spinz): | <EOL>if spinz[<NUM_LIT:0>] == <NUM_LIT:0>:<EOL><INDENT>return np.ones_like(spinz)<EOL><DEDENT>spinz = np.array(spinz)<EOL>bound = np.sign(np.absolute(high_spin) - np.absolute(spinz))<EOL>bound += np.sign(<NUM_LIT:1> - np.absolute(spinz))<EOL>if key == '<STR_LIT>':<EOL><INDENT>pdf = (np.log(high_spin - np.log(abs(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) | f16018:m8 |
def inj_distance_pdf(key, distance, low_dist, high_dist, mchirp = <NUM_LIT:1>): | distance = np.array(distance)<EOL>if key == '<STR_LIT>':<EOL><INDENT>pdf = np.ones_like(distance)/(high_dist - low_dist)<EOL>bound = np.sign((high_dist - distance)*(distance - low_dist))<EOL>idx = np.where(bound != <NUM_LIT:1>)<EOL>pdf[idx] = <NUM_LIT:0><EOL>return pdf<EOL><DEDENT>if key == '<STR_LIT>':<EOL><INDENT>wei... | 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... | f16018:m9 |
def insert_processing_option_group(parser): | processing_group = parser.add_argument_group("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>processing_group.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>" + str(list(set(scheme_prefix.values()))) +<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<S... | Adds the options used to choose a processing scheme. This should be used
if your program supports the ability to select the processing scheme.
Parameters
----------
parser : object
OptionParser instance | f16019:m5 |
def from_cli(opt): | scheme_str = opt.processing_scheme.split('<STR_LIT::>')<EOL>name = scheme_str[<NUM_LIT:0>]<EOL>if name == "<STR_LIT>":<EOL><INDENT>logging.info("<STR_LIT>")<EOL>ctx = CUDAScheme(opt.processing_device_id)<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>if len(scheme_str) > <NUM_LIT:1>:<EOL><INDENT>numt = scheme_str[<N... | Parses the command line options and returns a precessing scheme.
Parameters
----------
opt: object
Result of parsing the CLI with OptionParser, or any object with
the required attributes.
Returns
-------
ctx: Scheme
Returns the requested processing scheme. | f16019:m6 |
def verify_processing_options(opt, parser): | scheme_types = scheme_prefix.values()<EOL>if opt.processing_scheme.split('<STR_LIT::>')[<NUM_LIT:0>] not in scheme_types:<EOL><INDENT>parser.error("<STR_LIT>")<EOL><DEDENT> | Parses the processing scheme options and verifies that they are
reasonable.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes.
parser : object
OptionParser instance. | f16019:m7 |
def complex_median(complex_list): | median_real = numpy.median([complex_number.real<EOL>for complex_number in complex_list])<EOL>median_imag = numpy.median([complex_number.imag<EOL>for complex_number in complex_list])<EOL>return median_real + <NUM_LIT>*median_imag<EOL> | 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. | f16021:m0 |
def avg_inner_product(data1, data2, bin_size): | assert data1.duration == data2.duration<EOL>assert data1.sample_rate == data2.sample_rate<EOL>seglen = int(bin_size * data1.sample_rate)<EOL>inner_prod = []<EOL>for idx in range(int(data1.duration / bin_size)):<EOL><INDENT>start, end = idx * seglen, (idx+<NUM_LIT:1>) * seglen<EOL>norm = len(data1[start:end])<EOL>bin_pr... | 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 d... | f16021:m1 |
def line_model(freq, data, tref, amp=<NUM_LIT:1>, phi=<NUM_LIT:0>): | freq_line = TimeSeries(zeros(len(data)), delta_t=data.delta_t,<EOL>epoch=data.start_time)<EOL>times = data.sample_times - float(tref)<EOL>alpha = <NUM_LIT:2> * numpy.pi * freq * times + phi<EOL>freq_line.data = amp * numpy.exp(<NUM_LIT> * alpha)<EOL>return freq_line<EOL> | 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}, op... | f16021:m2 |
def matching_line(freq, data, tref, bin_size=<NUM_LIT:1>): | template_line = line_model(freq, data, tref=tref)<EOL>_, amp, phi = avg_inner_product(data, template_line,<EOL>bin_size=bin_size)<EOL>return line_model(freq, data, tref=tref, amp=amp, phi=phi)<EOL> | 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.
b... | f16021:m3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.