Exemplo n.º 1
0
    def plot_optical_depth(
        self,
        pos,
        line=True,
        star=True,
        iperiod=0,
        label='None',
        ls='-',
        Tstar=pars.TSTAR,
        Rstar=pars.RSTAR
    ):

        if line:
            lgEdotSorted, distSorted = zip(*sorted(zip(
                self.lgEdotLine,
                self.distPulsarLine[iperiod]
            )))
            lgEdotPlot, distPlot = list(), list()
            for i in range(len(lgEdotSorted)):
                if i % 5 == 0:
                    lgEdotPlot.append(lgEdotSorted[i])
                    distPlot.append(distSorted[i])

            Obs = np.array([0, 0, -1])
            Abs = absorption.Absorption(Tstar=Tstar, Rstar=Rstar)

            tau = [
                Abs.TauGG(en=0.2, obs=Obs, pos=pos * self.dist[iperiod] * (1 - r) / norm(pos))
                for r in distPlot
            ]

            tauMin = Abs.TauGG(
                en=0.2,
                obs=Obs,
                pos=pos * (self.dist[iperiod] - self.distPulsarMin[iperiod]) / norm(pos)
            )

            plt.plot(
                [10**l for l in lgEdotPlot],
                tau,
                marker='None',
                ls=ls,
                c=self.color,
                label=label
            )

            if star:
                plt.plot(
                    [10**self.lgEdotMin],
                    [tauMin],
                    marker='*',
                    ls='None',
                    c=self.color,
                    markersize=12
                )
Exemplo n.º 2
0
def test_alpha():
    # Ploting energy and alpha dependence
    Abs = abso.Absorption(
        Tstar=TSTAR,
        Rstar=RSTAR,
        read_table=True,
        name_table='absorption_table.dat'
    )

    # Alpha
    alpha = np.linspace(0, 175, 40)

    plt.figure(figsize=(8, 6), tight_layout=True)
    ax = plt.gca()
    ax.set_yscale('log')
    ax.set_ylabel(r'$\lambda_{\gamma \gamma}$')
    ax.set_xlabel(r'$\alpha$ [deg]')

    ax.plot(
        alpha,
        [Abs.LambdaGG(en0=0.1, U=1, alpha=a) for a in alpha],
        label='E=0.2 TeV',
        color='k',
        linestyle='-'
    )
    ax.plot(
        alpha,
        [Abs.LambdaGG(en0=1.2, U=1, alpha=a) for a in alpha],
        label='E=1.2 TeV',
        color='k',
        linestyle='--'
    )

    ax.plot(
        alpha,
        [abso.LambdaGG(en0=0.1, U=1, Tstar=TSTAR, alpha=a) for a in alpha],
        label='E=0.2 TeV',
        color='r',
        linestyle='-'
    )
    ax.plot(
        alpha,
        [abso.LambdaGG(en0=1.2, U=1, Tstar=TSTAR, alpha=a) for a in alpha],
        label='E=1.2 TeV',
        color='r',
        linestyle='--'
    )

    ax.legend(frameon=False)

    plt.show()
Exemplo n.º 3
0
def test_energy():
    # Energy
    Abs = abso.Absorption(
        Tstar=TSTAR,
        Rstar=RSTAR,
        read_table=True,
        name_table='absorption_table.dat'
    )

    energy = np.logspace(-1, 0.9, 40)

    plt.figure(figsize=(8, 6), tight_layout=True)
    ax = plt.gca()
    ax.set_yscale('log')
    ax.set_xscale('log')
    ax.set_ylabel(r'$\lambda_{\gamma \gamma}$')
    ax.set_xlabel(r'$E$ [TeV]')

    ax.plot(
        energy,
        [Abs.LambdaGG(en0=e, U=1, alpha=120) for e in energy],
        label=r'$\alpha=120$ deg',
        color='k',
        linestyle='-'
    )
    ax.plot(
        energy,
        [Abs.LambdaGG(en0=e, U=1, alpha=60) for e in energy],
        label=r'$\alpha=60$ deg',
        color='k',
        linestyle='--'
    )

    ax.plot(
        energy,
        [abso.LambdaGG(en0=e, U=1, Tstar=TSTAR, alpha=120) for e in energy],
        label=r'$\alpha=120$ deg',
        color='r',
        linestyle='-'
    )
    ax.plot(
        energy,
        [abso.LambdaGG(en0=e, U=1, Tstar=TSTAR, alpha=60) for e in energy],
        label=r'$\alpha=60$ deg',
        color='r',
        linestyle='--'
    )

    ax.legend(frameon=False)

    plt.show()
Exemplo n.º 4
0
def test_tau():
    obs = np.array([0, 0, -1])
    Abs = abso.Absorption(
        Tstar=TSTAR,
        Rstar=RSTAR,
        read_table=True,
        name_table='absorption_table.dat'
    )

    logging.info('Tau from class')
    tau0 = Abs.TauGG(en=1, obs=obs, pos=np.array([0, 2, 1.5]), dx_ratio=0.05, min_tau=1e-3)
    logging.info('Tau0 = {}'.format(tau0))

    logging.info('Tau from external function - no_int=True')

    tau1 = abso.TauGG(
        en=1,
        Tstar=TSTAR,
        Rstar=RSTAR,
        obs=obs,
        pos=np.array([0, 2, 1.5]),
        no_int=True,
        dx_ratio=0.05,
        min_tau=1e-3
    )
    logging.info('Tau1 = {}'.format(tau1))

    logging.info('Tau from external function - no_int=False')
    tau2 = abso.TauGG(
        en=1,
        Tstar=TSTAR,
        Rstar=RSTAR,
        obs=obs,
        pos=np.array([0, 2, 1.5]),
        no_int=False,
        dx_ratio=0.05,
        min_tau=1e-3
    )
    logging.info('Tau2 = {}'.format(tau2))
Exemplo n.º 5
0
def do_fit(
    periods,   # [0, 1],
    ThetaIC,   # np.array([90, 90]),
    Pos3D,     # [[1, 1, 1], [1, 1, 1]],
    Dist,      # np.array([2, 2]),
    Alpha,     # np.array([2.58, 2.16])
    label='',
    do_abs=True,
    lgEdot_min=31,
    lgEdot_max=37.5,
    lgEdot_bins=10,
    lgSigma_min=-3,
    lgSigma_max=-1,
    lgSigma_bins=10,
    Tstar=pars.TSTAR,
    Rstar=pars.RSTAR,
    AlphaSigma=1,
    Mdot=1e-8,
    Vw=1500
):

    logging.info('Starting fitting')
    OutFit = open('fit_results/fit_results_' + label + '.txt', 'w')

    NEdot = (lgEdot_max - lgEdot_min) * lgEdot_bins
    NSigma = (lgSigma_max - lgSigma_min) * lgSigma_bins
    Edot_list = np.logspace(lgEdot_min, lgEdot_max, int(NEdot))
    Sigma_list = np.logspace(lgSigma_min, lgSigma_max, int(NSigma))

    logging.info('{} iterations'.format(NEdot * NSigma))

    print(Edot_list)
    print(Sigma_list)

    n_periods = len(periods)

    if len(ThetaIC) != n_periods:
        logging.error('Argument with wrong dimensions - aborting')
        return None

    # Absorption
    if not do_abs:
        logging.info('Skipping absorption')
    else:
        # Computing Taus
        logging.info('Computing absorption')
        start = time.time()
        Obs = np.array([0, 0, -1])
        Abs = abso.Absorption(Tstar=Tstar, Rstar=Rstar)

        data_en, data_fl, data_fl_er = list(), list(), list()
        Tau = list()
        DistTau = list()
        for iper in periods:
            en, fl, fl_er = data.get_data(iper, GT=True)
            data_en.append(en)
            data_fl.append(fl)
            data_fl_er.append(fl_er)
            DistTau.append(list())
            tt = dict()
            for i in range(len(en)):
                tt[i] = list()
            Tau.append(tt)

        DistFrac = np.linspace(0.01, 1, 50)

        for ff in DistFrac:
            for i_per in range(n_periods):
                dist = ff * norm(Pos3D[i_per])
                PosStar = Pos3D[i_per] * dist / norm(Pos3D[i_per])
                for i_en in range(len(data_en[i_per])):
                    tau = Abs.TauGG(en=data_en[i_per][i_en] * u.keV.to(u.TeV), obs=Obs, pos=PosStar)
                    Tau[i_per][i_en].append(tau)
                DistTau[i_per].append(dist)

        logging.info('Abs done, dt/s = {}'.format(time.time() - start))

        # # Ploting tau vs dist
        # plt.figure(figsize=(8, 6), tight_layout=True)
        # ax = plt.gca()
        # ax.set_yscale('log')
        # ax.set_ylabel(r'$\tau_{\gamma \gamma}$')
        # ax.set_xlabel(r'$D$ [AU]')

        # ax.plot(DistTau0, Tau0[92], marker='o', linestyle='-')
        # ax.plot(DistTau0, Tau0[95], marker='o', linestyle='-')
        # plt.show()

    for (Edot, Sigma) in itertools.product(Edot_list, Sigma_list):

        logging.debug('Starting Edot={}, Sigma={}'.format(Edot, Sigma))

        # Computed parameters
        DistPulsar = [psr.Rshock(Edot=Edot, Mdot=Mdot, Vw=Vw, D=d) for d in Dist]
        DistStar = Dist - DistPulsar
        DistRef = 4.
        # SigmaFac = [pow(Dist[0] / d, AlphaSigma) for d in Dist]
        SigmaFac = [pow(DistRef / d, AlphaSigma) for d in Dist]
        SigmaShock = [Sigma * f for f in SigmaFac]
        Bfield = [psr.B2_KC(Edot=Edot, Rs=dp, sigma=s) for (dp, s) in zip(DistPulsar, SigmaShock)]
        Density = [psr.PhotonDensity(Tstar=Tstar, Rstar=Rstar, d=d) for d in DistStar]

        if 0 in Bfield:
            logging.info('Bfield is 0 - skipping')
            continue

        # Normalization
        Norm0 = np.array([1e24 / b for b in Bfield])

        # Fitting
        fix_n = [True for p in range(pars.MAX_PERIOD)]
        fit_n = [Norm0[0] for p in range(pars.MAX_PERIOD)]

        for idx, iper in enumerate(periods):
            fix_n[iper] = False
            fit_n[iper] = Norm0[idx]

        logging.info('fix_n:')
        logging.info(fix_n)
        logging.info('fit_n:')
        logging.info(fit_n)

        npar = 5 - sum([int(f) for f in fix_n])

        ####################
        # Further parameters
        Eref = 1 * u.TeV
        Ecut = 50 * u.TeV
        Emax = 20 * u.PeV
        Emin = 10 * u.GeV
        SourceDist = pars.SRC_DIST * u.kpc
        EnergyToPlot = np.logspace(-2, 11, 500) * u.keV

        ######################
        # Loading data

        data_en, data_fl, data_fl_er = list(), list(), list()
        tau = list()
        model = list()
        for ii in range(pars.MAX_PERIOD):
            idx = periods.index(ii) if (ii in periods) else 0

            en, fl, fl_er = data.get_data(ii, GT=True)
            data_en.append(en)
            data_fl.append(fl)
            data_fl_er.append(fl_er)

            thisTau = list()
            if do_abs and (ii in periods):
                for ien in range(len(en)):
                    thisTau.append(np.interp(DistStar[idx], xp=DistTau[idx], fp=Tau[idx][ien]))
            else:
                thisTau = [0] * len(en)

            tau.append(thisTau)

            ECPL = ExponentialCutoffPowerLaw(
                amplitude=1e20 / u.eV,
                e_0=Eref,
                alpha=Alpha[idx],
                e_cutoff=Ecut
            )

            SYN = Synchrotron(
                particle_distribution=ECPL,
                B=Bfield[idx] * u.G,
                Eemax=Emax,
                Eemin=Emin
            )

            IC = InverseCompton(
                particle_distribution=ECPL,
                seed_photon_fields=[[
                    'STAR',
                    Tstar * u.K,
                    Density[idx] * u.erg / u.cm**3,
                    ThetaIC[idx] * u.deg
                ]],
                Eemax=Emax,
                Eemin=Emin
            )

            thisModel = (
                SYN.sed(photon_energy=[e * u.keV for e in en], distance=SourceDist) +
                IC.sed(photon_energy=[e * u.keV for e in en], distance=SourceDist)
            )

            if do_abs:
                thisModel = [math.exp(-t) * m for (m, t) in zip(thisModel, thisTau)]

            model.append(thisModel)
        # END for

        def least_square(n0, n1, n2, n3, n4):
            chisq = 0
            for ii, nn in enumerate([n0, n1, n2, n3, n4]):
                if fix_n[ii]:
                    continue
                chisq += sum(util.vecChiSq(
                    [(nn / 1e20) * m.value for m in model[ii]],
                    data_fl[ii],
                    data_fl_er[ii])
                )
            return chisq

        minuit = Minuit(
            least_square,
            n0=fit_n[0], fix_n0=fix_n[0],
            n1=fit_n[1], fix_n1=fix_n[1],
            n2=fit_n[2], fix_n2=fix_n[2],
            n3=fit_n[3], fix_n3=fix_n[3],
            n4=fit_n[4], fix_n4=fix_n[4],
            limit_n0=(fit_n[0] * 0.001, fit_n[0] * 1000),
            limit_n1=(fit_n[1] * 0.001, fit_n[1] * 1000),
            limit_n2=(fit_n[2] * 0.001, fit_n[2] * 1000),
            limit_n3=(fit_n[3] * 0.001, fit_n[3] * 1000),
            limit_n4=(fit_n[4] * 0.001, fit_n[4] * 1000)
        )

        fmin, param = minuit.migrad()

        logging.info(minuit.matrix(correlation=True))
        chisq_min = minuit.fval
        n_fit, n_err = list(), list()
        ndf = 0
        for ii in range(pars.MAX_PERIOD):
            n_fit.append(param[ii]['value'])
            n_err.append(param[ii]['error'])
            if not fix_n[ii]:
                ndf += len(data_en[ii])
        ndf -= npar
        # p_value = 1 - stats.chi2.cdf(chisq_min, ndf)

        logging.info('Fit')
        logging.info('ChiSq/ndf = {}'.format(chisq_min / ndf))
        logging.info('ChiSq - ndf = {}'.format(chisq_min - ndf))

        # # plot testing
        # for ii, nn in enumerate(n_fit):
        #     if fix_n[ii]:
        #         continue
        #     plt.figure(figsize=(8, 6), tight_layout=True)
        #     ax = plt.gca()
        #     ax.set_xscale('log')
        #     ax.set_yscale('log')
        #     ax.set_title(ii)

        #     ax.errorbar(
        #         data_en[ii],
        #         data_fl[ii],
        #         yerr=data_fl_er[ii],
        #         marker='o',
        #         linestyle='none'
        #     )

        #     ax.plot(
        #         data_en[ii],
        #         [(nn / 1e20) * m.value for m in model[ii]],
        #         marker='o',
        #         linestyle='none'
        #     )
        #     plt.show()

    #     print('p-value', p_value)

    #     if do_abs:
    #         TauPrint0 = [tau0[len(data_en0) - 4], tau0[len(data_en0) - 1]]
    #         TauPrint1 = [tau1[len(data_en1) - 3], tau1[len(data_en1) - 1]]
    #     else:
    #         TauPrint0 = [0, 0]
    #         TauPrint1 = [0, 0]

        if chisq_min - ndf < 1e3:
            OutFit.write(str(chisq_min) + ' ')
            OutFit.write(str(ndf) + ' ')
            for ii in range(pars.MAX_PERIOD):
                if not fix_n[ii]:
                    OutFit.write(str(math.log10(n_fit[ii])) + ' ')
            OutFit.write(str(math.log10(Edot)) + ' ')
            OutFit.write(str(math.log10(Sigma)) + ' ')
            for ii in range(pars.MAX_PERIOD):
                if not fix_n[ii]:
                    idx = periods.index(ii)
                    OutFit.write(str(Dist[idx]) + ' ')
                    OutFit.write(str(DistPulsar[idx]) + ' ')
                    OutFit.write(str(Bfield[idx]) + ' ')
    #         OutFit.write(str(TauPrint0[0]) + ' ')
    #         OutFit.write(str(TauPrint0[1]) + ' ')
    #         OutFit.write(str(TauPrint1[0]) + ' ')
    #         OutFit.write(str(TauPrint1[1]) + '\n')
            OutFit.write('\n')

    OutFit.close()
Exemplo n.º 6
0
def test_make_table():
    Abs = abso.Absorption(Tstar=TSTAR, Rstar=RSTAR, read_table=False)
    Abs.ProduceLambdaTable(n_en=10, n_alpha=10, name='absorption_table_test.dat')
Exemplo n.º 7
0
def do_fit(
        ThetaIC,  # np.array([90, 90]),
        Pos3D,  # [[1, 1, 1], [1, 1, 1]],
        Dist,  # np.array([2, 2]),
        label='',
        do_abs=True,
        lgEdot_min=31,
        lgEdot_max=37.5,
        lgEdot_bins=10,
        lgSigma_min=-3,
        lgSigma_max=-1,
        lgSigma_bins=10,
        Tstar=pars.TSTAR_LS,
        Rstar=pars.RSTAR_LS,
        AlphaSigma=1,
        Mdot=pars.MDOT_LS,
        Vw=pars.VW_LS):

    logging.info('Starting fitting')
    OutFit = open('fit_results/fit_results_ls5039_' + label + '.txt', 'w')

    # Loading data
    phaseData, fluxSuzaku, fluxErrSuzaku, gammaSuzaku, gammaErrSuzaku = get_data_ls5039(
        'SUZAKU')
    phaseData, fluxHESS, fluxErrHESS, gammaHESS, gammaErrHESS = get_data_ls5039(
        'HESS')

    logging.debug('PhaseData')
    logging.debug(phaseData)

    # Loading energy
    energyXrays = np.logspace(0, 1, 5)
    energyGamma = np.logspace(math.log10(0.2e9), math.log10(5e9), 10)
    energyAll = np.concatenate((energyXrays, energyGamma))
    logging.debug('Energies')
    logging.debug(energyXrays)
    logging.debug(energyGamma)
    logging.debug(energyAll)

    # Loading grid
    NEdot = int((lgEdot_max - lgEdot_min) * lgEdot_bins)
    NSigma = int((lgSigma_max - lgSigma_min) * lgSigma_bins)
    Edot_list = np.logspace(lgEdot_min, lgEdot_max, int(NEdot))
    Sigma_list = np.logspace(lgSigma_min, lgSigma_max, int(NSigma))

    logging.info('{} iterations'.format(len(Edot_list) * len(Sigma_list)))

    if (len(ThetaIC) != len(phaseData) or len(Pos3D) != len(phaseData)
            or len(Dist) != len(phaseData)):
        logging.error('Argument with wrong dimensions - aborting')
        return None

    # Absorption
    if not do_abs:
        logging.info('Skipping absorption')
    else:
        if Path('abs_pars.json').exists():
            logging.debug('Reading abs pars')
            with open('abs_pars.json', 'r') as file:
                data = json.load(file)

            DistFrac = data['DistFrac']
            DistTau = data['DistTau']
            Tau = data['Tau']
        else:
            # Computing Taus
            logging.info('Computing absorption')
            start = time.time()
            Obs = np.array([0, 0, -1])
            Abs = abso.Absorption(Tstar=Tstar,
                                  Rstar=Rstar,
                                  name_table='absorption_table_ls5039.dat')

            Tau = list()
            DistTau = list()
            for iph in range(len(phaseData)):
                DistTau.append(list())
                tt = dict()
                for i in range(len(energyAll)):
                    tt[i] = list()
                Tau.append(tt)

            DistFrac = np.concatenate(
                (np.linspace(0.005, 0.2, 20), np.linspace(0.201, 1.0, 10)))

            for ff in DistFrac:
                for iph in range(len(phaseData)):
                    dist = ff * norm(Pos3D[iph])
                    PosStar = Pos3D[iph] * dist / norm(Pos3D[iph])
                    for ien in range(len(energyAll)):
                        tau = Abs.TauGG(en=energyAll[ien] * u.keV.to(u.TeV),
                                        obs=Obs,
                                        pos=PosStar)
                        Tau[iph][ien].append(tau)
                    DistTau[iph].append(dist)

            logging.info('Abs done, dt/s = {}'.format(time.time() - start))

            absToSave = dict()
            absToSave['DistFrac'] = list(DistFrac)
            absToSave['DistTau'] = list(DistTau)
            absToSave['Tau'] = list(Tau)

            logging.debug('Writing abs to json file')
            with open('abs_pars.json', 'w') as file:
                json.dump(absToSave, file)

        # # Ploting tau vs dist
        # plt.figure(figsize=(8, 6), tight_layout=True)
        # ax = plt.gca()
        # ax.set_yscale('log')
        # ax.set_ylabel(r'$\tau_{\gamma \gamma}$')
        # ax.set_xlabel(r'$D$ [AU]')

        # ax.plot(DistTau[7], Tau[7][str(5)], marker='o', linestyle='-')
        # ax.plot(DistTau[7], Tau[7][str(13)], marker='o', linestyle='-')
        # plt.show()

    chisqMin = 1e10
    minEdot = 0
    minSigma = 0

    for (Edot, Sigma) in itertools.product(Edot_list, Sigma_list):

        print('Starting Edot={}, Sigma={}'.format(Edot, Sigma))

        # Computed parameters
        DistPulsar = [
            psr.Rshock(Edot=Edot, Mdot=Mdot, Vw=Vw, D=d) for d in Dist
        ]
        DistStar = Dist - DistPulsar
        SigmaFac = [pow(0.1 / d, AlphaSigma) for d in DistPulsar]
        SigmaShock = [Sigma * f for f in SigmaFac]
        Bfield = [
            psr.B2_KC(Edot=Edot, Rs=dp, sigma=s)
            for (dp, s) in zip(DistPulsar, SigmaShock)
        ]
        Density = [
            psr.PhotonDensity(Tstar=Tstar, Rstar=Rstar, d=d) for d in DistStar
        ]

        # plt.figure(figsize=(8, 6), tight_layout=True)
        # ax = plt.gca()
        # ax.set_yscale('log')
        # ax.set_ylabel(r'$\tau_{\gamma \gamma}$')
        # ax.set_xlabel(r'$D$ [AU]')

        # ax.plot(DistPulsar, SigmaShock, marker='o', linestyle='-')
        # plt.show()

        # logging.debug('DistPulsar')
        # logging.debug(DistPulsar)
        # logging.debug('DistStar')
        # logging.debug(DistStar)
        # logging.debug('SigmaShock')
        # logging.debug(SigmaShock)
        # logging.debug('SigmaFac')
        # logging.debug(SigmaFac)
        logging.debug('Bfield')
        logging.debug(Bfield)
        logging.debug('MeanBfield')
        logging.debug(sum(Bfield) / len(Bfield))

        if 0 in Bfield:
            logging.info('Bfield is 0 - skipping')
            continue

        # Normalization
        NormStart = np.array([1e23 / b for b in Bfield])

        npar = len(phaseData)

        # Further parameters
        Ecut = [rad.Emax(b, 1) * u.TeV for b in Bfield]
        Eref = 1 * u.TeV
        Emax = 100 * u.PeV
        Emin = 10 * u.GeV
        SourceDist = pars.SRC_DIST_LS * u.kpc

        # Computing Alpha
        Alpha = [2 * g - 1 for g in gammaSuzaku]
        # print('Alpha')
        # print(Alpha)
        # print('gamma')
        # print(gammaSuzaku)

        # Computing Model
        tau = list()
        modelAll = list()
        for iph in range(len(phaseData)):

            thisTau = list()
            if do_abs:
                for ien in range(len(energyAll)):
                    thisTau.append(
                        np.interp(DistStar[iph],
                                  xp=DistTau[iph],
                                  fp=Tau[iph][str(ien)]))
            else:
                thisTau = [0] * len(energyAll)

            tau.append(thisTau)

            ECPL = ExponentialCutoffPowerLaw(amplitude=1e20 / u.eV,
                                             e_0=Eref,
                                             alpha=Alpha[iph],
                                             e_cutoff=Ecut[iph])

            SYN = Synchrotron(particle_distribution=ECPL,
                              B=Bfield[iph] * u.G,
                              Eemax=Emax,
                              Eemin=Emin)

            IC = InverseCompton(particle_distribution=ECPL,
                                seed_photon_fields=[[
                                    'STAR', Tstar * u.K,
                                    Density[iph] * u.erg / u.cm**3,
                                    ThetaIC[iph] * u.deg
                                ]],
                                Eemax=Emax,
                                Eemin=Emin)

            thisModel = (SYN.sed(photon_energy=[e * u.keV for e in energyAll],
                                 distance=SourceDist) +
                         IC.sed(photon_energy=[e * u.keV for e in energyAll],
                                distance=SourceDist))

            if do_abs:
                thisModel = [
                    math.exp(-t) * m for (m, t) in zip(thisModel, thisTau)
                ]

            # Ploting tau vs dist
            # plt.figure(figsize=(8, 6), tight_layout=True)
            # ax = plt.gca()
            # ax.set_yscale('log')
            # ax.set_xscale('log')
            # ax.set_ylabel(r'$\tau_{\gamma \gamma}$')
            # ax.set_xlabel(r'$E$ [keV]')

            # print(energyAll)
            # print(thisTau)

            # ax.plot(energyAll[5:], thisTau[5:], marker='o', linestyle='-')
            # ax.set_xlim(1e8, 1e10)
            # plt.show()

            modelAll.append(thisModel)
        # END for

        fluxModelSuzaku, fluxModelHESS, gammaModelHESS = list(), list(), list()
        for thisModel in modelAll:
            sedSuzaku = [f for (f, e) in zip(thisModel, energyAll) if e < 1e3]
            energySuzaku = [e for e in energyAll if e < 1e3]
            sedHESS = [f for (f, e) in zip(thisModel, energyAll) if e > 1e3]
            energyHESS = [e for e in energyAll if e > 1e3]
            fluxModelSuzaku.append(getSuzakuFlux(sedSuzaku, energySuzaku))
            n, g = getHESSFluxAndGamma(sedHESS, energyHESS)
            fluxModelHESS.append(n)
            gammaModelHESS.append(g)

        def computeModelPars(N, model, energy):
            thisModel = [(N / 1e20) * m for m in model]

            sedSuzaku = [f for (f, e) in zip(thisModel, energy) if e < 1e3]
            energySuzaku = [e for e in energyAll if e < 1e3]
            sedHESS = [f for (f, e) in zip(thisModel, energy) if e > 1e3]
            energyHESS = [e for e in energyAll if e > 1e3]

            thisFluxModelSuzaku = getSuzakuFlux(sedSuzaku, energySuzaku)
            thisFluxModelHESS, thisGammaModelHESS = getHESSFluxAndGamma(
                sedHESS, energyHESS)
            return thisFluxModelSuzaku, thisFluxModelHESS, thisGammaModelHESS

        chisqFit, nFit = list(), list()
        fluxFitSuzaku, fluxFitHESS, gammaFitHESS = list(), list(), list()

        for ii in range(len(phaseData)):

            def least_square(n):
                chisq = 0

                fitFluxModelSuzaku, fitFluxModelHESS, fitGammaModelHESS = computeModelPars(
                    n, modelAll[ii], energyAll)

                chisq += ((fitFluxModelSuzaku.value * 1e12 - fluxSuzaku[ii]) /
                          fluxErrSuzaku[ii])**2
                chisq += ((fitFluxModelHESS.value * 1e12 - fluxHESS[ii]) /
                          fluxErrHESS[ii])**2
                # chisq += ((fitGammaModelHESS - gammaHESS[ii]) / gammaErrHESS[ii])**2

                return chisq

            minuit = Minuit(least_square,
                            n=NormStart[ii],
                            fix_n=False,
                            limit_n=(NormStart[ii] * 0.0001,
                                     NormStart[ii] * 10000),
                            errordef=1.)

            fmin, param = minuit.migrad()

            chisqFit.append(minuit.fval)
            nFit.append(param[0]['value'])

            fitFS, fitFH, fitGH = computeModelPars(param[0]['value'],
                                                   modelAll[ii], energyAll)
            fluxFitSuzaku.append(fitFS)
            fluxFitHESS.append(fitFH)
            gammaFitHESS.append(fitGH)

        # print('N*B')
        # print([n * b for (n,b) in zip(nFit, Bfield)])
        # print([c / 2 for c in chisqFit])
        totalChiSq = sum(chisqFit) / 10.

        if totalChiSq < chisqMin:
            chisqMin = totalChiSq
            minEdot = Edot
            minSigma = Sigma

        print('ChiSq = {}'.format(totalChiSq))

        if totalChiSq < 1e20:
            plotResults(phaseData=phaseData,
                        nFit=nFit,
                        fluxFitSuzaku=fluxFitSuzaku,
                        fluxSuzaku=fluxSuzaku,
                        fluxErrSuzaku=fluxErrSuzaku,
                        fluxFitHESS=fluxFitHESS,
                        fluxHESS=fluxHESS,
                        fluxErrHESS=fluxErrHESS,
                        gammaFitHESS=gammaFitHESS,
                        gammaHESS=gammaHESS,
                        gammaErrHESS=gammaErrHESS,
                        modelAll=modelAll,
                        energyAll=energyAll)

        continue

        # logging.info('Fit')
        # logging.info('ChiSq/ndf = {}'.format(chisq_min / ndf))
        # logging.info('ChiSq - ndf = {}'.format(chisq_min - ndf))

        # # plot testing
        # for ii, nn in enumerate(n_fit):
        #     if fix_n[ii]:
        #         continue
        #     plt.figure(figsize=(8, 6), tight_layout=True)
        #     ax = plt.gca()
        #     ax.set_xscale('log')
        #     ax.set_yscale('log')
        #     ax.set_title(ii)

        #     ax.errorbar(
        #         data_en[ii],
        #         data_fl[ii],
        #         yerr=data_fl_er[ii],
        #         marker='o',
        #         linestyle='none'
        #     )

        #     ax.plot(
        #         data_en[ii],
        #         [(nn / 1e20) * m.value for m in model[ii]],
        #         marker='o',
        #         linestyle='none'
        #     )
        #     plt.show()

        #     print('p-value', p_value)

        #     if do_abs:
        #         TauPrint0 = [tau0[len(data_en0) - 4], tau0[len(data_en0) - 1]]
        #         TauPrint1 = [tau1[len(data_en1) - 3], tau1[len(data_en1) - 1]]
        #     else:
        #         TauPrint0 = [0, 0]
        #         TauPrint1 = [0, 0]

        if chisq_min - ndf < 1e3:
            OutFit.write(str(chisq_min) + ' ')
            OutFit.write(str(ndf) + ' ')
            for ii in range(pars.MAX_PERIOD):
                if not fix_n[ii]:
                    OutFit.write(str(math.log10(n_fit[ii])) + ' ')
            OutFit.write(str(math.log10(Edot)) + ' ')
            OutFit.write(str(math.log10(Sigma)) + ' ')
            for ii in range(pars.MAX_PERIOD):
                if not fix_n[ii]:
                    idx = periods.index(ii)
                    OutFit.write(str(Dist[idx]) + ' ')
                    OutFit.write(str(DistPulsar[idx]) + ' ')
                    OutFit.write(str(Bfield[idx]) + ' ')
    #         OutFit.write(str(TauPrint0[0]) + ' ')
    #         OutFit.write(str(TauPrint0[1]) + ' ')
    #         OutFit.write(str(TauPrint1[0]) + ' ')
    #         OutFit.write(str(TauPrint1[1]) + '\n')
            OutFit.write('\n')

    print('ChiSqMin {}'.format(chisqMin))
    print('lgEdot {}'.format(math.log10(minEdot)))
    print('Sigma {}'.format(minSigma))

    OutFit.close()
Exemplo n.º 8
0
    def plot_sed(
        self,
        iperiod=0,
        period=0,
        best_solution=True,
        Edot=1e36,
        theta_ic=90,
        dist=2,
        pos=np.array([1, 1, 1]),
        ls='-',
        lw=1,
        label='None',
        Tstar=pars.TSTAR,
        Rstar=pars.RSTAR,
        emin=0.1,
        ecut=50,
        fast=False
    ):
        Alpha = pars.ELEC_SPEC_INDEX[period]

        Eref = 1 * u.TeV
        Ecut = ecut * u.TeV
        Emax = 20 * u.PeV
        Emin = emin * u.TeV
        SourceDist = pars.SRC_DIST * u.kpc
        n_en = 1 if fast else 2

        Obs = np.array([0, 0, -1])
        Abs = absorption.Absorption(Tstar=Tstar, Rstar=Rstar)

        if best_solution:
            b_sed = self.bMin[iperiod]
            norm_sed = self.normMin[iperiod]
            dist_sed = self.distPulsarMin[iperiod]
            dist_star = dist - dist_sed
            density_sed = psr.PhotonDensity(Tstar=Tstar, Rstar=Rstar, d=dist_star)
        else:
            idx = np.argmin(np.array([math.fabs(l - math.log10(Edot)) for l in self.lgEdotLine]))
            b_sed = self.bLine[iperiod][idx]
            norm_sed = 10**self.lgNormLine[iperiod][idx]
            dist_sed = self.distPulsarLine[iperiod][idx]
            dist_star = dist * (1 - dist_sed)
            density_sed = psr.PhotonDensity(Tstar=Tstar, Rstar=Rstar, d=dist_star)

        EnergyToPlot = np.logspace(-0.5, 9.6, n_en * 300) * u.keV

        ECPL = ExponentialCutoffPowerLaw(
            amplitude=norm_sed / u.eV,
            e_0=Eref,
            alpha=Alpha,
            e_cutoff=Ecut
        )

        SYN = Synchrotron(
            particle_distribution=ECPL,
            B=b_sed * u.G,
            Eemax=Emax,
            Eemin=Emin
        )
        IC = InverseCompton(
            particle_distribution=ECPL,
            seed_photon_fields=[[
                'STAR',
                Tstar * u.K,
                density_sed * u.erg / u.cm**3,
                theta_ic * u.deg
            ]],
            Eemax=Emax,
            Eemin=Emin
        )

        tau = list()
        for e in EnergyToPlot:
            if e.value * u.keV.to(u.TeV) < 1e-4:
                tau.append(0)
            else:
                tau.append(Abs.TauGG(
                    en=e.value * u.keV.to(u.TeV),
                    obs=Obs,
                    pos=pos * dist_star / norm(pos)
                ))

        model = (
            SYN.sed(photon_energy=EnergyToPlot, distance=SourceDist)
            + IC.sed(photon_energy=EnergyToPlot, distance=SourceDist)
        )
        model_abs = [math.exp(-t) * m.value for (m, t) in zip(model, tau)]

        EnergyToPlot, model_abs = util.fix_naima_bug(EnergyToPlot, model_abs)
        model_abs = util.smooth_break(EnergyToPlot, model_abs)

        ax = plt.gca()
        ax.plot(EnergyToPlot, model_abs, ls=ls, lw=lw, c=self.color, label=label)