Skip to content

Commit

Permalink
Merge branch 'master' into update_docs_ref
Browse files Browse the repository at this point in the history
Signed-off-by: Arnau Aguasca-Cabot <[email protected]>
  • Loading branch information
aaguasca committed Oct 17, 2023
2 parents f61ffea + ade0655 commit 52ae67e
Show file tree
Hide file tree
Showing 93 changed files with 1,525 additions and 347 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/cffconvert.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
pip install eossr
- name: Check out a copy of the repository
uses: actions/checkout@v3
uses: actions/checkout@v4

- name: Check whether the citation metadata from CITATION.cff is valid
uses: citation-file-format/[email protected]
Expand Down
8 changes: 4 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ jobs:
name: Black check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: psf/black@stable
with:
version: "22.6.0"
Expand Down Expand Up @@ -61,7 +61,7 @@ jobs:
allowed_fail: true
steps:
- name: Check out repository
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Python ${{ matrix.python }}
Expand Down Expand Up @@ -109,7 +109,7 @@ jobs:
GAMMAPY_DATA: /home/runner/work/gammapy/gammapy/gammapy-datasets/dev
steps:
- name: Check out repository
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Python ${{ matrix.python }}
Expand Down Expand Up @@ -140,7 +140,7 @@ jobs:
shell: bash -l {0}
steps:
- name: checkout repo
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: create and activate env
uses: mamba-org/provision-with-micromamba@main
with:
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Update tags
run: git fetch --tags --force
- name: Set up Python
Expand All @@ -35,7 +35,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Release
uses: softprops/action-gh-release@v1
with:
Expand Down
5 changes: 2 additions & 3 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,8 @@
.. image:: https://zenodo.org/badge/DOI/10.5281/zenodo.4701488.svg?style=flat
:target: https://doi.org/10.5281/zenodo.4701488

.. image:: https://archive.softwareheritage.org/badge/swh:1:dir:27e81770f5e2e977017789ef5aa4a35978137fa6/
:target: https://archive.softwareheritage.org/swh:1:dir:27e81770f5e2e977017789ef5aa4a35978137fa6;origin=https://github.com/gammapy/gammapy;visit=swh:1:snp:6017d488cdb0faaa2373663b86f751eafdf2a1d5;anchor=swh:1:rev:e2591a43bc04db8e51e693d0711c21ac0738203c

.. image:: https://archive.softwareheritage.org/badge/origin/https://github.com/gammapy/gammapy/
:target: https://archive.softwareheritage.org/browse/origin/?origin_url=https://github.com/gammapy/gammapy

Gammapy
=======
Expand Down
55 changes: 55 additions & 0 deletions docs/development/dev_howto.rst
Original file line number Diff line number Diff line change
Expand Up @@ -884,3 +884,58 @@ Example what to put as a test::
assert str(p).startswith('Hi')
assert p.info(add_location=True).endswith('Heidelberg')


Output in Jupyter notebook cells
++++++++++++++++++++++++++++++++

In addition to the standard `repr` and `str` outputs, Jupyter notebook
cells have the option to display nicely formatted (HTML) output, using
the IPython rich display options (other output options also exist,
such as LaTeX or SVG, but these are less used). This requires the
implementation of a `_repr_html_(self)` method (note: single
underscore) in a class.

By default, this method can just return the string representation of
the object (which may already produce a nicely formatted output). That
is often nicer than the default, which is to return the `repr` output,
which tends to be shorter and may miss details of the object. Thus,
the following would be a good default for a new class::

def _repr_html_(self):
return f'<pre>html.escape(str(self))</pre>'

The surrounding `<pre>` takes care that the formatting in HTML is the
same as that for the normal `__str__` method, while `html.escape`
handles escaping HTML special characters (<, >, &, " and ').

Note that if no `__str__` method is implemented, `__repr__` is used,
and ultimately, the Python built-in `__repr__` method serves as the
final fallback (which looks like `<gammapy.data.event_list.EventList
at 0x129602550>` or similar).

If more specific HTML output is preferred (for example, output
formatted in a HTML table or list), it is best to create a separate
`to_html(self)` method in the class, which is more explicit (and can
be documentated as part of the API), and let `_repr_html_` call this
method::

def _repr_html_(self):
return self.to_html(self)

Thus very similar to `__str__` calling `info()`, with optional
parameters if needed.

To allow for both options, the following default `_repr_html_` can be
implemented instead::

def _repr_html_(self):
try:
return self.to_html(self)
except AttributeError:
return f'<pre>html.escape(str(self))</pre>'

Nearly all base classes in Gammapy implement this default
`_repr_html_`. If a new class derives from an existing Gammapy class,
a default implementation is not needed, since it will rely on its
(grand)parent. As a result, for specific HTML output, only the
`to_html` method needs to be implented for the relevant class.
4 changes: 2 additions & 2 deletions docs/user-guide/estimators.rst
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ Quantity Definition
norm_errp Positive error of the norm, given as absolute difference to the best fit norm
norm_errn Negative error of the norm, given as absolute difference to the best fit norm
norm_ul Upper limit of the norm
norm_scan Norm scan
stat_scan Fit statistics scan
norm_scan Norm parameter values used for the fit statistic scan
stat_scan Fit statistics values associated with norm_scan
================= =================================================

To compute the error, asymmetric errors as well as upper limits one can
Expand Down
11 changes: 10 additions & 1 deletion examples/tutorials/analysis-2d/detect.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
from IPython.display import display
from gammapy.datasets import MapDataset
from gammapy.estimators import ASmoothMapEstimator, TSMapEstimator
from gammapy.estimators.utils import find_peaks
from gammapy.estimators.utils import find_peaks, find_peaks_in_flux_map
from gammapy.irf import EDispKernelMap, PSFMap
from gammapy.maps import Map
from gammapy.modeling.models import PointSpatialModel, PowerLawSpectralModel, SkyModel
Expand Down Expand Up @@ -213,6 +213,15 @@

# sphinx_gallery_thumbnail_number = 3


######################################################################
# We can also utilise `~gammapy.estimators.utils.find_peaks_in_flux_map`
# to display various parameters from the FluxMaps

sources_flux_map = find_peaks_in_flux_map(maps, threshold=5, min_distance="0.25 deg")
display(sources_flux_map)


######################################################################
# Note that we used the instrument point-spread-function (PSF) as kernel,
# so the hypothesis we test is the presence of a point source. In order to
Expand Down
57 changes: 26 additions & 31 deletions examples/tutorials/analysis-2d/ring_background.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
from gammapy.datasets import MapDatasetOnOff
from gammapy.estimators import ExcessMapEstimator
from gammapy.makers import RingBackgroundMaker
from gammapy.visualization import plot_distribution

log = logging.getLogger(__name__)

Expand Down Expand Up @@ -258,41 +259,35 @@

# create a 2D mask for the images
significance_map_off = significance_map * exclusion_mask
significance_all = significance_map.data[np.isfinite(significance_map.data)]
significance_off = significance_map_off.data[np.isfinite(significance_map_off.data)]

fig, ax = plt.subplots()
ax.hist(
significance_all,
density=True,
alpha=0.5,
color="red",
label="all bins",
bins=21,

kwargs_axes = {"xlabel": "Significance", "yscale": "log", "ylim": (1e-5, 1)}

ax, _ = plot_distribution(
significance_map,
kwargs_hist={
"density": True,
"alpha": 0.5,
"color": "red",
"label": "all bins",
"bins": 21,
},
kwargs_axes=kwargs_axes,
)

ax.hist(
significance_off,
density=True,
alpha=0.5,
color="blue",
label="off bins",
bins=21,
ax, res = plot_distribution(
significance_map_off,
ax=ax,
func="norm",
kwargs_hist={
"density": True,
"alpha": 0.5,
"color": "blue",
"label": "off bins",
"bins": 21,
},
kwargs_axes=kwargs_axes,
)

# Now, fit the off distribution with a Gaussian
mu, std = norm.fit(significance_off)
x = np.linspace(-8, 8, 50)
p = norm.pdf(x, mu, std)
ax.plot(x, p, lw=2, color="black")
ax.legend()
ax.set_xlabel("Significance")
ax.set_yscale("log")
ax.set_ylim(1e-5, 1)
xmin, xmax = np.min(significance_all), np.max(significance_all)
ax.set_xlim(xmin, xmax)

print(f"Fit results: mu = {mu:.2f}, std = {std:.2f}")
plt.show()

# sphinx_gallery_thumbnail_number = 2
31 changes: 10 additions & 21 deletions examples/tutorials/analysis-3d/analysis_3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
# Check setup
# -----------
from gammapy.utils.check import check_tutorials_setup
from gammapy.visualization import plot_distribution

check_tutorials_setup()

Expand Down Expand Up @@ -306,34 +307,22 @@
######################################################################
# Distribution of residuals significance in the full map geometry:
#
significance_data = result["sqrt_ts"].data
significance_map = result["sqrt_ts"]

# Remove bins that are inside an exclusion region, that would create an artificial peak at significance=0.
selection = np.isfinite(significance_data)
significance_data = significance_data[selection]
kwargs_hist = {"density": True, "alpha": 0.9, "color": "red", "bins": 40}

fig, ax = plt.subplots()

ax.hist(significance_data, density=True, alpha=0.9, color="red", bins=40)
mu, std = norm.fit(significance_data)

x = np.linspace(-5, 5, 100)
p = norm.pdf(x, mu, std)

ax.plot(
x,
p,
lw=2,
color="black",
label=r"$\mu$ = {:.2f}, $\sigma$ = {:.2f}".format(mu, std),
ax, res = plot_distribution(
significance_map,
func="norm",
kwargs_hist=kwargs_hist,
kwargs_axes={"xlim": (-5, 5)},
)
ax.legend(fontsize=17)
ax.set_xlim(-5, 5)

plt.show()


######################################################################
# Here we can plot the number of predicted counts for each model and
# Here we could also plot the number of predicted counts for each model and
# for the background in our dataset by using the
# `~gammapy.visualization.plot_npred_signal` function.
#
Expand Down
Loading

0 comments on commit 52ae67e

Please sign in to comment.