Exemple #1
0
    def attempt_advance(self, blocksize, timeout=10):
        """ Attempt to advance the frame buffer. Retry upon failure, except
        if the frame file is beyond the timeout limit.

        Parameters
        ----------
        blocksize: int
            The number of seconds to attempt to read from the channel
        timeout: {int, 10}, Optional
            Number of seconds before giving up on reading a frame

        Returns
        -------
        data: TimeSeries
            TimeSeries containg 'blocksize' seconds of frame data
        """
        if self.force_update_cache:
            self.update_cache()
        
        try:
            if self.increment_update_cache:
                self.update_cache_by_increment(blocksize)

            return DataBuffer.advance(self, blocksize)

        except RuntimeError:
            if lal.GPSTimeNow() > timeout + self.raw_buffer.end_time:
                # The frame is not there and it should be by now, so we give up
                # and treat it as zeros
                DataBuffer.null_advance(self, blocksize)
                return None
            else:
                # I am too early to give up on this frame, so we should try again
                time.sleep(1)
                return self.attempt_advance(blocksize, timeout=timeout)
Exemple #2
0
    def parseTimeDelayDegeneracy(self, ifos, gpstime=lal.GPSTimeNow(),\
                                 dt=0.0005):

        # get detectors
        detectors = [inject.cached_detector.get(inject.prefix_to_name[ifo])\
                         for ifo in ifos]

        timeDelays = []
        degenerate = []

        new = table.new_from_template(self)
        for n, row in enumerate(self):
            # get all time delays for this point
            timeDelays.append([])
            for i in xrange(len(ifos)):
                for j in xrange(i + 1, len(ifos)):
                    timeDelays[n].append(date.XLALArrivalTimeDiff(\
                                             detectors[i].location,\
                                             detectors[j].location,\
                                             row.longitude,\
                                             row.latitude,\
                                             LIGOTimeGPS(gpstime)))
            # skip the first point
            if n == 0:
                degenerate.append(False)
                new.append(row)
                continue
            else:
                degenerate.append(True)
            # test this point against all others
            for i in xrange(0, n):
                # if check point is degenerate, skip
                if degenerate[i]:
                    continue
                # check each time delay individually
                for j in xrange(0, len(timeDelays[n])):
                    # if this time delay is non-degenerate the point is valid
                    if np.fabs(timeDelays[i][j] - timeDelays[n][j]) >= dt:
                        degenerate[n] = False
                        break
                    else:
                        degenerate[n] = True
                if degenerate[n]:
                    break

            if not degenerate[n]:
                new.append(row)

        return new
Exemple #3
0
    def setUp(self):
        available_detectors = get_available_detectors()
        available_detectors = [a[0] for a in available_detectors]
        self.assertTrue('H1' in available_detectors)
        self.assertTrue('L1' in available_detectors)
        self.assertTrue('V1' in available_detectors)
        self.detectors = [Detector(d) for d in ['H1', 'L1', 'V1']]
        self.sample_rate = 4096.
        self.earth_time = lal.REARTH_SI / lal.C_SI

        # create a few random injections
        self.injections = []
        start_time = float(lal.GPSTimeNow())
        taper_choices = ('TAPER_NONE', 'TAPER_START', 'TAPER_END',
                         'TAPER_STARTEND')
        for i, taper in zip(xrange(20), itertools.cycle(taper_choices)):
            inj = MyInjection()
            inj.end_time = start_time + 40000 * i + \
                    numpy.random.normal(scale=3600)
            random = numpy.random.uniform
            inj.mass1 = random(low=1., high=20.)
            inj.mass2 = random(low=1., high=20.)
            inj.distance = random(low=0.9, high=1.1) * 1e6 * lal.PC_SI
            inj.latitude = numpy.arccos(random(low=-1, high=1))
            inj.longitude = random(low=0, high=2 * lal.PI)
            inj.inclination = numpy.arccos(random(low=-1, high=1))
            inj.polarization = random(low=0, high=2 * lal.PI)
            inj.taper = taper
            self.injections.append(inj)

        # create LIGOLW document
        xmldoc = ligolw.Document()
        xmldoc.appendChild(ligolw.LIGO_LW())

        # create sim inspiral table, link it to document and fill it
        sim_table = lsctables.New(lsctables.SimInspiralTable)
        xmldoc.childNodes[-1].appendChild(sim_table)
        for i in xrange(len(self.injections)):
            row = sim_table.RowType()
            self.injections[i].fill_sim_inspiral_row(row)
            row.process_id = 'process:process_id:0'
            row.simulation_id = 'sim_inspiral:simulation_id:%d' % i
            sim_table.append(row)

        # write document to temp file
        self.inj_file = tempfile.NamedTemporaryFile(suffix='.xml')
        ligolw_utils.write_fileobj(xmldoc, self.inj_file)
Exemple #4
0
def write_sky_map(filename, prob, objid=None, url=None, instruments=None,
    gps_time=None, gps_creation_time=None, creator=None, runtime=None):
    """Write a gravitational-wave sky map to a file, populating the header
    with optional metadata."""

    #
    # Populate optional header fieds.
    #

    extra_metadata = []

    if objid is not None:
        extra_metadata.append(('OBJECT', objid,
            'Unique identifier for this event'))

    if url is not None:
        extra_metadata.append(('REFERENC', url,
            'URL of this event'))

    if instruments is not None:
        extra_metadata.append(('INSTRUME', instruments,
            'Gravitational-wave instruments contributing data to this event'))

    if gps_time is not None:
        extra_metadata.append(('DATE-OBS', gps_to_iso8601(gps_time),
            'UTC date of the observation'))
        extra_metadata.append(('MJD-OBS', gps_to_mjd(gps_time),
            'modified Julian date of the observation'))

    if gps_creation_time is None:
        gps_creation_time = lal.GPSTimeNow()
    extra_metadata.append(('DATE', gps_to_iso8601(gps_creation_time),
        'UTC date of file creation'))

    if creator is not None:
        extra_metadata.append(('CREATOR', creator,
            'Program that created this file'))

    if runtime is not None:
        extra_metadata.append(('RUNTIME', runtime,
            'Runtime in seconds of the CREATOR program'))

    write_map(filename, prob, nest=False, fits_IDL=True, coord='C',
        column_names=('PROB',), unit='pix-1', extra_metadata=extra_metadata)
Exemple #5
0
#####################################################################
# Input
USAGE='''%prog [options] [args]
Run external analysis programs on internally generated post-merger injections
with Gaussian noise.
'''

opts, args, cp = parser()

# Data configuration
datalen=cp.getfloat('analysis', 'datalength')
flow=cp.getfloat('analysis','flow')
srate=cp.getfloat('analysis','srate')

seed=opts.init_seed
seed+=random.randint(0,lal.GPSTimeNow())

target_snr=opts.target_snr
if target_snr is None and cp.has_option('injections','target-snr'):
    target_snr=cp.getfloat('injections','target-snr')

epoch=0.0
trigtime=0.5*datalen+epoch

if opts.output_dir is None:
    outdir=cp.get('program', 'output-dir')

ts0=time.time()

######################################################################
# Data Generation
Exemple #6
0
def localize(event,
             waveform='o2-uberbank',
             f_low=30.0,
             min_inclination=0,
             max_inclination=np.pi / 2,
             min_distance=None,
             max_distance=None,
             prior_distance_power=None,
             cosmology=False,
             mcmc=False,
             chain_dump=None,
             enable_snr_series=True,
             f_high_truncate=0.95):
    """Localize a compact binary signal using the BAYESTAR algorithm.

    Parameters
    ----------
    event : `ligo.skymap.io.events.Event`
        The event candidate.
    waveform : str, optional
        The name of the waveform approximant.
    f_low : float, optional
        The low frequency cutoff.
    min_distance, max_distance : float, optional
        The limits of integration over luminosity distance, in Mpc
        (default: determine automatically from detector sensitivity).
    prior_distance_power : int, optional
        The power of distance that appears in the prior
        (default: 2, uniform in volume).
    cosmology: bool, optional
        Set to enable a uniform in comoving volume prior (default: false).
    mcmc : bool, optional
        Set to use MCMC sampling rather than more accurate Gaussian quadrature.
    chain_dump : str, optional
        Save posterior samples to this filename if `mcmc` is set.
    enable_snr_series : bool, optional
        Set to False to disable SNR time series.
    f_high_truncate : float, optional
        Truncate the noise power spectral densities at this factor times the
        highest sampled frequency to suppress artifacts caused by incorrect
        PSD conditioning by some matched filter pipelines.

    Returns
    -------
    skymap : `astropy.table.Table`
        A 3D sky map in multi-order HEALPix format.
    """

    # Hide event parameters, but show all other arguments
    def formatvalue(value):
        if isinstance(value, Event):
            return '=...'
        else:
            return '=' + repr(value)

    frame = inspect.currentframe()
    argstr = inspect.formatargvalues(*inspect.getargvalues(frame),
                                     formatvalue=formatvalue)
    run_time = time.perf_counter()

    epoch, sample_rate, toas, snr_series, responses, locations, horizons = \
        condition(event, waveform=waveform, f_low=f_low,
                  enable_snr_series=enable_snr_series,
                  f_high_truncate=f_high_truncate)

    min_distance, max_distance, prior_distance_power, cosmology = \
        condition_prior(horizons, min_distance, max_distance,
                        prior_distance_power, cosmology)

    gmst = lal.GreenwichMeanSiderealTime(epoch)

    # Time and run sky localization.
    log.debug('starting computationally-intensive section')
    args = (min_inclination, max_inclination, min_distance, max_distance,
            prior_distance_power, cosmology, gmst, sample_rate, toas,
            snr_series, responses, locations, horizons)
    if mcmc:
        max_abs_t = 2 * snr_series.data.shape[1] / sample_rate
        skymap = localize_emcee(
            args=args,
            xmin=[0, -1, min_distance, -1, 0, 0],
            xmax=[2 * np.pi, 1, max_distance, 1, 2 * np.pi, 2 * max_abs_t],
            chain_dump=chain_dump)
    else:
        skymap, log_bci, log_bsn = core.toa_phoa_snr(*args)
        skymap = Table(skymap)
        skymap.meta['log_bci'] = log_bci
        skymap.meta['log_bsn'] = log_bsn

    # Convert distance moments to parameters
    try:
        distmean = skymap.columns.pop('DISTMEAN')
        diststd = skymap.columns.pop('DISTSTD')
    except KeyError:
        distmean, diststd, _ = distance.parameters_to_moments(
            skymap['DISTMU'], skymap['DISTSIGMA'])
    else:
        skymap['DISTMU'], skymap['DISTSIGMA'], skymap['DISTNORM'] = \
            distance.moments_to_parameters(distmean, diststd)

    # Add marginal distance moments
    good = np.isfinite(distmean) & np.isfinite(diststd)
    prob = (moc.uniq2pixarea(skymap['UNIQ']) * skymap['PROBDENSITY'])[good]
    distmean = distmean[good]
    diststd = diststd[good]
    rbar = (prob * distmean).sum()
    r2bar = (prob * (np.square(diststd) + np.square(distmean))).sum()
    skymap.meta['distmean'] = rbar
    skymap.meta['diststd'] = np.sqrt(r2bar - np.square(rbar))

    run_time = time.perf_counter() - run_time
    end_time = lal.GPSTimeNow()
    log.info('finished computationally-intensive section in %.3f s', run_time)

    # Fill in metadata and return.
    program, _ = os.path.splitext(os.path.basename(sys.argv[0]))
    skymap.meta.update(metadata_for_version_module(version))
    skymap.meta['creator'] = 'BAYESTAR'
    skymap.meta['origin'] = 'LIGO/Virgo'
    skymap.meta['gps_time'] = float(epoch)
    skymap.meta['runtime'] = float(run_time)
    skymap.meta['instruments'] = {single.detector for single in event.singles}
    skymap.meta['gps_creation_time'] = end_time
    skymap.meta['history'] = [
        '', 'Generated by calling the following Python function:',
        '{}.{}{}'.format(__name__, frame.f_code.co_name, argstr), '',
        'This was the command line that started the program:',
        ' '.join([program] + sys.argv[1:])
    ]

    return skymap
Exemple #7
0
def write_sky_map(filename,
                  prob,
                  nest=False,
                  objid=None,
                  url=None,
                  instruments=None,
                  gps_time=None,
                  gps_creation_time=None,
                  creator=None,
                  origin=None,
                  runtime=None):
    """Write a gravitational-wave sky map to a file, populating the header
    with optional metadata."""

    #
    # Populate optional header fieds.
    #

    extra_metadata = []

    if objid is not None:
        extra_metadata.append(
            ('OBJECT', objid, 'Unique identifier for this event'))

    if url is not None:
        extra_metadata.append(('REFERENC', url, 'URL of this event'))

    if instruments is not None:
        if not isinstance(instruments, basestring):
            instruments = str(lsctables.ifos_from_instrument_set(instruments))
        extra_metadata.append(
            ('INSTRUME', instruments, 'Instruments that triggered this event'))

    if gps_time is not None:
        extra_metadata.append(('DATE-OBS', gps_to_iso8601(gps_time),
                               'UTC date of the observation'))
        extra_metadata.append(('MJD-OBS', gps_to_mjd(gps_time),
                               'modified Julian date of the observation'))

    if gps_creation_time is None:
        gps_creation_time = lal.GPSTimeNow()
    extra_metadata.append(('DATE', gps_to_iso8601(gps_creation_time),
                           'UTC date of file creation'))

    if creator is not None:
        extra_metadata.append(
            ('CREATOR', creator, 'Program that created this file'))

    if origin is not None:
        extra_metadata.append(
            ('ORIGIN', origin, 'Organization responsible for this FITS file'))

    if runtime is not None:
        extra_metadata.append(
            ('RUNTIME', runtime, 'Runtime in seconds of the CREATOR program'))

    write_map(filename,
              prob,
              nest=nest,
              fits_IDL=True,
              coord='C',
              column_names=('PROB', ),
              unit='pix-1',
              extra_metadata=extra_metadata)
Exemple #8
0
def write_sky_map(filename, m, nest=False, objid=None, url=None, instruments=None,
    gps_time=None, gps_creation_time=None, creator=None, origin=None,
    runtime=None, distmean=None, diststd=None):
    """Write a gravitational-wave sky map to a file, populating the header
    with optional metadata."""

    #
    # Populate optional header fieds.
    #

    extra_header = []

    if objid is not None:
        extra_header.append(('OBJECT', objid,
            'Unique identifier for this event'))

    if url is not None:
        extra_header.append(('REFERENC', url,
            'URL of this event'))

    if instruments is not None:
        if not isinstance(instruments, six.string_types):
            instruments = str(lsctables.ifos_from_instrument_set(instruments))
        extra_header.append(('INSTRUME', instruments,
            'Instruments that triggered this event'))

    if gps_time is not None:
        extra_header.append(('DATE-OBS', gps_to_iso8601(gps_time),
            'UTC date of the observation'))
        extra_header.append(('MJD-OBS', gps_to_mjd(gps_time),
            'modified Julian date of the observation'))

    if gps_creation_time is None:
        gps_creation_time = lal.GPSTimeNow()
    extra_header.append(('DATE', gps_to_iso8601(gps_creation_time),
        'UTC date of file creation'))

    if creator is not None:
        extra_header.append(('CREATOR', creator,
            'Program that created this file'))

    if origin is not None:
        extra_header.append(('ORIGIN', origin,
            'Organization responsible for this FITS file'))

    if runtime is not None:
        extra_header.append(('RUNTIME', runtime,
            'Runtime in seconds of the CREATOR program'))

    if distmean is not None:
        extra_header.append(('DISTMEAN', distmean,
            'Posterior mean distance in Mpc'))

    if diststd is not None:
        extra_header.append(('DISTSTD', diststd,
            'Posterior standard deviation of distance in Mpc'))

    m = np.atleast_2d(m)

    hp.write_map(filename, m, nest=nest, fits_IDL=True, coord='C',
        column_names=('PROB', 'DISTMU', 'DISTSIGMA', 'DISTNORM')[:len(m)],
        column_units=('pix-1', 'Mpc', 'Mpc', 'Mpc-2')[:len(m)],
        extra_header=extra_header)
def localize(event,
             waveform='o2-uberbank',
             f_low=30.0,
             min_distance=None,
             max_distance=None,
             prior_distance_power=None,
             cosmology=False,
             method='toa_phoa_snr',
             nside=-1,
             chain_dump=None,
             enable_snr_series=True,
             f_high_truncate=0.95):
    """Convenience function to produce a sky map from LIGO-LW rows. Note that
    min_distance and max_distance should be in Mpc.

    Returns a 'NESTED' ordering HEALPix image as a Numpy array.
    """
    frame = inspect.currentframe()
    argstr = inspect.formatargvalues(*inspect.getargvalues(frame))
    start_time = lal.GPSTimeNow()

    singles = event.singles
    if not enable_snr_series:
        singles = [single for single in singles if single.snr is not None]

    ifos = [single.detector for single in singles]

    # Extract SNRs from table.
    snrs = np.ma.asarray([
        np.ma.masked if single.snr is None else single.snr
        for single in singles
    ])

    # Look up physical parameters for detector.
    detectors = [
        lalsimulation.DetectorPrefixToLALDetector(str(ifo)) for ifo in ifos
    ]
    responses = np.asarray([det.response for det in detectors])
    locations = np.asarray([det.location for det in detectors])

    # Power spectra for each detector.
    psds = [single.psd for single in singles]
    psds = [
        timing.InterpolatedPSD(filter.abscissa(psd),
                               psd.data.data,
                               f_high_truncate=f_high_truncate) for psd in psds
    ]

    log.debug('calculating templates')
    H = filter.sngl_inspiral_psd(waveform, f_min=f_low, **event.template_args)

    log.debug('calculating noise PSDs')
    HS = [filter.signal_psd_series(H, S) for S in psds]

    # Signal models for each detector.
    log.debug('calculating Fisher matrix elements')
    signal_models = [timing.SignalModel(_) for _ in HS]

    # Get SNR=1 horizon distances for each detector.
    horizons = np.asarray([
        signal_model.get_horizon_distance() for signal_model in signal_models
    ])

    weights = np.ma.asarray([
        1 / np.square(signal_model.get_crb_toa_uncert(snr))
        for signal_model, snr in zip(signal_models, snrs)
    ])

    # Center detector array.
    locations -= np.sum(locations * weights.reshape(-1, 1),
                        axis=0) / np.sum(weights)

    if cosmology:
        log.warn('Enabling cosmological prior. ' 'This feature is UNREVIEWED.')

    if enable_snr_series:
        log.warn('Enabling input of SNR time series. '
                 'This feature is UNREVIEWED.')
        snr_series = [single.snr_series for single in singles]
        if all(s is None for s in snr_series):
            snr_series = None
    else:
        snr_series = None

    # Maximum barycentered arrival time error:
    # |distance from array barycenter to furthest detector| / c + 5 ms.
    # For LHO+LLO, this is 15.0 ms.
    # For an arbitrary terrestrial detector network, the maximum is 26.3 ms.
    max_abs_t = np.max(np.sqrt(np.sum(np.square(locations / lal.C_SI),
                                      axis=1))) + 0.005

    if snr_series is None:
        log.warn(
            "No SNR time series found, so we are creating a zero-noise "
            "SNR time series from the whitened template's autocorrelation "
            "sequence. The sky localization uncertainty may be "
            "underestimated.")

        acors, sample_rates = zip(
            *[filter.autocorrelation(_, max_abs_t) for _ in HS])
        sample_rate = sample_rates[0]
        deltaT = 1 / sample_rate
        nsamples = len(acors[0])
        assert all(sample_rate == _ for _ in sample_rates)
        assert all(nsamples == len(_) for _ in acors)
        nsamples = nsamples * 2 - 1

        snr_series = []
        for acor, single in zip(acors, singles):
            series = lal.CreateCOMPLEX8TimeSeries('fake SNR', 0, 0, deltaT,
                                                  lal.StrainUnit, nsamples)
            series.epoch = single.time - 0.5 * (nsamples - 1) * deltaT
            acor = np.concatenate((np.conj(acor[:0:-1]), acor))
            series.data.data = single.snr * filter.exp_i(single.phase) * acor
            snr_series.append(series)

    # Ensure that all of the SNR time series have the same sample rate.
    # FIXME: for now, the Python wrapper expects all of the SNR time sries to
    # also be the same length.
    deltaT = snr_series[0].deltaT
    sample_rate = 1 / deltaT
    if any(deltaT != series.deltaT for series in snr_series):
        raise ValueError('BAYESTAR does not yet support SNR time series with '
                         'mixed sample rates')

    # Ensure that all of the SNR time series have odd lengths.
    if any(len(series.data.data) % 2 == 0 for series in snr_series):
        raise ValueError('SNR time series must have odd lengths')

    # Trim time series to the desired length.
    max_abs_n = int(np.ceil(max_abs_t * sample_rate))
    desired_length = 2 * max_abs_n - 1
    for i, series in enumerate(snr_series):
        length = len(series.data.data)
        if length > desired_length:
            snr_series[i] = lal.CutCOMPLEX8TimeSeries(
                series, length // 2 + 1 - max_abs_n, desired_length)

    # FIXME: for now, the Python wrapper expects all of the SNR time sries to
    # also be the same length.
    nsamples = len(snr_series[0].data.data)
    if any(nsamples != len(series.data.data) for series in snr_series):
        raise ValueError('BAYESTAR does not yet support SNR time series of '
                         'mixed lengths')

    # Perform sanity checks that the middle sample of the SNR time series match
    # the sngl_inspiral records. Relax valid interval slightly from
    # +/- 0.5 deltaT to +/- 0.6 deltaT for floating point roundoff error.
    for single, series in zip(singles, snr_series):
        if np.abs(0.5 * (nsamples - 1) * series.deltaT +
                  float(series.epoch - single.time)) >= 0.6 * deltaT:
            raise ValueError('BAYESTAR expects the SNR time series to be '
                             'centered on the single-detector trigger times')

    # Extract the TOAs in GPS nanoseconds from the SNR time series, assuming
    # that the trigger happened in the middle.
    toas_ns = [
        series.epoch.ns() + 1e9 * 0.5 *
        (len(series.data.data) - 1) * series.deltaT for series in snr_series
    ]

    # Collect all of the SNR series in one array.
    snr_series = np.vstack([series.data.data for series in snr_series])

    # Center times of arrival and compute GMST at mean arrival time.
    # Pre-center in integer nanoseconds to preserve precision of
    # initial datatype.
    epoch = sum(toas_ns) // len(toas_ns)
    toas = 1e-9 * (np.asarray(toas_ns) - epoch)
    # FIXME: np.average does not yet support masked arrays.
    # Replace with np.average when numpy 1.13.0 is available.
    mean_toa = np.sum(toas * weights) / np.sum(weights)
    toas -= mean_toa
    epoch += int(np.round(1e9 * mean_toa))
    epoch = lal.LIGOTimeGPS(0, int(epoch))
    gmst = lal.GreenwichMeanSiderealTime(epoch)

    # Translate SNR time series back to time of first sample.
    toas -= 0.5 * (nsamples - 1) * deltaT

    # If minimum distance is not specified, then default to 0 Mpc.
    if min_distance is None:
        min_distance = 0

    # If maximum distance is not specified, then default to the SNR=4
    # horizon distance of the most sensitive detector.
    if max_distance is None:
        max_distance = max(horizons) / 4

    # If prior_distance_power is not specified, then default to 2
    # (p(r) ~ r^2, uniform in volume).
    if prior_distance_power is None:
        prior_distance_power = 2

    # Raise an exception if 0 Mpc is the minimum effective distance and the
    # prior is of the form r**k for k<0
    if min_distance == 0 and prior_distance_power < 0:
        raise ValueError(
            ('Prior is a power law r^k with k={}, '
             'undefined at min_distance=0').format(prior_distance_power))

    # Time and run sky localization.
    log.debug('starting computationally-intensive section')
    if method == 'toa_phoa_snr':
        skymap, log_bci, log_bsn = _sky_map.toa_phoa_snr(
            min_distance, max_distance, prior_distance_power, cosmology, gmst,
            sample_rate, toas, snr_series, responses, locations, horizons)
        skymap = Table(skymap)
        skymap.meta['log_bci'] = log_bci
        skymap.meta['log_bsn'] = log_bsn
    elif method == 'toa_phoa_snr_mcmc':
        skymap = localize_emcee(
            logl=_sky_map.log_likelihood_toa_phoa_snr,
            loglargs=(gmst, sample_rate, toas, snr_series, responses,
                      locations, horizons),
            logp=toa_phoa_snr_log_prior,
            logpargs=(min_distance, max_distance, prior_distance_power,
                      max_abs_t),
            xmin=[0, -1, min_distance, -1, 0, 0],
            xmax=[2 * np.pi, 1, max_distance, 1, 2 * np.pi, 2 * max_abs_t],
            nside=nside,
            chain_dump=chain_dump)
    else:
        raise ValueError('Unrecognized method: %s' % method)

    # Convert distance moments to parameters
    distmean = skymap.columns.pop('DISTMEAN')
    diststd = skymap.columns.pop('DISTSTD')
    skymap['DISTMU'], skymap['DISTSIGMA'], skymap['DISTNORM'] = \
        distance.moments_to_parameters(distmean, diststd)

    # Add marginal distance moments
    good = np.isfinite(distmean) & np.isfinite(diststd)
    prob = (moc.uniq2pixarea(skymap['UNIQ']) * skymap['PROBDENSITY'])[good]
    distmean = distmean[good]
    diststd = diststd[good]
    rbar = (prob * distmean).sum()
    r2bar = (prob * (np.square(diststd) + np.square(distmean))).sum()
    skymap.meta['distmean'] = rbar
    skymap.meta['diststd'] = np.sqrt(r2bar - np.square(rbar))

    log.debug('finished computationally-intensive section')
    end_time = lal.GPSTimeNow()

    # Fill in metadata and return.
    program, _ = os.path.splitext(os.path.basename(sys.argv[0]))
    skymap.meta['creator'] = 'BAYESTAR'
    skymap.meta['origin'] = 'LIGO/Virgo'
    skymap.meta['vcs_info'] = vcs_info
    skymap.meta['gps_time'] = float(epoch)
    skymap.meta['runtime'] = float(end_time - start_time)
    skymap.meta['instruments'] = {single.detector for single in singles}
    skymap.meta['gps_creation_time'] = end_time
    skymap.meta['history'] = [
        '', 'Generated by calling the following Python function:',
        '{}.{}{}'.format(__name__, frame.f_code.co_name, argstr), '',
        'This was the command line that started the program:',
        ' '.join([program] + sys.argv[1:])
    ]

    return skymap
#
# Produce data with a coherent signal in H1, L1, V1
#
data_dict = {}
Psig = None

# Read in *coincidence* XML (overridden by injection, if present)
if opts.coinc:
    print("Loading coinc XML:", opts.coinc)
    xmldoc = utils.load_filename(opts.coinc)
    coinc_table = table.get_table(xmldoc,
                                  lsctables.CoincInspiralTable.tableName)
    assert len(coinc_table) == 1
    coinc_row = coinc_table[0]
    event_time = float(coinc_row.get_end())  #
    event_time_gps = lal.GPSTimeNow(
    )  # Pack as GPSTime *explicitly*, so all time operations are type-consistent
    event_time_gps.gpsSeconds = int(event_time)
    event_time_gps.gpsNanoSeconds = int(
        1e9 * (event_time - event_time_gps.gpsSeconds))
    theEpochFiducial = event_time_gps  # really should avoid duplicate names
    print("Coinc XML loaded, event time: %s" % str(coinc_row.get_end()))
    # Populate the SNR sequence and mass sequence
    sngl_inspiral_table = table.get_table(
        xmldoc, lsctables.SnglInspiralTable.tableName)
    m1, m2 = None, None
    for sngl_row in sngl_inspiral_table:
        # NOTE: gstlal is exact match, but other pipelines may not be
        assert m1 is None or (sngl_row.mass1 == m1 and sngl_row.mass2 == m2)
        m1, m2 = sngl_row.mass1, sngl_row.mass2
        rhoExpected[str(
            sngl_row.ifo)] = sngl_row.snr  # record for comparisons later
Exemple #11
0
def ligolw_sky_map(sngl_inspirals,
                   waveform,
                   f_low,
                   min_distance=None,
                   max_distance=None,
                   prior_distance_power=None,
                   method="toa_phoa_snr",
                   psds=None,
                   nside=-1,
                   chain_dump=None,
                   phase_convention='antifindchirp',
                   snr_series=None,
                   enable_snr_series=False):
    """Convenience function to produce a sky map from LIGO-LW rows. Note that
    min_distance and max_distance should be in Mpc.

    Returns a 'NESTED' ordering HEALPix image as a Numpy array.
    """

    # Ensure that sngl_inspiral is either a single template or a list of
    # identical templates
    for key in 'mass1 mass2 spin1x spin1y spin1z spin2x spin2y spin2z'.split():
        if hasattr(sngl_inspirals[0], key):
            value = getattr(sngl_inspirals[0], key)
            if any(value != getattr(_, key) for _ in sngl_inspirals):
                raise ValueError(
                    '{0} field is not the same for all detectors'.format(key))

    ifos = [sngl_inspiral.ifo for sngl_inspiral in sngl_inspirals]

    # Extract SNRs from table.
    snrs = np.ma.asarray([
        np.ma.masked if sngl_inspiral.snr is None else sngl_inspiral.snr
        for sngl_inspiral in sngl_inspirals
    ])

    # Look up physical parameters for detector.
    detectors = [
        lalsimulation.DetectorPrefixToLALDetector(str(ifo)) for ifo in ifos
    ]
    responses = np.asarray([det.response for det in detectors])
    locations = np.asarray([det.location for det in detectors])

    # Power spectra for each detector.
    if psds is None:
        psds = [timing.get_noise_psd_func(ifo) for ifo in ifos]

    log.debug('calculating templates')
    H = filter.sngl_inspiral_psd(sngl_inspirals[0], waveform, f_min=f_low)

    log.debug('calculating noise PSDs')
    HS = [filter.signal_psd_series(H, S) for S in psds]

    # Signal models for each detector.
    log.debug('calculating Fisher matrix elements')
    signal_models = [timing.SignalModel(_) for _ in HS]

    # Get SNR=1 horizon distances for each detector.
    horizons = np.asarray([
        signal_model.get_horizon_distance() for signal_model in signal_models
    ])

    weights = np.ma.asarray([
        1 / np.square(signal_model.get_crb_toa_uncert(snr))
        for signal_model, snr in zip(signal_models, snrs)
    ])

    # Center detector array.
    locations -= np.sum(locations * weights.reshape(-1, 1),
                        axis=0) / np.sum(weights)

    if enable_snr_series:
        log.warn(
            'Enabling input of SNR time series. This feature is UNREVIEWED.')
    else:
        snr_series = None

    # Maximum barycentered arrival time error:
    # |distance from array barycenter to furthest detector| / c + 5 ms.
    # For LHO+LLO, this is 15.0 ms.
    # For an arbitrary terrestrial detector network, the maximum is 26.3 ms.
    max_abs_t = np.max(np.sqrt(np.sum(np.square(locations / lal.C_SI),
                                      axis=1))) + 0.005

    if snr_series is None:
        log.warn(
            "No SNR time series found, so we are creating a zero-noise "
            "SNR time series from the whitened template's autocorrelation "
            "sequence. The sky localization uncertainty may be "
            "underestimated.")

        acors, sample_rates = zip(
            *[filter.autocorrelation(_, max_abs_t) for _ in HS])
        sample_rate = sample_rates[0]
        deltaT = 1 / sample_rate
        nsamples = len(acors[0])
        assert all(sample_rate == _ for _ in sample_rates)
        assert all(nsamples == len(_) for _ in acors)
        nsamples = nsamples * 2 - 1

        snr_series = []
        for acor, sngl in zip(acors, sngl_inspirals):
            series = lal.CreateCOMPLEX8TimeSeries('fake SNR', 0, 0, deltaT,
                                                  lal.StrainUnit, nsamples)
            series.epoch = sngl.end - 0.5 * (nsamples - 1) * deltaT
            acor = np.concatenate((np.conj(acor[:0:-1]), acor))
            if phase_convention.lower() == 'antifindchirp':
                # The matched filter phase convention does NOT affect the
                # template autocorrelation sequence; however it DOES affect
                # the maximum-likelihood phase estimate AND the SNR time series.
                # So if we are going to apply the anti-findchirp phase
                # correction later, we'll have to apply a complex conjugate to
                # the autocorrelation sequence to cancel it here.
                acor = np.conj(acor)
            series.data.data = sngl.snr * filter.exp_i(sngl.coa_phase) * acor
            snr_series.append(series)

    # Ensure that all of the SNR time series have the same sample rate.
    # FIXME: for now, the Python wrapper expects all of the SNR time sries to
    # also be the same length.
    deltaT = snr_series[0].deltaT
    sample_rate = 1 / deltaT
    if any(deltaT != series.deltaT for series in snr_series):
        raise ValueError(
            'BAYESTAR does not yet support SNR time series with mixed sample rates'
        )

    # Ensure that all of the SNR time series have odd lengths.
    if any(len(series.data.data) % 2 == 0 for series in snr_series):
        raise ValueError('SNR time series must have odd lengths')

    # Trim time series to the desired length.
    max_abs_n = int(np.ceil(max_abs_t * sample_rate))
    desired_length = 2 * max_abs_n - 1
    for i, series in enumerate(snr_series):
        length = len(series.data.data)
        if length > desired_length:
            snr_series[i] = lal.CutCOMPLEX8TimeSeries(
                series, length // 2 + 1 - max_abs_n, desired_length)

    # FIXME: for now, the Python wrapper expects all of the SNR time sries to
    # also be the same length.
    nsamples = len(snr_series[0].data.data)
    if any(nsamples != len(series.data.data) for series in snr_series):
        raise ValueError(
            'BAYESTAR does not yet support SNR time series of mixed lengths')

    # Perform sanity checks that the middle sample of the SNR time series match
    # the sngl_inspiral records.
    for sngl_inspiral, series in zip(sngl_inspirals, snr_series):
        if np.abs(0.5 * (nsamples - 1) * series.deltaT +
                  float(series.epoch - sngl_inspiral.end)) >= 0.5 * deltaT:
            raise ValueError(
                'BAYESTAR expects the SNR time series to be centered on the sngl_inspiral end times'
            )

    # Extract the TOAs in GPS nanoseconds from the SNR time series, assuming
    # that the trigger happened in the middle.
    toas_ns = [
        series.epoch.ns() + 1e9 * 0.5 *
        (len(series.data.data) - 1) * series.deltaT for series in snr_series
    ]

    # Collect all of the SNR series in one array.
    snr_series = np.vstack([series.data.data for series in snr_series])

    # Fudge factor for excess estimation error in gstlal_inspiral.
    fudge = 0.83
    snr_series *= fudge

    # If using 'findchirp' phase convention rather than gstlal/mbta,
    # then flip signs of phases.
    if phase_convention.lower() == 'antifindchirp':
        log.warn('Using anti-FINDCHIRP phase convention; inverting phases. '
                 'This is currently the default and it is appropriate for '
                 'gstlal and MBTA but not pycbc as of observing run 1 ("O1"). '
                 'The default setting is likely to change in the future.')
        snr_series = np.conj(snr_series)

    # Center times of arrival and compute GMST at mean arrival time.
    # Pre-center in integer nanoseconds to preserve precision of
    # initial datatype.
    epoch = sum(toas_ns) // len(toas_ns)
    toas = 1e-9 * (np.asarray(toas_ns) - epoch)
    # FIXME: np.average does not yet support masked arrays.
    # Replace with np.average when numpy 1.13.0 is available.
    mean_toa = np.sum(toas * weights) / np.sum(weights)
    toas -= mean_toa
    epoch += int(np.round(1e9 * mean_toa))
    epoch = lal.LIGOTimeGPS(0, int(epoch))
    gmst = lal.GreenwichMeanSiderealTime(epoch)

    # Translate SNR time series back to time of first sample.
    toas -= 0.5 * (nsamples - 1) * deltaT

    # If minimum distance is not specified, then default to 0 Mpc.
    if min_distance is None:
        min_distance = 0

    # If maximum distance is not specified, then default to the SNR=4
    # horizon distance of the most sensitive detector.
    if max_distance is None:
        max_distance = max(horizons) / 4

    # If prior_distance_power is not specified, then default to 2
    # (p(r) ~ r^2, uniform in volume).
    if prior_distance_power is None:
        prior_distance_power = 2

    # Raise an exception if 0 Mpc is the minimum effective distance and the prior
    # is of the form r**k for k<0
    if min_distance == 0 and prior_distance_power < 0:
        raise ValueError(
            ("Prior is a power law r^k with k={}, " +
             "undefined at min_distance=0").format(prior_distance_power))

    # Rescale distances to horizon distance of most sensitive detector.
    max_horizon = np.max(horizons)
    horizons /= max_horizon
    min_distance /= max_horizon
    max_distance /= max_horizon

    # Time and run sky localization.
    log.debug('starting computationally-intensive section')
    start_time = lal.GPSTimeNow()
    if method == "toa_phoa_snr":
        skymap = Table(
            _sky_map.toa_phoa_snr(min_distance, max_distance,
                                  prior_distance_power, gmst, sample_rate,
                                  toas, snr_series, responses, locations,
                                  horizons))
    elif method == "toa_phoa_snr_mcmc":
        skymap = emcee_sky_map(
            logl=_sky_map.log_likelihood_toa_phoa_snr,
            loglargs=(gmst, sample_rate, toas, snr_series, responses,
                      locations, horizons),
            logp=toa_phoa_snr_log_prior,
            logpargs=(min_distance, max_distance, prior_distance_power,
                      max_abs_t),
            xmin=[0, -1, min_distance, -1, 0, 0],
            xmax=[2 * np.pi, 1, max_distance, 1, 2 * np.pi, 2 * max_abs_t],
            nside=nside,
            chain_dump=chain_dump,
            max_horizon=max_horizon * fudge)
    else:
        raise ValueError("Unrecognized method: %s" % method)

    # Convert distance moments to parameters
    distmean = skymap.columns.pop('DISTMEAN')
    diststd = skymap.columns.pop('DISTSTD')
    skymap['DISTMU'], skymap['DISTSIGMA'], skymap['DISTNORM'] = \
        distance.moments_to_parameters(distmean, diststd)

    # Add marginal distance moments
    good = np.isfinite(distmean) & np.isfinite(diststd)
    prob = (moc.uniq2pixarea(skymap['UNIQ']) * skymap['PROBDENSITY'])[good]
    distmean = distmean[good]
    diststd = diststd[good]
    rbar = (prob * distmean).sum()
    r2bar = (prob * (np.square(diststd) + np.square(distmean))).sum()
    skymap.meta['distmean'] = rbar
    skymap.meta['diststd'] = np.sqrt(r2bar - np.square(rbar))

    # Rescale
    rescale = max_horizon * fudge
    skymap['DISTMU'] *= rescale
    skymap['DISTSIGMA'] *= rescale
    skymap.meta['distmean'] *= rescale
    skymap.meta['diststd'] *= rescale
    skymap['DISTNORM'] /= np.square(rescale)

    end_time = lal.GPSTimeNow()
    log.debug('finished computationally-intensive section')

    # Fill in metadata and return.
    skymap.meta['creator'] = 'BAYESTAR'
    skymap.meta['origin'] = 'LIGO/Virgo'
    skymap.meta['gps_time'] = float(epoch)
    skymap.meta['runtime'] = float(end_time - start_time)
    skymap.meta['instruments'] = {
        sngl_inspiral.ifo
        for sngl_inspiral in sngl_inspirals
    }
    skymap.meta['gps_creation_time'] = end_time

    return skymap
Exemple #12
0
from __future__ import division
import pycbc
import lal
import itertools
import numpy
from pycbc.detector import Detector
from pycbc.inject import InjectionSet
from pycbc.types import TimeSeries
from glue.ligolw import ligolw
from glue.ligolw import lsctables
from glue.ligolw import utils as ligolw_utils

end_time = float(lal.GPSTimeNow())
mass1 = 30
mass2 = 30
distance = 1e6 * lal.PC_SI
taper = 'TAPER_STARTEND'

random = numpy.random.uniform
latitude = numpy.arccos(random(low=-1, high=1))
longitude = random(low=0, high=2 * lal.PI)
inclination = numpy.arccos(random(low=-1, high=1))
polarization = random(low=0, high=2 * lal.PI)

# create LIGOLW document
xmldoc = ligolw.Document()
xmldoc.appendChild(ligolw.LIGO_LW())

# create sim inspiral table, link it to document and fill it
sim_table = lsctables.New(lsctables.SimInspiralTable)
Exemple #13
0
def pick_coinc():
    """Pick a coincidence from the "First Two Years" paper."""
    filename = pkg_resources.resource_filename(
        __name__, '../data/first2years/2016/gstlal.xml.gz')
    xmldoc = utils.load_filename(filename, contenthandler=ContentHandler)
    root, = xmldoc.childNodes

    # Remove unneeded tables
    for lsctable in (lsctables.FilterTable, lsctables.SegmentTable,
                     lsctables.SegmentDefTable, lsctables.SimInspiralTable,
                     lsctables.SummValueTable, lsctables.SearchSummVarsTable):
        root.removeChild(lsctable.get_table(xmldoc))

    coinc_inspiral_table = table = lsctables.CoincInspiralTable.get_table(
        xmldoc)

    # Determine event with most recent sideral time
    gps_time_now = lal.GPSTimeNow()
    gmsts = np.asarray([lal.GreenwichMeanSiderealTime(_.end) for _ in table])
    gmst_now = lal.GreenwichMeanSiderealTime(gps_time_now)
    div, rem = divmod(gmst_now - gmsts, 2 * np.pi)
    i = np.argmin(rem)
    new_gmst = div[i] * 2 * np.pi + gmsts[i]
    old_time = table[i].end
    new_time = lal.LIGOTimeGPS()
    result = lal.GreenwichMeanSiderealTimeToGPS(new_gmst, new_time)
    result.disown()
    del result
    delta_t = new_time - old_time
    target_coinc_event_id = int(table[i].coinc_event_id)

    # Remove unneeded rows
    table[:] = [
        row for row in table
        if int(row.coinc_event_id) == target_coinc_event_id
    ]
    target_end_time = table[0].get_end()

    coinc_table = table = lsctables.CoincTable.get_table(xmldoc)
    table[:] = [
        row for row in table
        if int(row.coinc_event_id) == target_coinc_event_id
    ]

    table = lsctables.CoincMapTable.get_table(xmldoc)
    table[:] = [
        row for row in table
        if int(row.coinc_event_id) == target_coinc_event_id
    ]
    target_sngl_inspirals = frozenset(row.event_id for row in table)

    sngl_inspiral_table = table = lsctables.SnglInspiralTable.get_table(xmldoc)
    table[:] = [row for row in table if row.event_id in target_sngl_inspirals]

    table = lsctables.ProcessTable.get_table(xmldoc)
    table[:] = [row for row in table if row.program == 'gstlal_inspiral']
    target_process_ids = frozenset(row.process_id for row in table)

    table = lsctables.SearchSummaryTable.get_table(xmldoc)
    table[:] = [
        row for row in table if target_end_time in row.get_out()
        and row.process_id in target_process_ids
    ]
    target_process_ids = frozenset(row.process_id for row in table)

    table = lsctables.ProcessTable.get_table(xmldoc)
    table[:] = [row for row in table if row.process_id in target_process_ids]

    table = lsctables.ProcessParamsTable.get_table(xmldoc)
    table[:] = [row for row in table if row.process_id in target_process_ids]

    # Shift event times
    for row in coinc_inspiral_table:
        row.end += delta_t
    for row in sngl_inspiral_table:
        row.end += delta_t
        row.end_time_gmst = lal.GreenwichMeanSiderealTime(row.end)

    # The old version of gstlal used to produce the "First Two Years" data set
    # stored likelihood in the coinc_event.likelihood column, but newer
    # versions store the *natural log* of the likelihood here. The p_astro
    # calculation requires this to be log likelihood.
    for row in coinc_table:
        row.likelihood = np.log(row.likelihood)

    # Gstlal stores the template's SVD bank index in the Gamma1 column.
    # Fill this in so that we can calculate p_astro
    # (see :mod:`gwcelery.tasks.p_astro_gstlal`).
    for row in sngl_inspiral_table:
        row.Gamma1 = 16

    coinc_xml = io.BytesIO()
    utils.write_fileobj(xmldoc, coinc_xml)
    return coinc_xml.getvalue()
#
# Generate an inner product using the original discrete PSD
# Perform an inner product using it *and* using an analytic PSD
#
# Populate signal
m1 = 10*lal.LAL_MSUN_SI
m2 = 10*lal.LAL_MSUN_SI

df = psd_dict[detectors[0]].deltaF
fSample = df * 2 *( len(psd_dict[detectors[0]].data.data)-1)  # rescale
print("To construct a signal, we  reconstruct the sampling rate and time window, consistent with the default PSD sampling: (fSample, 1/df) = ", fSample, 1/df)
Psig = lalsimutils.ChooseWaveformParams(
    m1 = m1,m2 =m2,
    fmin = 30, 
    fref=100, ampO=0,
    tref = lal.GPSTimeNow(),   # factored_likelihood requires GPS be assigned 
    radec=True, theta=1.2, phi=2.4,
    detector='H1', 
    dist=25.*1.e6*lal.LAL_PC_SI,
    deltaT=1./fSample,
    deltaF = df
    )
data_dict={}
data_dict['H1'] = lalsimutils.non_herm_hoff(Psig)
Psig.detector = 'L1'
data_dict['L1'] = lalsimutils.non_herm_hoff(Psig)
Psig.detector = 'V1'
data_dict['V1'] = lalsimutils.non_herm_hoff(Psig)
psd_analytic_dict = {}
psd_analytic_dict['H1'] = lalsim.SimNoisePSDaLIGOZeroDetHighPower# lal.LIGOIPsd
psd_analytic_dict['L1'] = lalsim.SimNoisePSDaLIGOZeroDetHighPower #lal.LIGOIPsd
)  # Use actual injection GPS time (assumed from trigger)
#theEpochFiducial = lal.LIGOTimeGPS(1000000000.000000000)     # Use epoch of the data
tEventFiducial = 0  #  time relative to fiducial epoch, used to identify window to look in.  Checked empirically.

detectors = ['H1', "L1", "V1"]
psd_dict['H1'] = lalsim.SimNoisePSDiLIGOSRD
#psd_dict['L1'] = lalsim.SimNoisePSDiLIGOSRD
psd_dict['V1'] = lalsim.SimNoisePSDiLIGOSRD

Psig = lalsimutils.xml_to_ChooseWaveformParams_array("mdc.xml.gz")[
    0]  # Load in the physical parameters of the injection (=first element)
Psig.approx = lalsim.SEOBNRv4
Psig.print_params()

# Load IFO FFTs.
tS = lal.GPSTimeNow()
# ASSUME data has same sampling rate!
df = 1. / 32
dt = 1. / fSample
Psig.deltaF = df
Psig.detector = 'H1'
data_dict['H1'] = lalsimutils.non_herm_hoff(Psig)
#Psig.detector='L1'
#data_dict['L1'] = lalsimutils.non_herm_hoff(Psig)
Psig.detector = 'V1'
data_dict['V1'] = lalsimutils.non_herm_hoff(Psig)

tE = lal.GPSTimeNow()
cost_dict['readin'] = tE - tS
#print data_dict['H1'].data.data[10]  # confirm data loaded
df = data_dict['H1'].deltaF
            m1, m2, opts.eff_lambda, opts.deff_lambda or 0)
        Psig.lambda1 = lambda1
        Psig.lambda2 = lambda2
if Psig and not opts.cache_file:  # Print parameters of fake data
    Psig.print_params()
    print("---- End injection parameters ----")

# Reset origin of time, if required. (This forces different parts of data to be read- important! )
if opts.force_gps_time:
    print(" +++ USER HAS OVERRIDDEN FIDUCIAL EPOCH +++ ")
    print(
        "  The zero of time (and the region to be windowed) will be changed; you had better know what you are doing.  "
    )
    print("    original ", lalsimutils.stringGPSNice(theEpochFiducial))
    print("    new      ", opts.force_gps_time)
    theEpochFiducial = lal.GPSTimeNow()
    theEpochFiducial = opts.force_gps_time
#    theEpochFiducial.gpsSeconds = int(opts.force_gps_time)
#    theEpochFiducial.gpsNanoSeconds =  int(1e9*(opts.force_gps_time - int(opts.force_gps_time)))

# Create artificial "signal".  Needed to minimize duplicate code when I
#  -  consistently test waveform duration
#  - copy template parameters
#  - [test code] : generate plots vs time [test code], expected SNR, etc
#       WARNING: Test code plots will not look perfect, because we don't know the true sky location (or phase, polarization, ...)
if not Psig and opts.channel_name:  # If data loaded but no signal generated
    if (not opts.template_mass1) or (not opts.template_mass2) or (
            not opts.force_gps_time):
        print(
            " CANCEL: For frame-file reading, arguments --mass1 --mass2 --event-time  all required "
        )
Exemple #17
0
def plot_segments_history(
        seglistdicts,
        segments_to_plot=['trigger buffers', 'h(t) gate', 'state vector'],
        t_max=None,
        length=86400.,
        labelspacing=10800.,
        colors={
            'H1': numpy.array((1.0, 0.0, 0.0)),
            'L1': numpy.array((0.0, 0.8, 0.0)),
            'V1': numpy.array((1.0, 0.0, 1.0)),
            'H1L1': numpy.array((.5, .5, .5))
        },
        fig=None,
        axes=None):
    if fig is None:
        fig = plt.figure(figsize=(15, 5), )
    if axes is None:
        axes = fig.add_subplot(111)
    # If t_max is specified, cut the segments so they end at t_max,
    # otherwise set it to the current time
    if t_max is None:
        t_max = float(lal.GPSTimeNow())
    else:
        seglist_to_drop = segments.segmentlist(
            [segments.segment(lal.LIGOTimeGPS(t_max), segments.PosInfinity)])
        for seglistdict in seglistdicts.values():
            for seglist in seglistdict.values():
                seglist -= seglist_to_drop
    t_min = t_max - length
    bottom = []
    width = []
    left_edge = []
    y_ticks = []
    y_tick_labels = []
    color_list = []
    color_dict = {
        'H1': numpy.array((1.0, 0.0, 0.0)),
        'L1': numpy.array((0.0, 0.8, 0.0)),
        'V1': numpy.array((1.0, 0.0, 1.0)),
        'H1L1': numpy.array((.5, .5, .5))
    }
    x_format = tkr.FuncFormatter(lambda x, pos: datetime.datetime(
        *lal.GPSToUTC(int(x))[:7]).strftime('%Y-%m-%d, %H:%M:%S UTC'))
    x_ticks = numpy.arange(t_min, t_max + labelspacing, labelspacing)

    for j, segtype in enumerate(segments_to_plot):
        for row, (ifo,
                  segmentlist) in enumerate(seglistdicts[segtype].items()):
            y_ticks.append(row + 2 * j + 0.5)
            y_tick_labels.append('%s %s' % (ifo, segtype))
            bottom.extend([row + 2 * j + 0.25] * len(segmentlist))
            color_list.extend([color_dict[ifo]] * len(segmentlist))
            for segment in segmentlist:
                width.append(float(segment[1]) - float(segment[0]))
                left_edge.append(float(segment[0]))

    edgecolor_list = ['w'] * len(bottom)
    fig.patch.set_alpha(0.0)
    axes.barh(bottom,
              width,
              height=0.5,
              left=left_edge,
              color=color_list,
              edgecolor=edgecolor_list)
    plt.xlim([t_min, t_max])
    axes.xaxis.set_major_formatter(x_format)
    plt.yticks(y_ticks, y_tick_labels)
    plt.xticks(x_ticks, rotation=10.)
    axes.tick_params(axis='y', which='both', left='off', right='off')
    axes.grid(color=(0.1, 0.4, 0.5), linewidth=2)
    # FIXME use this grid() when we have a newer matplotlib
    # axes.grid(color=(0.1,0.4,0.5), linewidth=2, which='both', axis='x')
    # FIXME Switch to tight_layout() when matplotlib is updated
    try:
        fig.tight_layout(pad=.8)
        return fig, axes
    except AttributeError:
        return fig, axes
Exemple #18
0
def write_sky_map(filename, m, nest=False, moc=False, objid=None, url=None,
    instruments=None, gps_time=None, gps_creation_time=None, creator=None,
    origin=None, runtime=None, distmean=None, diststd=None):
    """Write a gravitational-wave sky map to a file, populating the header
    with optional metadata."""

    #
    # Populate optional header fieds.
    #

    extra_header = []

    if objid is not None:
        extra_header.append(('OBJECT', objid,
            'Unique identifier for this event'))

    if url is not None:
        extra_header.append(('REFERENC', url,
            'URL of this event'))

    if instruments is not None:
        if not isinstance(instruments, six.string_types):
            instruments = str(lsctables.ifos_from_instrument_set(instruments))
        extra_header.append(('INSTRUME', instruments,
            'Instruments that triggered this event'))

    if gps_time is not None:
        extra_header.append(('DATE-OBS', gps_to_iso8601(gps_time),
            'UTC date of the observation'))
        extra_header.append(('MJD-OBS', gps_to_mjd(gps_time),
            'modified Julian date of the observation'))

    if gps_creation_time is None:
        gps_creation_time = lal.GPSTimeNow()
    extra_header.append(('DATE', gps_to_iso8601(gps_creation_time),
        'UTC date of file creation'))

    if creator is not None:
        extra_header.append(('CREATOR', creator,
            'Program that created this file'))

    if origin is not None:
        extra_header.append(('ORIGIN', origin,
            'Organization responsible for this FITS file'))

    if runtime is not None:
        extra_header.append(('RUNTIME', runtime,
            'Runtime in seconds of the CREATOR program'))

    if distmean is not None:
        extra_header.append(('DISTMEAN', distmean,
            'Posterior mean distance in Mpc'))

    if diststd is not None:
        extra_header.append(('DISTSTD', diststd,
            'Posterior standard deviation of distance in Mpc'))

    if moc:
        m = m.copy()
        for name, default_unit in (('PROBDENSITY', u.steradian**-1),
                                   ('DISTMU', u.Mpc),
                                   ('DISTSIGMA', u.Mpc),
                                   ('DISTNORM', u.Mpc**-2)):
            try:
                col = m[name]
            except KeyError:
                continue
            if not col.unit:
                col.unit = default_unit
        hdu = fits.table_to_hdu(m)
        hdu.header.extend((
            ('PIXTYPE', 'HEALPIX', 'HEALPIX pixelisation'),
            ('ORDERING', 'NUNIQ', 'Pixel ordering scheme: RING, NESTED, or NUNIQ'),
            ('COORDSYS', 'C', 'Ecliptic, Galactic or Celestial (equatorial)')))
        hdu.header.extend(extra_header)
        hdulist = fits.HDUList([fits.PrimaryHDU(), hdu])
        hdulist.writeto(filename, clobber=True)
    else:
        m = np.atleast_2d(m)
        hp.write_map(filename, m, nest=nest, fits_IDL=True, coord='C',
            column_names=('PROB', 'DISTMU', 'DISTSIGMA', 'DISTNORM')[:len(m)],
            column_units=('pix-1', 'Mpc', 'Mpc', 'Mpc-2')[:len(m)],
            extra_header=extra_header)
Exemple #19
0
                              )  # plot in Mpc, not m.  Note PDF has to change
            pdfvalsPrior = pdfvalsPrior * (1e6 * lal.LAL_PC_SI
                                           )  # rescale units
            pdfvals = pdfvals * (1e6 * lal.LAL_PC_SI)  # rescale units
        plt.plot(xvals,
                 pdfvalsPrior,
                 label="prior:" + str(param),
                 linestyle='--')
        plt.plot(xvals, pdfvals, label=str(param))
        plt.plot(xvals, cdfvals, label='cdf:' + str(param))
        plt.xlabel(str(param))
        plt.legend()
        plt.savefig("test_like_and_samp-" + str(param) + ".pdf")
#    plt.show()

tGPSStart = lal.GPSTimeNow()
res, var, ret, lnLmarg, neff = sampler.integrate(
    likelihood_function,
    "ra",
    "dec",
    "tref",
    "phi",
    "incl",
    "psi",
    "dist",
    n=100,
    nmax=nMaxEvals,
    igrandmax=rho2Net / 2,
    full_output=True,
    neff=100,
    igrand_threshold_fraction=fracThreshold,