示例#1
0
def main(input_files, verbose, output):
    setup_logging(verbose=verbose)

    eventlist_list = []
    for f in input_files:
        eventlist_list.append(EventList.read(f))
    events = eventlist_list[0]
    for e in eventlist_list[1:]:
        events.stack(e)

    figures = []
    figures.append(plt.figure())
    ax = figures[-1].add_subplot(1, 1, 1)
    events.plot_energy(ax=ax)

    figures.append(plt.figure())
    ax = figures[-1].add_subplot(1, 1, 1)
    events.plot_energy_offset(ax=ax)

    figures.append(plt.figure())
    ax = figures[-1].add_subplot(1, 1, 1)
    events.plot_offset2_distribution(ax=ax)

    figures.append(plt.figure())
    ax = figures[-1].add_subplot(1, 1, 1)
    events.plot_time(ax=ax)

    if output is None:
        plt.show()
    else:
        with PdfPages(output) as pdf:
            for fig in figures:
                fig.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
                pdf.savefig(fig)
示例#2
0
from cta_tools.plotting import preliminary
import matplotlib.pyplot as plt
import click
from pathlib import Path
from gammapy.analysis import Analysis, AnalysisConfig
from gammapy.modeling.models import create_crab_spectral_model
from gammapy.estimators import LightCurveEstimator
import astropy.units as u
from cta_tools.logging import setup_logging


log = setup_logging()


@click.command()
@click.argument("config_path", type=click.Path(exists=True, dir_okay=False))
@click.argument("models_path", type=click.Path(exists=True, dir_okay=False))
@click.option("-o", "--output", type=click.Path(dir_okay=False))
@click.option("-r", "--reference", type=str, help="Crab Reference Spectrum. Crab Only!")
def main(config_path, models_path, output, reference):
    config = AnalysisConfig.read(config_path)
    analysis = Analysis(config)
    log.info(config)

    analysis.get_observations()
    log.info(analysis)
    log.info(dir(analysis))
    log.info(analysis.datasets)
    log.info(analysis.datasets[0].counts)
    analysis.get_datasets()
    analysis.read_models(models_path)
示例#3
0
def main(infile, verbose, output):
    setup_logging(verbose=verbose)
    figures = []
    try:
        magic = QTable.read("magic_sensitivity_2014.ecsv")
    except Exception as e:
        log.warning(e)
        magic = None

    sens = QTable.read(infile, hdu="SENSITIVITY")
    figures.append(plt.figure())
    ax = figures[-1].add_subplot(1, 1, 1)
    plot_sensitivity(sens[1:-1], ax, label="LST-1")

    if magic:
        for k in filter(
            lambda k: k.startswith("sensitivity_") or k.startswith("e_"), magic.colnames
        ):
            magic[k].info.format = ".3g"
        magic["reco_energy_low"] = magic["e_min"]
        magic["reco_energy_high"] = magic["e_max"]
        magic["reco_energy_center"] = magic["e_center"]
        magic["flux_sensitivity"] = magic["sensitivity_lima_5off"]

        plot_sensitivity(magic, ax, label="MAGIC")
    ax.legend()

    figures.append(plt.figure())
    ax = figures[-1].add_subplot(1, 1, 1)
    plot_sensitivity_gp(sens[1:-1], ax)

    aeff = QTable.read(infile, hdu="EFFECTIVE_AREA")
    aeff_only_gh = QTable.read(infile, hdu="EFFECTIVE_AREA_ONLY_GH")
    aeff_no_cuts = QTable.read(infile, hdu="EFFECTIVE_AREA_NO_CUTS")
    figures.append(plt.figure())
    ax = figures[-1].add_subplot(1, 1, 1)
    plot_aeff(aeff[0], ax, label="gh + theta")
    plot_aeff(aeff_only_gh[0], ax, label="Only GH")
    plot_aeff(aeff_no_cuts[0], ax, label="No Cuts")
    ax.legend()

    edisp = QTable.read(infile, hdu="ENERGY_DISPERSION")
    edisp_only_gh = QTable.read(infile, hdu="ENERGY_DISPERSION_ONLY_GH")
    figures.append(plt.figure())
    ax = figures[-1].add_subplot(1, 1, 1)
    plot_edisp(edisp[0], ax, label="gh + theta")
    plot_edisp(edisp_only_gh[0], ax, label="only gh")

    angres = QTable.read(infile, hdu="ANGULAR_RESOLUTION")
    figures.append(plt.figure())
    ax = figures[-1].add_subplot(1, 1, 1)
    plot_angular_resolution(angres, ax)

    energres = QTable.read(infile, hdu="ENERGY_BIAS_RESOLUTION")
    figures.append(plt.figure())
    ax = figures[-1].add_subplot(1, 1, 1)
    plot_energy_bias_resolution(energres, ax)

    bkg = QTable.read(infile, hdu="BACKGROUND")[0]
    rad_max = QTable.read(infile, hdu="RAD_MAX")[0]
    figures.append(plt.figure())
    ax = figures[-1].add_subplot(1, 1, 1)
    plot_background(bkg, rad_max, ax)

    thetacuts = QTable.read(infile, hdu="THETA_CUTS")
    figures.append(plt.figure())
    ax = figures[-1].add_subplot(1, 1, 1)
    plot_theta_cuts(thetacuts, ax)

    ghcuts = QTable.read(infile, hdu="GH_CUTS")
    figures.append(plt.figure())
    ax = figures[-1].add_subplot(1, 1, 1)
    plot_gh_cuts(ghcuts, ax)

    signal = QTable.read(infile, hdu="SIGNAL")
    signal_gh = QTable.read(infile, hdu="SIGNAL_GH")
    signal_cuts = QTable.read(infile, hdu="SIGNAL_CUTS")
    figures.append(plt.figure())
    ax = figures[-1].add_subplot(1, 1, 1)
    plot_efficiency({"NO CUTS": signal, "ONLY GH": signal_gh, "CUTS": signal_cuts}, ax)
    ax.legend()

    if output is None:
        plt.show()
    else:
        with PdfPages(output) as pdf:
            for fig in figures:
                fig.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
                pdf.savefig(fig)
示例#4
0
def main(
    input_files,
    protons,
    electrons,
    source_gammas,
    binsizes_config,
    cuts,
    verbose,
    output,
):
    setup_logging(verbose=verbose)
    observations = {}
    if binsizes_config:
        with open(binsizes_config) as f:
            binsizes = yaml.safe_load(f)
    else:
        binsizes = None
    if cuts:
        with open(cuts) as f:
            selection = yaml.safe_load(f).get("selection")
    else:
        selection = None

    cache = Path(output).with_suffix(".h5")
    if cache.exists():
        plot_data = read_plot_data(cache)
    else:
        plot_data = {}
        observations, obstime = read_lst_dl2_runs(input_files)
        combined = vstack(list(observations.values()))
        log.info(combined.keys())

        if protons:
            protons = load_mc(protons, obstime, IRFDOC_PROTON_SPECTRUM)
        if electrons:
            electrons = load_mc(electrons, obstime, IRFDOC_ELECTRON_SPECTRUM)
        if electrons and protons:
            background = vstack([protons, electrons])
        elif protons:
            background = protons
        elif electrons:
            background = electrons
        else:
            background = None

        if source_gammas:
            gammas = load_mc(source_gammas, obstime, CRAB_MAGIC_JHEAP2015)
        else:
            gammas = None

        if selection:
            mask = create_mask_selection(combined, selection)
            combined = combined[mask]
            if background:
                mask = create_mask_selection(background, selection)
                background = background[mask]
            if gammas:
                mask = create_mask_selection(gammas, selection)
                gammas = gammas[mask]

        for feature in combined.keys():
            plot_data[feature] = {}
            plot_data[feature]["bins"] = pd.Series(dtype=np.float64)
            plot_data[feature]["values"] = pd.DataFrame()

            log.info(feature)
            if binsizes:
                if feature in binsizes:
                    min_, max_, n = binsizes[feature]
                else:
                    min_ = get_value(combined, feature).min()
                    max_ = get_value(combined, feature).max()
                    n = 30
            else:
                min_ = get_value(combined, feature).min()
                max_ = get_value(combined, feature).max()
                n = 30
            log.debug(min_)
            log.debug(max_)
            if feature in logx:
                bins = np.logspace(np.log10(min_), np.log10(max_), n)
            else:
                bins = np.linspace(min_, max_, n)

            plot_data[feature]["bins"] = pd.Series(bins)
            feature_df = pd.DataFrame()
            feature_df["observations"], _ = np.histogram(
                get_value(combined, feature), bins=bins
            )
            if background:
                feature_df["background"], _ = np.histogram(
                    get_value(background, feature),
                    weights=background["weights"],
                    bins=bins,
                )
            if gammas:
                feature_df["gammas"], _ = np.histogram(
                    get_value(gammas, feature), weights=gammas["weights"], bins=bins
                )
            for run_data in observations:
                run_id = run_data[0]["obs_id"]
                log.info(f"Filling feature df for run {run_id}")
                # why would that happen?
                if feature not in run_data.keys():
                    log.debug(f"{feature} missing in keys: {run_data.keys()}")
                    continue
                feature_df[run_id], _ = np.histogram(
                    get_value(run_data, feature), bins=bins
                )
            plot_data[feature]["values"] = feature_df
        save_plot_data(cache, plot_data)

    figs = []

    datamc = ["observations"]
    if protons or electrons:
        datamc.append("background")
    if source_gammas:
        datamc.append("gammas")
    for feature in combined.keys():
        log.debug(f"Plotting feature: {feature}")
        if not plot_data[feature]["values"].empty:
            log.debug("And indeed there is data")
            figs.append(
                compare_datasets(plot_data, feature, datamc, logx=feature in logx)
            )
            figs.append(
                compare_datasets(
                    plot_data,
                    feature,
                    set(plot_data[feature]["values"].keys()) - set(datamc),
                    logx=feature in logx,
                )
            )

    if output is None:
        matplotlib.pyplot.show()
    else:
        with PdfPages(output) as pdf:
            for fig in figs:
                fig.tight_layout(pad=0)
                pdf.savefig(fig)