def coinc_without_inj(coinc, tmpdir): """Produce a coinc.xml file with the found coincs stripped out.""" filename = str(tmpdir / 'coinc_without_inj.xml') xmldoc = ligolw_utils.load_filename(coinc, contenthandler=ContentHandler) # Prune coinc_def table coinc_def_table = lsctables.CoincDefTable.get_table(xmldoc) included = [row for row in coinc_def_table if row.search_coinc_type == InspiralCoincDef.search_coinc_type and row.search == InspiralCoincDef.search] included_coinc_def_ids = {row.coinc_def_id for row in included} coinc_def_table[:] = included # Prune coinc table coinc_table = lsctables.CoincTable.get_table(xmldoc) included = [row for row in coinc_table if row.coinc_def_id in included_coinc_def_ids] included_coinc_ids = {row.coinc_event_id for row in included} coinc_table[:] = included # Prune coinc_map table coinc_map_table = lsctables.CoincMapTable.get_table(xmldoc) coinc_map_table[:] = [row for row in coinc_map_table if row.coinc_event_id in included_coinc_ids] ligolw_utils.write_filename(xmldoc, filename) return filename
def write_bank(filename, banks, verbose=False): """Write template bank to LIGO_LW xml file.""" xmldoc = ligolw.Document() head = xmldoc.appendChild(ligolw.LIGO_LW()) head.Name = u"gstlal_template_bank" for bank in banks: cloned_table = bank.sngl_inspiral_table.copy() cloned_table.extend(bank.sngl_inspiral_table) head.appendChild(cloned_table) head.appendChild( ligolw_param.Param.from_pyvalue('template_bank_filename', bank.template_bank_filename)) head.appendChild( ligolw_param.Param.from_pyvalue('sample_rate', bank.sample_rate)) head.appendChild( ligolw_param.Param.from_pyvalue('bank_id', bank.bank_id)) head.appendChild(ligolw_array.Array.build('templates', bank.templates)) head.appendChild( ligolw_array.Array.build('autocorrelation_bank', bank.autocorrelation_bank)) head.appendChild( ligolw_array.Array.build('autocorrelation_mask', bank.autocorrelation_mask)) head.appendChild( ligolw_array.Array.build('sigmasq', numpy.array(bank.sigmasq))) ligolw_utils.write_filename(xmldoc, filename, gz=filename.endswith('.gz'), verbose=verbose)
def psd_from_event(gid, outdir=".", save=False, filename="psd.xml.gz", verbose=False): """Get the psd.xml.gz given a gracedb event id. Args: gid (str): The gracedb event id. outdir (str, default="."): The output directory. filename (str, default="psd.xml.gz"): The output filename. save (bool, default=False): True if want to save the file, False otherwise. verbose (bool, default=False): Be verbose. Returns: A dictionary of complex LAL Series key by instrument. """ gracedb_client = gracedb.GraceDb() psd_fileobj = lvalert_helper.get_filename(gracedb_client, gid, filename) xmldoc = ligolw_utils.load_fileobj( psd_fileobj, contenthandler=lal.series.PSDContentHandler) if save: if verbose: sys.stderr.write("saving psd file to %s ...\n" % os.path.join(outdir, filename)) ligolw_utils.write_filename(xmldoc, filename, gz=filename.endswith("gz")) return lal.series.read_psd_xmldoc(xmldoc)
def write_tables(target, tables, append=False, overwrite=False, **kwargs): """Write an LIGO_LW table to file Parameters ---------- target : `str`, `file`, :class:`~ligo.lw.ligolw.Document` the file or document to write into tables : `list`, `tuple` of :class:`~ligo.lw.table.Table` the tables to write append : `bool`, optional, default: `False` if `True`, append to an existing file/table, otherwise `overwrite` overwrite : `bool`, optional, default: `False` if `True`, delete an existing instance of the table type, otherwise append new rows **kwargs other keyword arguments to pass to :func:`~ligo.lw.utils.load_filename`, or :func:`~ligo.lw.utils.load_fileobj` as appropriate """ from ligo.lw.ligolw import (Document, LIGO_LW, LIGOLWContentHandler) from ligo.lw import utils as ligolw_utils # allow writing directly to XML if isinstance(target, (Document, LIGO_LW)): xmldoc = target # open existing document, if possible elif append: xmldoc = open_xmldoc( target, contenthandler=kwargs.pop('contenthandler', LIGOLWContentHandler)) # fail on existing document and not overwriting elif (not overwrite and isinstance(target, string_types) and os.path.isfile(target)): raise IOError("File exists: {}".format(target)) else: # or create a new document xmldoc = Document() # convert table to format write_tables_to_document(xmldoc, tables, overwrite=overwrite) # write file if isinstance(target, string_types): kwargs.setdefault('gz', target.endswith('.gz')) ligolw_utils.write_filename(xmldoc, target, **kwargs) elif isinstance(target, FILE_LIKE): kwargs.setdefault('gz', target.name.endswith('.gz')) ligolw_utils.write_fileobj(xmldoc, target, **kwargs)
def write_tables(target, tables, append=False, overwrite=False, **kwargs): """Write an LIGO_LW table to file Parameters ---------- target : `str`, `file`, :class:`~ligo.lw.ligolw.Document` the file or document to write into tables : `list`, `tuple` of :class:`~ligo.lw.table.Table` the tables to write append : `bool`, optional, default: `False` if `True`, append to an existing file/table, otherwise `overwrite` overwrite : `bool`, optional, default: `False` if `True`, delete an existing instance of the table type, otherwise append new rows **kwargs other keyword arguments to pass to :func:`~ligo.lw.utils.load_filename`, or :func:`~ligo.lw.utils.load_fileobj` as appropriate """ from ligo.lw.ligolw import (Document, LIGO_LW, LIGOLWContentHandler) from ligo.lw import utils as ligolw_utils # allow writing directly to XML if isinstance(target, (Document, LIGO_LW)): xmldoc = target # open existing document, if possible elif append: xmldoc = open_xmldoc( target, contenthandler=kwargs.pop('contenthandler', LIGOLWContentHandler)) # fail on existing document and not overwriting elif (not overwrite and isinstance(target, str) and os.path.isfile(target)): raise IOError("File exists: {}".format(target)) else: # or create a new document xmldoc = Document() # convert table to format write_tables_to_document(xmldoc, tables, overwrite=overwrite) # write file if isinstance(target, str): kwargs.setdefault('gz', target.endswith('.gz')) ligolw_utils.write_filename(xmldoc, target, **kwargs) elif isinstance(target, FILE_LIKE): kwargs.setdefault('gz', target.name.endswith('.gz')) ligolw_utils.write_fileobj(xmldoc, target, **kwargs)
def save(self, filename): """Write this trigger to gracedb compatible xml format Parameters ---------- filename: str Name of file to write to disk. """ ligolw_utils.write_filename(self.outdoc, filename, compress='auto') # save source probabilities in a json file if self.probabilities is not None: prob_fname = filename.replace('.xml.gz', '_probs.json') with open(prob_fname, 'w') as prob_outfile: json.dump(self.probabilities, prob_outfile) logging.info('Source probabilities file saved as %s', prob_fname)
def save(self, fname): """Write this trigger to gracedb compatible xml format Parameters ---------- fname: str Name of file to write to disk. """ ligolw_utils.write_filename(self.outdoc, fname, compress='auto') if self.basename is None: # here assume compression self.basename = fname.replace('.xml.gz', '') # Save multi-cpt p astro as json if self.astro_probs is not None: self.multipa_file = self.basename + '_p_astro.json' with open(self.multipa_file, 'w') as multipaf: json.dump(self.astro_probs, multipaf) logging.info('Multi p_astro file saved as %s', self.multipa_file) # Don't save any other files! return # Save source probabilities in a json file if self.probabilities is not None: self.prob_file = self.basename + '_probs.json' with open(self.prob_file, 'w') as probf: json.dump(self.probabilities, probf) logging.info('Source probabilities file saved as %s', self.prob_file) return # Save p astro / p terr as json if self.p_astro is not None: self.pastro_file = self.basename + '_pa_pterr.json' with open(self.pastro_file, 'w') as pastrof: json.dump({ 'p_astro': self.p_astro, 'p_terr': self.p_terr }, pastrof) logging.info('P_astro file saved as %s', self.pastro_file) return
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'))
def make_exttrig_file(cp, ifos, sci_seg, out_dir): ''' Make an ExtTrig xml file containing information on the external trigger Parameters ---------- cp : pycbc.workflow.configuration.WorkflowConfigParser object The parsed configuration options of a pycbc.workflow.core.Workflow. ifos : str String containing the analysis interferometer IDs. sci_seg : ligo.segments.segment The science segment for the analysis run. out_dir : str The output directory, destination for xml file. Returns ------- xml_file : pycbc.workflow.File object The xml file with external trigger information. ''' # Initialise objects xmldoc = ligolw.Document() xmldoc.appendChild(ligolw.LIGO_LW()) tbl = lsctables.New(lsctables.ExtTriggersTable) cols = tbl.validcolumns xmldoc.childNodes[-1].appendChild(tbl) row = tbl.appendRow() # Add known attributes for this GRB setattr(row, "event_ra", float(cp.get("workflow", "ra"))) setattr(row, "event_dec", float(cp.get("workflow", "dec"))) setattr(row, "start_time", int(cp.get("workflow", "trigger-time"))) setattr(row, "event_number_grb", str(cp.get("workflow", "trigger-name"))) # Fill in all empty rows for entry in cols.keys(): if hasattr(row, entry): continue if cols[entry] in ['real_4', 'real_8']: setattr(row, entry, 0.) elif cols[entry] in ['int_4s', 'int_8s']: setattr(row, entry, 0) elif cols[entry] == 'lstring': setattr(row, entry, '') elif entry == 'process_id': row.process_id = 0 elif entry == 'event_id': row.event_id = 0 else: raise ValueError("Column %s not recognized" % entry) # Save file xml_file_name = "triggerGRB%s.xml" % str(cp.get("workflow", "trigger-name")) xml_file_path = os.path.join(out_dir, xml_file_name) utils.write_filename(xmldoc, xml_file_path) xml_file_url = urljoin("file:", pathname2url(xml_file_path)) xml_file = File(ifos, xml_file_name, sci_seg, file_url=xml_file_url) xml_file.add_pfn(xml_file_url, site="local") return xml_file
def write_simplified_sngl_inspiral_table(m1, m2, s1x, s1y, s1z, s2x, s2y, s2z, instrument, approximant, filename=None): """Writing a simplified sngl_inspiral_table containing only one template. Args: m1 (float): mass1. m2 (float): mass2. s1x (float): spin 1 x-axis. s1y (float): spin 1 y-axis. s1z (float): spin 1 z-axis. s2x (float): spin 2 x-axis. s2y (float): spin 2 y-axis. s2z (float): spin 2 z-axis. instrument (str): The instrument for the template. approximant (str): The approximant used to simulate the waveform. filename (str, default=None): The output filename. Return: The file object representing the xmldoc. """ # Check if it is valid approximant templates.gstlal_valid_approximant(approximant) xmldoc = ligolw.Document() root = xmldoc.appendChild(ligolw.LIGO_LW()) table = lsctables.New(lsctables.SnglInspiralTable) rows = table.RowType() # set all slots to impossible/dummy value for t, c in zip(table.columntypes, table.columnnames): if t == u"real_4" or t == u"real_8": rows.__setattr__(c, 0) elif t == u"int_4s" or t == u"int_8s": rows.__setattr__(c, 0) elif t == u"lstring": rows.__setattr__(c, "") else: rows.__setattr__(c, None) rows.mass1 = m1 rows.mass2 = m2 rows.mtotal = m1 + m2 rows.mchirp = (m1 * m2)**0.6 / (m1 + m2)**0.2 rows.spin1x = s1x rows.spin1y = s1y rows.spin1z = s1z rows.spin2x = s2x rows.spin2y = s2y rows.spin2z = s2z rows.ifo = instrument table.append(rows) root.appendChild(table) #FIXME: do something better than this root.appendChild( ligolw_param.Param.from_pyvalue("approximant", approximant)) if filename is not None: ligolw_utils.write_filename(xmldoc, filename, gz=filename.endswith("gz")) return xmldoc
# How many slides will go into this file? # N = int(round(float(len(time_slides)) / len(filenames))) # # Put them in. # for offsetvect in time_slides[:N]: timeslidetable.append_offsetvector(offsetvect, process) del time_slides[:N] # # Finish off the document. # ligolw_process.set_process_end_time(process) # # Write. # filename = filenames.pop(0) ligolw_utils.write_filename(xmldoc, filename, verbose=options.verbose, gz=(filename or "stdout").endswith(".gz")) assert not time_slides
def write_bank(filename, banks, psd_input, cliplefts=None, cliprights=None, verbose=False): """Write SVD banks to a LIGO_LW xml file.""" # Create new document xmldoc = ligolw.Document() lw = xmldoc.appendChild(ligolw.LIGO_LW()) for bank, clipleft, clipright in zip(banks, cliplefts, cliprights): # set up root for this sub bank root = lw.appendChild( ligolw.LIGO_LW(Attributes({u"Name": u"gstlal_svd_bank_Bank"}))) # FIXME FIXME FIXME move this clipping stuff to the Bank class # set the right clipping index clipright = len(bank.sngl_inspiral_table) - clipright # Apply clipping option to sngl inspiral table # put the bank table into the output document new_sngl_table = bank.sngl_inspiral_table.copy() for row in bank.sngl_inspiral_table[clipleft:clipright]: # FIXME need a proper id column row.Gamma1 = int(bank.bank_id.split("_")[0]) new_sngl_table.append(row) # put the possibly clipped table into the file root.appendChild(new_sngl_table) # Add root-level scalar params root.appendChild( ligolw_param.Param.from_pyvalue('filter_length', bank.filter_length)) root.appendChild( ligolw_param.Param.from_pyvalue('gate_threshold', bank.gate_threshold)) root.appendChild( ligolw_param.Param.from_pyvalue('logname', bank.logname or "")) root.appendChild( ligolw_param.Param.from_pyvalue('snr_threshold', bank.snr_threshold)) root.appendChild( ligolw_param.Param.from_pyvalue('template_bank_filename', bank.template_bank_filename)) root.appendChild( ligolw_param.Param.from_pyvalue('bank_id', bank.bank_id)) root.appendChild( ligolw_param.Param.from_pyvalue('new_deltaf', bank.newdeltaF)) root.appendChild( ligolw_param.Param.from_pyvalue('working_f_low', bank.working_f_low)) root.appendChild(ligolw_param.Param.from_pyvalue('f_low', bank.f_low)) root.appendChild( ligolw_param.Param.from_pyvalue('sample_rate_max', int(bank.sample_rate_max))) root.appendChild( ligolw_param.Param.from_pyvalue('gstlal_fir_whiten', os.environ['GSTLAL_FIR_WHITEN'])) # apply clipping to autocorrelations and sigmasq bank.autocorrelation_bank = bank.autocorrelation_bank[ clipleft:clipright, :] bank.autocorrelation_mask = bank.autocorrelation_mask[ clipleft:clipright, :] bank.sigmasq = bank.sigmasq[clipleft:clipright] # Add root-level arrays # FIXME: ligolw format now supports complex-valued data root.appendChild( ligolw_array.Array.build('autocorrelation_bank_real', bank.autocorrelation_bank.real)) root.appendChild( ligolw_array.Array.build('autocorrelation_bank_imag', bank.autocorrelation_bank.imag)) root.appendChild( ligolw_array.Array.build('autocorrelation_mask', bank.autocorrelation_mask)) root.appendChild( ligolw_array.Array.build('sigmasq', numpy.array(bank.sigmasq))) # Write bank fragments for i, frag in enumerate(bank.bank_fragments): # Start new bank fragment container el = root.appendChild(ligolw.LIGO_LW()) # Apply clipping option if frag.mix_matrix is not None: frag.mix_matrix = frag.mix_matrix[:, clipleft * 2:clipright * 2] frag.chifacs = frag.chifacs[clipleft * 2:clipright * 2] # Add scalar params el.appendChild( ligolw_param.Param.from_pyvalue('rate', int(frag.rate))) el.appendChild(ligolw_param.Param.from_pyvalue( 'start', frag.start)) el.appendChild(ligolw_param.Param.from_pyvalue('end', frag.end)) # Add arrays el.appendChild(ligolw_array.Array.build('chifacs', frag.chifacs)) if frag.mix_matrix is not None: el.appendChild( ligolw_array.Array.build('mix_matrix', frag.mix_matrix)) el.appendChild( ligolw_array.Array.build('orthogonal_template_bank', frag.orthogonal_template_bank)) if frag.singular_values is not None: el.appendChild( ligolw_array.Array.build('singular_values', frag.singular_values)) if frag.sum_of_squares_weights is not None: el.appendChild( ligolw_array.Array.build('sum_of_squares_weights', frag.sum_of_squares_weights)) # put a copy of the processed PSD file in # FIXME in principle this could be different for each bank included in # this file, but we only put one here psd = psd_input[bank.sngl_inspiral_table[0].ifo] lal.series.make_psd_xmldoc({bank.sngl_inspiral_table[0].ifo: psd}, lw) # Write to file ligolw_utils.write_filename(xmldoc, filename, gz=filename.endswith('.gz'), verbose=verbose)
def write_url(xmldoc, filename, verbose=False): ligolw_utils.write_filename(xmldoc, filename, gz=filename.endswith(".gz"), verbose=verbose)
connection.commit() connection.close() dbtables.put_connection_filename(filename, working_filename, verbose=options.verbose) if options.verbose: print >> sys.stderr, "FAP and FAR assignment complete" # # write parameter and ranking stat distribution file now with # zero-lag counts populated # # FIXME: do not write this output file, rely on stand-alone tool to # collect zero-lag counts before running this program, and make that # information available to other tools that way # xmldoc = ligolw.Document() xmldoc.appendChild(ligolw.LIGO_LW()) xmldoc.childNodes[-1].appendChild(rankingstatpdf.to_xml()) # FIXME dont hard code outname = "post_STRING_RANKINGSTATPDF.xml.gz" ligolw_utils.write_filename(xmldoc, outname, gz=outname.endswith(".gz"), verbose=options.verbose) if options.verbose: print >> sys.stderr, "done"
def save(self, path, group=None, ifo='P1'): """ Save frequency series to a Numpy .npy, hdf, or text file. The first column contains the sample frequencies, the second contains the values. In the case of a complex frequency series saved as text, the imaginary part is written as a third column. When using hdf format, the data is stored as a single vector, along with relevant attributes. Parameters ---------- path: string Destination file path. Must end with either .hdf, .npy or .txt. group: string Additional name for internal storage use. Ex. hdf storage uses this as the key value. Raises ------ ValueError If path does not end in .npy or .txt. """ ext = _os.path.splitext(path)[1] if ext == '.npy': output = _numpy.vstack((self.sample_frequencies.numpy(), self.numpy())).T _numpy.save(path, output) elif ext == '.txt': if self.kind == 'real': output = _numpy.vstack((self.sample_frequencies.numpy(), self.numpy())).T elif self.kind == 'complex': output = _numpy.vstack((self.sample_frequencies.numpy(), self.numpy().real, self.numpy().imag)).T _numpy.savetxt(path, output) elif ext == '.xml' or path.endswith('.xml.gz'): from pycbc.io.live import make_psd_xmldoc from ligo.lw import utils if self.kind != 'real': raise ValueError('XML only supports real frequency series') output = self.lal() # When writing in this format we must *not* have the 0 values at # frequencies less than flow. To resolve this we set the first # non-zero value < flow. data_lal = output.data.data first_idx = _numpy.argmax(data_lal>0) if not first_idx == 0: data_lal[:first_idx] = data_lal[first_idx] psddict = {ifo: output} utils.write_filename(make_psd_xmldoc(psddict), path, gz=path.endswith(".gz")) elif ext == '.hdf': key = 'data' if group is None else group with h5py.File(path, 'a') as f: ds = f.create_dataset(key, data=self.numpy(), compression='gzip', compression_opts=9, shuffle=True) if self.epoch is not None: ds.attrs['epoch'] = float(self.epoch) ds.attrs['delta_f'] = float(self.delta_f) else: raise ValueError('Path must end with .npy, .txt, .xml, .xml.gz ' 'or .hdf')
(1.0 - options.overlap_fraction), frequency=options.f_low + j * options.delta_f * (1.0 - options.overlap_fraction), bandwidth=options.delta_f, duration=options.delta_t, # brightness. hrss is ignored, set # egw_over_rsquared to 1, to be re-scaled # after measuring waveform's real # brightness hrss=hrss, egw_over_rsquared=1.) # generate waveform, then scale egw_over_rsquared # to get desired brightness row.egw_over_rsquared *= hrss / lalsimulation.MeasureHrss( *lalburst.GenerateSimBurst(row, 1.0 / options.sample_rate)) # put row into table sim_burst_tbl.append(row) del progress # # write output # ligolw_utils.write_filename(xmldoc, options.output, gz=(options.output or "stdout").endswith(".gz"), verbose=options.verbose)
vetoes = ligolw_segments.segmenttable_get_by_name(xmldoc, options.vetoes_name).coalesce() # # Run coincidence algorithm. # thinca.ligolw_thinca( xmldoc, process_id = process.process_id, delta_t = options.threshold, ntuple_comparefunc = ntuple_comparefunc, seglists = None, # FIXME veto_segments = vetoes, min_instruments = options.min_instruments, verbose = options.verbose ) # # Close out the process table. # ligolw_process.set_process_end_time(process) # # Write back to disk, and clean up. # ligolw_utils.write_filename(xmldoc, filename, verbose = options.verbose, gz = (filename or "stdout").endswith(".gz")) xmldoc.unlink() lsctables.reset_next_ids(lsctables.TableByName.values())
segmentdb_utils.add_to_segment(outdoc, proc_id, sci_def_id, sciSegs) segmentdb_utils.add_to_segment(outdoc, proc_id, sciok_def_id, sciokSegs) segmentdb_utils.add_to_segment(outdoc, proc_id, sciavailable_def_id, sciavailableSegs) segmentdb_utils.add_to_segment(outdoc, proc_id, analysable_def_id, analysableSegs) segmentdb_utils.add_to_segment_summary(outdoc, proc_id, sci_def_id, summSegs, comment='') segmentdb_utils.add_to_segment_summary(outdoc, proc_id, sciok_def_id, summSegs, comment='') segmentdb_utils.add_to_segment_summary(outdoc, proc_id, sciavailable_def_id, summSegs, comment='') segmentdb_utils.add_to_segment_summary(outdoc, proc_id, analysable_def_id, summSegs, comment='') ligolw_utils.write_filename(outdoc, "SUMMARY.xml")
def output_sngl_inspiral_table(outputFile, tempBank, metricParams, ethincaParams, programName="", optDict = None, outdoc=None): """ Function that converts the information produced by the various PyCBC bank generation codes into a valid LIGOLW XML file containing a sngl_inspiral table and outputs to file. Parameters ----------- outputFile : string Name of the file that the bank will be written to tempBank : iterable Each entry in the tempBank iterable should be a sequence of [mass1,mass2,spin1z,spin2z] in that order. 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. ethincaParams: {ethincaParameters instance, None} Structure holding options relevant to the ethinca metric computation including the upper frequency cutoff to be used for filtering. NOTE: The computation is currently only valid for non-spinning systems and uses the TaylorF2 approximant. programName (key-word-argument) : string Name of the executable that has been run optDict (key-word argument) : dictionary Dictionary of the command line arguments passed to the program outdoc (key-word argument) : ligolw xml document If given add template bank to this representation of a xml document and write to disk. If not given create a new document. """ if optDict is None: optDict = {} if outdoc is None: outdoc = ligolw.Document() outdoc.appendChild(ligolw.LIGO_LW()) # get IFO to put in search summary table ifos = [] if 'channel_name' in optDict.keys(): if optDict['channel_name'] is not None: ifos = [optDict['channel_name'][0:2]] proc = create_process_table( outdoc, program_name=programName, detectors=ifos, options=optDict ) proc_id = proc.process_id sngl_inspiral_table = convert_to_sngl_inspiral_table(tempBank, proc_id) # Calculate Gamma components if needed if ethincaParams is not None: if ethincaParams.doEthinca: for sngl in sngl_inspiral_table: # Set tau_0 and tau_3 values needed for the calculation of # ethinca metric distances (sngl.tau0,sngl.tau3) = pnutils.mass1_mass2_to_tau0_tau3( sngl.mass1, sngl.mass2, metricParams.f0) fMax_theor, GammaVals = calculate_ethinca_metric_comps( metricParams, ethincaParams, sngl.mass1, sngl.mass2, spin1z=sngl.spin1z, spin2z=sngl.spin2z, full_ethinca=ethincaParams.full_ethinca) # assign the upper frequency cutoff and Gamma0-5 values sngl.f_final = fMax_theor for i in range(len(GammaVals)): setattr(sngl, "Gamma"+str(i), GammaVals[i]) # If Gamma metric components are not wanted, assign f_final from an # upper frequency cutoff specified in ethincaParams elif ethincaParams.cutoff is not None: for sngl in sngl_inspiral_table: sngl.f_final = pnutils.frequency_cutoff_from_name( ethincaParams.cutoff, sngl.mass1, sngl.mass2, sngl.spin1z, sngl.spin2z) # set per-template low-frequency cutoff if 'f_low_column' in optDict and 'f_low' in optDict and \ optDict['f_low_column'] is not None: for sngl in sngl_inspiral_table: setattr(sngl, optDict['f_low_column'], optDict['f_low']) outdoc.childNodes[0].appendChild(sngl_inspiral_table) # get times to put in search summary table start_time = 0 end_time = 0 if 'gps_start_time' in optDict.keys() and 'gps_end_time' in optDict.keys(): start_time = optDict['gps_start_time'] end_time = optDict['gps_end_time'] # make search summary table search_summary_table = lsctables.New(lsctables.SearchSummaryTable) search_summary = return_search_summary( start_time, end_time, len(sngl_inspiral_table), ifos ) search_summary_table.append(search_summary) outdoc.childNodes[0].appendChild(search_summary_table) # write the xml doc to disk ligolw_utils.write_filename(outdoc, outputFile)
# band- and time-limited white-noise burst row.waveform = "BTLWNB" row.waveform_number = 0 row.pol_ellipse_e = row.pol_ellipse_angle = 0 # time-frequency co-ordinates row.frequency = options.f_low + j * options.delta_f * (1.0 - options.overlap_fraction) gps = options.gps_start_time + i * options.delta_t * (1.0 - options.overlap_fraction) row.time_geocent_gps, row.time_geocent_gps_ns = gps.seconds, gps.nanoseconds row.bandwidth = options.delta_f row.duration = options.delta_t # amplitude. hrss column is ignored by waveform # generation code. it is included for convenience. # the waveform is normalized by generating the # burst, measuring its hrss, then rescaling to # achieve the desired value. this process requires # the sample rate to be known. row.hrss = options.hrss_scale * img.getpixel((i, height - 1 - j)) / 255.0 if row.hrss != 0: row.egw_over_rsquared = 1 row.egw_over_rsquared *= row.hrss / lalsimulation.MeasureHrss(*lalburst.GenerateSimBurst(row, 1.0 / 16384)) sim_burst_tbl.append(row) if options.verbose: print("generating sim_burst table ... %d injections\r" % len(sim_burst_tbl), end=' ', file=sys.stderr) if options.verbose: print(file=sys.stderr) ligolw_utils.write_filename(xmldoc, options.output, gz = (options.output or "stdout").endswith(".gz"), verbose = options.verbose)