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

model fitting should prohibit selecting subset not in bounds of data #1911

Closed
Jdaviz-Triage-Bot opened this issue Dec 9, 2022 · 0 comments · Fixed by #1935
Closed

model fitting should prohibit selecting subset not in bounds of data #1911

Jdaviz-Triage-Bot opened this issue Dec 9, 2022 · 0 comments · Fixed by #1935
Labels
bug Something isn't working plugin Label for plugins common to multiple configurations specviz

Comments

@Jdaviz-Triage-Bot
Copy link

Jdaviz-Triage-Bot commented Dec 9, 2022

Reporter: Kyle Conroy

Selecting a data/subset combo which does not result in any data points in the mask should raise an error from the API and prevent clicking compute with a message in the plugin UI.

To reproduce:

import numpy as np
from jdaviz import Specviz


import tempfile
from astroquery.mast import Observations
data_dir = tempfile.gettempdir()
fn = "jw02732-o004_t004_miri_ch1-shortmediumlong_x1d.fits"
result = Observations.download_file(f"mast:JWST/product/\{fn}", local_path=f'\{data_dir}/\{fn}')
specviz = Specviz()
specviz.load_spectrum(f'\{data_dir}/\{fn}', "right_spectrum")
sp = specviz.app.get_data_from_viewer('spectrum-viewer', 'right_spectrum')

from specutils import Spectrum1D

sp2 = Spectrum1D(spectral_axis=sp.spectral_axis - 2*sp.spectral_axis.unit,
                 flux=sp.flux * 1.25)

specviz.load_spectrum(sp2, data_label="left_spectrum")


specviz.show()
from glue.core.roi import XRangeROI

specviz.app.get_viewer('spectrum-viewer').apply_roi(XRangeROI(4, 4.4))  # on left (second) only

mf = specviz.plugins['Model Fitting']
mf.create_model_component('Linear1D')
mf.dataset = 'left_spectrum'  # second to be added
mf.spectral_subset = 'Subset 1'


mf.calculate_fit()

mf.dataset = 'right_spectrum'  # first to be added
mf.calculate_fit()

image

Note that an additional call to mf.calculate_fit() (see #1910) results in a Traceback:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In [3], line 1
----> 1 mf.calculate_fit()

File ~/repos/jdaviz/jdaviz/configs/default/plugins/model_fitting/model_fitting.py:648, in ModelFitting.calculate_fit(self, add_data)
    646     return self._fit_model_to_cube(add_data=add_data)
    647 else:
--> 648     return self._fit_model_to_spectrum(add_data=add_data)

File ~/repos/jdaviz/jdaviz/configs/default/plugins/model_fitting/model_fitting.py:675, in ModelFitting._fit_model_to_spectrum(self, add_data)
    672         self._spectrum1d.mask += subset_mask
    674 try:
--> 675     fitted_model, fitted_spectrum = fit_model_to_spectrum(
    676         self._spectrum1d,
    677         models_to_fit,
    678         self.model_equation,
    679         run_fitter=True)
    680 except AttributeError:
    681     msg = SnackbarMessage("Unable to fit: model equation may be invalid",
    682                           color="error", sender=self)

File ~/repos/jdaviz/jdaviz/configs/default/plugins/model_fitting/fitting_backend.py:75, in fit_model_to_spectrum(spectrum, component_list, expression, run_fitter, window, n_cpu)
     73     return _fit_3D(initial_model, spectrum, window=window, n_cpu=n_cpu)
     74 else:
---> 75     return _fit_1D(initial_model, spectrum, run_fitter, window=window)

File ~/repos/jdaviz/jdaviz/configs/default/plugins/model_fitting/fitting_backend.py:104, in _fit_1D(initial_model, spectrum, run_fitter, window)
    102 if run_fitter:
    103     weights = 'unc' if spectrum.uncertainty else None
--> 104     output_model = fit_lines(spectrum, initial_model, weights=weights, window=window)
    105     output_values = output_model(spectrum.spectral_axis)
    106 else:
    107     # Return without fitting.

File /opt/miniconda3/envs/jdaviz-dev/lib/python3.8/site-packages/specutils/fitting/fitmodels.py:355, in fit_lines(spectrum, model, fitter, exclude_regions, weights, window, get_fit_info, **kwargs)
    348 #
    349 # Check to see if the model has units. If it does not
    350 # have units then we are going to ignore them.
    351 #
    353 ignore_units = getattr(model_guess, model_guess.param_names[0]).unit is None
--> 355 fit_model = _fit_lines(spectrum, model_guess, fitter,
    356                        exclude_regions, weights, model_window,
    357                        ignore_units, get_fit_info, **kwargs)
    358 if model_guess.name is not None:
    359     fit_model.name = model_guess.name

File /opt/miniconda3/envs/jdaviz-dev/lib/python3.8/site-packages/specutils/fitting/fitmodels.py:497, in _fit_lines(spectrum, model, fitter, exclude_regions, weights, window, get_fit_info, ignore_units, **kwargs)
    494     if weights is not None:
    495         weights = weights[nmask]
--> 497 fit_model = fitter(model, dispersion,
    498                    flux, weights=weights, **kwargs)
    500 if hasattr(fitter, 'fit_info') and get_fit_info:
    501     fit_model.meta['fit_info'] = fitter.fit_info

File ~/repos/astropy/astropy/modeling/fitting.py:282, in fitter_unit_support.<locals>.wrapper(self, model, x, y, z, **kwargs)
    280 # We run the fitting
    281 if z is None:
--> 282     model_new = func(self, model, xdata, ydata, **kwargs)
    283 else:
    284     model_new = func(self, model, xdata, ydata, zdata, **kwargs)

File ~/repos/astropy/astropy/modeling/fitting.py:1351, in _NonLinearLSQFitter.__call__(self, model, x, y, z, weights, maxiter, acc, epsilon, estimate_jacobian, filter_non_finite)
   1345     x, y, z = self._filter_non_finite(x, y, z)
   1346 farg = (
   1347     model_copy,
   1348     weights,
   1349 ) + _convert_input(x, y, z)
-> 1351 init_values, fitparams, cov_x = self._run_fitter(
   1352     model_copy, farg, maxiter, acc, epsilon, estimate_jacobian
   1353 )
   1355 self._compute_param_cov(model_copy, y, init_values, cov_x, fitparams, farg)
   1357 model.sync_constraints = True

File ~/repos/astropy/astropy/modeling/fitting.py:1415, in LevMarLSQFitter._run_fitter(self, model, farg, maxiter, acc, epsilon, estimate_jacobian)
   1413     dfunc = self._wrap_deriv
   1414 init_values, _, _ = model_to_fit_params(model)
-> 1415 fitparams, cov_x, dinfo, mess, ierr = optimize.leastsq(
   1416     self.objective_function,
   1417     init_values,
   1418     args=farg,
   1419     Dfun=dfunc,
   1420     col_deriv=model.col_fit_deriv,
   1421     maxfev=maxiter,
   1422     epsfcn=epsilon,
   1423     xtol=acc,
   1424     full_output=True,
   1425 )
   1426 fitter_to_model_params(model, fitparams)
   1427 self.fit_info.update(dinfo)

File /opt/miniconda3/envs/jdaviz-dev/lib/python3.8/site-packages/scipy/optimize/_minpack_py.py:414, in leastsq(func, x0, args, Dfun, full_output, col_deriv, ftol, xtol, gtol, maxfev, epsfcn, factor, diag)
    411 m = shape[0]
    413 if n > m:
--> 414     raise TypeError(f"Improper input: func input vector length N={n} must"
    415                     f" not exceed func output vector length M={m}")
    417 if epsfcn is None:
    418     epsfcn = finfo(dtype).eps

TypeError: Improper input: func input vector length N=2 must not exceed func output vector length M=0

🐱


DISCLAIMER: This issue was autocreated by the Jdaviz Issue Creation Bot on behalf of the reporter. If any information is incorrect, please contact Duy Nguyen

@pllim pllim added bug Something isn't working specviz plugin Label for plugins common to multiple configurations labels Dec 9, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working plugin Label for plugins common to multiple configurations specviz
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants