Exemplo n.º 1
0
def test_simple_fit_binned():
    """Make sure objects adequately implement mathematical intent."""

    lct = lctemplate.get_gauss2()

    # load in simulated phases
    ph = np.loadtxt(datadir + "/template_phases.asc")
    lcf = lcfitters.LCFitter(lct, ph)
    lcf.fit(unbinned=False, estimate_errors=True)
    expected_val = r"""
Log Likelihood for fit: 1080.31

Mixture Amplitudes
------------------
P1 : 0.5840 +\- 0.0220
P2 : 0.4160 +\- 0.0220
DC : 0.0000 +\- 0.0000

P1 -- Gaussian
------------------
Width   : 0.0106 +\- 0.0004
Location: 0.1007 +\- 0.0006

P2 -- Gaussian
------------------
Width   : 0.0213 +\- 0.0010
Location: 0.5493 +\- 0.0015

delta   : 0.1007 +\- 0.0006
Delta   : 0.4486 +\- 0.0016
"""

    assert expected_val.strip() == str(lcf).strip()
def get_TOA_accuracy(phases):
    # Given some subset of the event times, phases, and weights, compute
    # the TOA based on a reference event near the middle of the span.
    # Build the TOA as a PINT TOA() object
    lcf = lcfitters.LCFitter(template, phases)
    if args.fitbg:
        for i in xrange(2):
            lcf.fit_position(unbinned=False)
            lcf.fit_background(unbinned=False)
    dphi, dphierr = lcf.fit_position(unbinned=args.unbinned)
    #print("The TOA error is: {}".format(dphierr/fbary))
    return (dphierr / fbary)
def estimate_toa(mjds, phases, tdbs):
    """ Return a pint TOA object for the provided times and phases."""

    # Given some subset of the event times, phases, and weights, compute
    # the TOA based on a reference event near the middle of the span.
    # Build the TOA as a PINT TOA() object
    lcf = lcfitters.LCFitter(template, phases)
    if args.fitbg:
        for i in xrange(2):
            lcf.fit_position(unbinned=False)
            lcf.fit_background(unbinned=False)
    dphi, dphierr = lcf.fit_position(unbinned=args.unbinned)
    log.info('Measured phase shift dphi={0}, dphierr={1}'.format(
        dphi, dphierr))

    # find MJD closest to center of observation and turn it into a TOA
    argmid = np.searchsorted(mjds, 0.5 * (mjds.min() + mjds.max()))
    tmid = tdbs[argmid]
    tplus = tmid + TimeDelta(1 * u.s, scale='tdb')
    toamid = pint.toa.TOA(tmid)
    toaplus = pint.toa.TOA(tplus)
    toas = pint.toa.TOAs(toalist=[toamid, toaplus])
    toas.compute_TDBs()
    toas.compute_posvels(ephem=args.ephem, planets=planets)
    phsi, phsf = modelin.phase(toas.table)
    fbary = (phsi[1] - phsi[0]) + (phsf[1] - phsf[0])
    fbary._unit = u.Hz
    # First delta is to get time of phase 0.0 of initial model
    # Second term corrects for the measured phase offset to align with template
    print("printing dphi: {}".format(dphi))
    print("printing fbary: {}".format(fbary))
    print("printing TimeDelta(dphi/fbary,scale='tdb'): {}".format(
        TimeDelta(dphi / fbary, scale='tdb')))
    tfinal = tmid + TimeDelta(-phsf[0].value / fbary, scale='tdb') + TimeDelta(
        dphi / fbary, scale='tdb')
    print("printing tfinal from trial5_uncertainty.py: {}".format(tfinal))
    # Use PINT's TOA writer to save the TOA
    nsrc = lcf.template.norm() * len(lcf.phases)
    nbkg = (1 - lcf.template.norm()) * len(lcf.phases)
    toafinal = pint.toa.TOA(tfinal,
                            nsrc='%.2f' % nsrc,
                            nbkg='%.2f' % nbkg,
                            exposure='%.2f' % exposure,
                            dphi='%.5f' % dphi)
    log.info("Src rate = {0} c/s, Bkg rate = {1} c/s".format(
        nsrc / exposure, nbkg / exposure))
    print("dphierr = {0}, fbary = {1}".format(dphierr, fbary))
    return toafinal, dphierr / fbary * 1e6
Exemplo n.º 4
0
def estimate_toa(mjds, phases, tdbs, topo, obs):
    """ Return a pint TOA object for the provided times and phases."""

    # Given some subset of the event times, phases, and weights, compute
    # the TOA based on a reference event near the middle of the span.
    # Build the TOA as a PINT TOA() object
    lcf = lcfitters.LCFitter(deepcopy(template), phases)
    # fitbg does not work!  Disabling.
    #    if args.fitbg:
    #        for i in xrange(2):
    #            lcf.fit_position(unbinned=False)
    #            lcf.fit_background(unbinned=False)
    dphi, dphierr = lcf.fit_position(unbinned=args.unbinned)
    log.info('Measured phase shift dphi={0}, dphierr={1}'.format(
        dphi, dphierr))

    # find MJD closest to center of observation and turn it into a TOA
    argmid = np.searchsorted(mjds, 0.5 * (mjds.min() + mjds.max()))
    tmid = tdbs[argmid]  # Should we used tdbld?

    if topo:  #tdbs are topocentric TT MJD times
        tplus = tmid + TimeDelta(1 * u.s, scale='tt')
        toamid = pint.toa.TOA(tmid, obs=obs.name)
        toaplus = pint.toa.TOA(tplus, obs=obs.name)
    else:  #tdbs are TDB MJD times
        tplus = tmid + TimeDelta(1 * u.s, scale='tdb')
        toamid = pint.toa.TOA(tmid)
        toaplus = pint.toa.TOA(tplus)

    toas = pint.toa.get_TOAs_list([toamid, toaplus],
                                  include_gps=args.use_gps,
                                  include_bipm=args.use_bipm,
                                  ephem=args.ephem,
                                  planets=planets)

    phsi, phsf = modelin.phase(toas, abs_phase=True)
    if topo:
        sc = 'tt'
    else:
        sc = 'tdb'
    # Compute frequency = d(phase)/dt
    f = (phsi[1] - phsi[0]) + (phsf[1] - phsf[0])
    f._unit = u.Hz

    # First delta is to get time of phase 0.0 of initial model
    # Second term corrects for the measured phase offset to align with template
    tfinal = tmid + TimeDelta(-phsf[0].value / f, scale=sc) + TimeDelta(
        dphi / f, scale=sc)

    # Use PINT's TOA writer to save the TOA
    nsrc = lcf.template.norm() * len(lcf.phases)
    nbkg = (1 - lcf.template.norm()) * len(lcf.phases)

    if args.topo:  #tfinal is a topocentric TT MJD
        telposvel = obs.posvel_gcrs(tfinal)
        x = telposvel.pos[0].to(u.km)
        y = telposvel.pos[1].to(u.km)
        z = telposvel.pos[2].to(u.km)
        vx = telposvel.vel[0].to(u.km / u.s)
        vy = telposvel.vel[1].to(u.km / u.s)
        vz = telposvel.vel[2].to(u.km / u.s)

        toafinal = pint.toa.TOA(tfinal.utc,
                                scale='utc',
                                obs='spacecraft',
                                nsrc='%.2f' % nsrc,
                                nbkg='%.2f' % nbkg,
                                exposure='%.2f' % exposure,
                                dphi='%.5f' % dphi,
                                mjdTT='%.8f' % tfinal.tt.mjd,
                                telx='%.8f' % x.value,
                                tely='%.8f' % y.value,
                                telz='%.8f' % z.value,
                                vx='%.8f' % vx.value,
                                vy='%.8f' % vy.value,
                                vz='%.8f' % vz.value)

    else:
        toafinal = pint.toa.TOA(tfinal,
                                nsrc='%.2f' % nsrc,
                                nbkg='%.2f' % nbkg,
                                exposure='%.2f' % exposure,
                                dphi='%.5f' % dphi)

    log.info("Src rate = {0} c/s, Bkg rate = {1} c/s".format(
        nsrc / exposure, nbkg / exposure))
    return toafinal, dphierr / f.value * 1.e6
Exemplo n.º 5
0
def estimate_toa(mjds, phases, ph_times, topo, obs, modelin, tmid=None):
    """ Return a pint TOA object for the provided times and phases.

    Longer description here.

    Parameters
    ----------
    mjds : array of floats
        The MJD times of each photon. These are for sorting the TOAs into
        groups and making plots, not for precision work! The timescale
        may be different for different datasets (see pint.toa.get_mjds)
    phases : array
        Array of model-computed phase values for each photon. Should be floats
        between 0.0 and 1.0
    ph_times : array of astropy.Time objects
        Array of photon times, as recorded at Observatory obs
        If obs=="Barycenter" then these should be BAT times in the TDB timescale
        with the Roemer delays removed (the usual sense of "barycentered" times)
    topo : bool
        If True, then TOA will be computed for the arrival time at the Spacecraft
        and the TOA line will have the spacecraft ECI position included.
        If False, then the TOA will be a Barycentric Arrival Time (BAT)
    obs : pint.observatory.Observatory
        The observatory corresponding to the photon event times.
        This is NOT necessarily the observatory for the output TOAs,
        which can be the Barycenter.
    tmid : Time (default=None)
        Fiducial time for TOA. If None, then use photon time closest to midpoint.
        Should be at observatory if topo, else should be a BAT
"""

    # Given some subset of the event times, phases, and weights, compute
    # the TOA based on a reference event near the middle of the span.
    # Build the TOA as a PINT TOA() object
    lcf = lcfitters.LCFitter(deepcopy(template), phases)
    # fitbg does not work!  Disabling.
    #    if args.fitbg:
    #        for i in xrange(2):
    #            lcf.fit_position(unbinned=False)
    #            lcf.fit_background(unbinned=False)
    dphi, dphierr = lcf.fit_position(unbinned=args.unbinned, track=args.track)
    log.info("Measured phase shift dphi={0}, dphierr={1}".format(
        dphi, dphierr))

    # find time of event closest to center of observation and turn it into a TOA
    argmid = np.searchsorted(mjds, 0.5 * (mjds.min() + mjds.max()))
    if tmid is None:
        tmid = ph_times[argmid]
    # So, tmid should be a time at the observatory if topo, otherwise
    # it should be a BAT (in TDB timescale with delays applied)
    # Here, convert tmid if not topo and data not barycentered

    if topo:
        tplus = tmid + TimeDelta(1 * u.s, scale=tmid.scale)
        toamid = pint.toa.TOA(tmid, obs=obs.name)
        toaplus = pint.toa.TOA(tplus, obs=obs.name)
    else:
        # If input data were not barycentered but we want barycentric TOAs
        # then make TMID into a BAT
        if tmid.scale not in ("tdb", "tcb"):
            log.debug("Making TOA, tmid {}, tmid.scale {}, obs {}".format(
                tmid, tmid.scale, obs.name))
            toas = pint.toa.get_TOAs_list(
                [pint.toa.TOA(tmid, obs=obs.name)],
                include_gps=args.use_gps,
                include_bipm=args.use_bipm,
                ephem=args.ephem,
                planets=planets,
            )
            tmid = Time(modelin.get_barycentric_toas(toas),
                        format="mjd",
                        scale="tdb")[0]
            log.debug("New tmid {}, tmid.scale {}".format(tmid, tmid.scale))

        tplus = tmid + TimeDelta(1 * u.s, scale=tmid.scale)
        toamid = pint.toa.TOA(tmid, obs="Barycenter")
        toaplus = pint.toa.TOA(tplus, obs="Barycenter")

    toas = pint.toa.get_TOAs_list(
        [toamid, toaplus],
        include_gps=args.use_gps,
        include_bipm=args.use_bipm,
        ephem=args.ephem,
        planets=planets,
    )

    phsi, phsf = modelin.phase(toas, abs_phase=True)
    if topo:
        sc = "tt"
    else:
        sc = "tdb"
    # Compute frequency = d(phase)/dt
    f = (phsi[1] - phsi[0]) + (phsf[1] - phsf[0])
    f._unit = u.Hz

    # First delta is to get time of phase 0.0 of initial model
    # Second term corrects for the measured phase offset to align with template
    tfinal = (tmid + TimeDelta(-phsf[0].value / f, scale=sc) +
              TimeDelta(dphi / f, scale=sc))

    # Use PINT's TOA writer to save the TOA
    nsrc = lcf.template.norm() * len(lcf.phases)
    nbkg = (1 - lcf.template.norm()) * len(lcf.phases)

    if args.topo:  # tfinal is a topocentric TT MJD
        telposvel = obs.posvel_gcrs(tfinal)
        x = telposvel.pos[0].to(u.km)
        y = telposvel.pos[1].to(u.km)
        z = telposvel.pos[2].to(u.km)
        vx = telposvel.vel[0].to(u.km / u.s)
        vy = telposvel.vel[1].to(u.km / u.s)
        vz = telposvel.vel[2].to(u.km / u.s)

        toafinal = pint.toa.TOA(
            tfinal.utc,
            obs="spacecraft",
            nsrc="%.2f" % nsrc,
            nbkg="%.2f" % nbkg,
            exposure="%.2f" % exposure,
            dphi="%.5f" % dphi,
            mjdTT="%.8f" % tfinal.tt.mjd,
            telx="%.8f" % x.value,
            tely="%.8f" % y.value,
            telz="%.8f" % z.value,
            vx="%.8f" % vx.value,
            vy="%.8f" % vy.value,
            vz="%.8f" % vz.value,
        )

    else:
        # Make a TOA for the Barycenter, which is the default obs
        toafinal = pint.toa.TOA(
            tfinal,
            obs="Barycenter",
            nsrc="%.2f" % nsrc,
            nbkg="%.2f" % nbkg,
            exposure="%.2f" % exposure,
            dphi="%.5f" % dphi,
        )
        toasfinal = pint.toa.get_TOAs_list(
            [toafinal],
            include_gps=args.use_gps,
            include_bipm=args.use_bipm,
            ephem=args.ephem,
            planets=planets,
        )
        log.debug("Modelin final phase {}".format(
            modelin.phase(toasfinal, abs_phase=True)))
    log.info("Src rate = {0} c/s, Bkg rate = {1} c/s".format(
        nsrc / exposure, nbkg / exposure))
    return toafinal, dphierr / f.value * 1.0e6
Exemplo n.º 6
0
log.info("Template properties: \n{0}".format(str(template)))

# load up events and exposure information
f = pyfits.open(args.eventname)
phases = f[1].data.field(args.phasecol)
try:
    exposure = f[1].header['exposure']
except:
    exposure = 0

h = float(hm(phases))
log.info("Htest : {0:.2f} ({1:.2f} sigma)".format(h, h2sig(h)))

# make sure template shape is fixed
lcf = lcfitters.LCFitter(template, phases)
for prim in lcf.template.primitives:
    prim.free[:] = False

# do iterative fit of position and background
for i in xrange(2):
    lcf.fit_position(unbinned=False)
    lcf.fit_background(unbinned=False)

# get exposure information
try:
    f = pyfits.open(args.eventname)
    f.close()
except:
    exposure = 0