コード例 #1
0
def test_slice_time_axis(time_intervals):
    axis = TimeMapAxis(time_intervals["t_min"], time_intervals["t_max"],
                       time_intervals["t_ref"])

    new_axis = axis.slice([2, 6, 9])
    squashed = axis.squash()

    assert new_axis.nbin == 3
    assert_allclose(squashed.time_max[0].mjd, 58937.041667)
    assert squashed.nbin == 1
    assert_allclose(squashed.time_max[0].mjd, 58937.041667)
コード例 #2
0
def test_bad_length_sort_time_axis(time_intervals):
    tref = time_intervals["t_ref"]
    tmin = time_intervals["t_min"]
    tmax_reverse = time_intervals["t_max"][::-1]
    tmax_short = time_intervals["t_max"][:-1]

    with pytest.raises(ValueError):
        TimeMapAxis(tmin, tmax_reverse, tref, name="time")

    with pytest.raises(ValueError):
        TimeMapAxis(tmin, tmax_short, tref, name="time")
コード例 #3
0
def test_incorrect_time_axis():
    tmin = np.linspace(0, 10, 20) * u.h
    tmax = np.linspace(1, 11, 20) * u.h

    # incorrect reference time
    with pytest.raises(ValueError):
        TimeMapAxis(tmin, tmax, reference_time=51000 * u.d, name="time")

    # overlapping time intervals
    with pytest.raises(ValueError):
        TimeMapAxis(tmin, tmax, reference_time=Time.now(), name="time")
コード例 #4
0
def test_slice_squash_time_axis(time_intervals):
    axis = TimeMapAxis(time_intervals["t_min"], time_intervals["t_max"],
                       time_intervals["t_ref"])
    axis_squash = axis.squash()
    axis_slice = axis.slice(slice(1, 5))

    assert axis_squash.nbin == 1
    assert_allclose(axis_squash.time_min[0].mjd, 58927)
    assert_allclose(axis_squash.time_delta.to_value("d"), 10.04166666)
    assert axis_slice.nbin == 4
    assert_allclose(axis_slice.time_delta.to_value("d")[0], 0.04166666666)
    assert axis_squash != axis_slice
コード例 #5
0
    def _make_source_object(self, index):
        """Make one source object.

        Parameters
        ----------
        index : int
            Row index

        Returns
        -------
        source : `SourceCatalogObject`
            Source object
        """
        data = table_row_to_dict(self.table[index])
        data[SourceCatalogObject._row_index_key] = index

        fp_energy_edges = getattr(self, "flux_points_energy_edges", None)

        if fp_energy_edges:
            data["fp_energy_edges"] = fp_energy_edges

        hist_table = getattr(self, "hist_table", None)
        hist2_table = getattr(self, "hist2_table", None)

        if hist_table:
            try:
                data["time_axis"] = TimeMapAxis.from_table(hist_table,
                                                           format="fermi-fgl")
            except KeyError:
                pass

        if hist2_table:
            try:
                data["time_axis_2"] = TimeMapAxis.from_table(
                    hist2_table, format="fermi-fgl")
            except KeyError:
                pass
        if "Extended_Source_Name" in data:
            name_extended = data["Extended_Source_Name"].strip()
        elif "Source_Name" in data:
            name_extended = data["Source_Name"].strip()
        else:
            name_extended = None
        try:
            idx = self._lookup_extended_source_idx[name_extended]
            data_extended = table_row_to_dict(self.extended_sources_table[idx])
        except (KeyError, AttributeError):
            data_extended = None

        source = self.source_object_class(data, data_extended)
        return source
コード例 #6
0
def test_TimeMapAxis_format_plot_xaxis(time_intervals):
    import matplotlib.pyplot as plt
    axis = TimeMapAxis(time_intervals["t_min"],
                       time_intervals["t_max"],
                       time_intervals["t_ref"],
                       name="time")

    with mpl_plot_check():
        ax = plt.gca()
        with quantity_support():
            ax.plot(axis.center, np.ones_like(axis.center))

    ax1 = axis.format_plot_xaxis(ax=ax)
    assert ax1.xaxis.label.properties()["text"] == "Time [iso]"
コード例 #7
0
def test_time_axis(time_intervals):
    axis = TimeMapAxis(time_intervals["t_min"], time_intervals["t_max"],
                       time_intervals["t_ref"])

    axis_copy = axis.copy()

    assert axis.nbin == 20
    assert axis.name == "time"
    assert axis.node_type == "intervals"

    assert_allclose(axis.time_delta.to_value("min"), 60)
    assert_allclose(axis.time_mid[0].mjd, 58927.020833333336)

    assert "time" in axis.__str__()
    assert "20" in axis.__str__()

    with pytest.raises(ValueError):
        axis.assert_name("bad")

    assert axis_copy == axis

    assert not axis.is_contiguous

    ax_cont = axis.to_contiguous()
    assert_allclose(ax_cont.nbin, 39)
コード例 #8
0
ファイル: test_axes.py プロジェクト: registerrier/gammapy
def test_time_axis_plot_helpers():
    time_ref = Time('1999-01-01T00:00:00.123456789')

    time_axis = TimeMapAxis(edges_min=[0, 1, 3] * u.d,
                            edges_max=[0.8, 1.9, 5.4] * u.d,
                            reference_time=time_ref)

    labels = time_axis.as_plot_labels
    assert labels[0] == "1999-01-01 00:00:00.123 - 1999-01-01 19:12:00.123"

    center = time_axis.as_plot_center
    assert center[0].year == 1999

    edges = time_axis.to_contiguous().as_plot_edges
    assert edges[0].year == 1999
コード例 #9
0
def test_mixed_axes():
    label_axis = LabelMapAxis(labels=["label-1", "label-2", "label-3"],
                              name="label")

    time_axis = TimeMapAxis(
        edges_min=[1, 10] * u.day,
        edges_max=[2, 13] * u.day,
        reference_time=Time("2020-03-19"),
    )

    energy_axis = MapAxis.from_energy_bounds("1 TeV", "10 TeV", nbin=4)

    axes = MapAxes(axes=[energy_axis, time_axis, label_axis])

    coords = axes.get_coord()

    assert coords["label"].shape == (1, 1, 3)
    assert coords["energy"].shape == (4, 1, 1)
    assert coords["time"].shape == (1, 2, 1)

    idx = axes.coord_to_idx(coords)

    assert_allclose(idx[0], np.arange(4).reshape((4, 1, 1)))
    assert_allclose(idx[1], np.arange(2).reshape((1, 2, 1)))
    assert_allclose(idx[2], np.arange(3).reshape((1, 1, 3)))

    hdu = axes.to_table_hdu(format="gadf")

    table = Table.read(hdu)

    assert table["LABEL"].dtype == np.dtype("<U7")
    assert len(table) == 24
コード例 #10
0
def test_from_time_edges_time_axis():
    t0 = Time("2020-03-19")
    t_min = t0 + np.linspace(0, 10, 20) * u.d
    t_max = t_min + 1 * u.h

    axis = TimeMapAxis.from_time_edges(t_min, t_max)
    axis_h = TimeMapAxis.from_time_edges(t_min, t_max, unit="h")

    assert axis.nbin == 20
    assert axis.name == "time"
    assert_time_allclose(axis.reference_time, t0)
    assert_allclose(axis.time_delta.to_value("min"), 60)
    assert_allclose(axis.time_mid[0].mjd, 58927.020833333336)
    assert_allclose(axis_h.time_delta.to_value("h"), 1)
    assert_allclose(axis_h.time_mid[0].mjd, 58927.020833333336)
    assert axis == axis_h
コード例 #11
0
    def plot(self, time_range, ax=None, **kwargs):
        """
        Plot Temporal Model.

        Parameters
        ----------
        time_range : `~astropy.time.Time`
            times to plot the model
        ax : `~matplotlib.axes.Axes`, optional
            Axis to plot on
        **kwargs : dict
            Keywords forwarded to `~matplotlib.pyplot.errorbar`

        Returns
        -------
        ax : `~matplotlib.axes.Axes`, optional
            axis
        """
        time_min, time_max = time_range
        time_axis = TimeMapAxis.from_time_bounds(time_min=time_min,
                                                 time_max=time_max,
                                                 nbin=100)
        time_axis.time_format = "mjd"

        m = RegionNDMap.create(region=None, axes=[time_axis])
        kwargs.setdefault("marker", "None")
        kwargs.setdefault("ls", "-")
        kwargs.setdefault("xerr", None)
        m.quantity = self(time_axis.time_mid)
        ax = m.plot(ax=ax, **kwargs)
        ax.set_ylabel("Norm / A.U.")
        return ax
コード例 #12
0
def test_map_time_axis_read_write(map_type):
    time_axis = TimeMapAxis(
        edges_min=[0, 2, 4] * u.d,
        edges_max=[1, 3, 5] * u.d,
        reference_time="2000-01-01",
    )

    energy_axis = MapAxis.from_energy_bounds("1 TeV", "10 TeV", nbin=5)

    m = Map.create(
        binsz=0.1,
        width=10.0,
        map_type=map_type,
        skydir=SkyCoord(0.0, 30.0, unit="deg"),
        axes=[energy_axis, time_axis],
    )

    hdulist = m.to_hdulist(hdu="COUNTS")

    m2 = Map.from_hdulist(hdulist)

    time_axis_new = m2.geom.axes["time"]
    assert time_axis_new == time_axis
    assert time_axis.reference_time.scale == "utc"
    assert time_axis_new.reference_time.scale == "tt"
コード例 #13
0
def test_map_with_time_axis(time_intervals):
    time_axis = TimeMapAxis(time_intervals["t_min"], time_intervals["t_max"],
                            time_intervals["t_ref"])
    energy_axis = MapAxis.from_energy_bounds(0.1, 10, 2, unit="TeV")
    region_map = RegionNDMap.create(region="fk5; circle(0,0,0.1)",
                                    axes=[energy_axis, time_axis])

    assert region_map.geom.data_shape == (20, 2, 1, 1)
コード例 #14
0
def test_from_gti_time_axis():
    filename = "$GAMMAPY_DATA/hess-dl3-dr1/data/hess_dl3_dr1_obs_id_020136.fits.gz"
    filename = make_path(filename)
    gti = GTI.read(filename)

    axis = TimeMapAxis.from_gti(gti)
    expected = Time(53090.123451203704, format="mjd", scale="tt")
    assert_time_allclose(axis.time_min[0], expected)
    assert axis.nbin == 1
コード例 #15
0
ファイル: lightcurve.py プロジェクト: LauraOlivera/gammapy
    def run(self, datasets):
        """Run light curve extraction.

        Normalize integral and energy flux between emin and emax.

        Parameters
        ----------
        datasets : list of `~gammapy.datasets.SpectrumDataset` or `~gammapy.datasets.MapDataset`
            Spectrum or Map datasets.

        Returns
        -------
        lightcurve : `~gammapy.estimators.FluxPoints`
            Light curve flux points
        """
        datasets = Datasets(datasets)

        if self.time_intervals is None:
            gti = datasets.gti
        else:
            gti = GTI.from_time_intervals(self.time_intervals)

        gti = gti.union(overlap_ok=False, merge_equal=False)

        rows = []
        valid_intervals = []
        for t_min, t_max in progress_bar(gti.time_intervals,
                                         desc="Time intervals"):
            datasets_to_fit = datasets.select_time(time_min=t_min,
                                                   time_max=t_max,
                                                   atol=self.atol)

            if len(datasets_to_fit) == 0:
                log.info(
                    f"No Dataset for the time interval {t_min} to {t_max}. Skipping interval."
                )
                continue

            valid_intervals.append([t_min, t_max])
            fp = self.estimate_time_bin_flux(datasets=datasets_to_fit)

            for name in ["counts", "npred", "npred_null"]:
                fp._data[name] = self.expand_map(fp._data[name],
                                                 dataset_names=datasets.names)
            rows.append(fp)

        if len(rows) == 0:
            raise ValueError(
                "LightCurveEstimator: No datasets in time intervals")

        gti = GTI.from_time_intervals(valid_intervals)
        axis = TimeMapAxis.from_gti(gti=gti)
        return FluxPoints.from_stack(
            maps=rows,
            axis=axis,
        )
コード例 #16
0
ファイル: test_axes.py プロジェクト: registerrier/gammapy
def test_single_interval_time_axis(time_interval):
    axis = TimeMapAxis(edges_min=time_interval["t_min"],
                       edges_max=time_interval["t_max"],
                       reference_time=time_interval["t_ref"])

    coord = Time(58933, format="mjd") + u.Quantity([1.5, 3.5, 10], unit="d")
    pix = axis.coord_to_pix(coord)

    assert axis.nbin == 1
    assert_allclose(axis.time_delta.to_value("d"), 10)
    assert_allclose(axis.time_mid[0].mjd, 58933)

    pix_min = axis.coord_to_pix(time_interval["t_min"] + 0.001 * u.s)
    assert_allclose(pix_min, -0.5)

    pix_max = axis.coord_to_pix(time_interval["t_max"] - 0.001 * u.s)
    assert_allclose(pix_max, 0.5)

    assert_allclose(pix, [0.15, 0.35, np.nan])
コード例 #17
0
def test_from_table_time_axis():
    t0 = Time("2006-02-12", scale="utc")
    t_min = np.linspace(0, 10, 10) * u.d
    t_max = t_min + 12 * u.h

    table = Table()
    table["TIME_MIN"] = t_min
    table["TIME_MAX"] = t_max
    table.meta.update(time_ref_to_dict(t0))
    table.meta["AXCOLS1"] = "TIME_MIN,TIME_MAX"

    axis = TimeMapAxis.from_table(table, format="gadf")

    assert axis.nbin == 10
    assert_allclose(axis.time_mid[0].mjd, 53778.25)
コード例 #18
0
ファイル: test_axes.py プロジェクト: registerrier/gammapy
def test_axes_basics():
    energy_axis = MapAxis.from_energy_edges([1, 3] * u.TeV)

    time_ref = Time('1999-01-01T00:00:00.123456789')

    time_axis = TimeMapAxis(edges_min=[0, 1, 3] * u.d,
                            edges_max=[0.8, 1.9, 5.4] * u.d,
                            reference_time=time_ref)

    axes = MapAxes([energy_axis, time_axis])

    assert axes.shape == (1, 3)
    assert axes.is_unidimensional
    assert not axes.is_flat

    assert axes.primary_axis.name == "time"
コード例 #19
0
ファイル: test_ndmap.py プロジェクト: registerrier/gammapy
def test_region_nd_map_plot_two_axes():
    energy_axis = MapAxis.from_energy_edges([1, 3, 10] * u.TeV)

    time_ref = Time('1999-01-01T00:00:00.123456789')

    time_axis = TimeMapAxis(edges_min=[0, 1, 3] * u.d,
                            edges_max=[0.8, 1.9, 5.4] * u.d,
                            reference_time=time_ref)

    m = RegionNDMap.create("icrs;circle(0, 0, 1)",
                           axes=[energy_axis, time_axis])
    m.data = 10 + np.random.random(m.data.size)

    with mpl_plot_check():
        m.plot(axis_name="energy")

    with mpl_plot_check():
        m.plot(axis_name="time")

    with pytest.raises(ValueError):
        m.plot()
コード例 #20
0
def test_coord_to_idx_time_axis(time_intervals):
    tmin = time_intervals["t_min"]
    tmax = time_intervals["t_max"]
    tref = time_intervals["t_ref"]
    axis = TimeMapAxis(tmin, tmax, tref, name="time")

    time = Time(58927.020833333336, format="mjd")

    times = axis.time_mid
    times[::2] += 1 * u.h
    times = times.insert(0, tref - [1, 2] * u.yr)

    idx = axis.coord_to_idx(time)
    indices = axis.coord_to_idx(times)

    pix = axis.coord_to_pix(time)
    pixels = axis.coord_to_pix(times)

    assert idx == 0
    assert_allclose(indices[1::2], [-1, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19])
    assert_allclose(indices[::2], -1)
    assert_allclose(pix, 0, atol=1e-10)
    assert_allclose(pixels[1::2], [np.nan, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19])
コード例 #21
0
def test_time_map_axis_from_time_bounds():
    t_min = Time("2006-02-12", scale="utc")
    t_max = t_min + 12 * u.h

    axis = TimeMapAxis.from_time_bounds(time_min=t_min, time_max=t_max, nbin=3)
    assert_allclose(axis.center, [0.083333, 0.25, 0.416667] * u.d, rtol=1e-5)