Esempio n. 1
0
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)
Esempio n. 2
0
def svd_banks_from_event(gid, outdir=".", save=False, verbose=False):
    """Find location of the SVD banks from gracedb event id.

	Args:
		gid (str): The gracedb event id.
		outdir (str, default="."): The output directory.
		save (bool, default=False): True if want to save the file, False otherwise.
		verbose (bool, default=False): Be verbose.

	Returns:
		banks_dict (dict of :obj: `Bank`): The SVD banks for an event key by instrument.
		bank_number (int)
		row_number (int)

	"""
    gracedb_client = gracedb.GraceDb()
    coinc_xmldoc = lvalert_helper.get_coinc_xmldoc(gracedb_client, gid)

    try:
        path = [
            row.value
            for row in lsctables.ProcessParamsTable.get_table(coinc_xmldoc)
            if row.param == "--gracedb-service-url"
        ]
        bank_urls = inspiral.parse_svdbank_string([
            row.value
            for row in lsctables.ProcessParamsTable.get_table(coinc_xmldoc)
            if row.param == "--svd-bank"
        ].pop())
        if path is not None:
            path = path.pop()
            for ifo, bank_url in bank_urls.items():
                bank_urls[ifo] = os.path.join(path, bank_url)
        banks_dict = inspiral.parse_bank_files(bank_urls, verbose=verbose)
    except IOError:
        sys.stderr.write(
            "Files Not Found! Make sure you are on the LIGO-Caltech Computing Cluster or check if files exist.\nAbortting...\n"
        )
        sys.exit()

    if save:
        try:
            for bank_url in bank_urls.values():
                outname = os.path.join(outdir, os.path.basename(bank_url))
                if verbose:
                    sys.stderr.write("saving SVD bank files to %s  ...\n" %
                                     outname)
                shutil.copyfile(bank_url, outname)
        # FIXME: in python > 2.7, OSError will be raised if destination is not writable.
        except IOError as e:
            raise e

    # Just get one of the template bank from any instrument,
    # the templates should all have the same template_id because they are exact-matched.
    bank_number, row_number = scan_svd_banks_for_row(coinc_xmldoc, banks_dict)

    return banks_dict, bank_number, row_number
Esempio n. 3
0
def gracedb_upload_injection(hwinj,
                             ifo_list,
                             pipeline="HardwareInjection",
                             group="Test"):
    """ Uploads an event to GraceDB.

    Parameters
    ----------
    hwinj: HardwareInjection
        The HardwareInjection event to upload to GraceDB.
    ifo_list: list
        A list of the IFOs that should be appended to this event.
    pipeline: str
        The pipeline to tag for the GraceDB event.
    group: str
        The group to tag for the GraceDB event.

    Returns
    ----------
    gracedb_id: str
        The GraceDB ID string for the HardwareInjection event that was
        uploaded.
    """

    # begin GraceDB API
    client = gracedb_rest.GraceDb()

    # read meta-data file
    if hwinj.metadata_path != "None":
        file_contents = inj_io.read_metadata(hwinj.metadata_path,
                                             hwinj.waveform_start_time,
                                             hwinj.schedule_time)

    # if there is no meta-data file make an empty sim_inspiral with the
    # scheduled time as the geocent_end_time column
    else:
        file_contents = inj_io.create_empty_sim_inspiral_xml(
            hwinj.schedule_time)

    # make a comma-delimited string the IFOs
    ifo_str = ",".join(ifo_list)

    # upload event to GraceDB
    out = client.createEvent(group,
                             pipeline,
                             hwinj.metadata_path,
                             filecontents=file_contents,
                             instrument=ifo_str,
                             source_channel="",
                             destination_channel="")

    # get GraceDB ID
    gracedb_id = out.json()["graceid"]

    return gracedb_id
Esempio n. 4
0
def gracedb_add_label(gracedb_id, label):
    """ Adds a message to the GraceDB entry.

    Parameters
    ----------
    gracedb_id: str
        The GraceDB ID of the entry to be appended.
    label: str
        The label to be appended to the GraceDB ID entry.
    """

    # begin GraceDB API
    client = gracedb_rest.GraceDb()

    # append comment to GraceDB entry
    out = client.writeLabel(gracedb_id, label)
Esempio n. 5
0
def gracedb_upload_message(gracedb_id, message, tagname="analyst comments"):
    """ Adds a message to the GraceDB entry.

    Parameters
    ----------
    gracedb_id: str
        The GraceDB ID of the entry to be appended.
    message: str
        The message to be appended to the GraceDB ID entry.
    tagname: str
        The name of the tag to use for GraceDB event.
    """

    # begin GraceDB API
    client = gracedb_rest.GraceDb()

    # append comment to GraceDB entry
    out = client.writeLog(gracedb_id, message, tagname=tagname)
Esempio n. 6
0
 def __init__(self, graceids, client=None):
     if client is None:
         client = rest.GraceDb()
     self._client = client
     self._graceids = graceids
Esempio n. 7
0
def framecache_from_event(gid,
                          observatories,
                          frame_types,
                          time_span=500,
                          outdir=".",
                          filename="frame.cache",
                          verbose=False):
    """Get the frame cache for an event given the gracedb event id.

	Args:
		gid (str): The gracedb event id.
		observatories (list): See gwdatafind.
		frame_type (list): See gwdatafind.
		time_span (float): The time span before and after the trigger time.
		outdir (str, default="."): The output directory.
		filename (str, default="frame.cache"): The output filename.
		verbose (bool): Be verbose.

	Returns:
		Dictionary of instruments, trigger_times, gps_start_time,
		gps_end_time, channels_name.

	"""
    assert time_span >= 500., "Please use time_span larger or equal to 500."

    obs2ifo = {"H": "H1", "L": "L1", "V": "V1"}

    observatories = set(observatories)
    frame_types = set(frame_types)

    if len(observatories) != len(frame_types):
        raise ValueError("Must have as many frame_types as observatories.")
    # FIXME: This is not reliable, have a better way to map frame_type to observatory?
    obs_type_dict = dict([(obs, frame_type) for obs in observatories
                          for frame_type in frame_types
                          if obs == frame_type[0]])

    gracedb_client = gracedb.GraceDb()
    coinc_xmldoc = lvalert_helper.get_coinc_xmldoc(gracedb_client, gid)
    eventid_trigger_dict = dict(
        (row.ifo, row)
        for row in lsctables.SnglInspiralTable.get_table(coinc_xmldoc))
    channel_names_dict = dict([
        (row.value.split("=")[0], row.value)
        for row in lsctables.ProcessParamsTable.get_table(coinc_xmldoc)
        if row.param == "--channel-name"
    ])

    gwdata_metavar_headers = [
        "instruments", "trigger_times", "gps_start_time", "gps_end_time",
        "channels_name"
    ]
    gwdata_metavar_values = []
    urls = []
    for observatory, frame_type in obs_type_dict.items():
        trigger_time = eventid_trigger_dict[obs2ifo[observatory]].end
        gps_start_time = int(trigger_time - time_span)
        gps_end_time = int(trigger_time + time_span)
        gwdata_metavar_values.append(
            (obs2ifo[observatory], trigger_time, gps_start_time, gps_end_time,
             channel_names_dict[obs2ifo[observatory]]))

        urls += gwdatafind.find_urls(observatory, frame_type, gps_start_time,
                                     gps_end_time)

    with open(os.path.join(outdir, "frame.cache"), "w") as cache:
        for url in urls:
            filename = str(CacheEntry.from_T050017(url))
            cache.write("%s\n" % filename)
            if verbose:
                sys.stderr.write(
                    "writing %s to %s\n" %
                    (filename, os.path.join(outdir, "frame.cache")))
        if verbose:
            sys.stderr.write("Done.\n")

    return dict(zip(gwdata_metavar_headers, zip(*gwdata_metavar_values)))