Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove FluxPointsDataset chi2assym option #2645

Merged
merged 2 commits into from
Dec 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 4 additions & 37 deletions gammapy/spectrum/flux_point.py
Original file line number Diff line number Diff line change
Expand Up @@ -1155,8 +1155,6 @@ class FluxPointsDataset(Dataset):
Flux points.
mask_fit : `numpy.ndarray`
Mask to apply for fitting
likelihood : {"chi2", "chi2assym"}
Likelihood function to use for the fit.
mask_safe : `numpy.ndarray`
Mask defining the safe data range.

Expand All @@ -1180,10 +1178,11 @@ class FluxPointsDataset(Dataset):
print(result.parameters.to_table())
"""

likelihood_type = "chi2"
tag = "FluxPointsDataset"

def __init__(
self, models, data, mask_fit=None, likelihood="chi2", mask_safe=None, name=""
self, models, data, mask_fit=None, mask_safe=None, name=""
):
self.data = data
self.mask_fit = mask_fit
Expand All @@ -1197,14 +1196,6 @@ def __init__(

self.mask_safe = mask_safe

if likelihood in ["chi2", "chi2assym"]:
self.likelihood_type = likelihood
else:
raise ValueError(
f"Invalid likelihood: {likelihood!r}."
" Choose either 'chi2' or 'chi2assym'."
)

@property
def models(self):
return self._models
Expand Down Expand Up @@ -1285,7 +1276,6 @@ def from_dict(cls, data, components, models):
data=FluxPoints(table),
mask_fit=mask_fit,
mask_safe=mask_safe,
likelihood=data["likelihood"],
)

def to_dict(self, filename=""):
Expand All @@ -1299,7 +1289,6 @@ def to_dict(self, filename=""):
"name": self.name,
"type": self.tag,
"models": models,
"likelihood": self.likelihood_type,
"filename": str(filename),
}

Expand Down Expand Up @@ -1349,26 +1338,13 @@ def __str__(self):
str_ += "\t \t {:23}: {:.2f} {} \n".format(
par.name, par.value, par.unit
)
str_ += "\t{:32}: {}\n".format("Likelihood type", self.likelihood_type)
str_ += "\t{:32}: {:.2f}\n".format("Likelihood value", self.stat_sum())
return str_

def data_shape(self):
"""Shape of the flux points data (tuple)."""
return self.data.e_ref.shape

@staticmethod
def _stat_chi2(data, model, sigma):
return ((data - model) / sigma).to_value("") ** 2

@staticmethod
def _stat_chi2_assym(data, model, sigma_n, sigma_p):
"""Assymetric chi2 statistics for a list of flux points and model."""
is_p = model > data
sigma = sigma_n
sigma[is_p] = sigma_p[is_p]
return FluxPointsDataset._stat_chi2(data, model, sigma)

def flux_pred(self):
"""Compute predicted flux."""
flux = 0.0
Expand All @@ -1380,17 +1356,8 @@ def stat_array(self):
"""Fit statistic array."""
model = self.flux_pred()
data = self.data.table["dnde"].quantity

if self.likelihood_type == "chi2":
sigma = self.data.table["dnde_err"].quantity
return self._stat_chi2(data, model, sigma)
elif self.likelihood_type == "chi2assym":
sigma_n = self.data.table["dnde_errn"].quantity
sigma_p = self.data.table["dnde_errp"].quantity
return self._stat_chi2_assym(data, model, sigma_n, sigma_p)
else:
# TODO: add fit statistic profiles
pass
sigma = self.data.table["dnde_err"].quantity
return ((data - model) / sigma).to_value("") ** 2

def residuals(self, method="diff"):
"""Compute the flux point residuals ().
Expand Down
40 changes: 19 additions & 21 deletions tutorials/sed_fitting_gammacat_fermi.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"from astropy import units as u\n",
"from gammapy.modeling.models import (\n",
" PowerLawSpectralModel,\n",
Expand All @@ -61,11 +62,7 @@
" SkyModel,\n",
")\n",
"from gammapy.spectrum import FluxPointsDataset, FluxPoints\n",
"from gammapy.catalog import (\n",
" SourceCatalog3FGL,\n",
" SourceCatalogGammaCat,\n",
" SourceCatalog3FHL,\n",
")\n",
"from gammapy.catalog import SOURCE_CATALOGS\n",
"from gammapy.modeling import Fit"
]
},
Expand All @@ -84,11 +81,9 @@
"metadata": {},
"outputs": [],
"source": [
"fermi_3fgl = SourceCatalog3FGL()\n",
"fermi_3fhl = SourceCatalog3FHL()\n",
"gammacat = SourceCatalogGammaCat(\n",
" \"$GAMMAPY_DATA/catalogs/gammacat/gammacat.fits.gz\"\n",
")"
"catalog_3fgl = SOURCE_CATALOGS[\"3fgl\"]()\n",
"catalog_3fhl = SOURCE_CATALOGS[\"3fhl\"]()\n",
"catalog_gammacat = SOURCE_CATALOGS[\"gamma-cat\"]()"
]
},
{
Expand All @@ -97,9 +92,9 @@
"metadata": {},
"outputs": [],
"source": [
"source_gammacat = gammacat[\"HESS J1507-622\"]\n",
"source_fermi_3fgl = fermi_3fgl[\"3FGL J1506.6-6219\"]\n",
"source_fermi_3fhl = fermi_3fhl[\"3FHL J1507.9-6228e\"]"
"source_fermi_3fgl = catalog_3fgl[\"3FGL J1506.6-6219\"]\n",
"source_fermi_3fhl = catalog_3fhl[\"3FHL J1507.9-6228e\"]\n",
"source_gammacat = catalog_gammacat[\"HESS J1507-622\"]"
]
},
{
Expand Down Expand Up @@ -153,13 +148,18 @@
"metadata": {},
"outputs": [],
"source": [
"# stack flux point tables\n",
"# Stack flux point tables\n",
"flux_points = FluxPoints.stack(\n",
" [flux_points_gammacat, flux_points_3fhl, flux_points_3fgl]\n",
")\n",
"\n",
"# drop the flux upper limit values\n",
"flux_points = flux_points.drop_ul()"
"t = flux_points.table\n",
"t[\"dnde_err\"] = 0.5 * (t[\"dnde_errn\"] + t[\"dnde_errp\"])\n",
"\n",
"# Remove upper limit points, where `dnde_errn = nan`\n",
"is_ul = np.isfinite(t[\"dnde_err\"])\n",
"flux_points = FluxPoints(t[is_ul])\n",
"flux_points"
]
},
{
Expand Down Expand Up @@ -196,7 +196,7 @@
"metadata": {},
"outputs": [],
"source": [
"dataset_pwl = FluxPointsDataset(model, flux_points, likelihood=\"chi2assym\")\n",
"dataset_pwl = FluxPointsDataset(model, flux_points)\n",
"fitter = Fit([dataset_pwl])\n",
"result_pwl = fitter.run()"
]
Expand Down Expand Up @@ -286,7 +286,7 @@
"metadata": {},
"outputs": [],
"source": [
"dataset_ecpl = FluxPointsDataset(model, flux_points, likelihood=\"chi2assym\")\n",
"dataset_ecpl = FluxPointsDataset(model, flux_points)\n",
"fitter = Fit([dataset_ecpl])\n",
"result_ecpl = fitter.run()\n",
"print(ecpl)"
Expand Down Expand Up @@ -342,9 +342,7 @@
"metadata": {},
"outputs": [],
"source": [
"dataset_log_parabola = FluxPointsDataset(\n",
" model, flux_points, likelihood=\"chi2assym\"\n",
")\n",
"dataset_log_parabola = FluxPointsDataset(model, flux_points)\n",
"fitter = Fit([dataset_log_parabola])\n",
"result_log_parabola = fitter.run()\n",
"print(log_parabola)"
Expand Down