question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Serialising covariance of CompoundSpectralModel with a TemplateSpectralModel

See original GitHub issue

Bug description

The covariance matrix is incorrectly written for a CompoundSpectralModel which is a product of a TemplateSpectralModel and a NormSpectralModel

To Reproduce

Either serialise the diffuse_iem model in the Fermi-LAT tutorial, or

from gammapy.modeling.models import *
t = TemplateSpectralModel(energy=[1,3,9]*u.TeV, 
                        values=[20,30,40]*1 / (u.cm*u.cm*u.MeV*u.s))
p = PowerLawNormSpectralModel()
sk = SkyModel(spectral_model=t*p, name="xx")
Models([sk]).write("test.yaml", overwrite=True)
m1 = Models.read("test.yaml")

This leads to an error

File ~/Gammapy-dev/gammapy/gammapy/modeling/models/core.py:362, in DatasetModels.covariance(self, covariance)
    359 @covariance.setter
    360 def covariance(self, covariance):
    361     self._check_covariance()
--> 362     self._covariance.data = covariance
    364     for model in self._models:
    365         subcovar = self._covariance.get_subcovariance(model.covariance.parameters)

File ~/Gammapy-dev/gammapy/gammapy/modeling/covariance.py:59, in Covariance.data(self, value)
     57 shape = (npars, npars)
     58 if value.shape != shape:
---> 59     raise ValueError(
     60         f"Invalid covariance shape: {value.shape}, expected {shape}"
     61     )
     63 self._data = value

ValueError: Invalid covariance shape: (13, 12), expected (13, 13)

This occurs because the norm parameter is present on both the TemplateSpectralModel and the normed model, and is incorrectly serialised during writing.

Other information

It would be good to sort this before 1.0 Otherwise, Fermi datasets serialisation is difficult.

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:27 (27 by maintainers)

github_iconTop GitHub Comments

2reactions
registerriercommented, Oct 5, 2022

Apparently changing to this:

def write_covariance(self, filename, **kwargs):
    """Write covariance to file
    Parameters
    ----------
    filename : str
        Filename
    **kwargs : dict
        Keyword arguments passed to `~astropy.table.Table.write`
    """
    names = self.parameters_unique_names
    table = Table()
    table["Parameters"] = names

    for idx, name in enumerate(names):
        values = self.covariance.data[idx]
        table[str(idx)] = values

    table.write(make_path(filename), **kwargs)

might be working.

We don’t need to have the name repeated on the lines and columns of the Table

1reaction
adonathcommented, Oct 5, 2022

Is this safe? It might be useful to have additive models with some correction from norm models, no?

Yes, but handling the hierarchy adds additional complexity. If we’d like to handle arbitrary complex hierarchies we need a recursive solution to generate the unique parameter names…

So we could end up with things like:

['xx.spectral.model1.model2.model1.norm',
 'xx.spectral.model2.model1.model2norm',
 ...]
Read more comments on GitHub >

github_iconTop Results From Across the Web

TemplateSpectralModel — gammapy vX.Y.Z
For more information see Template spectral model. Parameters. energy Quantity. Array of energies at which the model values are given. values ...
Read more >
gammapy.modeling · GitHub
A Python package for gamma-ray astronomy. Contribute to gammapy/gammapy development by creating an account on GitHub.
Read more >
Modeling Data and Curve Fitting
curve_fit with the model function, data arrays, and initial guesses. The results returned are the optimal values for the parameters and the covariance...
Read more >
Available CRAN Packages By Name - Microsoft
Available CRAN Packages By Name ; bastah, Big Data Statistical Analysis for High-Dimensional Models ; BAT, Biodiversity Assessment Tools ; batade, HTML reports...
Read more >
MestreNova Manual
Reference of 2D-NMR spectra with the 1D external trace ... After subtracting the estimated baseline model, this is the resulting spectrum:.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found