Example #1
0
    def test_physical_ephem_model_setIII(self):
        """Test physical ephemeris model"""

        # define signals with and without epoch TOAs
        eph1 = deterministic_signals.PhysicalEphemerisSignal(
            sat_orb_elements=True, model="setIII")
        eph2 = deterministic_signals.PhysicalEphemerisSignal(
            sat_orb_elements=True, use_epoch_toas=False, model="setIII")

        # initialize signals
        e1, e2 = eph1(self.psr), eph2(self.psr)

        # set parameters
        params = {
            "d_jupiter_mass":
            -8.561198198000628e-12,
            "d_neptune_mass":
            1.0251757860647059e-11,
            "d_saturn_mass":
            6.22114376130324e-12,
            "d_uranus_mass":
            -2.1157536169469958e-10,
            "frame_drift_rate":
            2.874659280396648e-10,
            "jup_orb_elements":
            np.array([
                0.04140015, -0.03422412, 0.01165894, -0.03525219, -0.00406852,
                0.0421522
            ]),
            "sat_orb_elements":
            np.array([
                -0.39701798, -0.13322608, -0.05025925, 0.36331171, -0.17080321,
                0.25093799
            ]),
        }

        # test against waveform and compare non-epoch and epoch TOA results
        d1 = e1.get_delay(params=params)
        d2 = e2.get_delay(params=params)

        (jup_mjd, jup_orbel,
         sat_orbel) = utils.get_planet_orbital_elements("setIII")

        d3 = utils.physical_ephem_delay(
            self.psr.toas,
            self.psr.planetssb,
            self.psr.pos_t,
            times=jup_mjd,
            jup_orbit=jup_orbel,
            sat_orbit=sat_orbel,
            **params,
        )

        msg1 = "Signal delay does not match function delay"
        assert np.allclose(d1, d3, rtol=1e-10), msg1
        msg2 = "epoch-TOA delay does not match full TOA delay"
        assert np.allclose(d1, d2, rtol=1e-10), msg2
Example #2
0
 def bayes_ephem(self, option="default"):
     """
 Deterministic signal from errors in Solar System ephemerides. 
 """
     eph = deterministic_signals.PhysicalEphemerisSignal(
         use_epoch_toas=True)
     return eph
        def test_ephemeris(self):
            """Test physical-ephemeris delay, made three ways: from
            marginalized GP, from coefficient-based GP, from
            deterministic model."""

            ef = white_signals.MeasurementNoise(
                efac=parameter.Uniform(0.1, 5.0))

            eph = gp_signals.FourierBasisCommonGP_physicalephem(
                sat_orb_elements=None)

            ephc = gp_signals.FourierBasisCommonGP_physicalephem(
                sat_orb_elements=None, coefficients=True)

            ephd = deterministic_signals.PhysicalEphemerisSignal(
                sat_orb_elements=False)

            model = ef + eph
            modelc = ef + ephc
            modeld = ef + ephd

            pta = signal_base.PTA([model(self.psr), model(self.psr2)])
            ptac = signal_base.PTA([modelc(self.psr), modelc(self.psr2)])
            ptad = signal_base.PTA([modeld(self.psr), modeld(self.psr2)])

            cf = 1e-3 * np.random.randn(11)
            cf[0] = 1e-5  # this is more sensitive to linearity

            bs = pta.get_basis()
            da = [np.dot(bs[0], cf), np.dot(bs[1], cf)]

            params = {
                "B1855+09_efac": 1,
                "B1937+21_efac": 1,
                "B1855+09_phys_ephem_gp_coefficients": cf,
                "B1937+21_phys_ephem_gp_coefficients": cf,
            }
            db = ptac.get_delay(params=params)

            dparams = {
                "B1855+09_efac": 1,
                "B1937+21_efac": 1,
                "frame_drift_rate": cf[0],
                "d_jupiter_mass": cf[1],
                "d_saturn_mass": cf[2],
                "d_uranus_mass": cf[3],
                "d_neptune_mass": cf[4],
                "jup_orb_elements": cf[5:],
            }
            dc = ptad.get_delay(params=dparams)

            msg = "Reconstructed ephemeris signals differ!"

            assert np.allclose(da[0], db[0]), msg
            assert np.allclose(da[1], db[1]), msg

            # we don't expect an exact match since we are linearizing
            assert np.allclose(da[0], dc[0], atol=1e-3), msg
            assert np.allclose(da[1], dc[1], atol=1e-3), msg
Example #4
0
    def __init__(self, psrs, params=None,
                 psrTerm=True, bayesephem=True, pta=None):
        
        if pta is None:
        
            # initialize standard model with fixed white noise
            # and powerlaw red noise
            # uses the implementation of ECORR in gp_signals
            print('Initializing the model...')
            
            tmin = np.min([p.toas.min() for p in psrs])
            tmax = np.max([p.toas.max() for p in psrs])
            Tspan = tmax - tmin
            
            s = deterministic.cw_block_circ(amp_prior='log-uniform',
                                            psrTerm=psrTerm, tref=tmin, name='cw')
            s += gp_signals.TimingModel()
            s += blocks.red_noise_block(prior='log-uniform', psd='powerlaw',
                                        Tspan=Tspan, components=30)
                                            
            if bayesephem:
                s += deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True)

            # adding white-noise, and acting on psr objects
            models = []
            for p in psrs:
                if 'NANOGrav' in p.flags['pta']:
                    s2 = s + blocks.white_noise_block(vary=False, inc_ecorr=True,
                                                      gp_ecorr=True)
                    models.append(s2(p))
                else:
                    s3 = s + blocks.white_noise_block(vary=False, inc_ecorr=False)
                    models.append(s3(p))
                    
            pta = signal_base.PTA(models)
            
            # set white noise parameters
            if params is None:
                print('No noise dictionary provided!')
            else:
                pta.set_default_params(params)

            self.pta = pta

        else:
        
            # user can specify their own pta object
            # if ECORR is included, use the implementation in gp_signals
            self.pta = pta
                    
        self.psrs = psrs
        self.params = params
                                   
        self.Nmats = self.get_Nmats()
    dmn = gp_signals.BasisGP(pl_dm, dm_basis, name='dm_gp', coefficients=False)
    # spin noise
    log10_A = parameter.Constant()
    gamma = parameter.Constant()
    pl = utils.powerlaw(log10_A=log10_A, gamma=gamma)
    selection = selections.Selection(selections.no_selection)
    spn = gp_signals.FourierBasisGP(pl,
                                    components=50,
                                    Tspan=None,
                                    coefficients=False,
                                    selection=selection,
                                    modes=None)

    dp = DPDM.dpdm_block(type_='Bayes')
    tm = gp_signals.TimingModel()
    eph = deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True)
    wnb = models.white_noise_block(vary=False)

    model = tm + dp + wnb + dmn + spn + eph
    nparams = []  # Get the number of parameters of each pulsar
    signals = []
    for psr in psrs:
        signal = model(psr)
        nparams.append(len(signal.params) -
                       5)  # Subtracting common DPDM params
        signals.append(signal)
    PTA = signal_base.PTA(signals)
    ndim = len(PTA.params) + 5

    # Use the best fit noise parameters!
    PTA.set_default_params(Dict)
    def test_physical_ephem_model(self):
        """Test physical ephemeris model"""

        if isinstance(self.psr, enterprise.pulsar.Tempo2Pulsar):
            # define signals with and without epoch TOAs
            eph1 = deterministic_signals.PhysicalEphemerisSignal(
                sat_orb_elements=True, model="orbel")
            eph2 = deterministic_signals.PhysicalEphemerisSignal(
                sat_orb_elements=True, use_epoch_toas=False, model="orbel")

            # initialize signals
            e1, e2 = eph1(self.psr), eph2(self.psr)

            # set parameters
            params = {
                "d_jupiter_mass":
                -8.561198198000628e-12,
                "d_neptune_mass":
                1.0251757860647059e-11,
                "d_saturn_mass":
                6.22114376130324e-12,
                "d_uranus_mass":
                -2.1157536169469958e-10,
                "frame_drift_rate":
                2.874659280396648e-10,
                "jup_orb_elements":
                np.array([
                    0.04140015, -0.03422412, 0.01165894, -0.03525219,
                    -0.00406852, 0.0421522
                ]),
                "sat_orb_elements":
                np.array([
                    -0.39701798, -0.13322608, -0.05025925, 0.36331171,
                    -0.17080321, 0.25093799
                ]),
            }

            # test against waveform and compare non-epoch and epoch TOA results
            d1 = e1.get_delay(params=params)
            d2 = e2.get_delay(params=params)

            (jup_mjd, jup_orbel,
             sat_orbel) = utils.get_planet_orbital_elements("orbel")

            d3 = utils.physical_ephem_delay(
                self.psr.toas,
                self.psr.planetssb,
                self.psr.pos_t,
                times=jup_mjd,
                jup_orbit=jup_orbel,
                sat_orbit=sat_orbel,
                **params,
            )

            msg1 = "Signal delay does not match function delay"
            assert np.allclose(d1, d3, rtol=1e-10), msg1
            msg2 = "epoch-TOA delay does not match full TOA delay"
            assert np.allclose(d1, d2, rtol=1e-10), msg2

            # test against pre-computed wafeform
            eph_wf = np.load(datadir + "/phys_ephem_1855_test.npy")
            msg = "Ephemeris delay does not match pre-computed values"
            assert np.allclose(d1, eph_wf, rtol=1e-10), msg

        # test PINT exception raising
        elif isinstance(self.psr, enterprise.pulsar.PintPulsar):
            with self.assertRaises(NotImplementedError) as context:
                eph1 = deterministic_signals.PhysicalEphemerisSignal(
                    sat_orb_elements=True)
                e1 = eph1(self.psr)

                msg = "Physical Ephemeris model is not compatible with PINT "
                msg += "at this time."
                self.assertEqual(msg, str(context.exception))
Example #7
0
def model_bwm(psrs,
              Tmin_bwm=None,
              Tmax_bwm=None,
              skyloc=None,
              logmin=-18,
              logmax=-11,
              upper_limit=False,
              bayesephem=False,
              sngl_psr=False,
              dmgp=False,
              free_rn=False):
    """
    Reads in list of enterprise Pulsar instance and returns a PTA
    instantiated with BWM model:
    per pulsar:
        1. fixed EFAC per backend/receiver system
        2. fixed EQUAD per backend/receiver system
        3. fixed ECORR per backend/receiver system
        4. Red noise modeled as a power-law with 30 sampling frequencies
        5. Linear timing model.
    global:
        1. Deterministic GW burst with memory signal.
        2. Optional physical ephemeris modeling.
    :param Tmin_bwm:
        Min time to search for BWM (MJD). If omitted, uses first TOA.
    :param Tmax_bwm:
        Max time to search for BWM (MJD). If omitted, uses last TOA.
    :param skyloc:
        Fixed sky location of BWM signal search as [cos(theta), phi].
        Search over sky location if ``None`` given.
    :param logmin:
        log of minimum BWM amplitude for prior (log10)
    :param logmax:
        log of maximum BWM amplitude for prior (log10)
    :param upper_limit:
        Perform upper limit on common red noise amplitude. By default
        this is set to False. Note that when perfoming upper limits it
        is recommended that the spectral index also be fixed to a specific
        value.
    :param bayesephem:
        Include BayesEphem model. Set to False by default
    :param sngl_psr:
        run on a single pulsar only. Uses different BWM parameterization to
        avoid problem with sky nulls. Set to False by default.
    :param free_rn:
        Use free red noise spectrum model. Set to False by default.
    """

    amp_prior = 'uniform' if upper_limit else 'log-uniform'

    # find the maximum time span to set GW frequency sampling
    tmin = np.min([p.toas.min() for p in psrs])
    tmax = np.max([p.toas.max() for p in psrs])
    Tspan = tmax - tmin

    if Tmin_bwm == None:
        Tmin_bwm = tmin / const.day
    if Tmax_bwm == None:
        Tmax_bwm = tmax / const.day

    # white noise
    s = white_noise_block(vary=False)

    # red noise
    if free_rn:
        s += free_noise_block(prior=amp_prior, Tspan=Tspan)
    else:
        s += red_noise_block(prior=amp_prior, Tspan=Tspan)

    # GW BWM signal block
    s += bwm_block(Tmin_bwm,
                   Tmax_bwm,
                   amp_prior=amp_prior,
                   skyloc=skyloc,
                   logmin=logmin,
                   logmax=logmax,
                   sngl=sngl_psr,
                   name='bwm')

    # ephemeris model
    if bayesephem:
        s += deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True)

    # timing model
    s += gp_signals.TimingModel(use_svd=True)

    # set up PTA
    pta = signal_base.PTA([s(psr) for psr in psrs])

    return pta
Example #8
0
def model_gwb(psrs,
              psd='powerlaw',
              gamma_common=None,
              orf=None,
              upper_limit=False,
              bayesephem=False):
    """
    Reads in list of enterprise Pulsar instance and returns a PTA
    instantiated with GWB model:
    per pulsar:
        1. fixed EFAC per backend/receiver system
        2. fixed EQUAD per backend/receiver system
        3. fixed ECORR per backend/receiver system
        4. Red noise modeled as a power-law with 30 sampling frequencies
        5. Linear timing model.
    global:
        1.Common red noise modeled with user defined PSD with
        30 sampling frequencies. Available PSDs are
        ['powerlaw', 'turnover']
        2. Optional physical ephemeris modeling.
    :param psd:
        PSD to use for common red noise signal. Available options
        are ['powerlaw', 'turnover']. 'powerlaw' is default
        value.
    :param gamma_common:
        Fixed common red process spectral index value. By default we
        vary the spectral index over the range [0, 7].
    :param orf:
        String representing which overlap reduction function to use.
        By default we do not use any spatial correlations. Permitted
        values are ['hd', 'dipole', 'monopole'].
    :param upper_limit:
        Perform upper limit on common red noise amplitude. By default
        this is set to False. Note that when perfoming upper limits it
        is recommended that the spectral index also be fixed to a specific
        value.
    :param bayesephem:
        Include BayesEphem model. Set to False by default
    """

    amp_prior = 'uniform' if upper_limit else 'log-uniform'

    # find the maximum time span to set GW frequency sampling
    tmin = np.min([p.toas.min() for p in psrs])
    tmax = np.max([p.toas.max() for p in psrs])
    Tspan = tmax - tmin

    # white noise
    s = white_noise_block(vary=False)

    # red noise
    s += red_noise_block(prior=amp_prior, Tspan=Tspan)

    # common red noise block
    s += common_red_noise_block(psd=psd,
                                prior=amp_prior,
                                Tspan=Tspan,
                                gamma_val=gamma_common,
                                name='gwb',
                                orf=orf)

    # ephemeris model
    if bayesephem:
        s += deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True)

    # timing model
    s += gp_signals.TimingModel()

    # set up PTA
    pta = signal_base.PTA([s(psr) for psr in psrs])

    return pta
Example #9
0
    def test_physical_ephem_model(self):
        """Tests physical ephemeris model (which is implemented as a deterministic signal)
        four ways:

        - computed directly with :func:`enterprise.signals.utils.physical_ephem_delay`;
        - computed with :meth:`enterprise.signals.deterministic_signals.PhysicalEphemerisSignal.get_delay`
          with `use_epoch_toas=True` (the default), which reduces computation by evaluating ephemeris corrections
          once per measurement epoch, and then interpolating to the full `toas` vector;
        - computed with :meth:`enterprise.signals.deterministic_signals.PhysicalEphemerisSignal.get_delay`,
          setting `use_epoch_toas=False`;
        - loaded from a golden copy.
        """

        if isinstance(self.psr, enterprise.pulsar.Tempo2Pulsar):
            # define signals with and without epoch TOAs
            eph1 = deterministic_signals.PhysicalEphemerisSignal(
                sat_orb_elements=True, model="orbel")
            eph2 = deterministic_signals.PhysicalEphemerisSignal(
                sat_orb_elements=True, use_epoch_toas=False, model="orbel")

            # initialize signals
            e1, e2 = eph1(self.psr), eph2(self.psr)

            # set parameters
            params = {
                "d_jupiter_mass":
                -8.561198198000628e-12,
                "d_neptune_mass":
                1.0251757860647059e-11,
                "d_saturn_mass":
                6.22114376130324e-12,
                "d_uranus_mass":
                -2.1157536169469958e-10,
                "frame_drift_rate":
                2.874659280396648e-10,
                "jup_orb_elements":
                np.array([
                    0.04140015, -0.03422412, 0.01165894, -0.03525219,
                    -0.00406852, 0.0421522
                ]),
                "sat_orb_elements":
                np.array([
                    -0.39701798, -0.13322608, -0.05025925, 0.36331171,
                    -0.17080321, 0.25093799
                ]),
            }

            # test against waveform and compare non-epoch and epoch TOA results
            d1 = e1.get_delay(params=params)
            d2 = e2.get_delay(params=params)

            (jup_mjd, jup_orbel,
             sat_orbel) = utils.get_planet_orbital_elements("orbel")

            d3 = utils.physical_ephem_delay(
                self.psr.toas,
                self.psr.planetssb,
                self.psr.pos_t,
                times=jup_mjd,
                jup_orbit=jup_orbel,
                sat_orbit=sat_orbel,
                **params,
            )

            msg1 = "Signal delay does not match function delay"
            assert np.allclose(d1, d3, rtol=1e-10), msg1
            msg2 = "epoch-TOA delay does not match full TOA delay"
            assert np.allclose(d1, d2, rtol=1e-10), msg2

            # test against pre-computed wafeform
            eph_wf = np.load(datadir + "/phys_ephem_1855_test.npy")
            msg = "Ephemeris delay does not match pre-computed values"
            assert np.allclose(d1, eph_wf, rtol=1e-10), msg
Example #10
0
def model_3d(psrs, psd='powerlaw', gamma_common=None, upper_limit=False, bayesephem=False):
    """
    Reads in list of enterprise Pulsar instance and returns a PTA
    instantiated with model 3D from the analysis paper:

    per pulsar:
        1. fixed EFAC per backend/receiver system
        2. fixed EQUAD per backend/receiver system
        3. fixed ECORR per backend/receiver system
        4. Red noise modeled as a power-law with 30 sampling frequencies
        5. Linear timing model.

    global:
        1. GWB with HD correlations modeled with user defined PSD with
        30 sampling frequencies. Available PSDs are
        ['powerlaw', 'turnover' 'spectrum']
        2. Monopole signal modeled with user defined PSD with
        30 sampling frequencies. Available PSDs are
        ['powerlaw', 'turnover' 'spectrum']
        3. Optional physical ephemeris modeling.

    :param psd:
        PSD to use for common red noise signal. Available options
        are ['powerlaw', 'turnover' 'spectrum'] 'powerlaw' is default
        value.
    :param gamma_common:
        Fixed common red process spectral index value. By default we
        vary the spectral index over the range [0, 7].
    :param upper_limit:
        Perform upper limit on common red noise amplitude. By default
        this is set to False. Note that when perfoming upper limits it
        is recommended that the spectral index also be fixed to a specific
        value.
    :param bayesephem:
        Include BayesEphem model. Set to False by default
    """

    amp_prior = 'uniform' if upper_limit else 'log-uniform'

    # find the maximum time span to set GW frequency sampling
    tmin = [p.toas.min() for p in psrs]
    tmax = [p.toas.max() for p in psrs]
    Tspan = np.max(tmax) - np.min(tmin)

    # white noise
    s = white_noise_block(vary=False)

    # red noise
    s += red_noise_block(prior=amp_prior, Tspan=Tspan)

    # common red noise block
    s += common_red_noise_block(psd=psd, prior=amp_prior, Tspan=Tspan,
                                gamma_val=gamma_common, orf='hd', name='gw')

    # monopole
    s += common_red_noise_block(psd=psd, prior=amp_prior, Tspan=Tspan,
                                gamma_val=gamma_common, orf='monopole',
                                name='monopole')

    # ephemeris model
    if bayesephem:
        s += deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True)

    # timing model
    s += gp_signals.TimingModel()

    # set up PTA
    pta = signal_base.PTA([s(psr) for psr in psrs])

    # set white noise parameters
    noisedict = get_noise_dict(psrlist=[p.name for p in psrs])
    pta.set_default_params(noisedict)

    return pta
Example #11
0
def model_simple(psrs, psd='powerlaw', efac=False, n_gwbfreqs=30,
                 components=30, freqs=None,
                 vary_gamma=False, upper_limit=False, bayesephem=False,
                 select='backend', red_noise=False, Tspan=None, hd_orf=False,
                 rn_dropout=False, dp_threshold=0.5):
    """
    Reads in list of enterprise Pulsar instance and returns a PTA
    instantiated with the most simple model allowable for enterprise:
    per pulsar:
        1. fixed EFAC per backend/receiver system at 1.0
        2. Linear timing model.
        3. Red noise modeled as a power-law with
            30 sampling frequencies. Default=False
    global:
        1.Common red noise modeled with user defined PSD with
        30 sampling frequencies. Available PSDs are
        ['powerlaw', 'turnover' 'spectrum']
        2. Optional physical ephemeris modeling.
    :param psd:
        PSD to use for common red noise signal. Available options
        are ['powerlaw', 'turnover' 'spectrum']. 'powerlaw' is default
        value.
    :param gamma_common:
        Fixed common red process spectral index value. By default we
        vary the spectral index over the range [0, 7].
    :param upper_limit:
        Perform upper limit on common red noise amplitude. By default
        this is set to False. Note that when performing upper limits it
        is recommended that the spectral index also be fixed to a specific
        value.
    :param bayesephem:
        Include BayesEphem model. Set to False by default
    """

    amp_prior = 'uniform' if upper_limit else 'log-uniform'

    # find the maximum time span to set GW frequency sampling
    if Tspan is None:
        Tspan = model_utils.get_tspan(psrs)

    # timing model
    model = gp_signals.TimingModel()

    #Only White Noise is EFAC set to 1.0
    selection = selections.Selection(selections.by_backend)
    if efac:
        ef = parameter.Uniform(0.1,10.0)
    else:
        ef = parameter.Constant(1.00)

    model += white_signals.MeasurementNoise(efac=ef, selection=selection)

    # common red noise block
    if upper_limit:
        log10_A_gw = parameter.LinearExp(-18,-12)('gw_log10_A')
    else:
        log10_A_gw = parameter.Uniform(-18,-12)('gw_log10_A')

    if vary_gamma:
        gamma_gw = parameter.Uniform(0,7)('gw_gamma')
    else:
        gamma_gw = parameter.Constant(4.33)('gw_gamma')

    pl = signal_base.Function(utils.powerlaw, log10_A=log10_A_gw,
                              gamma=gamma_gw)


    if hd_orf:
        if freqs is None:
            gw = gp_signals.FourierBasisCommonGP(spectrum=pl,
                                                 orf=utils.hd_orf(),
                                                 components=n_gwbfreqs,
                                                 Tspan=Tspan,
                                                 name='gw')
        else:
            gw = gp_signals.FourierBasisCommonGP(spectrum=pl,
                                                 orf=utils.hd_orf(),
                                                 modes=freqs,
                                                 name='gw')
        model += gw
    else:
        if freqs is None:
            crn = gp_signals.FourierBasisGP(spectrum=pl, components=n_gwbfreqs,
                                            Tspan=Tspan, name='gw')
        else:
            crn = gp_signals.FourierBasisGP(spectrum=pl, modes=freqs,
                                            name='gw')
        model += crn

    if red_noise and rn_dropout:
        if amp_prior == 'uniform':
            log10_A = parameter.LinearExp(-20, -11)
        elif amp_prior == 'log-uniform':
            log10_A = parameter.Uniform(-20, -11)
        else:
            log10_A = parameter.Uniform(-20, -11)

        gamma = parameter.Uniform(0, 7)
        k_drop = parameter.Uniform(0, 1)
        if dp_threshold == 6.0:
            dp_threshold = parameter.Uniform(0,1)('k_threshold')
        pl = dropout.dropout_powerlaw(log10_A=log10_A, gamma=gamma,
                                     k_drop=k_drop, k_threshold=dp_threshold)
        rn = gp_signals.FourierBasisGP(pl, components=components,
                                       Tspan=Tspan, name='red_noise')
        model += rn
    elif red_noise:
        # red noise
        model += models.red_noise_block(prior=amp_prior, Tspan=Tspan,
                                        components=components)

    # ephemeris model
    if bayesephem:
        model += deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True)

    # set up PTA
    pta = signal_base.PTA([model(p) for p in psrs])

    return pta
Example #12
0
            deter_sw, name='sw_{0}'.format(ii + 1))
    elif len(power) > 1:
        print('3 ', power, pr_range)
        n_earth = parameter.Uniform(pr_range[0],
                                    pr_range[1])('nE_{0}'.format(ii + 1))
        sw_power = parameter.Uniform(power[0],
                                     power[1])('sw_power_{0}'.format(ii + 1))
        log10_ne = True if pr_range[0] < 0 else False
        deter_sw = SW.solar_wind_r_to_p(n_earth=n_earth,
                                        power=sw_power,
                                        log10_ne=log10_ne)
        dm_block += deterministic_signals.Deterministic(
            deter_sw, name='sw_{0}'.format(ii + 1))

if args.bayes_ephem:
    eph = deterministic_signals.PhysicalEphemerisSignal(model='setIII',
                                                        use_epoch_toas=True)
    model += eph

if args.sw_pta_gp:

    @signal_base.function
    def solar_wind_perturb(toas,
                           freqs,
                           planetssb,
                           sunssb,
                           pos_t,
                           n_earth_rho=0,
                           n_mean=5,
                           nmodes=20,
                           Tspan=None,
                           logf=False,
Example #13
0
def model_bwm(psrs,
              Tmin_bwm=None,
              Tmax_bwm=None,
              skyloc=None,
              logmin=-18,
              logmax=-11,
              amp_prior='log-uniform',
              bayesephem=False,
              dmgp=False,
              free_rn=False):
    """
    Reads in list of enterprise Pulsar instance and returns a PTA
    instantiated with BWM model:
    per pulsar:
        1. fixed EFAC per backend/receiver system
        2. fixed EQUAD per backend/receiver system
        3. fixed ECORR per backend/receiver system
        4. Red noise modeled as a power-law with 30 sampling frequencies
        5. Linear timing model.
    global:
        1. Deterministic GW burst with memory signal.
        2. Optional physical ephemeris modeling.
    :param Tmin_bwm:
        Min time to search for BWM (MJD). If omitted, uses first TOA.
    :param Tmax_bwm:
        Max time to search for BWM (MJD). If omitted, uses last TOA.
    :param skyloc:
        Fixed sky location of BWM signal search as [cos(theta), phi].
        Search over sky location if ``None`` given.
    :param logmin:
        log of minimum BWM amplitude for prior (log10)
    :param logmax:
        log of maximum BWM amplitude for prior (log10)
    :param upper_limit:
        Perform upper limit on common red noise amplitude. By default
        this is set to False. Note that when perfoming upper limits it
        is recommended that the spectral index also be fixed to a specific
        value.
    :param bayesephem:
        Include BayesEphem model. Set to False by default
    :param free_rn:
        Use free red noise spectrum model. Set to False by default
    """

    # find the maximum time span to set GW frequency sampling
    tmin = np.min([p.toas.min() for p in psrs])
    tmax = np.max([p.toas.max() for p in psrs])
    Tspan = tmax - tmin

    if Tmin_bwm == None:
        Tmin_bwm = tmin / const.day
    if Tmax_bwm == None:
        Tmax_bwm = tmax / const.day

    # white noise
    s = models.white_noise_block(vary=False)

    # red noise
    if free_rn:
        s += models.free_noise_block(prior=amp_prior, Tspan=Tspan)
    else:
        s += red_noise_block(prior=amp_prior, Tspan=Tspan)

    # GW BWM signal block
    s += bwm_sngl_block(Tmin_bwm,
                        Tmax_bwm,
                        amp_prior=amp_prior,
                        logmin=logmin,
                        logmax=logmax,
                        name='bwm')

    # ephemeris model
    if bayesephem:
        s += deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True)

    # timing model
    s += gp_signals.TimingModel(use_svd=True)

    # DM variations model
    if dmgp:
        s += models.dm_noise_block(gp_kernel='diag',
                                   psd='powerlaw',
                                   prior=amp_prior,
                                   Tspan=Tspan)
        s += models.dm_annual_signal()

        # DM exponential dip for J1713's DM event
        dmexp = models.dm_exponential_dip(tmin=54500, tmax=54900)
        s2 = s + dmexp

    # set up PTA
    mods = []
    for p in psrs:
        if dmgp and 'J1713+0747' == p.name:
            mods.append(s2(p))
        else:
            mods.append(s(p))

    pta = signal_base.PTA(mods)

    return pta
ec = white_signals.EcorrKernelNoise(log10_ecorr=ecorr, selection=bkend_NG)

dmgp = gp_signals.BasisGP(dm_pl, dm_basis, name='dm_gp')
dmexp = models.dm_exponential_dip(tmin=54500, tmax=55000, name='dmexp_1')
dm1yr = models.dm_annual_signal()

rn = gp_signals.FourierBasisGP(spectrum=rn_pl, components=30, Tspan=Tspan)
gwb = gp_signals.FourierBasisCommonGP(gwb_pl,
                                      orf,
                                      components=30,
                                      Tspan=Tspan,
                                      name='gw')

tm = gp_signals.TimingModel(use_svd=True)
be = deterministic_signals.PhysicalEphemerisSignal(  # widen prior on jup orbit
    use_epoch_toas=True,
    jup_orb_elements=parameter.Uniform(-0.1, 0.1, size=6)('jup_orb_elements'))

# full model
mod_root = tm + ef + eq + dmgp + dm1yr + rn + gwb
if args.be: mod_root += be
mod_J1713 = mod_root + dmexp
mod_ecorr = mod_root + ec

mods = []
for psr in psrs:
    if 'J1713+0747' == psr.name:
        if 'NANOGrav' in psr.flags['pta']:
            mod_J1713 += ec
        mods.append(mod_J1713(psr))
    elif 'NANOGrav' in psr.flags['pta']:
  def bayes_ephem(self,option="default"):
    """
    Deterministic signal from errors in Solar System ephemerides.
    """
    
    ekw = {}
    ekw['model'] = "setIII"
    if isinstance(option, dict):
      # Converting parameters to bool masks
      for bekey, beval in option.items():
        if isinstance(beval, list):
          option[bekey] = np.array(beval, dtype=bool)
        else:
          option[bekey] = bool(beval)
      options = '_'.join(option.keys())
    else:
      options = option

    print(options)
    print(option)

    #adding keyword arguments to PhysicalEphemerisSignal based on input options
    #where PhysicalEphemerisSignal kwargs default to True, here we set to False
    if "framedr" in option:
      ekw['frame_drift_rate'] = parameter.Uniform(-1e-10, 1e-10)\
                                                 ('frame_drift_rate')
    else:
      ekw['frame_drift_rate'] = False

    if "mer_m" in option or "inner" in option:
      ekw['d_mercury_mass'] = parameter.Normal(0, 1.66e-10)('d_mer_mass')
    if "mer_el" in option:
      if isinstance(option, dict):
        ekw['mer_orb_elements'] = UniformMask(-0.5, 0.5, option['mer_el'])\
                                             ('mer_oe')
      else:
        ekw['mer_orb_elements'] = parameter.Uniform(-0.5, 0.5, size=6)('mer_oe')

    if "ven_m" in options or "inner" in options:
      ekw['d_venus_mass'] = parameter.Normal(0, 2.45e-9)('d_ven_mass')
    if "ven_el" in options:
      if isinstance(option, dict):
        ekw['ven_orb_elements'] = UniformMask(-1., 1., option['ven_el'])('ven_oe')
      else:
        ekw['ven_orb_elements'] = parameter.Uniform(-1., 1., size=6)('ven_oe')

    if "mar_m" in option or "inner" in option:
      ekw['d_mars_mass'] = parameter.Normal(0, 3.23e-10)('d_mar_mass')
    if "mar_el" in option:
      if isinstance(option, dict):
        ekw['mar_orb_elements'] = UniformMask(-5., 5., option['mar_el'])('mar_oe')
      else:
        ekw['mar_orb_elements'] = parameter.Uniform(-5., 5., size=6)('mar_oe')

    if "jup_m" in option or "d_jupiter_mass" in option or "outer" in option or "default" in option:
      ekw['d_jupiter_mass'] = parameter.Normal(0, 1e-10)('d_jup_mass')
      #parameter.Normal(0, 1.54976690e-11)('d_jup_mass')
    else:
      ekw['d_jupiter_mass'] = False
      
    if "jup_el" in option or "outer" in option or "default" in option:
      if isinstance(option, dict) and (type(option['jup_el']) is list or \
                                       type(option['jup_el']) is np.ndarray):
        ekw['jup_orb_elements'] = UniformMask(-0.5, 0.5, option['jup_el'])\
                                             ('jup_oe')
      else:
        ekw['jup_orb_elements'] = parameter.Uniform(-0.5, 0.5, size=6)\
                                                   ('jup_oe')
    else:
      ekw['jup_orb_elements'] = False

    if "sat_m" in option or "outer" in option or "default" in option:
      ekw['d_saturn_mass'] = parameter.Normal(0, 8.17306184e-12)('d_sat_mass')
    else:
      ekw['d_saturn_mass'] = False
      
    if "sat_el" in option or "outer" in option:
      if isinstance(option, dict):
        ekw['sat_orb_elements'] = UniformMask(-5., 5., option['sat_el'])('sat_oe')
      else:
        ekw['sat_orb_elements'] = parameter.Uniform(-5., 5., size=6)('sat_oe')
    else:
      ekw['sat_orb_elements'] = False

    if "ura_m" in option or "outer" in option or "default" in option:
      ekw['d_uranus_mass'] = parameter.Normal(0, 5.71923361e-11)('d_ura_mass')
    else:
      ekw['d_uranus_mass'] = False
    if "ura_el" in option:
      if isinstance(option, dict):
        ekw['ura_orb_elements'] = UniformMask(-.5, .5, option['ura_el'])('ura_oe')
      else:
        ekw['ura_orb_elements'] = parameter.Uniform(-0.5, 0.5, size=6)('ura_oe')
    #else:
    #  ekw['ura_orb_elements'] = False

    if "nep_m" in option or "outer" in option or "default" in option:
      ekw['d_neptune_mass'] = parameter.Normal(0, 7.96103855e-11)\
                                              ('d_nep_mass')
    else:
      ekw['d_neptune_mass'] = False
    if "nep_el" in option:
      if isinstance(option, dict):
        ekw['nep_orb_elements'] = UniformMask(-.5, .5, option['nep_el'])('nep_oe')
      else:
        ekw['nep_orb_elements'] = parameter.Uniform(-0.5, 0.5, size=6)('nep_oe')
    #else:
    #  ekw['nep_orb_elements'] = False

    #print(ekw)
    eph = deterministic_signals.PhysicalEphemerisSignal(**ekw)
    return eph