Ejemplo n.º 1
0
def plot_fit_results(tool):
    """plot the SEDs result of the gammapy / sherpa fit
    for comparison with the literature we choose only the Mayer spectrum

    Here we plot the butterfly as a result of the multivariate sampling
    with the 68% containment in flux
    """
    fig, ax = plt.subplots()

    model_meyer_ref = CrabSpectrum("meyer").model
    model_meyer_ref.plot(
        [10 * u.GeV, 100 * u.TeV],
        energy_power=2,
        flux_unit="erg-1 cm-2 s-1",
        ls=":",
        lw=2.2,
        color="#555555",
        label="Meyer et al. (2010)",
    )

    # where to take the results, configurations for the individual butterflies
    instruments = ["fermi", "magic", "veritas", "fact", "hess", "joint"]
    labels = ["Fermi-LAT", "MAGIC", "VERITAS", "FACT", "H.E.S.S.", "joint fit"]
    lss = ["--", "--", "--", "--", "--", "-"]
    colors = COLORS
    # with one loop we realize all the butterfly plots
    for instrument, label, color, ls in zip(instruments, labels, colors, lss):

        path = (
            config.repo_path /
            f"results/fit/{tool}/{instrument}/fit_results_logparabola.yaml")

        if not path.exists():
            log.warning(f"Missing: {path} . Skipping.")
            continue

        results = load_yaml(path)
        parameters = results["parameters"]

        model_lp = LogParabola.from_log10(
            amplitude=parameters[0]["value"] * u.Unit(parameters[0]["unit"]),
            reference=parameters[1]["value"] * u.Unit(parameters[1]["unit"]),
            alpha=parameters[2]["value"] * u.Unit(parameters[2]["unit"]),
            beta=parameters[3]["value"] * u.Unit(parameters[3]["unit"]),
        )

        # energy range for the plot
        dataset = config.get_dataset(instrument)
        energy_range = dataset.energy_range

        # just in case of the joint fit put a thicker line and a less transparent butterfly
        if instrument == "joint":
            model_lp.plot(
                energy_range,
                energy_power=2,
                flux_unit="erg-1 cm-2 s-1",
                ls=ls,
                lw=3,
                color=color,
                label=label,
            )
        else:
            model_lp.plot(
                energy_range,
                energy_power=2,
                flux_unit="erg-1 cm-2 s-1",
                ls=ls,
                lw=2.2,
                color=color,
                label=label,
            )

        # read the butterfly from the multivariate sampling results
        table_path = Path(
            f"{config.repo_path}/results/figures/stat_err/{instrument}_flux_errorband.dat"
        )
        log.info(f"reading butterfly values from {table_path}")
        t = Table.read(table_path, format="ascii.ecsv")
        energies = t["energies"].data * t["energies"].unit
        flux_lo = t["flux_lo"].data * t["flux_lo"].unit
        flux_hi = t["flux_hi"].data * t["flux_hi"].unit

        if instrument == "joint":
            alpha = 0.38
        else:
            alpha = 0.28

        plt.fill_between(
            energies.to("TeV"),
            (energies**2 * flux_lo).to("erg cm-2 s-1"),
            (energies**2 * flux_hi).to("erg cm-2 s-1"),
            color=color,
            alpha=alpha,
            label="",
        )

    ax.legend(fontsize=FONTSIZE)
    ax.set_ylim([1e-12, 2e-10])

    ax.set_xlabel(E_UNIT_LABEL, size=FONTSIZE)
    ax.set_ylabel(SED_UNIT_LABEL, size=FONTSIZE)
    # make axis thicker
    for axis in ["top", "bottom", "left", "right"]:
        ax.spines[axis].set_linewidth(1.6)
    ax.tick_params("both",
                   length=7,
                   width=1.6,
                   which="major",
                   labelsize=FONTSIZE)
    ax.tick_params("both",
                   length=4,
                   width=1.6,
                   which="minor",
                   labelsize=FONTSIZE)

    plt.tight_layout()

    filename = f"results/figures/crab_sed_{tool}_fit.png"
    filename_pdf = f"results/figures/crab_sed_{tool}_fit.pdf"
    log.info(f"Writing {filename}")
    fig.savefig(filename)
    fig.savefig(filename_pdf)
Ejemplo n.º 2
0
def counts_histogram(predicted=False):
    """function to plot the excesses per dataset and compare them with the predicted counts
    if predicted == True will shwo the predicted counts from the results of the fit (for debug purpose)
    """
    log.info("loading the results from the joint fit to predict the counts")
    results = load_yaml(
        f"{config.repo_path}/results/fit/gammapy/joint/fit_results_logparabola.yaml"
    )
    parameters = results["parameters"]

    model_lp = LogParabola.from_log10(
        amplitude=parameters[0]["value"] * u.Unit(parameters[0]["unit"]),
        reference=parameters[1]["value"] * u.Unit(parameters[1]["unit"]),
        alpha=parameters[2]["value"] * u.Unit(parameters[2]["unit"]),
        beta=parameters[3]["value"] * u.Unit(parameters[3]["unit"]),
    )

    # defining the figure
    dict_color = {
        "fermi": COLORS[0],
        "magic": COLORS[1],
        "veritas": COLORS[2],
        "fact": COLORS[3],
        "hess": COLORS[4],
    }
    fig, ax = plt.subplots()

    for which in config.all_datasets:
        log.info(f"predicting counts for {which} dataset")
        dataset = config.get_dataset(which)
        obs = dataset.get_SpectrumObservationList().stack()
        cts_pred = CountsPredictor(model=model_lp,
                                   aeff=obs.aeff,
                                   edisp=obs.edisp,
                                   livetime=obs.livetime)
        cts_pred.run()

        e_max = dataset.energy_range[1].to("TeV").value
        e_min = dataset.energy_range[0].to("TeV").value

        kwargs_mdl = dict(ls=":",
                          range=(e_min, e_max),
                          lw=2.2,
                          color=dict_color[which])
        kwargs_data = dict(ls="-",
                           range=(e_min, e_max),
                           lw=2.2,
                           color=dict_color[which])

        # CountsSpectrum with observed and predicted excesses
        ex_pred = cts_pred.npred
        ex_obs = obs.excess_vector
        # if it is an IACT rebin the counts before plotting
        if which != "fermi":
            ex_pred = ex_pred.rebin(2)
            ex_obs = ex_obs.rebin(2)

        if predicted:  # if you want to display the predicted counts
            ex_pred.plot_hist(ax, **kwargs_mdl)
        ex_obs.plot_hist(ax, **kwargs_data)

    # custom legend
    legend_observed = mlines.Line2D([], [],
                                    color="gray",
                                    marker="",
                                    ls="-",
                                    lw=2,
                                    label="observed")
    legend_expected = mlines.Line2D([], [],
                                    color="gray",
                                    marker="",
                                    ls=":",
                                    lw=2,
                                    label="expected")
    legend_fermi = mlines.Line2D([], [],
                                 color=COLORS[0],
                                 marker="",
                                 ls="-",
                                 lw=2,
                                 label="Fermi-LAT")
    legend_magic = mlines.Line2D([], [],
                                 color=COLORS[1],
                                 marker="",
                                 ls="-",
                                 lw=2,
                                 label="MAGIC")
    legend_veritas = mlines.Line2D([], [],
                                   color=COLORS[2],
                                   marker="",
                                   ls="-",
                                   lw=2,
                                   label="VERITAS")
    legend_fact = mlines.Line2D([], [],
                                color=COLORS[3],
                                marker="",
                                ls="-",
                                lw=2,
                                label="FACT")
    legend_hess = mlines.Line2D([], [],
                                color=COLORS[4],
                                marker="",
                                ls="-",
                                lw=2,
                                label="H.E.S.S.")
    legend_handles = [
        legend_fermi,
        legend_magic,
        legend_veritas,
        legend_fact,
        legend_hess,
    ]
    if predicted:  # if you want to display the predicted counts
        legend_handles = [legend_observed, legend_expected] + legend_handles

    ax.legend(handles=legend_handles, fontsize=FONTSIZE)

    ax.set_xscale("log")
    ax.set_ylabel("Excess counts", size=FONTSIZE)
    ax.set_xlabel(E_UNIT_LABEL, size=FONTSIZE)

    # make axis thicker
    for axis in ["top", "bottom", "left", "right"]:
        ax.spines[axis].set_linewidth(1.6)
    ax.tick_params("both",
                   length=7,
                   width=1.6,
                   which="major",
                   labelsize=FONTSIZE)
    ax.tick_params("both",
                   length=4,
                   width=1.6,
                   which="minor",
                   labelsize=FONTSIZE)

    plt.tight_layout()

    filename = f"{config.repo_path}/results/figures/counts_spectra.png"
    filename_pdf = f"{config.repo_path}/results/figures/counts_spectra.pdf"
    log.info(f"saving figure in {filename}")
    fig.savefig(filename)
    fig.savefig(filename_pdf)
Ejemplo n.º 3
0
     model=LogParabola(
         alpha=2.3 * u.Unit(""),
         amplitude=4 / u.cm ** 2 / u.s / u.TeV,
         reference=1 * u.TeV,
         beta=0.5 * u.Unit(""),
     ),
     val_at_2TeV=u.Quantity(0.6387956571420305, "cm-2 s-1 TeV-1"),
     integral_1_10TeV=u.Quantity(2.255689748270628, "cm-2 s-1"),
     eflux_1_10TeV=u.Quantity(3.9586515834989267, "TeV cm-2 s-1"),
     e_peak=0.74082 * u.TeV,
 ),
 dict(
     name="logpar10",
     model=LogParabola.from_log10(
         alpha=2.3 * u.Unit(""),
         amplitude=4 / u.cm ** 2 / u.s / u.TeV,
         reference=1 * u.TeV,
         beta=1.151292546497023 * u.Unit(""),
     ),
     val_at_2TeV=u.Quantity(0.6387956571420305, "cm-2 s-1 TeV-1"),
     integral_1_10TeV=u.Quantity(2.255689748270628, "cm-2 s-1"),
     eflux_1_10TeV=u.Quantity(3.9586515834989267, "TeV cm-2 s-1"),
     e_peak=0.74082 * u.TeV,
 ),
 dict(
     name="constant",
     model=ConstantModel(const=4 / u.cm ** 2 / u.s / u.TeV),
     val_at_2TeV=u.Quantity(4, "cm-2 s-1 TeV-1"),
     integral_1_10TeV=u.Quantity(35.9999999999999, "cm-2 s-1"),
     eflux_1_10TeV=u.Quantity(198.00000000000006, "TeV cm-2 s-1"),
 ),
 dict(