Ejemplo n.º 1
0
def heatmap(post, ax, color_map='OrRd', colorbar=False, colorbar_label=''):
    '''
    generate mollweide projection of heatmap with requested annotations
    '''
    plt.sca(ax)
    lalinf_plot.healpix_heatmap(post, cmap=plt.get_cmap(
        color_map))  ### is this buggy when projection=="mollweide"?
    if colorbar:
        cb = plt.colorbar(
            orientation='horizontal', fraction=0.15, pad=0.03,
            shrink=0.8)  ### FIXME: hard-coded options are a bit fragile...
        cb.set_label(colorbar_label)
Ejemplo n.º 2
0
def plot_skymap(output, skypost, pixresol=np.pi/180.0, nest=True,inj=None, fast=True):
    nside = 1
    while hp.nside2resol(nside) > pixresol:
        nside *= 2

    pix_post = skypost.as_healpix(nside, nest=nest, fast=fast)

    fig = pp.figure(frameon=False)
    ax = pp.subplot(111, projection='astro mollweide')
    ax.cla()
    ax.grid()
    plot.healpix_heatmap(pix_post, nest=nest, vmin=0.0, vmax=np.max(pix_post), cmap=pp.get_cmap('cylon'))

    if inj is not None:
        # If using an injection file, also plot an X at the true position
        pp.plot(inj['ra'], inj['dec'], 'kx', ms=30, mew=1)

    pp.savefig(output)
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., vmax=vmax)

# Add colorbar.
if opts.colorbar:
    cb = plot.colorbar()
    cb.set_label(r'prob. per deg$^2$')

# Add contours.
if opts.contour:
    cls = 100 * postprocess.find_greedy_credible_levels(skymap)
    cs = plot.healpix_contour(
        cls, dlon=dlon, nest=metadata['nest'],
        colors='k', linewidths=0.5, levels=opts.contour)
    fmt = r'%g\%%' if rcParams['text.usetex'] else '%g%%'
    plt.clabel(cs, fmt=fmt, fontsize=6, inline=True)
skymap, metadata = fits.read_sky_map(infilename, 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., vmax=vmax, cmap=plt.get_cmap(opts.colormap))

if opts.colorbar:
    # Plot colorbar.
    cb = plot.colorbar()

    # Set colorbar label.
    cb.set_label(r'prob. per deg$^2$')

# Add contours.
if opts.contour:
    indices = np.argsort(-skymap)
    region = np.empty(skymap.shape)
    region[indices] = 100 * np.cumsum(skymap[indices])
    cs = plot.healpix_contour(
Ejemplo n.º 5
0
def mollweideScaffold( post, post_masked, mask=None, projection="astro mollweide", contours=False, color_map='OrRd', contour_color='grey', LatLon=None):
    """
    a standardized plotting routine for the mollweide projections needed in simPlot.py
    each mask supplied via *masks is overlayed on the masked plot

    LatLon will be marked with a red dot iff projection=="mollweide" (assumed EarthFixed coords)
    """
    ### set up figure and axis objects
    figwidth = 10
    figheight = 10

    fig = plt.figure(figsize=(figwidth,figheight))
    ax1 = plt.subplot(2,1,1, projection=projection)
    ax2 = plt.subplot(2,1,2, projection=projection)

    ### establish color map
    cmap = plt.get_cmap(color_map)

    ### establish range for color map
    vmin = min(np.min(post), np.min(post_masked))
    vmax = max(np.max(post), np.max(post_masked))

    ### plot heatmaps
    plt.sca( ax1 )
    lalinf_plot.healpix_heatmap( post, cmap=cmap, vmin=vmin, vmax=vmax, nest=False )
    
    plt.sca( ax2 )
    lalinf_plot.healpix_heatmap( post_masked, cmap=cmap, vmin=vmin, vmax=vmax, nest=False )

    if mask!=None: ### plot the mask as a shaded region
        mask = np.ma.masked_where(mask==1, mask)
        lalinf_plot.healpix_heatmap( mask, cmap=plt.get_cmap('Greys_r'), vmin=0, vmax=1, nest=False, alpha=0.1 )

    if projection=="mollweide": ### add continents
        geojson_filename = os.path.join(os.path.dirname(lalinf_plot.__file__),
            'ne_simplified_coastline.json')
        with open(geojson_filename, 'r') as geojson_file:
            geojson = json.load(geojson_file)
        for shape in geojson['geometries']:
            verts = np.deg2rad(shape['coordinates'])
            color='k'
            ax1.plot(verts[:, 0], verts[:, 1], color=color, linewidth=0.5)
            ax2.plot(verts[:, 0], verts[:, 1], color=color, linewidth=0.5)

    ### plot contours
    if contours:
        if np.sum(post):
            cpost = np.empty(post.shape)
            indecies = np.argsort(post)[::-1]
            cpost[indecies] = np.cumsum(post[indecies])

            plt.sca( ax1 )
            lalinf_plot.healpix_contour( cpost, alpha=0.25, levels=[0.1, 0.5, 0.9], colors=contour_color )
        if np.sum(post_masked):
            cpost = np.empty(post_masked.shape)
            indecies = np.argsort(post_masked)[::-1]
            cpost[indecies] = np.cumsum(post_masked[indecies])

            plt.sca( ax2 )
            lalinf_plot.healpix_contour( cpost, alpha=0.25, levels=[0.1, 0.5, 0.9], colors=contour_color )

    ### set titles
    ax1.set_title('posterior')
    ax2.set_title('masked posterior')

    ### decoration
    for ax in [ax1, ax2]:
        if LatLon!=None:
            lat, lon = LatLon
            ax.plot( lon, lat, marker='o', markeredgecolor='r', markerfacecolor='r', markersize=3, linestyle='none')
        ax.patch.set_alpha(0.)
        ax.set_alpha(0.)

    ### return fig and ax handles
    return fig, [ax1, ax2]
Ejemplo n.º 6
0
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.,
                     vmax=vmax)

# Add colorbar.
if opts.colorbar:
    cb = plot.colorbar()
    cb.set_label(r'prob. per deg$^2$')

# Add contours.
if opts.contour:
    cls = 100 * postprocess.find_greedy_credible_levels(skymap)
    cs = plot.healpix_contour(cls,
                              dlon=dlon,
                              nest=metadata['nest'],
                              colors='k',
Ejemplo n.º 7
0
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.
if opts.colorbar:
    cb = plot.colorbar()
    cb.set_label(r"prob. per deg$^2$")

# Add contours.
if opts.contour:
    cls = 100 * postprocess.find_greedy_credible_levels(skymap)
    cs = plot.healpix_contour(cls, dlon=dlon, nest=metadata["nest"], colors="k", linewidths=0.5, levels=opts.contour)
    fmt = r"%g\%%" if rcParams["text.usetex"] else "%g%%"
    plt.clabel(cs, fmt=fmt, fontsize=6, inline=True)

# Add continents.
if opts.geo:
Ejemplo n.º 8
0
def make_skyview(directory='.',
                 mdc=None,
                 NSIDE=128,
                 ra=None,
                 dec=None,
                 results=None,
                 npost=5000):

    # -- Close any open figures
    plt.close('all')

    # ----------------
    # Read S6 MDC log file
    # -----------------
    if mdc is None:
        print "No MDC log provided."

    # -- Save PWD for future reference
    topdir = os.getcwd()

    # -- Enter requested directory
    os.chdir(directory)
    print "Entered", os.getcwd()
    jobname = glob.glob('*bayeswave.run')[0]

    # ---------------------------------------
    # Extract information from bayeswave.run
    # Note: We may only need the trigger time from this
    # ---------------------------------------
    bayeswave = open(jobname, 'r')
    ifoNames = []
    for line in bayeswave:
        spl = line.split()
        if len(spl) < 1: continue

        # Determine names of IFOs and MDC scale factor
        if spl[0] == 'Command' and spl[1] == 'line:':
            for index, splElement in enumerate(spl):
                if splElement == '--ifo':
                    ifoNames.append(spl[index + 1])

        del spl[-1]
        # Determine number of IFOs
        if ' '.join(spl) == 'number of detectors':
            spl = line.split()
            ifoNum = spl[3]
            continue
        # Determine gps trigger time
        if ' '.join(spl) == 'trigger time (s)':
            spl = line.split()
            gps = spl[3]
            break
    bayeswave.close()

    # --------------------------------
    # Create skymap summary statistics
    # --------------------------------
    # -- Get run name
    params = BwbParams()

    jobname = params.jobname

    # -- Input skymap data
    # num, L, ralist, sin_dec, psi, e, dA, dphi, dt = np.loadtxt(filename, unpack=True)
    print "Extracting RA/DEC samples"
    filename = './chains/' + jobname + 'signal_params.dat.0'
    data = np.loadtxt(filename, unpack=True, usecols=(0, 1, 2))
    ralist = data[1]
    sin_dec = data[2]
    print "Total samples are {0}".format(ralist.size)

    # -- Remove burn in samples
    burnin = ralist.size / 4
    ralist = ralist[burnin:]
    sin_dec = sin_dec[burnin:]
    print "After removing burn-in samples are {0}".format(ralist.size)

    declist = np.arcsin(sin_dec)
    thetalist = np.pi / 2.0 - declist

    radec = np.column_stack((ralist, declist))

    if radec.shape[0] > npost:
        radec = np.random.permutation(radec)[:npost, :]

    kde = sky.ClusteredSkyKDEPosterior(radec)

    # -- Get the sidereal time
    print "Finding sidereal time"
    print "Using GPS {0}".format(gps)
    trigtime = float(gps)
    lalgps = LIGOTimeGPS(trigtime)
    sidtime = XLALGreenwichSiderealTime(lalgps, 0)
    sidtime = sidtime % (np.pi * 2)

    # -- Get the injection location
    print "GOT MDC?"
    print mdc
    if mdc is None:
        injtheta = 0
        injphi = 0
        injdec = 0
        injra = 0
    else:
        injtheta, injphi = mdc.get_theta_phi(trigtime)
        injra = injphi + sidtime
        injdec = np.pi / 2 - injtheta
        print "GOT INJECTION PARAMTERS"
        print injtheta, injra

    # -- Special handling for injections drawn from prior
    if params.ra is not None:
        injdec = params.dec
        injra = params.ra
        injtheta = np.pi / 2 - injdec
        mdc = True

    # -- Make plots directory, if needed
    plotsDir = './plots'
    if not os.path.exists(plotsDir):
        os.makedirs(plotsDir)

    # Add markers (e.g., for injections or external triggers).
    if (ra is not None and dec is not None):
        # Convert the right ascension to either a reference angle from -pi to pi
        # or a wrapped angle from 0 to 2 pi, depending on the version of Matplotlib.
        #for rarad, decrad in [np.deg2rad([ra, dec])]:
        (rarad, decrad) = np.deg2rad([ra, dec])
        if geo:
            dlon = -sidtime  # + or -?
            #rarad = lalinference.plot.reference_angle(rarad + dlon)
            rarad = rarad + dlon
            while rarad > np.pi:
                rarad = rarad - 2 * np.pi
            while rarad < -np.pi:
                rarad = rarad + 2 * np.pi
        else:
            #rarad = lalinference.plot.wrapped_angle(rarad)
            while rarad > 2 * np.pi:
                rarad = rarad - 2 * np.pi
            while rarad < 0:
                rarad = rarad + 2 * np.pi
        # Shift the declination to match hp.projscatter conventions
        decrad = np.pi * 0.5 - decrad

    # -- Plot the skymap and injection location
    skymap = kde.as_healpix(NSIDE, nest=True)

    #fig = plt.figure(frameon=False)
    fig = plt.figure(figsize=(8, 6), frameon=False)
    ax = plt.subplot(111, projection='astro mollweide')
    ax.cla()
    ax.grid()
    lp.healpix_heatmap(skymap,
                       nest=True,
                       vmin=0.0,
                       vmax=np.max(skymap),
                       cmap=plt.get_cmap('cylon'))

    if (ra is not None and dec is not None):
        plt.plot(rarad, dec, 'kx', ms=30, mew=1)
    if mdc is not None:
        plt.plot(injra, injdec, 'kx', ms=30, mew=1)
    plt.savefig(plotsDir + '/skymap.png')
    plt.close()

    lf.write_sky_map('skymap_{0}.fits'.format(gps),
                     skymap,
                     nest=True,
                     gps_time=trigtime)

    # -- Calculate the 50 and 90% credible intervals
    sq_deg = (180.0 / np.pi)**2
    print "Calculating sky area ..."
    (area50, area90) = kde.sky_area([0.5, 0.9]) * sq_deg
    print "Got area50 of {0}".format(area50)

    # -- Get the found contour and searched areas
    if mdc is not None:
        print "Calculating p value of injection"
        injcontour = kde.p_values(np.array([[injra, injdec]]))[0]
        print "Got contour of {0}".format(injcontour)

        print "Calculating searched area..."
        searcharea = (kde.searched_area(np.array([[injra, injdec]])) *
                      sq_deg)[0]
        print "Got searched area of {0}".format(searcharea)
    else:
        injcontour = 0
        searcharea = 0

    pixarea = hp.nside2pixarea(NSIDE, degrees=True)
    print("here")
    if results is not None:
        for name in ['injcontour', 'area50', 'area90', 'searcharea']:
            if name not in results: results[name] = []
            results[name].append(eval(name))

    # -- Make an output file with key statistics
    outfile = open('skystats.txt', 'w')
    outfile.write("# area50  area90  searcharea  injcontour \n")
    outfile.write("{0} {1} {2} {3}".format(area50, area90, searcharea,
                                           injcontour))
    outfile.close()
Ejemplo n.º 9
0
def make_skyview(directory='.', mdc=None, NSIDE=128, ra=None, dec=None, results=None, npost=5000):

    # -- Close any open figures
    plt.close('all')

    # ----------------
    # Read S6 MDC log file
    # -----------------
    if mdc is None:
        print "No MDC log provided."

    # -- Save PWD for future reference
    topdir = os.getcwd()

    # -- Enter requested directory
    os.chdir(directory)
    print "Entered", os.getcwd()
    jobname = glob.glob('*bayeswave.run')[0]
    
    # ---------------------------------------
    # Extract information from bayeswave.run
    # Note: We may only need the trigger time from this
    # ---------------------------------------
    bayeswave = open(jobname, 'r')
    ifoNames = []
    for line in bayeswave:
        spl = line.split()
        if len(spl) < 1: continue
        
        # Determine names of IFOs and MDC scale factor
        if spl[0] == 'Command' and spl[1] == 'line:':
            for index, splElement in enumerate(spl):
                if splElement == '--ifo':
                    ifoNames.append(spl[index+1]) 
                    
        del spl[-1]
        # Determine number of IFOs
        if ' '.join(spl) == 'number of detectors':
            spl = line.split()
            ifoNum = spl[3]
            continue         
        # Determine gps trigger time
        if ' '.join(spl) == 'trigger time (s)':
            spl = line.split()
            gps = spl[3]
            break
    bayeswave.close()

    # --------------------------------
    # Create skymap summary statistics
    # --------------------------------
    # -- Get run name
    params = BwbParams()


    jobname = params.jobname

    # -- Input skymap data
    # num, L, ralist, sin_dec, psi, e, dA, dphi, dt = np.loadtxt(filename, unpack=True)
    print "Extracting RA/DEC samples"
    filename = './chains/' + jobname + 'signal_params.dat.0'
    data = np.loadtxt(filename, unpack=True,usecols=(0,1,2))
    ralist = data[1]
    sin_dec = data[2]
    print "Total samples are {0}".format(ralist.size)

    # -- Remove burn in samples
    burnin = ralist.size/4
    ralist = ralist[burnin:]
    sin_dec = sin_dec[burnin:]
    print "After removing burn-in samples are {0}".format(ralist.size)

    declist = np.arcsin(sin_dec)
    thetalist = np.pi/2.0 - declist

    radec = np.column_stack((ralist, declist))

    if radec.shape[0] > npost:
        radec = np.random.permutation(radec)[:npost,:]

    kde = sky.ClusteredSkyKDEPosterior(radec)

    # -- Get the sidereal time
    print "Finding sidereal time"
    print "Using GPS {0}".format(gps)
    trigtime = float(gps)
    lalgps = LIGOTimeGPS(trigtime)
    sidtime = XLALGreenwichSiderealTime(lalgps, 0)
    sidtime = sidtime % (np.pi*2)

    # -- Get the injection location
    print "GOT MDC?"
    print mdc
    if mdc is None:
        injtheta = 0
        injphi   = 0
        injdec   = 0
        injra    = 0
    else:
        injtheta, injphi = mdc.get_theta_phi(trigtime)
        injra = injphi + sidtime
        injdec = np.pi/2 - injtheta
        print "GOT INJECTION PARAMTERS"
        print injtheta, injra

    # -- Special handling for injections drawn from prior
    if params.ra is not None:
        injdec = params.dec 
        injra =  params.ra
        injtheta = np.pi/2 - injdec
        mdc = True
    
    # -- Make plots directory, if needed
    plotsDir = './plots'
    if not os.path.exists(plotsDir):
        os.makedirs(plotsDir)

    # Add markers (e.g., for injections or external triggers).
    if (ra is not None and dec is not None):
        # Convert the right ascension to either a reference angle from -pi to pi
        # or a wrapped angle from 0 to 2 pi, depending on the version of Matplotlib.
        #for rarad, decrad in [np.deg2rad([ra, dec])]:
        (rarad, decrad) = np.deg2rad([ra, dec])
        if geo:
            dlon = -sidtime # + or -?
            #rarad = lalinference.plot.reference_angle(rarad + dlon)
            rarad = rarad + dlon
            while rarad > np.pi:
                rarad = rarad - 2*np.pi
            while rarad < -np.pi:
                rarad = rarad + 2*np.pi
        else:
            #rarad = lalinference.plot.wrapped_angle(rarad)
            while rarad > 2*np.pi:
                rarad = rarad - 2*np.pi
            while rarad < 0:
                rarad = rarad + 2*np.pi
        # Shift the declination to match hp.projscatter conventions
        decrad = np.pi*0.5 - decrad
   
    # -- Plot the skymap and injection location
    skymap = kde.as_healpix(NSIDE, nest=True)
   
    #fig = plt.figure(frameon=False)
    fig = plt.figure(figsize=(8,6), frameon=False)
    ax = plt.subplot(111, projection='astro mollweide')
    ax.cla()
    ax.grid()
    lp.healpix_heatmap(skymap, nest=True, vmin=0.0, vmax=np.max(skymap), cmap=plt.get_cmap('cylon'))
	
    if (ra is not None and dec is not None):
        plt.plot(rarad, dec, 'kx', ms=30, mew=1)
    if mdc is not None:
        plt.plot(injra, injdec, 'kx', ms=30, mew=1)
    plt.savefig(plotsDir+'/skymap.png')
    plt.close()

    lf.write_sky_map('skymap_{0}.fits'.format(gps), skymap, nest=True, gps_time=trigtime)

    # -- Calculate the 50 and 90% credible intervals
    sq_deg = (180.0/np.pi)**2
    print "Calculating sky area ..."
    (area50, area90) = kde.sky_area( [0.5, 0.9] )*sq_deg
    print "Got area50 of {0}".format(area50)

    # -- Get the found contour and searched areas
    if mdc is not None:
        print "Calculating p value of injection"
        injcontour = kde.p_values( np.array([[injra, injdec]]) )[0]
        print "Got contour of {0}".format(injcontour)
    
        print "Calculating searched area..."
        searcharea = (kde.searched_area( np.array([[injra, injdec]]) )*sq_deg)[0]
        print "Got searched area of {0}".format(searcharea)
    else:
        injcontour = 0
        searcharea = 0

    pixarea = hp.nside2pixarea(NSIDE, degrees=True)
    print("here")
    if results is not None:
        for name in ['injcontour', 'area50', 'area90', 'searcharea']:
            if name not in results: results[name] = []
            results[name].append(eval(name)) 


    # -- Make an output file with key statistics
    outfile = open('skystats.txt', 'w')
    outfile.write("# area50  area90  searcharea  injcontour \n")
    outfile.write("{0} {1} {2} {3}".format(area50, area90, searcharea, injcontour))
    outfile.close()