diff --git a/pyproject.toml b/pyproject.toml index 0783c25..f02e244 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,7 +23,7 @@ dependencies = [ "named-arrays~=2.19", "numba", "scipy", - "fiasco~=0.8.2", + "fiasco~=0.9.0", "sunpy~=8.0", ] dynamic = ["version"] diff --git a/utu/spectrum/__init__.py b/utu/spectrum/__init__.py index e5e9e56..7b0a471 100644 --- a/utu/spectrum/__init__.py +++ b/utu/spectrum/__init__.py @@ -2,6 +2,7 @@ from ._lines import ( contribution_function, + contribution_function_line, ions, lines, ) @@ -11,6 +12,7 @@ __all__ = [ "contribution_function", + "contribution_function_line", "ions", "lines", "spectroscopic", diff --git a/utu/spectrum/_lines.py b/utu/spectrum/_lines.py index 1c2c973..273e84c 100644 --- a/utu/spectrum/_lines.py +++ b/utu/spectrum/_lines.py @@ -10,6 +10,7 @@ __all__ = [ "contribution_function", + "contribution_function_line", "ions", "lines", ] @@ -122,6 +123,11 @@ def _catalog( # the ions of the database they are read from, not of the default one database = kwargs.get("hdf5_dbase_root") + # Only the abundance and the transitions of each ion are read, not its + # ratio of protons to electrons, which an ion built without one computes + # by walking the whole database. So each ion is given one. + kwargs = {"proton_electron_ratio": 1} | kwargs + for name in fiasco.list_ions(hdf5_dbase_root=database): try: ion = fiasco.Ion(name, 1 * u.MK, **kwargs) @@ -192,13 +198,14 @@ def contribution_function( The name to give the axis along the lines of the result. proton_electron_ratio The ratio of protons to electrons at each temperature of ``ion``. - If :obj:`None` (the default), :mod:`fiasco` computes it, which walks - the whole database and takes an order of magnitude longer than the - rest of this function put together. It depends on the temperature - and on nothing else, so a caller with more than one ion should - compute it once with :func:`fiasco.proton_electron_ratio` and pass - it here. Doing so primes the cache of ``ion`` with the value it - would otherwise have computed for itself. + If :obj:`None` (the default), the ratio ``ion`` was built with. + Given here, it replaces that ratio, in ``ion`` and in the ion it + recombines from. :class:`fiasco.Ion` computes the ratio as an ion is + built, unless it is given one, which walks the whole database. The + ratio depends on the temperature and on nothing else, so a caller + with more than one ion should compute it once with + :func:`fiasco.proton_electron_ratio` and pass it to + :class:`fiasco.Ion` as each ion is built. Examples -------- @@ -240,7 +247,7 @@ def contribution_function( ax.set_ylabel(f"$G(T)$ ({result.outputs.unit:latex_inline})") """ if proton_electron_ratio is not None: - ion.__dict__["proton_electron_ratio"] = _quantity(proton_electron_ratio) + ion.proton_electron_ratio = _quantity(proton_electron_ratio) axis_density = tuple(na.shape(density)) @@ -285,6 +292,259 @@ def _not_single_ion(record: logging.LogRecord) -> bool: return "Using single-ion model" not in record.getMessage() +def contribution_function_line( + ion: str | na.AbstractScalar, + wavelength: u.Quantity | na.AbstractScalar, + temperature: na.AbstractScalar, + density: u.Quantity | na.AbstractScalar, + axis_temperature: str = "temperature", + proton_electron_ratio: None | u.Quantity | na.AbstractScalar = None, + tolerance: u.Quantity = 0.01 * u.mAA, + size_chunk: None | int = None, + **kwargs: object, +) -> na.FunctionArray: + r""" + Compute the contribution function of an observed line, named by its ion + and its wavelength. + + An observed line is every transition of its ion at its wavelength, of + which there can be more than one, so the contribution functions of all + the transitions within ``tolerance`` of the wavelength are summed. This + is the difference from :func:`contribution_function`, which returns + every transition of an ion and leaves picking one out to the caller. + + The result is laid out as :func:`contribution_function` lays it out, so + that it can be handed to :func:`synthesize`: the wavelength of each line + as the inputs, and its contribution function along ``axis_temperature`` + and the axes of the lines as the outputs. A density along an axis of its + own keeps the name of that axis, which :func:`contribution_function` + calls ``_density``. Its units are those of :mod:`fiasco`, which leaves + the ratio of the density of hydrogen to that of electrons out, so the + emission measure it goes with is :math:`\int n_e n_H \, dh`. + + Parameters + ---------- + ion + The ion which emits each line, named as :mod:`fiasco` names it, + ``"O 5"`` for instance. It broadcasts against ``wavelength``, so + several lines are an ion and a wavelength for each along the same + axis, or one ion and several wavelengths. An ion with more than one + of the lines is built once and solved once at each temperature, even + if it is named two ways, ``"O 5"`` and ``"O V"`` for instance. + wavelength + The wavelength of each line, as CHIANTI lists it. + temperature + The temperatures of the plasma, along ``axis_temperature`` and no + other axis. + density + The number density of electrons. A scalar is the same density at + every temperature. A density along ``axis_temperature`` is one + density per temperature, an isobaric atmosphere for instance. A + density along one axis of its own is every density at every + temperature, and costs as many times more. It may not share an axis + with the lines. + axis_temperature + The name of the axis of ``temperature``. + proton_electron_ratio + The ratio of protons to electrons at each temperature. + If :obj:`None` (the default), it is computed here, once, which walks + the whole database. It is given to each ion as the ion is built, + and passed on by the ion to the ion it recombines from. Pass it to + compute lines over one grid of temperatures more than once without + paying for it again. + tolerance + How close to ``wavelength`` a transition must be to belong to the + line. Two transitions of an ion which CHIANTI lists at different + wavelengths are at least a tenth of a milliangstrom apart, and many + are only half a milliangstrom apart, so the default is a tenth of + that least spacing. It gathers + every transition listed at the wavelength and none beside it, as + long as the wavelength is given as CHIANTI lists it. + size_chunk + How many temperatures to solve at once. + If :obj:`None` (the default), all of them. The level populations of + an ion are solved at every temperature at once, in a matrix as wide + as the ion and the ion it recombines from have levels, which for an + ion with hundreds of levels on a fine grid of temperatures is tens + of gigabytes. Each temperature is solved on its own, so solving a + few at a time changes nothing in the result. + kwargs + Additional arguments passed to :class:`fiasco.Ion` for every ion, + and to :func:`fiasco.proton_electron_ratio`. They are passed + unchanged to every chunk of ``size_chunk`` temperatures, so none of + them may vary with the temperature, as an ``ionization_fraction`` + given as an array would. + + Examples + -------- + The contribution functions of the line ESIS was built to observe and of + the line of :math:`\mathrm{Mg\,X}` nearest it. + + .. jupyter-execute:: + + import astropy.units as u + import matplotlib.pyplot as plt + import named_arrays as na + import numpy as np + import utu + + axis = "temperature" + temperature = na.geomspace(1e4, 1e7, axis=axis, num=61) * u.K + + ion = na.ScalarArray(np.array(["O 5", "Mg 10"]), axes="line") + wavelength = na.ScalarArray([629.732, 624.941] * u.AA, axes="line") + + result = utu.spectrum.contribution_function_line( + ion=ion, + wavelength=wavelength, + temperature=temperature, + density=1e15 * u.K / u.cm ** 3 / temperature, + axis_temperature=axis, + ) + + fig, ax = plt.subplots(constrained_layout=True) + na.plt.plot( + temperature, + result.outputs, + ax=ax, + axis=axis, + label=utu.spectrum.spectroscopic(ion), + ) + ax.set_xscale("log") + ax.set_yscale("log") + ax.set_ylim(1e-26, 1e-21) + ax.set_xlabel(f"temperature ({temperature.unit:latex_inline})") + ax.set_ylabel(f"$G(T)$ ({result.outputs.unit:latex_inline})") + ax.legend() + """ + temperature = na.as_named_array(temperature) + if tuple(temperature.shape) != (axis_temperature,): + raise ValueError( + f"The temperature must be along {axis_temperature!r} and no other " + f"axis, got {temperature.shape}." + ) + num_temperature = temperature.shape[axis_temperature] + if num_temperature == 0: + raise ValueError("The temperature is empty.") + + if size_chunk is None: + size_chunk = num_temperature + if size_chunk < 1: + raise ValueError(f"size_chunk must be at least 1, got {size_chunk}.") + + ion = na.as_named_array(ion) + wavelength = na.as_named_array(wavelength) + shape = na.shape_broadcasted(ion, wavelength) + if axis_temperature in shape: + raise ValueError( + f"The lines must not be along the axis of the temperature, " + f"{axis_temperature!r}." + ) + ion = ion.broadcast_to(shape) + + # a copy, so that the inputs of the result are its own and can be written + wavelength = wavelength.broadcast_to(shape).copy() + + # A scalar density is the same density at every temperature, and is + # computed as such, so that it adds no axis to the result. + density = na.as_named_array(density) + axes_density = tuple(density.shape) + if not axes_density: + density = density.broadcast_to(temperature.shape) + axes_density = (axis_temperature,) + if len(axes_density) > 1 or set(axes_density) & set(shape): + raise ValueError( + f"The density must be a scalar, along {axis_temperature!r}, or " + f"along one axis of its own which the lines are not along, got " + f"{density.shape}." + ) + coupled = axes_density == (axis_temperature,) + + shape_result = {axis_temperature: num_temperature} + if not coupled: + shape_result |= density.shape + shape_result |= shape + + result = na.ScalarArray.zeros(shape_result) << (u.erg * u.cm**3 / u.s) + + # Every line is matched to its transitions before any ion is solved, so + # that a wavelength with no transition fails at once rather than after + # the ions before it. The lines are grouped by the ion rather than by its + # name, so that an ion named two ways is still solved once. The + # wavelengths do not depend on the ratio of protons to electrons, which + # is given only so that fiasco does not compute it. + axis_transition = "_transition" + wavelength_ion: dict[tuple[int, int], u.Quantity] = {} + selections: dict[tuple[int, int], list[tuple[dict, na.ScalarArray]]] = {} + for index in na.ndindex(shape): + name = str(ion[index].ndarray) + key = fiasco.util.parse_ion_name(name) + + if key not in selections: + transitions = fiasco.Ion( + key, + temperature.ndarray, + proton_electron_ratio=1, + **kwargs, + ).transitions + wavelength_ion[key] = transitions.wavelength[transitions.is_bound_bound] + selections[key] = [] + + w = wavelength[index].ndarray + near = np.abs(wavelength_ion[key] - w) < tolerance + if not np.any(near): + raise ValueError( + f"CHIANTI lists no transition of {name} within {tolerance} of {w}." + ) + transition = na.ScalarArray(np.flatnonzero(near), axes=axis_transition) + selections[key].append((index, transition)) + + # The ratio of protons to electrons depends on the temperature and on + # nothing else, and computing it walks the entire database, so it is + # computed once and sliced along with the temperature. + if proton_electron_ratio is None: + proton_electron_ratio = fiasco.proton_electron_ratio( + temperature.ndarray, + **kwargs, + ) + if not isinstance(proton_electron_ratio, na.AbstractArray): + proton_electron_ratio = na.ScalarArray( + ndarray=proton_electron_ratio, + axes=(axis_temperature,), + ) + + for key, selection in selections.items(): + for start in range(0, num_temperature, size_chunk): + chunk = {axis_temperature: slice(start, start + size_chunk)} + + g = contribution_function( + ion=fiasco.Ion( + key, + temperature[chunk].ndarray, + proton_electron_ratio=proton_electron_ratio[chunk].ndarray, + **kwargs, + ), + density=density[chunk], + axis_temperature=axis_temperature, + axis=axis_transition, + ) + + # the axis of a density of its own, by the name it was given + outputs = g.outputs + if not coupled: + axes = [axes_density[0] if a == "_density" else a for a in outputs.axes] + outputs = outputs.replace(axes=tuple(axes)) + + for index, transition in selection: + line = outputs[{axis_transition: transition}] + result[index | chunk] = line.sum(axis_transition) + + return na.FunctionArray( + inputs=wavelength, + outputs=result, + ) + + def lines( temperature: na.AbstractScalar, density: u.Quantity | na.AbstractScalar, @@ -344,8 +604,8 @@ def lines( proton_electron_ratio The ratio of protons to electrons at each temperature. If :obj:`None` (the default), it is computed here, once, and given - to every ion. Pass it to compute more than one spectrum over one - grid of temperatures without paying for it again. + to every ion as the ion is built. Pass it to compute more than one + spectrum over one grid of temperatures without paying for it again. axis_temperature The name of the axis of ``temperature``. axis @@ -381,11 +641,16 @@ def lines( # The ratio of protons to electrons depends on the temperature and on # nothing else, and computing it walks the entire database. Computed - # once here and handed to every ion, which is most of what makes this - # bearable. + # once here and given to every ion as it is built, which passes it on to + # the ion it recombines from. if proton_electron_ratio is None: proton_electron_ratio = fiasco.proton_electron_ratio(t, **kwargs) + # Broadcast here, so that a ratio which does not fit the temperature + # fails here, rather than as each ion is built below, where a failure is + # taken to mean that the ion cannot be computed and the ion is skipped. + proton_electron_ratio = _quantity(proton_electron_ratio) * np.ones(t.shape) + wavelength_all = [] intensity_all = [] ion_all = [] @@ -400,11 +665,15 @@ def lines( for name in ions: try: g = contribution_function( - ion=fiasco.Ion(name, t, **kwargs), + ion=fiasco.Ion( + name, + t, + proton_electron_ratio=proton_electron_ratio, + **kwargs, + ), density=density, axis_temperature=axis_temperature, axis=axis, - proton_electron_ratio=proton_electron_ratio, ) except Exception: # pragma: nocover # an ion whose atomic model the database cannot complete diff --git a/utu/spectrum/_tests/test_lines.py b/utu/spectrum/_tests/test_lines.py index a902a74..74974a4 100644 --- a/utu/spectrum/_tests/test_lines.py +++ b/utu/spectrum/_tests/test_lines.py @@ -103,13 +103,16 @@ def list_ions(hdf5_dbase_root: object = None, sort: bool = True) -> list[str]: @needs_database def test_contribution_function(proton_electron_ratio: u.Quantity): - ion = fiasco.Ion("O 5", temperature.ndarray) + ion = fiasco.Ion( + "O 5", + temperature.ndarray, + proton_electron_ratio=proton_electron_ratio, + ) result = utu.spectrum.contribution_function( ion=ion, density=density, axis_temperature="temperature", - proton_electron_ratio=proton_electron_ratio, ) assert isinstance(result, na.FunctionArray) @@ -122,10 +125,33 @@ def test_contribution_function(proton_electron_ratio: u.Quantity): assert "_density" not in na.shape(result.outputs) +@needs_database +def test_contribution_function_ratio(proton_electron_ratio: u.Quantity) -> None: + """ + A ratio of protons to electrons given here replaces the one the ion was + built with, in the ion and in the ion it recombines from. + """ + ion = fiasco.Ion("Mg 10", temperature.ndarray, proton_electron_ratio=1) + + utu.spectrum.contribution_function( + ion=ion, + density=density, + axis_temperature="temperature", + proton_electron_ratio=proton_electron_ratio, + ) + + assert np.all(ion.proton_electron_ratio == proton_electron_ratio) + assert np.all(ion.next_ion().proton_electron_ratio == proton_electron_ratio) + + @needs_database def test_contribution_function_grid(proton_electron_ratio: u.Quantity): """A density on its own axis is every density at every temperature.""" - ion = fiasco.Ion("O 5", temperature.ndarray) + ion = fiasco.Ion( + "O 5", + temperature.ndarray, + proton_electron_ratio=proton_electron_ratio, + ) density_grid = na.ScalarArray( ndarray=np.array([1e9, 1e10]) / u.cm**3, @@ -136,7 +162,6 @@ def test_contribution_function_grid(proton_electron_ratio: u.Quantity): ion=ion, density=density_grid, axis_temperature="temperature", - proton_electron_ratio=proton_electron_ratio, ) shape = na.shape(result.outputs) @@ -154,7 +179,11 @@ def test_contribution_function_single_ion( the single-ion model and warns about, is solved the same way without the warning. """ - ion = fiasco.Ion("O 5", temperature.ndarray) + ion = fiasco.Ion( + "O 5", + temperature.ndarray, + proton_electron_ratio=proton_electron_ratio, + ) fiasco.log.addHandler(caplog.handler) try: @@ -162,7 +191,6 @@ def test_contribution_function_single_ion( ion=ion, density=density, axis_temperature="temperature", - proton_electron_ratio=proton_electron_ratio, ) assert not any("single-ion" in r.getMessage() for r in caplog.records) @@ -287,3 +315,318 @@ def test_lines_ions( # and there were other ions to be had in this window assert len(ions_window) > 1 + + +# Two lines of one ion and one of another. CHIANTI lists two transitions of +# O V at 122.133 angstroms, so the second line is a blend of them. +ion_line = na.ScalarArray(np.array(["O 5", "O 5", "Mg 10"]), axes="line") +wavelength_line = na.ScalarArray([629.732, 122.133, 624.941] * u.AA, axes="line") + + +@needs_database +def test_contribution_function_line(proton_electron_ratio: u.Quantity) -> None: + """ + Each line is the sum of the transitions CHIANTI lists for its ion at its + wavelength. + """ + result = utu.spectrum.contribution_function_line( + ion=ion_line, + wavelength=wavelength_line, + temperature=temperature, + density=density, + proton_electron_ratio=proton_electron_ratio, + ) + + assert isinstance(result, na.FunctionArray) + assert np.all(result.inputs == wavelength_line) + + expected = [] + num_transition = [] + for i in range(ion_line.shape["line"]): + index = {"line": i} + g = utu.spectrum.contribution_function( + ion=fiasco.Ion( + ion_line[index].ndarray.item(), + temperature.ndarray, + proton_electron_ratio=proton_electron_ratio, + ), + density=density, + axis_temperature="temperature", + axis="transition", + ) + w = wavelength_line[index].ndarray + near = g.inputs.ndarray == w + outputs = g.outputs.ndarray_aligned(("temperature", "transition")) + expected.append(outputs[:, near].sum(axis=~0)) + num_transition.append(np.count_nonzero(near)) + + # which makes the second line a test of the sum + assert num_transition == [1, 2, 1] + + expected = na.ScalarArray( + ndarray=np.stack(expected, axis=~0), + axes=("temperature", "line"), + ) + assert np.all(result.outputs == expected) + + +@needs_database +@pytest.mark.parametrize("size_chunk", [1, 4]) +def test_contribution_function_line_chunk( + proton_electron_ratio: u.Quantity, + size_chunk: int, +) -> None: + """ + Solving the temperatures a few at a time changes nothing but the memory, + including in a last chunk smaller than the others. + """ + kwargs = dict( + ion=ion_line, + wavelength=wavelength_line, + temperature=temperature, + density=density, + ) + + expected = utu.spectrum.contribution_function_line( + proton_electron_ratio=proton_electron_ratio, + **kwargs, + ) + + # the ratio may be given with its axis as well as without + result = utu.spectrum.contribution_function_line( + proton_electron_ratio=na.ScalarArray( + ndarray=proton_electron_ratio, + axes=("temperature",), + ), + size_chunk=size_chunk, + **kwargs, + ) + + assert np.all(result.inputs == expected.inputs) + assert np.all(result.outputs == expected.outputs) + + +@needs_database +def test_contribution_function_line_scalar(proton_electron_ratio: u.Quantity) -> None: + """ + A single line, named by a plain string and a plain quantity, without + the ratio of protons to electrons, which is then computed the way the + fixture computes it. + """ + result = utu.spectrum.contribution_function_line( + ion="O 5", + wavelength=629.732 * u.AA, + temperature=temperature, + density=density, + ) + + expected = utu.spectrum.contribution_function_line( + ion=ion_line, + wavelength=wavelength_line, + temperature=temperature, + density=density, + proton_electron_ratio=proton_electron_ratio, + ) + + assert result.outputs.shape == temperature.shape + assert np.all(result.outputs == expected.outputs[{"line": 0}]) + + +@needs_database +def test_contribution_function_line_ions(proton_electron_ratio: u.Quantity) -> None: + """ + The lines of one ion need not be next to each other, nor be named the + same way, and one ion may be given for several wavelengths. Whichever + way, each ion is solved once. + """ + kwargs = dict( + temperature=temperature, + density=density, + proton_electron_ratio=proton_electron_ratio, + ) + + expected = utu.spectrum.contribution_function_line( + ion=ion_line, + wavelength=wavelength_line, + **kwargs, + ) + + # the lines of O V on either side of the line of Mg X, one by another name + order = na.ScalarArray(np.array([0, 2, 1]), axes="line") + + solved = [] + contribution_function = utu.spectrum._lines.contribution_function + + def counting(ion: fiasco.Ion, **kw: object) -> na.FunctionArray: + """Record the ion solved, then solve it.""" + solved.append(ion.ion_name) + return contribution_function(ion=ion, **kw) + + with pytest.MonkeyPatch.context() as monkeypatch: + monkeypatch.setattr(utu.spectrum._lines, "contribution_function", counting) + + result = utu.spectrum.contribution_function_line( + ion=na.ScalarArray(np.array(["O 5", "Mg 10", "O V"]), axes="line"), + wavelength=wavelength_line[{"line": order}], + **kwargs, + ) + assert sorted(solved) == ["Mg 10", "O 5"] + + # one ion, given once for both of its lines + solved.clear() + result_one = utu.spectrum.contribution_function_line( + ion="O 5", + wavelength=wavelength_line[{"line": slice(2)}], + **kwargs, + ) + assert solved == ["O 5"] + + assert np.all(result.inputs == expected.inputs[{"line": order}]) + assert np.all(result.outputs == expected.outputs[{"line": order}]) + + assert np.all(result_one.inputs == expected.inputs[{"line": slice(2)}]) + assert np.all(result_one.outputs == expected.outputs[{"line": slice(2)}]) + + # the inputs are a copy of their own, which can be written + assert result_one.inputs.ndarray.flags.writeable + + +@needs_database +def test_contribution_function_line_density_scalar( + proton_electron_ratio: u.Quantity, +) -> None: + """ + A scalar density is the same density at every temperature, and adds no + axis to the result. + """ + kwargs = dict( + ion=ion_line, + wavelength=wavelength_line, + temperature=temperature, + proton_electron_ratio=proton_electron_ratio, + ) + + density_scalar = 1e10 / u.cm**3 + + result = utu.spectrum.contribution_function_line( + density=density_scalar, + **kwargs, + ) + + expected = utu.spectrum.contribution_function_line( + density=density_scalar * na.ScalarArray.ones(temperature.shape), + **kwargs, + ) + + assert result.outputs.shape == expected.outputs.shape + assert np.all(result.outputs == expected.outputs) + + +def test_contribution_function_line_empty() -> None: + """No lines at all is an empty result, and needs no database.""" + num_temperature = temperature.shape["temperature"] + + result = utu.spectrum.contribution_function_line( + ion=na.ScalarArray(np.array([], dtype=str), axes="line"), + wavelength=na.ScalarArray([] * u.AA, axes="line"), + temperature=temperature, + density=density, + proton_electron_ratio=np.ones(num_temperature), + ) + + assert result.outputs.shape == dict(temperature=num_temperature, line=0) + assert result.outputs.unit.is_equivalent(u.erg * u.cm**3 / u.s) + + +@needs_database +def test_contribution_function_line_grid(proton_electron_ratio: u.Quantity) -> None: + """ + A density on its own axis is every density at every temperature, and + keeps the name of its axis. + """ + density_grid = na.ScalarArray( + ndarray=np.array([1e9, 1e10]) / u.cm**3, + axes=("density",), + ) + + result = utu.spectrum.contribution_function_line( + ion=ion_line, + wavelength=wavelength_line, + temperature=temperature, + density=density_grid, + proton_electron_ratio=proton_electron_ratio, + size_chunk=4, + ) + + expected = utu.spectrum.contribution_function( + ion=fiasco.Ion( + "O 5", + temperature.ndarray, + proton_electron_ratio=proton_electron_ratio, + ), + density=density_grid, + axis_temperature="temperature", + axis="transition", + ) + near = expected.inputs == wavelength_line[{"line": 0}] + index = {"transition": int(np.flatnonzero(near.ndarray).item())} + expected = expected.outputs[index] + + num_temperature = temperature.shape["temperature"] + assert result.outputs.shape == dict(temperature=num_temperature, density=2, line=3) + + axes = ("temperature", "density") + assert np.all( + result.outputs[{"line": 0}].ndarray_aligned(axes) + == expected.ndarray_aligned(("temperature", "_density")) + ) + + +@needs_database +def test_contribution_function_line_missing( + proton_electron_ratio: u.Quantity, +) -> None: + """A wavelength at which the ion has no transition is an error.""" + with pytest.raises(ValueError, match="no transition of O 5"): + utu.spectrum.contribution_function_line( + ion="O 5", + wavelength=630 * u.AA, + temperature=temperature, + density=density, + proton_electron_ratio=proton_electron_ratio, + ) + + +@pytest.mark.parametrize( + argnames="kwargs, match", + argvalues=[ + ( + dict(temperature=temperature * na.ScalarArray(np.ones(2), axes="x")), + "no other axis", + ), + (dict(temperature=temperature[{"temperature": slice(0)}]), "is empty"), + (dict(size_chunk=0), "at least 1"), + ( + dict(wavelength=wavelength_line * (temperature / temperature)), + "axis of the temperature", + ), + ( + dict(density=na.ScalarArray(np.ones(3) / u.cm**3, axes="line")), + "the lines are not along", + ), + ( + dict(density=density * na.ScalarArray(np.ones(2), axes="x")), + "the lines are not along", + ), + ], +) +def test_contribution_function_line_invalid(kwargs: dict, match: str) -> None: + """Arguments which cannot describe lines are refused before any is solved.""" + arguments = dict( + ion=ion_line, + wavelength=wavelength_line, + temperature=temperature, + density=density, + ) + with pytest.raises(ValueError, match=match): + utu.spectrum.contribution_function_line(**(arguments | kwargs))