Beispiel #1
0
        for sngl_inspiral in sngl_inspirals)

    # Loop over sky localization methods
    for method in opts.method:
        log.info("%s:method '%s':computing sky map", coinc.coinc_event_id, method)
        if opts.chain_dump:
            chain_dump = '%s.chain.npy' % int(coinc.coinc_event_id)
        else:
            chain_dump = None
        try:
            sky_map, epoch, elapsed_time = ligolw_sky_map.ligolw_sky_map(
                sngl_inspirals, approximant, amplitude_order, phase_order, f_low,
                opts.min_distance, opts.max_distance, opts.prior_distance_power,
                psds=psds, method=method, nside=opts.nside, chain_dump=chain_dump)
        except (ArithmeticError, ValueError):
            log.exception("%s:method '%s':sky localization failed", coinc.coinc_event_id, method)
            count_sky_maps_failed += 1
            if not opts.keep_going:
                raise
        else:
            log.info("%s:method '%s':saving sky map", coinc.coinc_event_id, method)
            fits.write_sky_map('%s.%s.fits.gz' % (int(coinc.coinc_event_id), method),
                sky_map, objid=str(coinc.coinc_event_id), gps_time=float(epoch),
                creator=parser.get_prog_name(), runtime=elapsed_time,
                instruments=instruments, nest=True)


if count_sky_maps_failed > 0:
    raise RuntimeError("{0} sky map{1} did not converge".format(
        count_sky_maps_failed, 's' if count_sky_maps_failed > 1 else ''))
Beispiel #2
0
    fits_nest = True

    if not args.enable_distance_map:
        hpmap = skypost.as_healpix(args.nside, nest=fits_nest, fast=not(args.slowsmoothskymaps))
    else:
        print('Constructing 3D clustered posterior.')
        try:
          skypost3d = sac.Clustered3DKDEPosterior(np.column_stack((data['ra'], data['dec'], data['dist'])))
        except:
          print("ERROR, cannot use skypost3d with LIB output. Exiting..\n")
          import sys
          sys.exit(1)

        print('Producing distance map')
        hpmap = skypost3d.as_healpix(args.nside, nest=fits_nest)
    names=data.dtype.names 
    if 'time' in names:
      gps_time=data['time'].mean()
    elif 'time_mean' in names:
      gps_time=data['time_mean'].mean()
    elif 'time_maxl' in names:
      gps_time=data['time_maxl'].mean()
    else:
      print("Cannot find time, time_mean, or time maxl variable in posterior. Not saving sky_pos obj.\n")
      exit(0)

    fits.write_sky_map(os.path.join(args.outdir, args.fitsoutname),
                       hpmap, creator=parser.get_prog_name(),
                       objid=args.objid, gps_time=gps_time,
                       nest=fits_nest)
        opts.min_distance, opts.max_distance, opts.prior_distance_power,
        phase_convention=opts.phase_convention, nside=opts.nside,
        f_high_truncate=opts.f_high_truncate,
        method=opts.method, chain_dump=chain_dump)
    prob, distmu, distsigma, _ = sky_map
    distmean, diststd = distance.parameters_to_marginal_moments(
        prob, distmu, distsigma)
    log.info("sky localization complete")

    # upload FITS file
    fitsdir = tempfile.mkdtemp()
    try:
        fitspath = os.path.join(fitsdir, opts.output)
        fits.write_sky_map(fitspath, sky_map, gps_time=float(epoch),
            creator=parser.prog, objid=str(graceid),
            url='https://gracedb.ligo.org/events/{0}'.format(graceid),
            runtime=elapsed_time, instruments=instruments,
            distmean=distmean, diststd=diststd,
            origin='LIGO/Virgo', nest=True)
        if not opts.dry_run:
            gracedb.writeLog(graceid, "INFO:BAYESTAR:uploaded sky map",
                filename=fitspath, tagname=("sky_loc", "lvem"))
        else:
            command.rename(fitspath, os.path.join('.', opts.output))
    finally:
        shutil.rmtree(fitsdir)
except:
    # Produce log message for any otherwise uncaught exception
    log.exception("sky localization failed")
    # Then re-raise the exception
    raise
    # perform sky localization
    log.info("starting sky localization")
    sky_map, epoch, elapsed_time, instruments = gracedb_sky_map(
        coinc_file, psd_file, "TaylorF2threePointFivePN", 10)
    log.info("sky localization complete")

    # upload FITS file
    fitsdir = tempfile.mkdtemp()
    try:
        fitspath = os.path.join(fitsdir, "skymap.fits.gz")
        fits.write_sky_map(
            fitspath,
            sky_map,
            gps_time=float(epoch),
            creator=parser.get_prog_name(),
            objid=str(graceid),
            url='https://gracedb.ligo.org/events/{0}'.format(graceid),
            runtime=elapsed_time,
            instruments=instruments,
            origin='LIGO/Virgo',
            nest=True)
        gracedb.writeLog(graceid,
                         "INFO:BAYESTAR:uploaded sky map",
                         filename=fitspath,
                         tagname="sky_loc")
    finally:
        shutil.rmtree(fitsdir)
except:
    # Produce log message for any otherwise uncaught exception
    log.exception("sky localization failed")
    # Then re-raise the exception
Beispiel #5
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()
        if opts.chain_dump:
            chain_dump = '%s.chain.npy' % int(coinc.coinc_event_id)
        else:
            chain_dump = None
        try:
            sky_map, epoch, elapsed_time = ligolw_sky_map.ligolw_sky_map(
                sngl_inspirals, opts.waveform, opts.f_low, opts.min_distance,
                opts.max_distance, opts.prior_distance_power, psds=psds,
                method=method, nside=opts.nside, chain_dump=chain_dump,
                phase_convention=opts.phase_convention)
            prob, distmu, distsigma, _ = sky_map
            distmean, diststd = distance.parameters_to_marginal_moments(
                prob, distmu, distsigma)
        except (ArithmeticError, ValueError):
            log.exception("%s:method '%s':sky localization failed", coinc.coinc_event_id, method)
            count_sky_maps_failed += 1
            if not opts.keep_going:
                raise
        else:
            log.info("%s:method '%s':saving sky map", coinc.coinc_event_id, method)
            fits.write_sky_map('%s.%s.fits.gz' % (int(coinc.coinc_event_id), method),
                sky_map, objid=str(coinc.coinc_event_id), gps_time=float(epoch),
                creator=parser.prog, runtime=elapsed_time,
                distmean=distmean, diststd=diststd,
                instruments=instruments, nest=True)


if count_sky_maps_failed > 0:
    raise RuntimeError("{0} sky map{1} did not converge".format(
        count_sky_maps_failed, 's' if count_sky_maps_failed > 1 else ''))
Beispiel #7
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()