Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ New Features
(``AWAV-GRA``) and vacuum (``WAVE-GRI``) spectral axis types in FITS WCS
export. [#316]

- Added ``specreduce.utils.measure_noise``, a robust estimator of the per-pixel
noise standard deviation of a 1D spectrum or of each row of a 2D spectral
image. It measures the sigma-clipped standard deviation of the second difference
of the flux along the dispersion axis, so it is insensitive to a smooth continuum
or residual background and to emission lines. Non-finite and masked pixels are
ignored. [#321]

API Changes
^^^^^^^^^^^

Expand All @@ -38,6 +45,25 @@ API Changes
on instantiation, and its removal has been rescheduled from v2.0 to v1.11.
Use ``specreduce.wavecal1d.WavelengthCalibration1D`` instead. [#316]

Bug Fixes
^^^^^^^^^

- ``line_matching.find_arc_lines`` now accepts spectra with any of the Astropy
uncertainty types (``StdDevUncertainty``, ``VarianceUncertainty``, or
``InverseVariance``). Non-standard-deviation uncertainties are converted to
``StdDevUncertainty`` on a copy of the spectrum before the line finding, which
previously failed with a unit conversion error for variance-type uncertainties.
[#321]

- ``line_matching.find_arc_lines`` now estimates the noise of a spectrum without
an uncertainty using ``measure_noise`` instead of the square root of the absolute
flux. The old fallback amounted to a fixed detection threshold of
``noise_factor**2`` flux units regardless of the actual noise, which missed
all lines in faint spectra and reported noise spikes as lines in noisy or
background-subtracted ones. Pixels flagged in the spectrum mask are excluded from
the estimate, and a ``ValueError`` is raised if the noise cannot be estimated
(constant spectrum, or no finite unmasked pixels). [#321]

Other changes
^^^^^^^^^^^^^

Expand Down
3 changes: 3 additions & 0 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ API Reference
.. automodapi:: specreduce.core
:no-inheritance-diagram:

.. automodapi:: specreduce.utils
:no-inheritance-diagram:

.. automodapi:: specreduce.utils.synth_data
:no-inheritance-diagram:

Expand Down
36 changes: 33 additions & 3 deletions specreduce/line_matching.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

from specutils import Spectrum

from specreduce.utils.utils import measure_noise

__all__ = ["find_arc_lines", "match_lines_wcs"]


Expand All @@ -29,8 +31,13 @@ def find_arc_lines(

Parameters
----------
spectrum : The extracted arc spectrum to search for lines. It should be background-subtracted
and must have an "uncertainty" attribute.
spectrum
The extracted arc spectrum to search for lines. It should be background-subtracted.
The uncertainty can be any of the Astropy uncertainty types
(`~astropy.nddata.StdDevUncertainty`, `~astropy.nddata.VarianceUncertainty`, or
`~astropy.nddata.InverseVariance`); it is converted to a standard deviation
before the line finding. If the spectrum has no uncertainty, a constant per-pixel
noise is estimated from the unmasked pixels with `~specreduce.utils.measure_noise`.

fwhm
Estimated full-width half-maximum of the lines in pixels.
Expand All @@ -46,6 +53,12 @@ def find_arc_lines(
-------
QTable
A table of detected arc lines and their properties: centroid, fwhm, and amplitude.

Raises
------
ValueError
If the spectrum has no uncertainty and its noise cannot be estimated from the
flux, as for a constant spectrum or one without finite unmasked pixels.
"""
# If fwhm is a float, convert it to a Quantity with the same unit as the spectral axis
# of the input spectrum.
Expand All @@ -55,9 +68,26 @@ def find_arc_lines(
if fwhm.unit != spectrum.spectral_axis.unit:
raise ValueError("fwhm must have the same units as spectrum.spectral_axis.")

# The line finding and fitting are always done using standard deviation uncertainties.
# If the spectrum has no uncertainty, estimate a constant per-pixel noise from the
# scatter in the data itself. If it has a variance or inverse variance uncertainty,
# convert it to a standard deviation. Either way, work on a copy so that the input
# spectrum is left untouched.
if spectrum.uncertainty is None:
flux = spectrum.flux.value
if spectrum.mask is not None:
flux = np.ma.masked_array(flux, mask=spectrum.mask)
noise = measure_noise(flux)
if not (np.isfinite(noise) and noise > 0):
raise ValueError(
"Could not estimate the noise of the spectrum from its flux "
f"(estimate: {noise}). Give the spectrum an uncertainty."
)
spectrum = deepcopy(spectrum)
spectrum.uncertainty = StdDevUncertainty(np.full(spectrum.flux.shape, noise))
elif not isinstance(spectrum.uncertainty, StdDevUncertainty):
spectrum = deepcopy(spectrum)
spectrum.uncertainty = StdDevUncertainty(np.sqrt(np.abs(spectrum.flux.value)))
spectrum.uncertainty = spectrum.uncertainty.represent_as(StdDevUncertainty)

detected_lines = find_lines_threshold(spectrum, noise_factor=noise_factor)
detected_lines = detected_lines[detected_lines["line_type"] == "emission"]
Expand Down
118 changes: 117 additions & 1 deletion specreduce/tests/test_line_matching.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@

from astropy.wcs import WCS
from astropy.modeling import models
from astropy.nddata import StdDevUncertainty
from astropy.nddata import StdDevUncertainty, VarianceUncertainty, InverseVariance
from specutils.fitting import fit_generic_continuum

from specreduce.calibration_data import load_pypeit_calibration_lines
from specutils import Spectrum
from specreduce.extract import BoxcarExtract
from specreduce import line_matching
from specreduce.line_matching import match_lines_wcs, find_arc_lines
from specreduce.tracing import FlatTrace
from specreduce.utils.synth_data import SynthImage
Expand Down Expand Up @@ -100,6 +101,121 @@ def test_find_arc_lines(mk_test_data):
assert len(lines) > 1


@pytest.fixture
def synthetic_arc():
"""
A small synthetic arc spectrum with Gaussian emission lines at known pixel positions
and a constant standard deviation of 3 DN per pixel.
"""
rng = np.random.default_rng(42)
x = np.arange(500.0)
centers = [50.0, 120.0, 210.0, 330.0, 410.0]
flux = np.zeros_like(x)
for c, a in zip(centers, [200.0, 80.0, 500.0, 60.0, 150.0]):
flux += a * np.exp(-0.5 * ((x - c) / 2.1) ** 2)
sigma = 3.0
flux += rng.normal(0.0, sigma, x.size)
return x * u.pix, flux * u.DN, np.full(x.size, sigma), np.array(centers)


@pytest.mark.filterwarnings("ignore:The fit may be unsuccessful")
@pytest.mark.filterwarnings("ignore:Spectrum is not below the threshold")
@pytest.mark.parametrize(
"uncertainty_cls, transform",
[
(StdDevUncertainty, lambda s: s),
(VarianceUncertainty, lambda s: s**2),
(InverseVariance, lambda s: 1.0 / s**2),
],
)
def test_find_arc_lines_uncertainty_types(synthetic_arc, uncertainty_cls, transform):
"""
find_arc_lines must accept any of the three astropy uncertainty types and produce
the same lines as it does for an equivalent StdDevUncertainty.
"""
spectral_axis, flux, sigma, _ = synthetic_arc
reference = Spectrum(
flux=flux, spectral_axis=spectral_axis, uncertainty=StdDevUncertainty(sigma)
)
spectrum = Spectrum(
flux=flux, spectral_axis=spectral_axis, uncertainty=uncertainty_cls(transform(sigma))
)

expected = find_arc_lines(reference, fwhm=5, window=3, noise_factor=5)
lines = find_arc_lines(spectrum, fwhm=5, window=3, noise_factor=5)

assert len(expected) >= 5
assert len(lines) == len(expected)
np.testing.assert_allclose(lines["centroid"].value, expected["centroid"].value)
np.testing.assert_allclose(lines["fwhm"].value, expected["fwhm"].value)
np.testing.assert_allclose(lines["amplitude"].value, expected["amplitude"].value)
# The input spectrum must not be modified in place.
assert isinstance(spectrum.uncertainty, uncertainty_cls)


@pytest.mark.filterwarnings("ignore:The fit may be unsuccessful")
@pytest.mark.filterwarnings("ignore:Spectrum is not below the threshold")
@pytest.mark.parametrize("scale", [1.0 / 30.0, 10.0 / 3.0], ids=["faint", "noisy"])
def test_find_arc_lines_estimates_noise_without_uncertainty(synthetic_arc, scale):
"""
Without an uncertainty, find_arc_lines must estimate the noise from the data so that
the detection threshold follows the actual noise level, independent of the flux scale.
"""
spectral_axis, flux, _, centers = synthetic_arc
spectrum = Spectrum(flux=flux * scale, spectral_axis=spectral_axis)

lines = find_arc_lines(spectrum, fwhm=5, window=3, noise_factor=5)

assert len(lines) == len(centers)
np.testing.assert_allclose(np.sort(lines["centroid"].value), centers, atol=0.5)


@pytest.mark.filterwarnings("ignore:The fit may be unsuccessful")
@pytest.mark.filterwarnings("ignore:Spectrum is not below the threshold")
def test_find_arc_lines_noise_estimate_ignores_masked_pixels(synthetic_arc, mocker):
"""The noise must be estimated from the unmasked pixels of the spectrum only."""
spectral_axis, flux, _, _ = synthetic_arc
mask = np.zeros(flux.size, dtype=bool)
mask[250:300] = True
spy = mocker.spy(line_matching, "measure_noise")

find_arc_lines(Spectrum(flux=flux, spectral_axis=spectral_axis, mask=mask), fwhm=5)

data = spy.call_args.args[0]
assert np.ma.isMaskedArray(data)
np.testing.assert_array_equal(data.mask, mask)


@pytest.mark.filterwarnings("ignore:The fit may be unsuccessful")
@pytest.mark.filterwarnings("ignore:Spectrum is not below the threshold")
@pytest.mark.filterwarnings("ignore:invalid value encountered in divide")
def test_find_arc_lines_low_count_spectrum_without_uncertainty():
"""
Integer data with less than a count per pixel has a zero median absolute deviation;
the noise estimate must not vanish and turn every positive pixel into a line.
"""
# The specutils continuum check divides the zero median by the zero MAD of the flux.
rng = np.random.default_rng(3)
x = np.arange(1000.0)
centers = np.array([150.0, 400.0, 620.0, 850.0])
expected = 0.2 + sum(40.0 * np.exp(-0.5 * ((x - c) / 2.0) ** 2) for c in centers)
spectrum = Spectrum(flux=rng.poisson(expected).astype(float) * u.ct, spectral_axis=x * u.pix)

lines = find_arc_lines(spectrum, fwhm=4.7)

# A noisy peak can be detected twice, so compare the sets of positions.
distances = np.abs(lines["centroid"].value[:, None] - centers)
assert (distances.min(axis=1) < 0.5).all()
assert (distances.min(axis=0) < 0.5).all()


@pytest.mark.parametrize("value", [np.nan, 100.0], ids=["all_nan", "constant"])
def test_find_arc_lines_raises_if_noise_cannot_be_estimated(value):
spectrum = Spectrum(flux=np.full(200, value) * u.ct, spectral_axis=np.arange(200) * u.pix)
with pytest.raises(ValueError, match="Could not estimate the noise"):
find_arc_lines(spectrum, fwhm=5)


@pytest.mark.remote_data
@pytest.mark.filterwarnings("ignore:No observer defined on WCS")
@pytest.mark.filterwarnings("ignore:Model is linear in parameters")
Expand Down
108 changes: 107 additions & 1 deletion specreduce/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from specutils import Spectrum
from specreduce.tracing import FitTrace
from specreduce.utils.utils import measure_cross_dispersion_profile
from specreduce.utils.utils import measure_cross_dispersion_profile, measure_noise


def mk_gaussian_img(nrows=20, ncols=16, mean=10, stddev=4):
Expand Down Expand Up @@ -169,3 +169,109 @@ def test_errors_warnings(self):
'or None to use all '
'cross-dispersion pixels.'):
measure_cross_dispersion_profile(img, width='.')


class TestMeasureNoise:
"""Tests for the robust second-difference noise estimator."""

@staticmethod
def _arc(rng, x, centers, amplitudes, fwhm=4.0):
sigma = fwhm / 2.3548
flux = np.zeros_like(x)
for c, a in zip(centers, amplitudes):
flux += a * np.exp(-0.5 * ((x - c) / sigma) ** 2)
return flux

def test_white_noise(self):
rng = np.random.default_rng(1)
flux = rng.normal(0.0, 3.0, 2000)
assert measure_noise(flux) == pytest.approx(3.0, rel=0.05)

def test_lines_and_residual_background(self):
rng = np.random.default_rng(2)
x = np.arange(2000.0)
flux = self._arc(rng, x, rng.uniform(0, 2000, 40), 10 ** rng.uniform(1, 3.3, 40))
flux += 120.0 * (x / 2000.0 - 0.5) ** 2
flux += rng.normal(0.0, 3.0, x.size)
noise = measure_noise(flux)
assert 0.9 * 3.0 < noise < 1.3 * 3.0

def test_2d_per_row_along_dispersion_axis(self):
rng = np.random.default_rng(3)
sigmas = np.array([1.0, 2.0, 4.0, 8.0])
flux = rng.normal(0.0, sigmas[:, None], (4, 1000))
noise = measure_noise(flux, axis=-1)
assert noise.shape == (4,)
np.testing.assert_allclose(noise, sigmas, rtol=0.1)
noise_t = measure_noise(flux.T, axis=0)
np.testing.assert_allclose(noise_t, noise)

def test_quantity_input_keeps_unit(self):
rng = np.random.default_rng(4)
flux = rng.normal(0.0, 3.0, 2000) * u.DN
noise = measure_noise(flux)
assert isinstance(noise, u.Quantity)
assert noise.unit == u.DN
assert noise.value == pytest.approx(3.0, rel=0.05)

def test_nan_pixels_are_ignored(self):
rng = np.random.default_rng(5)
flux = rng.normal(0.0, 3.0, 2000)
flux[100:110] = np.nan
assert measure_noise(flux) == pytest.approx(3.0, rel=0.05)

@pytest.mark.parametrize("invalid", ["nan", "masked"])
def test_invalid_pixels_do_not_disable_line_clipping(self, invalid):
# A NaN or masked pixel must not switch off the clipping of the strong lines.
rng = np.random.default_rng(6)
x = np.arange(1000.0)
flux = self._arc(rng, x, [150.0, 400.0, 620.0, 850.0], [500.0] * 4)
flux += rng.normal(0.0, 2.0, x.size)
reference = measure_noise(flux)
assert reference == pytest.approx(2.0, rel=0.1)
if invalid == "nan":
flux[300] = np.nan
else:
flux = np.ma.masked_array(flux, mask=np.zeros(x.size, dtype=bool))
flux.mask[300:303] = True
assert measure_noise(flux) == pytest.approx(reference, rel=0.02)

def test_masked_outliers_are_excluded(self):
rng = np.random.default_rng(7)
flux = rng.normal(0.0, 3.0, 2000)
mask = np.zeros(flux.size, dtype=bool)
mask[:1800] = True
flux[mask] = rng.normal(0.0, 300.0, 1800)
assert measure_noise(flux) > 100.0
assert measure_noise(np.ma.masked_array(flux, mask=mask)) == pytest.approx(3.0, rel=0.1)

def test_low_count_integer_data(self):
# More than half of the second differences are zero, so the MAD is zero.
rng = np.random.default_rng(8)
x = np.arange(1000.0)
lines = self._arc(rng, x, [150.0, 400.0, 620.0, 850.0], [40.0] * 4)
flux = rng.poisson(0.2 + lines).astype(float)
noise = measure_noise(flux)
assert np.sqrt(0.2) < noise < 3 * np.sqrt(0.2)

def test_zero_padded_spectrum(self):
rng = np.random.default_rng(9)
flux = rng.normal(0.0, 2.0, 1000)
flux[400:] = 0.0
assert 0.5 * 2.0 < measure_noise(flux) < 2.0 * 2.0

def test_degenerate_rows(self):
rng = np.random.default_rng(10)
flux = np.zeros((3, 100))
flux[0] = np.nan
flux[1] = rng.normal(0.0, 2.0, 100)
flux[2] = 7.0
noise = measure_noise(flux)
assert np.isnan(noise[0])
assert noise[1] == pytest.approx(2.0, rel=0.3)
assert noise[2] == 0.0
assert np.isnan(measure_noise(np.full(100, np.nan)))

def test_too_short_input_raises(self):
with pytest.raises(ValueError, match="at least 5"):
measure_noise(np.zeros(4))
Loading
Loading