def process(fitsfilename):
    sky_map = fits.read_sky_map(fitsfilename, moc=True)

    coinc_event_id = sky_map.meta['objid']
    try:
        runtime = sky_map.meta['runtime']
    except KeyError:
        runtime = float('nan')

    contour_pvalues = 0.01 * np.asarray(contours)

    row = db.execute(
        """
        SELECT DISTINCT sim.simulation_id AS simulation_id,
        sim.longitude AS ra, sim.latitude AS dec, sim.distance AS distance,
        ci.combined_far AS far, ci.snr AS snr
        FROM coinc_event_map AS cem1 INNER JOIN coinc_event_map AS cem2
        ON (cem1.coinc_event_id = cem2.coinc_event_id)
        INNER JOIN sim_inspiral AS sim ON (cem1.event_id = sim.simulation_id)
        INNER JOIN coinc_inspiral AS ci ON (cem2.event_id = ci.coinc_event_id)
        WHERE cem1.table_name = 'sim_inspiral'
        AND cem2.table_name = 'coinc_event' AND cem2.event_id = ?
        """, (coinc_event_id, )).fetchone()
    if row is None:
        raise ValueError(
            "No database record found for event '{0}' in '{1}'".format(
                coinc_event_id, command.sqlite_get_filename(db)))
    simulation_id, true_ra, true_dec, true_dist, far, snr = row
    searched_area, searched_prob, offset, searched_modes, contour_areas, \
        area_probs, contour_modes, searched_prob_dist, contour_dists, \
        searched_vol, searched_prob_vol, contour_vols = find_injection_moc(
            sky_map, true_ra, true_dec, true_dist, contours=contour_pvalues,
            areas=areas, modes=modes)

    if snr is None:
        snr = np.nan
    if far is None:
        far = np.nan
    distmean = sky_map.meta.get('distmean', np.nan)
    diststd = sky_map.meta.get('diststd', np.nan)
    log_bci = sky_map.meta.get('log_bci', np.nan)
    log_bsn = sky_map.meta.get('log_bsn', np.nan)

    ret = [coinc_event_id, simulation_id, far, snr, searched_area,
           searched_prob, searched_prob_dist, searched_vol, searched_prob_vol,
           offset, runtime, distmean, diststd, log_bci, log_bsn] \
          + contour_areas + area_probs + contour_dists + contour_vols
    if modes:
        ret += [searched_modes] + contour_modes
    return ret
def process(fitsfilename):
    sky_map = fits.read_sky_map(fitsfilename, moc=True)

    coinc_event_id = sky_map.meta['objid']
    try:
        runtime = sky_map.meta['runtime']
    except KeyError:
        runtime = float('nan')

    contour_pvalues = 0.01 * np.asarray(contours)

    row = db.execute(
        """
        SELECT DISTINCT sim.simulation_id AS simulation_id,
        sim.longitude AS ra, sim.latitude AS dec, sim.distance AS distance,
        ci.combined_far AS far, ci.snr AS snr
        FROM coinc_event_map AS cem1 INNER JOIN coinc_event_map AS cem2
        ON (cem1.coinc_event_id = cem2.coinc_event_id)
        INNER JOIN sim_inspiral AS sim ON (cem1.event_id = sim.simulation_id)
        INNER JOIN coinc_inspiral AS ci ON (cem2.event_id = ci.coinc_event_id)
        WHERE cem1.table_name = 'sim_inspiral'
        AND cem2.table_name = 'coinc_event' AND cem2.event_id = ?
        """, (coinc_event_id,)).fetchone()
    if row is None:
        raise ValueError(
            "No database record found for event '{0}' in '{1}'".format(
                coinc_event_id, command.sqlite_get_filename(db)))
    simulation_id, true_ra, true_dec, true_dist, far, snr = row
    searched_area, searched_prob, offset, searched_modes, contour_areas, \
        area_probs, contour_modes, searched_prob_dist, contour_dists, \
        searched_vol, searched_prob_vol, contour_vols = find_injection_moc(
            sky_map, true_ra, true_dec, true_dist, contours=contour_pvalues,
            areas=areas, modes=modes)

    if snr is None:
        snr = np.nan
    if far is None:
        far = np.nan
    distmean = sky_map.meta.get('distmean', np.nan)
    diststd = sky_map.meta.get('diststd', np.nan)
    log_bci = sky_map.meta.get('log_bci', np.nan)
    log_bsn = sky_map.meta.get('log_bsn', np.nan)

    ret = [coinc_event_id, simulation_id, far, snr, searched_area,
           searched_prob, searched_prob_dist, searched_vol, searched_prob_vol,
           offset, runtime, distmean, diststd, log_bci, log_bsn] \
          + contour_areas + area_probs + contour_dists + contour_vols
    if modes:
        ret += [searched_modes] + contour_modes
    return ret
Пример #3
0
def process(fitsfilename):
    sky_map, metadata = fits.read_sky_map(fitsfilename, nest=None)

    coinc_event_id = metadata['objid']
    try:
        runtime = metadata['runtime']
    except KeyError:
        runtime = float('nan')

    row = db.execute(
        """
        SELECT DISTINCT sim.simulation_id AS simulation_id, sim.longitude AS ra, sim.latitude AS dec,
        ci.combined_far AS far, ci.snr AS snr
        FROM coinc_event_map AS cem1 INNER JOIN coinc_event_map AS cem2
        ON (cem1.coinc_event_id = cem2.coinc_event_id)
        INNER JOIN sim_inspiral AS sim ON (cem1.event_id = sim.simulation_id)
        INNER JOIN coinc_inspiral AS ci ON (cem2.event_id = ci.coinc_event_id)
        WHERE cem1.table_name = 'sim_inspiral'
        AND cem2.table_name = 'coinc_event' AND cem2.event_id = ?""",
        (coinc_event_id, )).fetchone()
    if row is None:
        raise ValueError(
            "No database record found for event '{0}' in '{1}'".format(
                coinc_event_id, command.sqlite_get_filename(db)))
    simulation_id, true_ra, true_dec, far, snr = row
    searched_area, searched_prob, offset, searched_modes, contour_areas, area_probs, contour_modes = postprocess.find_injection(
        sky_map,
        true_ra,
        true_dec,
        contours=[0.01 * p for p in contours],
        areas=areas,
        modes=modes,
        nest=metadata['nest'])

    if snr is None:
        snr = float('nan')
    if far is None:
        far = float('nan')
    distmean = metadata.get('distmean', float('nan'))
    diststd = metadata.get('diststd', float('nan'))

    ret = [
        coinc_event_id, simulation_id, far, snr, searched_area, searched_prob,
        offset, runtime, distmean, diststd
    ] + contour_areas + area_probs
    if modes:
        ret += [searched_modes] + contour_modes
    return ret
def process(fitsfilename):
    sky_map, metadata = fits.read_sky_map(fitsfilename, nest=None)

    coinc_event_id = metadata['objid']
    try:
        runtime = metadata['runtime']
    except KeyError:
        runtime = float('nan')

    row = db.execute("""
        SELECT DISTINCT sim.simulation_id AS simulation_id, sim.longitude AS ra, sim.latitude AS dec,
        ci.combined_far AS far, ci.snr AS snr
        FROM coinc_event_map AS cem1 INNER JOIN coinc_event_map AS cem2
        ON (cem1.coinc_event_id = cem2.coinc_event_id)
        INNER JOIN sim_inspiral AS sim ON (cem1.event_id = sim.simulation_id)
        INNER JOIN coinc_inspiral AS ci ON (cem2.event_id = ci.coinc_event_id)
        WHERE cem1.table_name = 'sim_inspiral'
        AND cem2.table_name = 'coinc_event' AND cem2.event_id = ?""",
        (coinc_event_id,)).fetchone()
    if row is None:
        raise ValueError(
            "No database record found for event '{0}' in '{1}'".format(
            coinc_event_id, command.sqlite_get_filename(db)))
    simulation_id, true_ra, true_dec, far, snr = row
    searched_area, searched_prob, offset, searched_modes, contour_areas, area_probs, contour_modes = postprocess.find_injection(
        sky_map, true_ra, true_dec, contours=[0.01 * p for p in contours],
        areas=areas, modes=modes, nest=metadata['nest'])

    if snr is None:
        snr = float('nan')
    if far is None:
        far = float('nan')
    distmean = metadata.get('distmean', float('nan'))
    diststd = metadata.get('diststd', float('nan'))

    ret = [coinc_event_id, simulation_id, far, snr, searched_area, searched_prob, offset, runtime, distmean, diststd] + contour_areas + area_probs
    if modes:
        ret += [searched_modes] + contour_modes
    return ret
                    type=argparse.FileType('rb'),
                    default='-',
                    nargs='?',
                    help='Input FITS file [default: stdin]')
opts = parser.parse_args()

# Late imports

from lalinference.io import fits
from lalinference.bayestar import postprocess
import healpy as hp
import numpy as np
import json

# Read input file
prob, _ = fits.read_sky_map(opts.input.name, nest=True)

# Resample if requested
if opts.nside is not None and opts.interpolate in ('nearest', 'nested'):
    prob = hp.ud_grade(prob, opts.nside, order_in='NESTED', power=-2)
elif opts.nside is not None and opts.interpolate == 'bilinear':
    prob = postprocess.smooth_ud_grade(prob, opts.nside, nest=True)
if opts.interpolate == 'nested':
    prob = postprocess.interpolate_nested(prob, nest=True)

# Find credible levels
i = np.flipud(np.argsort(prob))
cumsum = np.cumsum(prob[i])
cls = np.empty_like(prob)
cls[i] = cumsum * 100
# Late imports
from matplotlib import pyplot as plt
from matplotlib import gridspec
from matplotlib import transforms
from lalinference.io import fits
from lalinference.plot import marker
from lalinference.bayestar.distance import (
    principal_axes, volume_render, marginal_pdf)
import healpy as hp
import numpy as np
import scipy.stats

# Read input, determine input resolution.
progress.update(-1, 'Loading FITS file')
(prob, mu, sigma, norm), metadata = fits.read_sky_map(
    opts.input.name, distances=True)
npix = len(prob)
nside = hp.npix2nside(npix)

progress.update(-1, 'Preparing projection')

if opts.align_to is None:
    prob2, mu2, sigma2 = prob, mu, sigma
else:
    (prob2, mu2, sigma2, _), _ = fits.read_sky_map(
        opts.align_to.name, distances=True)
R = np.ascontiguousarray(principal_axes(prob2, mu2, sigma2))

if opts.chain:
    chain = np.recfromtxt(opts.chain, names=True)
    chain = np.dot(R.T, (hp.ang2vec(
Пример #7
0
progress = ProgressBar()

progress.max = len(opts.fitsfilenames)

matplotlib.rc('path', simplify=True, simplify_threshold=1)

if opts.colormap is None:
    colors = ['k'] * len(opts.fitsfilenames)
else:
    colors = matplotlib.cm.get_cmap(opts.colormap)
    colors = colors(np.linspace(0, 1, len(opts.fitsfilenames)))
for count_records, (color,
                    fitsfilename) in enumerate(zip(colors,
                                                   opts.fitsfilenames)):
    progress.update(count_records, fitsfilename)
    skymap, metadata = fits.read_sky_map(fitsfilename, nest=None)
    nside = hp.npix2nside(len(skymap))
    gmst = lal.GreenwichMeanSiderealTime(metadata['gps_time']) % (2 * np.pi)

    indices = np.argsort(-skymap)
    region = np.empty(skymap.shape)
    region[indices] = 100 * np.cumsum(skymap[indices])
    plot.healpix_contour(region,
                         nest=metadata['nest'],
                         dlon=-gmst,
                         colors=[color],
                         linewidths=0.5,
                         levels=[opts.contour],
                         alpha=opts.alpha)

progress.update(-1, 'saving figure')
Пример #8
0
import os
import json
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
import healpy as hp
import lal
from lalinference.io import fits
from lalinference import plot
from lalinference.bayestar import postprocess

fig = plt.figure(frameon=False)
ax = plt.axes(projection='mollweide' if opts.geo else 'astro hours mollweide')
ax.grid()

skymap, metadata = fits.read_sky_map(opts.input.name, nest=None)
nside = hp.npix2nside(len(skymap))

if opts.geo:
    dlon = -lal.GreenwichMeanSiderealTime(lal.LIGOTimeGPS(
        metadata['gps_time'])) % (2 * np.pi)
else:
    dlon = 0

# Convert sky map from probability to probability per square degree.
probperdeg2 = skymap / hp.nside2pixarea(nside, degrees=True)

# Plot sky map.
vmax = probperdeg2.max()
plot.healpix_heatmap(probperdeg2,
                     dlon=dlon,
Пример #9
0
import os
import json
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
import healpy as hp
import lal
from lalinference.io import fits
from lalinference import plot
from lalinference.bayestar import postprocess

fig = plt.figure(frameon=False)
ax = plt.axes(projection="mollweide" if opts.geo else "astro hours mollweide")
ax.grid()

skymap, metadata = fits.read_sky_map(opts.input.name, nest=None)
nside = hp.npix2nside(len(skymap))

if opts.geo:
    dlon = -lal.GreenwichMeanSiderealTime(lal.LIGOTimeGPS(metadata["gps_time"])) % (2 * np.pi)
else:
    dlon = 0

# Convert sky map from probability to probability per square degree.
probperdeg2 = skymap / hp.nside2pixarea(nside, degrees=True)

# Plot sky map.
vmax = probperdeg2.max()
plot.healpix_heatmap(probperdeg2, dlon=dlon, nest=metadata["nest"], vmin=0.0, vmax=vmax)

# Add colorbar.
#
incl_sampler = mcsampler.cos_samp_vector # this is NOT dec_samp_vector, because the angular zero point is different!
sampler.add_parameter("inclination", pdf = incl_sampler, cdf_inv = None, left_limit = param_limits["inclination"][0], right_limit = param_limits["inclination"][1], prior_pdf = mcsampler.uniform_samp_theta, adaptive_sampling = not opts.no_adapt)

#
# Distance - luminosity distance to source in parsecs
# sampler: uniform distance over [dmin, dmax), adaptive sampling
#
dist_sampler = functools.partial(mcsampler.uniform_samp_vector, param_limits["distance"][0], param_limits["distance"][1])
sampler.add_parameter("distance", pdf = dist_sampler, cdf_inv = None, left_limit = param_limits["distance"][0], right_limit = param_limits["distance"][1], prior_pdf = numpy.vectorize(lambda x: x**2/(param_limits["distance"][1]**3/3. - param_limits["distance"][0]**3/3.)), adaptive_sampling = not opts.no_adapt)

if opts.skymap_file is not None:
    #
    # Right ascension and declination -- use a provided skymap
    #
    smap, _ = bfits.read_sky_map(opts.skymap_file)
    ss_sampler = mcsampler.HealPixSampler(smap)
    isotropic_bstar_sampler = numpy.vectorize(lambda dec, ra: 1.0/len(smap))

    # FIXME: Should the left and right limits be modified?
    sampler.add_parameter(("declination", "right_ascension"), \
        pdf = ss_sampler.pseudo_pdf, \
        cdf_inv = ss_sampler.pseudo_cdf_inverse, \
        left_limit = (param_limits["declination"][0], param_limits["right_ascension"][0]), \
        right_limit = (param_limits["declination"][1], param_limits["right_ascension"][1]), \
        prior_pdf = isotropic_bstar_sampler)

else:
    #
    # Right ascension - angle in radians from prime meridian plus hour angle
    # sampler: uniform in [0, 2pi), adaptive sampling
Пример #11
0
parser.add_argument(
    'input', metavar='INPUT.fits[.gz]', type=argparse.FileType('rb'),
    default='-', nargs='?', help='Input FITS file [default: stdin]')
opts = parser.parse_args()

# Late imports

from lalinference.io import fits
from lalinference.bayestar import postprocess
import healpy as hp
import numpy as np
import json


# Read input file
prob, _ = fits.read_sky_map(opts.input.name, nest=True)

# Resample if requested
if opts.nside is not None and opts.interpolate in ('nearest', 'nested'):
    prob = hp.ud_grade(prob, opts.nside, order_in='NESTED', power=-2)
elif opts.nside is not None and opts.interpolate == 'bilinear':
    prob = postprocess.smooth_ud_grade(prob, opts.nside, nest=True)
if opts.interpolate == 'nested':
    prob = postprocess.interpolate_nested(prob, nest=True)

# Find credible levels
i = np.flipud(np.argsort(prob))
cumsum = np.cumsum(prob[i])
cls = np.empty_like(prob)
cls[i] = cumsum * 100
Пример #12
0
fig = plt.figure(frameon=False)
ax = plt.axes(projection='mollweide')
ax.grid()

progress = ProgressBar()

progress.update(-1, 'obtaining filenames of sky maps')
fitsfilenames = tuple(command.chainglob(opts.fitsfileglobs))

progress.max = len(fitsfilenames)

matplotlib.rc('path', simplify=True, simplify_threshold=1)

for count_records, fitsfilename in enumerate(fitsfilenames):
    progress.update(count_records, fitsfilename)
    skymap, metadata = fits.read_sky_map(fitsfilename, nest=None)
    nside = hp.npix2nside(len(skymap))
    gmst = lal.GreenwichMeanSiderealTime(metadata['gps_time']) % (2*np.pi)

    indices = np.argsort(-skymap)
    region = np.empty(skymap.shape)
    region[indices] = 100 * np.cumsum(skymap[indices])
    plot.healpix_contour(
        region, nest=metadata['nest'], dlon=-gmst, colors='k', linewidths=0.5,
        levels=[opts.contour], alpha=opts.alpha)

progress.update(-1, 'saving figure')

# If we are using a new enough version of matplotlib, then
# add a white outline to all text to make it stand out from the background.
plot.outline_text(ax)
Пример #13
0
# Late imports
from matplotlib import pyplot as plt
from matplotlib import gridspec
from matplotlib import transforms
from lalinference.io import fits
from lalinference.plot import marker
from lalinference.bayestar.distance import (principal_axes, volume_render,
                                            marginal_pdf)
import healpy as hp
import numpy as np
import scipy.stats

# Read input, determine input resolution.
progress.update(-1, 'Loading FITS file')
(prob, mu, sigma, norm), metadata = fits.read_sky_map(opts.input.name,
                                                      distances=True)
npix = len(prob)
nside = hp.npix2nside(npix)

progress.update(-1, 'Preparing projection')

if opts.align_to is None:
    prob2, mu2, sigma2 = prob, mu, sigma
else:
    (prob2, mu2, sigma2, _), _ = fits.read_sky_map(opts.align_to.name,
                                                   distances=True)
R = np.ascontiguousarray(principal_axes(prob2, mu2, sigma2))

if opts.chain:
    chain = np.recfromtxt(opts.chain, names=True)
    chain = np.dot(R.T, (hp.ang2vec(0.5 * np.pi - chain['dec'], chain['ra']) *
                    help='Input FITS files')
parser.add_argument(
    '-o',
    '--output',
    metavar='OUTPUT.fits[.gz]',
    help='Ouptut FITS file [default: derived from input filenames]')
opts = parser.parse_args()

# Late imports
import os.path
import healpy as hp
import numpy as np
from lalinference.io import fits

# Read all input sky maps
probs, metas = zip(*(fits.read_sky_map(file.name, nest=True)
                     for file in opts.input))

# Determine output HEALPix resolution
npix = max(len(prob) for prob in probs)
nside = hp.npix2nside(npix)

# Average sky maps
prob = np.mean([
    hp.ud_grade(prob, nside, order_in='NESTED', order_out='NESTED', power=-2)
    for prob in probs
],
               axis=0)

# Describe the processing of this file
history = ['Arithmetic mean of the following {} sky maps:'.format(len(probs))]