spacetelescope / jdaviz

JWST astronomical data analysis tools in the Jupyter platform
https://jdaviz.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
142 stars 74 forks source link

model fitting changing dataset with spectral subset requires two fits #1910

Open Jdaviz-Triage-Bot opened 1 year ago

Jdaviz-Triage-Bot commented 1 year ago

Reporter: Kyle Conroy

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(5.2, 5.6))  # overlapping region

mf = specviz.plugins['Model Fitting']
mf.create_model_component('Linear1D')
mf.spectral_subset = 'Subset 1'

mf.dataset = 'left_spectrum'
mf.calculate_fit()

mf.dataset = 'right_spectrum'
mf.calculate_fit()  # succeeds but fit incorrect
image
mf.calculate_fit()  # now a reasonable fit
image

:cat:


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

kecnry commented 1 year ago

Tracked down the root cause: model fitting applies the subset mask from #1834 by using spectral_subset.selected_subset_mask, which in turn relies on app.get_data_from_viewer('spectrum-viewer', subset), which suffers from #1843/#1921 meaning the returned mask does not not necessarily correspond to the selected data set. After calling calculate_fit and adding those results to the viewer, successive calls to retrieve the mask are getting the mask on the new model data entry which is therefore correct.

On top of that, the initializers to estimate model component parameters are not listening to the input subset (have a WIP fix for this). This isn't critical and isn't the root cause of the bug seen here, but will help for faster convergence, etc.