From f64890bf3ab8278cc1f1c307d9c3725933df5123 Mon Sep 17 00:00:00 2001
From: "P. L. Lim" <2090236+pllim@users.noreply.github.com>
Date: Tue, 28 Mar 2023 21:30:52 -0400
Subject: [PATCH] Fix unit conversion plugin but still needs unreleased glue
[ci skip] [rtd skip]
---
docs/specviz/plugins.rst | 15 +-
jdaviz/app.py | 2 -
.../default/plugins/line_lists/line_lists.py | 3 +-
.../imviz/plugins/coords_info/coords_info.py | 50 +--
.../tests/test_unit_conversion.py | 324 ++++--------------
.../unit_conversion/unit_conversion.py | 288 +++-------------
.../unit_conversion/unit_conversion.vue | 19 +-
jdaviz/configs/specviz/specviz.yaml | 2 +-
jdaviz/configs/specviz/tests/test_helper.py | 30 +-
.../configs/specviz2d/tests/test_parsers.py | 5 +-
jdaviz/core/tests/test_tools.py | 21 +-
jdaviz/core/validunits.py | 55 +--
jdaviz/tests/test_subsets.py | 31 +-
.../concepts/specviz_unit_conversion.ipynb | 61 ----
14 files changed, 204 insertions(+), 702 deletions(-)
delete mode 100644 notebooks/concepts/specviz_unit_conversion.ipynb
diff --git a/docs/specviz/plugins.rst b/docs/specviz/plugins.rst
index e6ed909749..8979e06ffa 100644
--- a/docs/specviz/plugins.rst
+++ b/docs/specviz/plugins.rst
@@ -118,15 +118,8 @@ To export the table into the notebook via the API, call
Unit Conversion
===============
-.. note::
-
- This plugin is temporarily disabled. Effort to improve it is being
- tracked at https://github.com/spacetelescope/jdaviz/issues/1972 .
-
The spectral flux density and spectral axis units can be converted
-using the Unit Conversion plugin. The Spectrum1D object to be
-converted is the currently selected spectrum in the spectrum viewer :guilabel:`Data`
-icon in the viewer toolbar.
+using the Unit Conversion plugin.
Select the frequency, wavelength, or energy unit in the
:guilabel:`New Spectral Axis Unit` pulldown
@@ -136,10 +129,8 @@ Select the flux density unit in the :guilabel:`New Flux Unit` pulldown
(e.g., Jansky, W/(Hz/m2), ph/(Angstrom cm2 s)).
The :guilabel:`Apply` button will convert the flux density and/or
-spectral axis units and create a new Spectrum1D object that
-is automatically switched to in the spectrum viewer.
-The name of the new Spectrum1D object is "_units_copy_" plus
-the flux and spectral units of the spectrum.
+spectral axis units being displayed in the spectrum viewer, if applicable.
+This does not affect the underlying data.
.. _line-lists:
diff --git a/jdaviz/app.py b/jdaviz/app.py
index 6324393f69..f9e998bdac 100644
--- a/jdaviz/app.py
+++ b/jdaviz/app.py
@@ -81,10 +81,8 @@ def equivalent_units(self, data, cid, units):
'W / (m2 Hz)', 'W / (Hz m2)', # Order is different in astropy v5.3
'eV / (s m2 Hz)', 'eV / (Hz s m2)',
'erg / (s cm2)',
- 'erg / (s cm2 um)', 'erg / (um s cm2)',
'erg / (s cm2 Angstrom)', 'erg / (Angstrom s cm2)',
'erg / (s cm2 Hz)', 'erg / (Hz s cm2)',
- 'ph / (s cm2 um)', 'ph / (um s cm2)',
'ph / (s cm2 Angstrom)', 'ph / (Angstrom s cm2)',
'ph / (s cm2 Hz)', 'ph / (Hz s cm2)'
])
diff --git a/jdaviz/configs/default/plugins/line_lists/line_lists.py b/jdaviz/configs/default/plugins/line_lists/line_lists.py
index bbb260bfbc..1061ff195d 100644
--- a/jdaviz/configs/default/plugins/line_lists/line_lists.py
+++ b/jdaviz/configs/default/plugins/line_lists/line_lists.py
@@ -199,7 +199,8 @@ def _on_viewer_data_changed(self, msg=None):
self._on_spectrum_viewer_limits_changed() # will also trigger _auto_slider_step
# set the choices (and default) for the units for new custom lines
- self.custom_unit_choices = create_spectral_equivalencies_list(viewer_data)
+ self.custom_unit_choices = create_spectral_equivalencies_list(
+ viewer_data.spectral_axis.unit)
self.custom_unit = str(viewer_data.spectral_axis.unit)
def _parse_redshift_msg(self, msg):
diff --git a/jdaviz/configs/imviz/plugins/coords_info/coords_info.py b/jdaviz/configs/imviz/plugins/coords_info/coords_info.py
index 13fe3b3f16..a66b3f1f9b 100644
--- a/jdaviz/configs/imviz/plugins/coords_info/coords_info.py
+++ b/jdaviz/configs/imviz/plugins/coords_info/coords_info.py
@@ -389,13 +389,10 @@ def _image_viewer_update(self, viewer, x, y):
def _spectrum_viewer_update(self, viewer, x, y):
def _cursor_fallback():
- statistic = getattr(viewer.state, 'function', None)
- cache_key = (viewer.state.layers[0].layer.label, statistic)
- sp = self.app._get_object_cache.get(cache_key, viewer.data()[0])
self._dict['axes_x'] = x
- self._dict['axes_x:unit'] = sp.spectral_axis.unit.to_string()
+ self._dict['axes_x:unit'] = viewer.state.x_display_unit
self._dict['axes_y'] = y
- self._dict['axes_y:unit'] = sp.flux.unit.to_string()
+ self._dict['axes_y:unit'] = viewer.state.y_display_unit
self._dict['data_label'] = ''
def _copy_axes_to_spectral():
@@ -418,8 +415,6 @@ def _copy_axes_to_spectral():
self.row3_text = ''
self.icon = 'mdi-cursor-default'
self.marks[viewer._reference_id].visible = False
- # get the units from the first layer
- # TODO: replace with display units once implemented
_cursor_fallback()
_copy_axes_to_spectral()
return
@@ -462,17 +457,22 @@ def _copy_axes_to_spectral():
subset_to_apply=subset_label)
self.app._get_object_cache[cache_key] = sp
+ # Calculations have to happen in the frame of viewer display units.
+ disp_wave = sp.spectral_axis.to_value(viewer.state.x_display_unit, u.spectral())
+ disp_flux = sp.flux.to_value(viewer.state.y_display_unit,
+ u.spectral_density(sp.spectral_axis))
+
# Out of range in spectral axis.
if (self.dataset.selected != lyr.layer.label and
- (x < sp.spectral_axis.value.min() or x > sp.spectral_axis.value.max())):
+ (x < disp_wave.min() or x > disp_wave.max())):
continue
- cur_i = np.argmin(abs(sp.spectral_axis.value - x))
- cur_wave = sp.spectral_axis[cur_i]
- cur_flux = sp.flux[cur_i]
+ cur_i = np.argmin(abs(disp_wave - x))
+ cur_wave = disp_wave[cur_i]
+ cur_flux = disp_flux[cur_i]
- dx = cur_wave.value - x
- dy = cur_flux.value - y
+ dx = cur_wave - x
+ dy = cur_flux - y
cur_distance = math.sqrt(dx * dx + dy * dy)
if (closest_distance is None) or (cur_distance < closest_distance):
closest_distance = cur_distance
@@ -497,30 +497,34 @@ def _copy_axes_to_spectral():
return
self.row2_title = 'Wave'
- self.row2_text = f'{closest_wave.value:10.5e} {closest_wave.unit.to_string()}'
- self._dict['axes_x'] = closest_wave.value
- self._dict['axes_x:unit'] = closest_wave.unit.to_string()
- if closest_wave.unit != u.pix:
+ self.row2_text = f'{closest_wave:10.5e} {viewer.state.x_display_unit}'
+ self._dict['axes_x'] = closest_wave
+ self._dict['axes_x:unit'] = viewer.state.x_display_unit
+ if viewer.state.x_display_unit != u.pix:
self.row2_text += f' ({int(closest_i)} pix)'
if self.app.config == 'cubeviz':
# float to be compatible with nan
self._dict['slice'] = float(closest_i)
- self._dict['spectral_axis'] = closest_wave.value
- self._dict['spectral_axis:unit'] = closest_wave.unit.to_string()
+ self._dict['spectral_axis'] = closest_wave
+ self._dict['spectral_axis:unit'] = viewer.state.x_display_unit
else:
# float to be compatible with nan
self._dict['index'] = float(closest_i)
+ if viewer.state.y_display_unit is None:
+ flux_unit = ""
+ else:
+ flux_unit = viewer.state.y_display_unit
self.row3_title = 'Flux'
- self.row3_text = f'{closest_flux.value:10.5e} {closest_flux.unit.to_string()}'
- self._dict['axes_y'] = closest_flux.value
- self._dict['axes_y:unit'] = closest_flux.unit.to_string()
+ self.row3_text = f'{closest_flux:10.5e} {flux_unit}'
+ self._dict['axes_y'] = closest_flux
+ self._dict['axes_y:unit'] = viewer.state.y_display_unit
if closest_icon is not None:
self.icon = closest_icon
else:
self.icon = ""
- self.marks[viewer._reference_id].update_xy([closest_wave.value], [closest_flux.value]) # noqa
+ self.marks[viewer._reference_id].update_xy([closest_wave], [closest_flux])
self.marks[viewer._reference_id].visible = True
_copy_axes_to_spectral()
diff --git a/jdaviz/configs/specviz/plugins/unit_conversion/tests/test_unit_conversion.py b/jdaviz/configs/specviz/plugins/unit_conversion/tests/test_unit_conversion.py
index cf1af35805..db3a5757f0 100644
--- a/jdaviz/configs/specviz/plugins/unit_conversion/tests/test_unit_conversion.py
+++ b/jdaviz/configs/specviz/plugins/unit_conversion/tests/test_unit_conversion.py
@@ -1,272 +1,84 @@
-import numpy as np
import pytest
-from astropy import units as u
-from astropy.nddata import UnknownUncertainty
-from astropy.tests.helper import assert_quantity_allclose
-from glue.core.roi import XRangeROI
-
-from jdaviz.configs.specviz.plugins.unit_conversion import unit_conversion as uc
-
-RESULT_SPECTRAL_AXIS = [0.6, 0.62222222, 0.64444444, 0.66666667,
- 0.68888889, 0.71111111, 0.73333333,
- 0.75555556, 0.77777778, 0.8] * u.micron
-
-RESULT_FLUX = [1.04067240e-07, 9.52912307e-08, 9.77144651e-08,
- 1.00212528e-07, 8.55573341e-08, 8.29285448e-08,
- 9.05651431e-08, 8.33870526e-08, 7.47628902e-08,
- 7.74896053e-08] * u.Unit("erg / (s cm2 um)")
-
-RESULT_UNCERTAINTY = [3.85914248e-09, 3.60631495e-09, 1.74661581e-09,
- 1.29057072e-08, 1.08965936e-08, 3.33352891e-09,
- 5.64618219e-09, 1.65028707e-09, 4.49994292e-09,
- 6.61559372e-09]
+# On failure, should not crash; essentially a no-op.
@pytest.mark.parametrize(
- ('new_spectral_axis', 'new_flux'),
- [("fail", "erg / (s cm2 um)"),
- ("None", "fail"),
- ("micron", "fail")])
-def test_value_error_exception(specviz_helper, spectrum1d, new_spectral_axis, new_flux):
- label = "Test 1D Spectrum"
- specviz_helper.load_spectrum(spectrum1d, data_label=label)
-
- conv_func = uc.UnitConversion.process_unit_conversion
- converted_spectrum = conv_func(specviz_helper.app, spectrum=spectrum1d,
- new_flux=new_flux,
- new_spectral_axis=new_spectral_axis)
-
- assert converted_spectrum is None
-
-
-def test_no_spec_no_flux_no_uncert(specviz_helper, spectrum1d):
- label = "Test 1D Spectrum"
- specviz_helper.load_spectrum(spectrum1d, data_label=label)
-
- spectrum1d.uncertainty = None
-
- conv_func = uc.UnitConversion.process_unit_conversion
- converted_spectrum = conv_func(specviz_helper.app, spectrum=spectrum1d)
-
- assert converted_spectrum.flux.unit == spectrum1d.flux.unit
- assert converted_spectrum.spectral_axis.unit == spectrum1d.spectral_axis.unit
- assert converted_spectrum.uncertainty is None
-
- # Test that applying and removing Subset disables and enables it, respectively.
- conv_plugin = specviz_helper.app.get_tray_item_from_name('g-unit-conversion')
- specviz_helper.app.get_viewer("spectrum-viewer").apply_roi(XRangeROI(6000, 6500))
- assert conv_plugin.disabled_msg == 'Please create Subsets only after unit conversion'
- specviz_helper.app.data_collection.remove_subset_group(
- specviz_helper.app.data_collection.subset_groups[0])
- assert conv_plugin.disabled_msg == ''
-
-
-def test_spec_no_flux_no_uncert(specviz_helper, spectrum1d):
- label = "Test 1D Spectrum"
- specviz_helper.load_spectrum(spectrum1d, data_label=label)
-
+ ('new_spectral_axis', 'new_flux', 'expected_spectral_axis', 'expected_flux'),
+ [("fail", "erg / (s cm2 um)", "Angstrom", "erg / (s cm2 um)"),
+ ("None", "fail", "Angstrom", "Jy"),
+ ("micron", "fail", "micron", "Jy")])
+def test_value_error_exception(specviz_helper, spectrum1d, new_spectral_axis, new_flux,
+ expected_spectral_axis, expected_flux):
+ specviz_helper.load_spectrum(spectrum1d, data_label="Test 1D Spectrum")
+ viewer = specviz_helper.app.get_viewer("spectrum-viewer")
+ plg = specviz_helper.plugins["Unit Conversion"]._obj
+
+ plg.new_spectral_axis_unit = new_spectral_axis
+ plg.new_flux_unit = new_flux
+ plg.vue_unit_conversion()
+
+ assert len(specviz_helper.app.data_collection) == 1
+ assert viewer.state.x_display_unit == expected_spectral_axis
+ assert viewer.state.y_display_unit == expected_flux
+
+
+@pytest.mark.parametrize('uncert', (False, True))
+def test_conv_wave_only(specviz_helper, spectrum1d, uncert):
+ if uncert is False:
+ spectrum1d.uncertainty = None
+ specviz_helper.load_spectrum(spectrum1d, data_label="Test 1D Spectrum")
+
+ viewer = specviz_helper.app.get_viewer("spectrum-viewer")
+ plg = specviz_helper.plugins["Unit Conversion"]._obj
new_spectral_axis = "micron"
- spectrum1d.uncertainty = None
-
- conv_func = uc.UnitConversion.process_unit_conversion
- converted_spectrum = conv_func(specviz_helper.app, spectrum=spectrum1d,
- new_spectral_axis=new_spectral_axis)
-
- assert_quantity_allclose(converted_spectrum.spectral_axis,
- RESULT_SPECTRAL_AXIS, atol=1e-5*u.um)
- assert converted_spectrum.flux.unit == spectrum1d.flux.unit
- assert converted_spectrum.spectral_axis.unit == new_spectral_axis
- assert converted_spectrum.uncertainty is None
-
-
-def test_no_spec_no_flux_uncert(specviz_helper, spectrum1d):
- label = "Test 1D Spectrum"
- specviz_helper.load_spectrum(spectrum1d, data_label=label)
+ plg.new_spectral_axis_unit = new_spectral_axis
+ plg.vue_unit_conversion()
- conv_func = uc.UnitConversion.process_unit_conversion
- converted_spectrum = conv_func(specviz_helper.app, spectrum=spectrum1d)
+ assert len(specviz_helper.app.data_collection) == 1
+ assert viewer.state.x_display_unit == new_spectral_axis
+ assert viewer.state.y_display_unit == 'Jy'
- assert converted_spectrum.flux.unit == spectrum1d.flux.unit
+@pytest.mark.parametrize('uncert', (False, True))
+def test_conv_flux_only(specviz_helper, spectrum1d, uncert):
+ if uncert is False:
+ spectrum1d.uncertainty = None
+ specviz_helper.load_spectrum(spectrum1d, data_label="Test 1D Spectrum")
-def test_no_spec_no_flux_uncert_unit_exp_none(specviz_helper, spectrum1d):
- np.random.seed(42)
- label = "Test 1D Spectrum"
- specviz_helper.load_spectrum(spectrum1d, data_label=label)
-
- spectrum1d.uncertainty = UnknownUncertainty(np.abs(
- np.random.randn(len(spectrum1d.spectral_axis))))
-
- conv_func = uc.UnitConversion.process_unit_conversion
- converted_spectrum = conv_func(specviz_helper.app, spectrum=spectrum1d)
-
- assert converted_spectrum.flux.unit == spectrum1d.flux.unit
- assert converted_spectrum.spectral_axis.unit == spectrum1d.spectral_axis.unit
- assert converted_spectrum.uncertainty is None
-
-
-def test_no_spec_flux_no_uncert(specviz_helper, spectrum1d):
- label = "Test 1D Spectrum"
- specviz_helper.load_spectrum(spectrum1d, data_label=label)
-
- spectrum1d.uncertainty = None
+ viewer = specviz_helper.app.get_viewer("spectrum-viewer")
+ plg = specviz_helper.plugins["Unit Conversion"]._obj
new_flux = "erg / (s cm2 um)"
+ plg.new_flux_unit = new_flux
+ plg.vue_unit_conversion()
- conv_func = uc.UnitConversion.process_unit_conversion
- converted_spectrum = conv_func(specviz_helper.app, spectrum=spectrum1d,
- new_flux=new_flux)
-
- assert_quantity_allclose(converted_spectrum.flux,
- RESULT_FLUX, atol=1e-5*u.Unit(new_flux))
- assert converted_spectrum.spectral_axis.unit == spectrum1d.spectral_axis.unit
- assert converted_spectrum.uncertainty is None
-
+ assert len(specviz_helper.app.data_collection) == 1
+ assert viewer.state.x_display_unit == 'Angstrom'
+ assert viewer.state.y_display_unit == new_flux
-def test_no_spec_flux_unit_exp_not_none(specviz_helper, spectrum1d):
- label = "Test 1D Spectrum"
- specviz_helper.load_spectrum(spectrum1d, data_label=label)
-
- new_flux = "erg / (s cm2 um)"
- conv_func = uc.UnitConversion.process_unit_conversion
- converted_spectrum = conv_func(specviz_helper.app, spectrum=spectrum1d,
- new_flux=new_flux)
-
- assert_quantity_allclose(converted_spectrum.flux,
- RESULT_FLUX, atol=1e-5*u.Unit(new_flux))
- assert_quantity_allclose(converted_spectrum.uncertainty.quantity.value,
- RESULT_UNCERTAINTY, atol=1e-11)
-
-
-def test_spec_flux_no_uncert(specviz_helper, spectrum1d):
- label = "Test 1D Spectrum"
- specviz_helper.load_spectrum(spectrum1d, data_label=label)
+@pytest.mark.parametrize('uncert', (False, True))
+def test_conv_wave_flux(specviz_helper, spectrum1d, uncert):
+ if uncert is False:
+ spectrum1d.uncertainty = None
+ specviz_helper.load_spectrum(spectrum1d, data_label="Test 1D Spectrum")
+ viewer = specviz_helper.app.get_viewer("spectrum-viewer")
+ plg = specviz_helper.plugins["Unit Conversion"]._obj
new_spectral_axis = "micron"
new_flux = "erg / (s cm2 um)"
-
- spectrum1d.uncertainty = None
-
- conv_func = uc.UnitConversion.process_unit_conversion
- converted_spectrum = conv_func(specviz_helper.app, spectrum=spectrum1d,
- new_flux=new_flux,
- new_spectral_axis=new_spectral_axis)
-
- assert_quantity_allclose(converted_spectrum.flux,
- RESULT_FLUX, atol=1e-5*u.Unit(new_flux))
- assert_quantity_allclose(converted_spectrum.spectral_axis,
- RESULT_SPECTRAL_AXIS, atol=1e-5*u.um)
- assert converted_spectrum.uncertainty is None
-
-
-def test_spec_no_flux_uncert_no_unit_exp(specviz_helper, spectrum1d):
- np.random.seed(42)
- label = "Test 1D Spectrum"
- specviz_helper.load_spectrum(spectrum1d, data_label=label)
-
- new_spectral_axis = "micron"
-
- spectrum1d.uncertainty = UnknownUncertainty(np.abs(
- np.random.randn(len(spectrum1d.spectral_axis))))
-
- conv_func = uc.UnitConversion.process_unit_conversion
- converted_spectrum = conv_func(specviz_helper.app, spectrum=spectrum1d,
- new_spectral_axis=new_spectral_axis)
-
- assert converted_spectrum.flux.unit == spectrum1d.flux.unit
- assert_quantity_allclose(converted_spectrum.spectral_axis,
- RESULT_SPECTRAL_AXIS, atol=1e-5*u.um)
- assert converted_spectrum.uncertainty is None
-
-
-def test_no_spec_flux_uncert_no_unit_exp(specviz_helper, spectrum1d):
- np.random.seed(42)
- label = "Test 1D Spectrum"
- specviz_helper.load_spectrum(spectrum1d, data_label=label)
-
- new_flux = "erg / (s cm2 um)"
-
- spectrum1d.uncertainty = UnknownUncertainty(np.abs(
- np.random.randn(len(spectrum1d.spectral_axis))))
-
- conv_func = uc.UnitConversion.process_unit_conversion
- converted_spectrum = conv_func(specviz_helper.app, spectrum=spectrum1d,
- new_flux=new_flux)
-
- assert converted_spectrum.spectral_axis.unit == spectrum1d.spectral_axis.unit
- assert_quantity_allclose(converted_spectrum.flux,
- RESULT_FLUX, atol=1e-5*u.Unit(new_flux))
- assert converted_spectrum.uncertainty is None
-
-
-def test_spec_no_flux_uncert_unit_exp(specviz_helper, spectrum1d):
- label = "Test 1D Spectrum"
- specviz_helper.load_spectrum(spectrum1d, data_label=label)
-
- new_spectral_axis = "micron"
-
- conv_func = uc.UnitConversion.process_unit_conversion
- converted_spectrum = conv_func(specviz_helper.app, spectrum=spectrum1d,
- new_spectral_axis=new_spectral_axis)
-
- assert_quantity_allclose(converted_spectrum.spectral_axis,
- RESULT_SPECTRAL_AXIS, atol=1e-5*u.um)
-
-
-def test_spec_flux_uncert_no_unit_exp(specviz_helper, spectrum1d):
- np.random.seed(42)
- label = "Test 1D Spectrum"
- specviz_helper.load_spectrum(spectrum1d, data_label=label)
-
- new_spectral_axis = "micron"
- new_flux = "erg / (s cm2 um)"
-
- spectrum1d.uncertainty = UnknownUncertainty(np.abs(
- np.random.randn(len(spectrum1d.spectral_axis))))
-
- conv_func = uc.UnitConversion.process_unit_conversion
- converted_spectrum = conv_func(specviz_helper.app, spectrum=spectrum1d,
- new_flux=new_flux,
- new_spectral_axis=new_spectral_axis)
-
- assert converted_spectrum.uncertainty is None
- assert_quantity_allclose(converted_spectrum.spectral_axis,
- RESULT_SPECTRAL_AXIS, atol=1e-5*u.um)
- assert_quantity_allclose(converted_spectrum.flux,
- RESULT_FLUX, atol=1e-5*u.Unit(new_flux))
-
-
-def test_spec_flux_uncert_unit_exp(specviz_helper, spectrum1d):
- label = "Test 1D Spectrum"
- specviz_helper.load_spectrum(spectrum1d, data_label=label)
-
- new_spectral_axis = "micron"
- new_flux = "erg / (s cm2 um)"
-
- conv_func = uc.UnitConversion.process_unit_conversion
- converted_spectrum = conv_func(specviz_helper.app, spectrum=spectrum1d,
- new_flux=new_flux,
- new_spectral_axis=new_spectral_axis)
-
- assert_quantity_allclose(converted_spectrum.spectral_axis,
- RESULT_SPECTRAL_AXIS, atol=1e-5*u.um)
- assert_quantity_allclose(converted_spectrum.flux,
- RESULT_FLUX, atol=1e-5*u.Unit(new_flux))
- assert_quantity_allclose(converted_spectrum.uncertainty.quantity.value,
- RESULT_UNCERTAINTY, atol=1e-11)
-
-
-def test_converted_spec_is_none(specviz_helper, spectrum1d):
- label = "Test 1D Spectrum"
- specviz_helper.load_spectrum(spectrum1d, data_label=label)
-
- new_spectral_axis = "feet"
-
- unit_conversion = specviz_helper.app.get_tray_item_from_name("g-unit-conversion")
- unit_conversion.new_spectral_axis_unit = new_spectral_axis
- converted_spectrum = unit_conversion.vue_unit_conversion(specviz_helper.app,
- spectrum=spectrum1d,
- new_flux=None,
- new_spectral_axis=new_spectral_axis)
-
- assert converted_spectrum is None
+ plg.new_spectral_axis_unit = new_spectral_axis
+ plg.new_flux_unit = new_flux
+ plg.vue_unit_conversion()
+
+ assert len(specviz_helper.app.data_collection) == 1
+ assert viewer.state.x_display_unit == new_spectral_axis
+ assert viewer.state.y_display_unit == new_flux
+
+
+def test_conv_no_data(specviz_helper):
+ """Should not crash."""
+ plg = specviz_helper.plugins["Unit Conversion"]._obj
+ plg.new_spectral_axis_unit = "micron"
+ plg.new_flux_unit = "erg / (s cm2 um)"
+ plg.vue_unit_conversion()
+ assert len(specviz_helper.app.data_collection) == 0
diff --git a/jdaviz/configs/specviz/plugins/unit_conversion/unit_conversion.py b/jdaviz/configs/specviz/plugins/unit_conversion/unit_conversion.py
index f2bcae1807..15348da23b 100644
--- a/jdaviz/configs/specviz/plugins/unit_conversion/unit_conversion.py
+++ b/jdaviz/configs/specviz/plugins/unit_conversion/unit_conversion.py
@@ -1,279 +1,91 @@
-from packaging.version import Version
-
-import specutils
from astropy import units as u
-from astropy.nddata import VarianceUncertainty, StdDevUncertainty, InverseVariance
-from glue.core.message import SubsetCreateMessage, SubsetDeleteMessage
-from traitlets import List, Unicode, Any, observe
+from traitlets import Any, List, Unicode
-from jdaviz.core.events import SnackbarMessage, RedshiftMessage
+from jdaviz.core.events import SnackbarMessage, AddDataMessage, RemoveDataMessage
from jdaviz.core.registries import tray_registry
-from jdaviz.core.template_mixin import PluginTemplateMixin, DatasetSelectMixin
+from jdaviz.core.template_mixin import PluginTemplateMixin
from jdaviz.core.validunits import (create_spectral_equivalencies_list,
create_flux_equivalencies_list)
-from jdaviz.configs.specviz.helper import _apply_redshift_to_spectra
__all__ = ['UnitConversion']
-unit_exponents = {StdDevUncertainty: 1,
- InverseVariance: -2,
- VarianceUncertainty: 2}
-SPECUTILS_GT_1_7_0 = Version(specutils.__version__) > Version('1.7.0')
-
@tray_registry('g-unit-conversion', label="Unit Conversion",
viewer_requirements='spectrum')
-class UnitConversion(PluginTemplateMixin, DatasetSelectMixin):
+class UnitConversion(PluginTemplateMixin):
template_file = __file__, "unit_conversion.vue"
- current_flux_unit = Unicode().tag(sync=True)
- current_spectral_axis_unit = Unicode().tag(sync=True)
- new_flux_unit = Any().tag(sync=True)
- new_spectral_axis_unit = Any().tag(sync=True)
+ current_flux_unit = Unicode("").tag(sync=True)
+ current_spectral_axis_unit = Unicode("").tag(sync=True)
+ new_flux_unit = Any("").tag(sync=True)
+ new_spectral_axis_unit = Any("").tag(sync=True)
spectral_axis_unit_equivalencies = List([]).tag(sync=True)
flux_unit_equivalencies = List([]).tag(sync=True)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
-
- self.hub.subscribe(self, SubsetCreateMessage, handler=self._on_viewer_subset_changed)
- self.hub.subscribe(self, SubsetDeleteMessage, handler=self._on_viewer_subset_changed)
-
- self._redshift = None
- self.app.hub.subscribe(self, RedshiftMessage, handler=self._redshift_listener)
-
self._default_spectrum_viewer_reference_name = kwargs.get(
"spectrum_viewer_reference_name", "spectrum-viewer"
)
+ self._viewer = self.app.get_viewer(self._default_spectrum_viewer_reference_name)
- # when accessing the selected data, access the spectrum-viewer version
- # TODO: we'll probably want to update unit-conversion to be able to act on cubes directly
- # in the future
- self.dataset._viewers = [self._default_spectrum_viewer_reference_name]
- # require entries to be in spectrum-viewer (not other cubeviz images, etc)
- self.dataset.add_filter('layer_in_spectrum_viewer')
+ self.session.hub.subscribe(self, AddDataMessage, handler=self._on_viewer_data_update)
+ self.session.hub.subscribe(self, RemoveDataMessage, handler=self._on_viewer_data_update)
- def _on_viewer_subset_changed(self, *args):
- if len(self.app.data_collection.subset_groups) == 0:
- self.disabled_msg = ''
+ def _on_viewer_data_update(self, msg):
+ """Set UI label to show current flux and spectral axis units."""
+ if self._viewer.state.y_display_unit:
+ self.current_flux_unit = self._viewer.state.y_display_unit
else:
- self.disabled_msg = 'Please create Subsets only after unit conversion'
-
- def _redshift_listener(self, msg):
- '''Save new redshifts (including from the helper itself)'''
- if msg.param == "redshift":
- self._redshift = msg.value
-
- @observe('dataset_selected')
- def update_ui(self, event=None):
- """
- Set up UI to have all values of currently visible spectra.
- """
- spectrum = self.dataset.selected_obj
- if spectrum is None:
- return
-
- viewer = self.app.get_viewer(self._default_spectrum_viewer_reference_name)
-
- # 1. Set UI label to show current flux and spectral axis units.
- # 2. Populate drop down with all valid options for unit conversion.
+ self.current_flux_unit = ""
- if viewer.state.y_display_unit is not None:
- self.current_flux_unit = viewer.state.y_display_unit
- self.flux_unit_equivalencies = create_flux_equivalencies_list(spectrum)
+ if self._viewer.state.x_display_unit:
+ self.current_spectral_axis_unit = self._viewer.state.x_display_unit
+ else:
+ self.current_spectral_axis_unit = ""
- if viewer.state.x_display_unit is not None:
- self.current_spectral_axis_unit = viewer.state.x_display_unit
- self.spectral_axis_unit_equivalencies = create_spectral_equivalencies_list(spectrum)
+ # Populate drop down with all valid options for unit conversion.
+ x_u = u.Unit(self._viewer.state.x_display_unit)
+ y_u = u.Unit(self._viewer.state.y_display_unit)
+ self.flux_unit_equivalencies = create_flux_equivalencies_list(y_u, x_u)
+ self.spectral_axis_unit_equivalencies = create_spectral_equivalencies_list(x_u)
def vue_unit_conversion(self, *args, **kwargs):
"""
Runs when the ``apply`` button is hit. Tries to change units if ``new`` units are set
and are valid.
"""
- if self._redshift is not None:
- # apply the global redshift to the new spectrum
- spectrum = _apply_redshift_to_spectra(self.dataset.selected_obj, self._redshift)
- else:
- spectrum = self.dataset.selected_obj
-
- converted_spec = self.process_unit_conversion(spectrum,
- self.new_flux_unit,
- self.new_spectral_axis_unit)
- if converted_spec is None:
- return
-
- label = f"_units_copy_Flux:{converted_spec.flux.unit}_" +\
- f"SpectralAxis:{converted_spec.spectral_axis.unit}"
- new_label = ""
-
- # Finds the '_units_copy_' spectrum and does unit conversions in that copy.
- if "_units_copy_" in self.dataset_selected:
-
- selected_data_label = self.dataset_selected
- selected_data_label_split = selected_data_label.split("_units_copy_")
+ viewer = self._viewer
+ update_axes = False
+ error_msgs = []
- new_label = selected_data_label_split[0] + label
-
- original_spectrum = self.data_collection[selected_data_label_split[0]]
- original_flux = original_spectrum.get_object().flux.unit
- original_spectral_axis = original_spectrum.get_object().spectral_axis.unit
-
- if new_label in self.data_collection:
- # Spectrum with these converted units already exists.
- msg = SnackbarMessage(
- "Spectrum with these units already exists, please check the data drop down.",
- color="warning",
- sender=self)
- self.hub.broadcast(msg)
- return
-
- elif converted_spec.flux.unit == original_flux and \
- converted_spec.spectral_axis.unit == original_spectral_axis:
- # Check if converted units already exist in the original spectrum.
- msg = SnackbarMessage(
- "These are the units of the original spectrum, please use "
- "that spectrum instead.",
- color="warning",
- sender=self)
- self.hub.broadcast(msg)
- return
-
- else:
- # Add spectrum with converted units to app.
- self.app.add_data(converted_spec, new_label)
- self.app.add_data_to_viewer(
- self._default_spectrum_viewer_reference_name,
- new_label, clear_other_data=True
- )
+ # TODO: DO we still have to worry about uncertainty and redshift?
- else:
- new_label = self.dataset_selected + label
-
- if new_label in self.data_collection:
- # Spectrum with these converted units already exists.
- msg = SnackbarMessage(
- "Spectrum with these units already exists, please check the data drop down.",
- color="warning",
- sender=self)
- self.hub.broadcast(msg)
-
- return
- else:
-
- # Replace old spectrum with new one with updated units.
- self.app.add_data(converted_spec, new_label)
-
- self.app.add_data_to_viewer(
- self._default_spectrum_viewer_reference_name,
- new_label, clear_other_data=True
- )
- snackbar_message = SnackbarMessage(
- f"Data set '{label}' units converted successfully.",
- color="success",
- sender=self)
- self.hub.broadcast(snackbar_message)
-
- def process_unit_conversion(self, spectrum, new_flux=None, new_spectral_axis=None):
- """
-
- Parameters
- ----------
- spectrum : `specutils.Spectrum1D`
- The spectrum that will have its units converted.
- new_flux
- The flux of spectrum will be converted to these units if they are provided.
- new_spectral_axis
- The spectral_axis of spectrum will be converted to these units if they are provided.
-
- Returns
- -------
- converted_spectrum : `specutils.Spectrum1D`
- A new spectrum with converted units.
- """
- set_spectral_axis_unit = spectrum.spectral_axis
- set_flux_unit = spectrum.flux
-
- current_flux_unit = spectrum.flux.unit.to_string()
- current_spectral_axis_unit = spectrum.spectral_axis.unit.to_string()
-
- # Try to set new units if set and are valid.
- if new_spectral_axis is not None \
- and new_spectral_axis != "" \
- and new_spectral_axis != current_spectral_axis_unit:
+ if self.new_flux_unit and (self.new_flux_unit != self.current_flux_unit):
try:
- set_spectral_axis_unit = spectrum.spectral_axis.to(u.Unit(new_spectral_axis))
- except ValueError as e:
- snackbar_message = SnackbarMessage(
- "Unable to convert spectral axis units for selected data. "
- f"Try different units: {repr(e)}",
- color="error",
- sender=self)
- self.hub.broadcast(snackbar_message)
-
- return
+ viewer.state.y_display_unit = self.new_flux_unit
+ except Exception as e:
+ error_msgs.append(repr(e))
+ else:
+ self.current_flux_unit = viewer.state.y_display_unit
+ update_axes = True
- # Try to set new units if set and are valid.
- if new_flux is not None \
- and new_flux != "" \
- and new_flux != current_flux_unit:
+ if (self.new_spectral_axis_unit and
+ (self.new_spectral_axis_unit != self.current_spectral_axis_unit)):
try:
- equivalencies = u.spectral_density(set_spectral_axis_unit)
- set_flux_unit = spectrum.flux.to(u.Unit(new_flux),
- equivalencies=equivalencies)
- except ValueError as e:
- snackbar_message = SnackbarMessage(
- "Unable to convert flux units for selected data. "
- f"Try different units: {repr(e)}",
- color="error",
- sender=self)
- self.hub.broadcast(snackbar_message)
-
- return
-
- # Uncertainty converted to new flux units
- if spectrum.uncertainty is not None:
- unit_exp = unit_exponents.get(spectrum.uncertainty.__class__)
- # If uncertainty type not in our lookup, drop the uncertainty
- if unit_exp is None:
- msg = SnackbarMessage(
- "Warning: Unrecognized uncertainty type, cannot guarantee "
- "conversion so dropping uncertainty in resulting data",
- color="warning",
- sender=self)
- self.hub.broadcast(msg)
- temp_uncertainty = None
+ viewer.state.x_display_unit = self.new_spectral_axis_unit
+ except Exception as e:
+ error_msgs.append(repr(e))
else:
- try:
- # Catch and handle error trying to convert variance uncertainties
- # between frequency and wavelength space.
- # TODO: simplify this when astropy handles it
- temp_uncertainty = spectrum.uncertainty.quantity**(1/unit_exp)
- temp_uncertainty = temp_uncertainty.to(u.Unit(set_flux_unit.unit),
- equivalencies=u.spectral_density(set_spectral_axis_unit)) # noqa
- temp_uncertainty **= unit_exp
- temp_uncertainty = spectrum.uncertainty.__class__(temp_uncertainty.value)
- except u.UnitConversionError:
- msg = SnackbarMessage(
- "Warning: Could not convert uncertainty, setting to "
- "None in converted data",
- color="warning",
- sender=self)
- self.hub.broadcast(msg)
- temp_uncertainty = None
- else:
- temp_uncertainty = None
+ self.current_spectral_axis_unit = viewer.state.x_display_unit
+ update_axes = True
- # Create new spectrum with new units.
- converted_spectrum = spectrum._copy(flux=set_flux_unit,
- wcs=None,
- spectral_axis=set_spectral_axis_unit,
- unit=set_flux_unit.unit,
- uncertainty=temp_uncertainty)
- if SPECUTILS_GT_1_7_0:
- converted_spectrum.shift_spectrum_to(redshift=spectrum.redshift)
- else:
- converted_spectrum.redshift = spectrum.redshift
- return converted_spectrum
+ if update_axes:
+ viewer.set_plot_axes()
+
+ if error_msgs:
+ self.hub.broadcast(SnackbarMessage(
+ f"Unit conversion failed: {', '.join(error_msgs)}",
+ color="error", sender=self))
diff --git a/jdaviz/configs/specviz/plugins/unit_conversion/unit_conversion.vue b/jdaviz/configs/specviz/plugins/unit_conversion/unit_conversion.vue
index fbf0b9f0a8..3b7394e292 100644
--- a/jdaviz/configs/specviz/plugins/unit_conversion/unit_conversion.vue
+++ b/jdaviz/configs/specviz/plugins/unit_conversion/unit_conversion.vue
@@ -6,16 +6,6 @@
:disabled_msg="disabled_msg"
:popout_button="popout_button">
-
-
-
-
+
-
+
-
+
- Apply
+ Apply
diff --git a/jdaviz/configs/specviz/specviz.yaml b/jdaviz/configs/specviz/specviz.yaml
index 03cfb32f6d..54c4fee7e8 100644
--- a/jdaviz/configs/specviz/specviz.yaml
+++ b/jdaviz/configs/specviz/specviz.yaml
@@ -22,7 +22,7 @@ tray:
- g-markers
- g-gaussian-smooth
- g-model-fitting
- #- g-unit-conversion
+ - g-unit-conversion
- g-line-list
- specviz-line-analysis
- g-export-plot
diff --git a/jdaviz/configs/specviz/tests/test_helper.py b/jdaviz/configs/specviz/tests/test_helper.py
index 82543695ff..f3041ab734 100644
--- a/jdaviz/configs/specviz/tests/test_helper.py
+++ b/jdaviz/configs/specviz/tests/test_helper.py
@@ -10,7 +10,6 @@
from astropy.utils.data import download_file
from jdaviz.app import Application
-from jdaviz.configs.specviz.plugins.unit_conversion import unit_conversion as uc
from jdaviz.core.marks import LineUncertainties
from jdaviz import Specviz
@@ -277,7 +276,7 @@ def test_get_spectral_regions_unit_conversion(specviz_helper, spectrum1d):
# If the reference (visible) data changes via unit conversion,
# check that the region's units convert too
- specviz_helper.load_spectrum(spectrum1d)
+ specviz_helper.load_spectrum(spectrum1d) # Originally Angstrom
# Also check coordinates info panel.
# x=0 -> 6000 A, x=1 -> 6222.222 A
@@ -293,27 +292,18 @@ def test_get_spectral_regions_unit_conversion(specviz_helper, spectrum1d):
assert label_mouseover.as_text() == ('', '', '')
assert label_mouseover.icon == ''
- # Convert the wavelength axis to microns
+ # Convert the wavelength axis to micron
new_spectral_axis = "micron"
- conv_func = uc.UnitConversion.process_unit_conversion
- converted_spectrum = conv_func(specviz_helper.app, spectrum=spectrum1d,
- new_spectral_axis=new_spectral_axis)
-
- # Add this new data and clear the other, making the converted spectrum our reference
- specviz_helper.app.add_data(converted_spectrum, "Converted Spectrum")
- specviz_helper.app.add_data_to_viewer("spectrum-viewer",
- "Converted Spectrum",
- clear_other_data=True)
+ spec_viewer.state.x_display_unit = new_spectral_axis
+ spec_viewer.set_plot_axes()
- specviz_helper.app.get_viewer("spectrum-viewer").apply_roi(XRangeROI(0.6, 0.7))
+ spec_viewer.apply_roi(XRangeROI(0.6, 0.7))
- # TODO: Is this test still relevant with the upcoming glue unit conversion changes?
# Retrieve the Subset
- # subsets = specviz_helper.get_spectral_regions()
- # reg = subsets.get('Subset 1')
- #
- # assert reg.lower.unit == u.Unit(new_spectral_axis)
- # assert reg.upper.unit == u.Unit(new_spectral_axis)
+ subsets = specviz_helper.get_spectral_regions()
+ reg = subsets.get('Subset 1')
+ assert reg.lower.unit == u.micron
+ assert reg.upper.unit == u.micron
# Coordinates info panel should show new unit
label_mouseover._viewer_mouse_event(spec_viewer,
@@ -321,7 +311,7 @@ def test_get_spectral_regions_unit_conversion(specviz_helper, spectrum1d):
label_mouseover.as_text() == ('Cursor 6.10000e-01, 1.25000e+01',
'Wave 6.00000e-01 micron (0 pix)',
'Flux 1.24967e+01 Jy')
- assert label_mouseover.icon == 'b'
+ assert label_mouseover.icon == 'a'
label_mouseover._viewer_mouse_event(spec_viewer, {'event': 'mouseleave'})
assert label_mouseover.as_text() == ('', '', '')
diff --git a/jdaviz/configs/specviz2d/tests/test_parsers.py b/jdaviz/configs/specviz2d/tests/test_parsers.py
index 1e4fea74b8..fd99c06e0c 100644
--- a/jdaviz/configs/specviz2d/tests/test_parsers.py
+++ b/jdaviz/configs/specviz2d/tests/test_parsers.py
@@ -81,9 +81,10 @@ def test_2d_parser_no_unit(specviz2d_helper, mos_spectrum2d):
label_mouseover._viewer_mouse_event(viewer_1d,
{'event': 'mousemove', 'domain': {'x': 6.5, 'y': 3}})
assert label_mouseover.as_text() == ('Cursor 6.50000e+00, 3.00000e+00',
- 'Wave 6.00000e+00 pix',
+ 'Wave 6.00000e+00 pixel',
'Flux -3.59571e+00')
- assert label_mouseover.icon == 'b'
+ # FIXME: as_text() has data but mouseover UI not displaying.
+ assert label_mouseover.icon == ''
def test_1d_parser(specviz2d_helper, spectrum1d):
diff --git a/jdaviz/core/tests/test_tools.py b/jdaviz/core/tests/test_tools.py
index 2785d0bce4..aace5d537c 100644
--- a/jdaviz/core/tests/test_tools.py
+++ b/jdaviz/core/tests/test_tools.py
@@ -1,24 +1,19 @@
-import numpy as np
-from glue.core import Data
+from numpy.testing import assert_allclose
-def test_boxzoom(cubeviz_helper, spectral_cube_wcs):
- data = Data(flux=np.ones((128, 128, 256)), label='Test Flux', coords=spectral_cube_wcs)
- cubeviz_helper.app.data_collection.append(data)
-
- cubeviz_helper.app.add_data_to_viewer('spectrum-viewer', 'Test Flux')
- cubeviz_helper.app.add_data_to_viewer('flux-viewer', 'Test Flux')
+def test_boxzoom(cubeviz_helper, image_cube_hdu_obj_microns):
+ cubeviz_helper.load_data(image_cube_hdu_obj_microns, data_label="Test Flux")
flux_viewer = cubeviz_helper.app.get_viewer('flux-viewer')
assert flux_viewer.state.y_min == -0.5
- assert flux_viewer.state.y_max == 127.5
+ assert flux_viewer.state.y_max == 8.5
assert flux_viewer.state.x_min == -0.5
- assert flux_viewer.state.x_max == 127.5
+ assert flux_viewer.state.x_max == 9.5
t = flux_viewer.toolbar.tools['jdaviz:boxzoom']
t.activate()
- t.interact.selected_x = [10, 20]
- t.interact.selected_y = [20, 60]
+ t.interact.selected_x = [1, 4]
+ t.interact.selected_y = [2, 6]
- assert t.get_x_axis_with_aspect_ratio() == (-5., 35.)
+ assert_allclose(t.get_x_axis_with_aspect_ratio(), [0.277778, 4.722222], rtol=1e-6)
diff --git a/jdaviz/core/validunits.py b/jdaviz/core/validunits.py
index 01a939ead0..d3130c1355 100644
--- a/jdaviz/core/validunits.py
+++ b/jdaviz/core/validunits.py
@@ -1,5 +1,4 @@
-import astropy.units as u
-import numpy as np
+from astropy import units as u
__all__ = ['units_to_strings', 'create_spectral_equivalencies_list',
'create_flux_equivalencies_list']
@@ -19,68 +18,55 @@ def units_to_strings(unit_list):
result : list
A list of the units with their best (i.e., most readable) string version.
"""
- return [u.Unit(unit).name
- if u.Unit(unit) == u.Unit("Angstrom")
- else u.Unit(unit).long_names[0] if (
- hasattr(u.Unit(unit), "long_names") and len(u.Unit(unit).long_names) > 0)
- else u.Unit(unit).to_string()
- for unit in unit_list]
+ return [u.Unit(unit).to_string() for unit in unit_list]
-def create_spectral_equivalencies_list(spectrum,
+def create_spectral_equivalencies_list(spectral_axis_unit,
exclude=[u.jupiterRad, u.earthRad, u.solRad,
u.lyr, u.AU, u.pc]):
- """Get all possible conversions from current spectral_axis_unit.
- """
- if spectrum.spectral_axis.unit == u.pix:
+ """Get all possible conversions from current spectral_axis_unit."""
+ if spectral_axis_unit in (u.pix, u.dimensionless_unscaled):
return []
# Get unit equivalencies.
- curr_spectral_axis_unit_equivalencies = u.Unit(
- spectrum.spectral_axis.unit).find_equivalent_units(
+ curr_spectral_axis_unit_equivalencies = spectral_axis_unit.find_equivalent_units(
equivalencies=u.spectral())
# Get local units.
- locally_defined_spectral_axis_units = ['angstrom', 'nanometer',
- 'micron', 'hertz', 'erg']
+ locally_defined_spectral_axis_units = ['Angstrom', 'nm',
+ 'micron', 'Hz', 'erg']
local_units = [u.Unit(unit) for unit in locally_defined_spectral_axis_units]
# Remove overlap units.
curr_spectral_axis_unit_equivalencies = list(set(curr_spectral_axis_unit_equivalencies)
- - set(local_units+exclude))
+ - set(local_units + exclude))
# Convert equivalencies into readable versions of the units and sorted alphabetically.
spectral_axis_unit_equivalencies_titles = sorted(units_to_strings(
curr_spectral_axis_unit_equivalencies))
# Concatenate both lists with the local units coming first.
- spectral_axis_unit_equivalencies_titles = sorted(units_to_strings(
- local_units)) + spectral_axis_unit_equivalencies_titles
-
- return spectral_axis_unit_equivalencies_titles
+ return sorted(units_to_strings(local_units)) + spectral_axis_unit_equivalencies_titles
-def create_flux_equivalencies_list(spectrum):
- """Get all possible conversions for flux from current flux units.
- """
- if ((spectrum.flux.unit == u.count) or (spectrum.spectral_axis.unit == u.pix)):
+def create_flux_equivalencies_list(flux_unit, spectral_axis_unit):
+ """Get all possible conversions for flux from current flux units."""
+ if ((flux_unit in (u.count, (u.MJy / u.sr), u.dimensionless_unscaled))
+ or (spectral_axis_unit in (u.pix, u.dimensionless_unscaled))):
return []
- # Get unit equivalencies.
- curr_flux_unit_equivalencies = u.Unit(
- spectrum.flux.unit).find_equivalent_units(
- equivalencies=u.spectral_density(np.sum(spectrum.spectral_axis)),
- include_prefix_units=False)
+ # Get unit equivalencies. Value passed into u.spectral_density() is irrelevant.
+ curr_flux_unit_equivalencies = flux_unit.find_equivalent_units(
+ equivalencies=u.spectral_density(1 * spectral_axis_unit),
+ include_prefix_units=False)
# Get local units.
locally_defined_flux_units = ['Jy', 'mJy', 'uJy',
'W / (m2 Hz)',
'eV / (s m2 Hz)',
'erg / (s cm2)',
- 'erg / (s cm2 um)',
'erg / (s cm2 Angstrom)',
'erg / (s cm2 Hz)',
- 'ph / (s cm2 um)',
'ph / (s cm2 Angstrom)',
'ph / (s cm2 Hz)']
local_units = [u.Unit(unit) for unit in locally_defined_flux_units]
@@ -93,7 +79,4 @@ def create_flux_equivalencies_list(spectrum):
flux_unit_equivalencies_titles = sorted(units_to_strings(curr_flux_unit_equivalencies))
# Concatenate both lists with the local units coming first.
- flux_unit_equivalencies_titles = (sorted(units_to_strings(local_units)) +
- flux_unit_equivalencies_titles)
-
- return flux_unit_equivalencies_titles
+ return sorted(units_to_strings(local_units)) + flux_unit_equivalencies_titles
diff --git a/jdaviz/tests/test_subsets.py b/jdaviz/tests/test_subsets.py
index 40cda42b08..782cc4d3cd 100644
--- a/jdaviz/tests/test_subsets.py
+++ b/jdaviz/tests/test_subsets.py
@@ -4,12 +4,10 @@
from astropy.tests.helper import assert_quantity_allclose
from glue.core import Data
from glue.core.roi import CircularROI, EllipticalROI, RectangularROI, XRangeROI
-
from glue.core.edit_subset_mode import AndMode, AndNotMode, OrMode
from regions import PixCoord, CirclePixelRegion, RectanglePixelRegion, EllipsePixelRegion
-
from numpy.testing import assert_allclose
-from specutils import SpectralRegion
+from specutils import SpectralRegion, Spectrum1D
from jdaviz.core.marks import ShadowSpatialSpectral
@@ -135,12 +133,10 @@ def test_region_from_subset_3d(cubeviz_helper):
def test_region_from_subset_profile(cubeviz_helper, spectral_cube_wcs):
- data = Data(flux=np.ones((128, 128, 256)), label='Test 1D Flux', coords=spectral_cube_wcs)
+ data = Spectrum1D(flux=np.ones((128, 128, 256)) * u.nJy, wcs=spectral_cube_wcs)
subset_plugin = cubeviz_helper.app.get_tray_item_from_name('g-subset-plugin')
- cubeviz_helper.app.data_collection.append(data)
-
- cubeviz_helper.app.add_data_to_viewer('spectrum-viewer', 'Test 1D Flux')
+ cubeviz_helper.load_data(data, data_label='Test 1D Flux')
cubeviz_helper.app.get_viewer("spectrum-viewer").apply_roi(XRangeROI(5, 15.5))
@@ -184,11 +180,8 @@ def test_region_from_subset_profile(cubeviz_helper, spectral_cube_wcs):
def test_region_spectral_spatial(cubeviz_helper, spectral_cube_wcs):
- data = Data(flux=np.ones((128, 128, 256)), label='Test Flux', coords=spectral_cube_wcs)
- cubeviz_helper.app.data_collection.append(data)
-
- cubeviz_helper.app.add_data_to_viewer('spectrum-viewer', 'Test Flux')
- cubeviz_helper.app.add_data_to_viewer('flux-viewer', 'Test Flux')
+ data = Spectrum1D(flux=np.ones((128, 128, 256)) * u.nJy, wcs=spectral_cube_wcs)
+ cubeviz_helper.load_data(data, data_label="Test Flux")
# use gaussian smooth plugin as a regression test for
# https://github.com/spacetelescope/jdaviz/issues/1853
@@ -236,11 +229,8 @@ def test_region_spectral_spatial(cubeviz_helper, spectral_cube_wcs):
def test_disjoint_spatial_subset(cubeviz_helper, spectral_cube_wcs):
- data = Data(flux=np.ones((128, 128, 256)), label='Test Flux', coords=spectral_cube_wcs)
- cubeviz_helper.app.data_collection.append(data)
-
- cubeviz_helper.app.add_data_to_viewer('spectrum-viewer', 'Test Flux')
- cubeviz_helper.app.add_data_to_viewer('flux-viewer', 'Test Flux')
+ data = Spectrum1D(flux=np.ones((128, 128, 256)) * u.nJy, wcs=spectral_cube_wcs)
+ cubeviz_helper.load_data(data, data_label="Test Flux")
flux_viewer = cubeviz_helper.app.get_viewer("flux-viewer")
flux_viewer.apply_roi(CircularROI(xc=3, yc=4, radius=1))
@@ -260,11 +250,8 @@ def test_disjoint_spatial_subset(cubeviz_helper, spectral_cube_wcs):
def test_disjoint_spectral_subset(cubeviz_helper, spectral_cube_wcs):
subset_plugin = cubeviz_helper.app.get_tray_item_from_name('g-subset-plugin')
- data = Data(flux=np.ones((128, 128, 256)), label='Test Flux', coords=spectral_cube_wcs)
- cubeviz_helper.app.data_collection.append(data)
-
- cubeviz_helper.app.add_data_to_viewer('spectrum-viewer', 'Test Flux')
- cubeviz_helper.app.add_data_to_viewer('flux-viewer', 'Test Flux')
+ data = Spectrum1D(flux=np.ones((128, 128, 256)) * u.nJy, wcs=spectral_cube_wcs)
+ cubeviz_helper.load_data(data, data_label="Test Flux")
spec_viewer = cubeviz_helper.app.get_viewer("spectrum-viewer")
spec_viewer.apply_roi(XRangeROI(5, 15.5))
diff --git a/notebooks/concepts/specviz_unit_conversion.ipynb b/notebooks/concepts/specviz_unit_conversion.ipynb
deleted file mode 100644
index 1402e6c56c..0000000000
--- a/notebooks/concepts/specviz_unit_conversion.ipynb
+++ /dev/null
@@ -1,61 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from jdaviz.configs.specviz.helper import Specviz\n",
- "import specutils\n",
- "import astropy.units as u\n",
- "import numpy as np"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "spec_url = 'https://dr14.sdss.org/optical/spectrum/view/data/format=fits/spec=lite?plateid=1323&mjd=52797&fiberid=12'\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "scrolled": false
- },
- "outputs": [],
- "source": [
- "specviz = Specviz()\n",
- "spec = specutils.Spectrum1D.read(spec_url)\n",
- "specviz.load_spectrum(spec)\n",
- "\n",
- "specviz.show()"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Python 3",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.8.5"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 4
-}