astropy / astropy

Astronomy and astrophysics core library
https://www.astropy.org
BSD 3-Clause "New" or "Revised" License
4.39k stars 1.75k forks source link

Fitting a CompoundModel including a composition or | operator which changes units does't seem to work. #17126

Open samaloney opened 2 days ago

samaloney commented 2 days ago

Description

Fitting a model with the composition operator sometime like (physical_model | response) where physical model has units has one unit e.g. watts or photons etc and the response model has other units e.g. dn or counts doesn't seem to work as expected and raises an error.

Expected behavior

The unit chain from each model to the next in taken into account rather than only the input and output units from the compound model and the fitter return the correct result.

How to Reproduce

import astropy.units as u
import numpy as np
from astropy.modeling import models, fitting
e = np.linspace(0, 25, 100)  * u.keV
phys = models.Linear1D(slope=-4*u.ph/u.keV, intercept=100*u.ph)
phys.output_units = {'y': u.ph}
response = models.Linear1D(slope=1*u.ct/u.ph, intercept=0*u.ct)
response.output_units = {'y': u.ct}
comb = phys | response
fake_data = comb(e)
fit = fitting.LevMarLSQFitter()
res = fit(comb, e, fake_data)
UnitConversionError: 'ph' and 'ct' are not convertible

Versions

import astropy
try:
    astropy.system_info()
except AttributeError:
    import platform; print(platform.platform())
    import sys; print("Python", sys.version)
    import astropy; print("astropy", astropy.__version__)
    import numpy; print("Numpy", numpy.__version__)
    import erfa; print("pyerfa", erfa.__version__)
    try:
        import scipy
        print("Scipy", scipy.__version__)
    except ImportError:
        print("Scipy not installed")
    try:
        import matplotlib
        print("Matplotlib", matplotlib.__version__)
    except ImportError:
        print("Matplotlib not installed")
platform
--------
platform.platform() = 'macOS-14.7-arm64-arm-64bit'
platform.version() = 'Darwin Kernel Version 23.6.0: Wed Jul 31 20:48:52 PDT 2024; root:xnu-10063.141.1.700.5~1/RELEASE_ARM64_T6020'
platform.python_version() = '3.11.7'
packages
--------
astropy              6.1.dev1790+g2f59b70e8b
numpy                1.26.4
scipy                1.13.0
matplotlib           3.8.4
pandas               2.2.1
pyerfa               2.0.1.1
pllim commented 2 days ago

cc @astropy/modeling