From 7edcd6cb2374550bb2dc8192576aa41cdfc5d323 Mon Sep 17 00:00:00 2001 From: Roy Smart Date: Thu, 12 Nov 2026 22:24:29 -0700 Subject: [PATCH 1/2] Add `utu.spectrum.contribution_function_line()`, the contribution function of an observed line `contribution_function()` returns every transition of an ion and leaves picking one out to the caller. The new function takes the lines by their ion and wavelength, along axes of their own, and sums the contribution functions of every transition of the ion within a tolerance of each wavelength, half a milliangstrom by default, so that a blend is counted whole. A wavelength with no transition there is an error. The result is laid out as `contribution_function()` lays it out, the wavelengths as the inputs and the contribution functions along the temperature and the lines as the outputs, so that it can be handed to `synthesize()`. An ion with more than one of the lines is built once. The ratio of protons to electrons is computed once if it is not given, and `size_chunk` solves the temperatures a few at a time to bound the memory of an ion with hundreds of levels, which changes nothing in the result. The tests check each line against the sum of the transitions picked out of `contribution_function()` by hand, exactly, including a blend of two transitions of O V at 122.133 angstroms, and that chunks, a density on its own axis, a single line given as plain values, and the ratio given with or without its axis all agree. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BYjDL98znSud1yFh9chnkP --- utu/spectrum/__init__.py | 2 + utu/spectrum/_lines.py | 207 ++++++++++++++++++++++++++++++ utu/spectrum/_tests/test_lines.py | 185 ++++++++++++++++++++++++++ 3 files changed, 394 insertions(+) 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..a6e69c1 100644 --- a/utu/spectrum/_lines.py +++ b/utu/spectrum/_lines.py @@ -10,6 +10,7 @@ __all__ = [ "contribution_function", + "contribution_function_line", "ions", "lines", ] @@ -285,6 +286,212 @@ 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.5 * 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. 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. Give it, and ``wavelength``, along axes of + their own to compute several lines at once. An ion with more than + one of the lines is built once, and solved once at each temperature. + 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, which may share the axis of the + temperature or have one of its own, as in + :func:`contribution_function`. + 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. 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. CHIANTI lists its wavelengths to the milliangstrom, so the + default is half of one. + 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. It does cost time: + :mod:`fiasco` builds the ion it recombines from anew for every chunk, + and that ion computes its own ratio of protons to electrons, which + walks the whole database again. + kwargs + Additional arguments passed to :class:`fiasco.Ion` and to + :func:`fiasco.proton_electron_ratio`. + + Examples + -------- + The contribution functions of the line ESIS was built to observe and of + the brighter of the two lines of :math:`\mathrm{Mg\,X}` beside 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 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) + wavelength = wavelength.broadcast_to(shape) + + density = na.as_named_array(density) + + # 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,), + ) + + axis_transition = "_transition" + result = None + + for name in np.unique(ion.ndarray): + # The lines of this ion, and the transitions which make up each of + # them. The transitions are found in the first chunk and kept, since + # their wavelengths do not depend on the temperature. + indices = [i for i in na.ndindex(shape) if ion[i].ndarray == name] + transitions = None + + for start in range(0, num_temperature, size_chunk): + chunk = {axis_temperature: slice(start, start + size_chunk)} + t = temperature[chunk] + + g = contribution_function( + ion=fiasco.Ion(str(name), t.ndarray, **kwargs), + density=density[chunk], + axis_temperature=axis_temperature, + axis=axis_transition, + proton_electron_ratio=proton_electron_ratio[chunk], + ) + + if transitions is None: + transitions = [] + for index in indices: + w = wavelength[index].ndarray + near = np.abs(g.inputs.ndarray - w) < tolerance + if not np.any(near): + raise ValueError( + f"CHIANTI lists no transition of {name} within " + f"{tolerance} of {w}." + ) + transitions.append( + na.ScalarArray(np.flatnonzero(near), axes=axis_transition) + ) + + if result is None: + shape_result = { + a: n for a, n in g.outputs.shape.items() if a != axis_transition + } + shape_result[axis_temperature] = num_temperature + result = na.ScalarArray.zeros(shape_result | shape) << g.outputs.unit + + for index, transition in zip(indices, transitions): + line = g.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, diff --git a/utu/spectrum/_tests/test_lines.py b/utu/spectrum/_tests/test_lines.py index a902a74..a97769f 100644 --- a/utu/spectrum/_tests/test_lines.py +++ b/utu/spectrum/_tests/test_lines.py @@ -287,3 +287,188 @@ 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 of its ion within half a + milliangstrom of 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), + density=density, + axis_temperature="temperature", + axis="transition", + proton_electron_ratio=proton_electron_ratio, + ) + w = wavelength_line[index].ndarray + near = np.abs(g.inputs.ndarray - w) < 0.5 * u.mAA + 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_grid(proton_electron_ratio: u.Quantity) -> None: + """A density on its own axis is every density at every temperature.""" + 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), + density=density_grid, + axis_temperature="temperature", + axis="transition", + proton_electron_ratio=proton_electron_ratio, + ) + near = np.abs(expected.inputs - wavelength_line[{"line": 0}]) < 0.5 * u.mAA + index = {"transition": int(np.flatnonzero(near.ndarray).item())} + + num_temperature = temperature.shape["temperature"] + assert result.outputs.shape == dict(temperature=num_temperature, _density=2, line=3) + assert np.all(result.outputs[{"line": 0}] == expected.outputs[index]) + + +@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(size_chunk=0), "at least 1"), + ( + dict(wavelength=wavelength_line * (temperature / temperature)), + "axis of the temperature", + ), + ], +) +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)) From f2bc31069013737f4596f3d438ed2a481d431605 Mon Sep 17 00:00:00 2001 From: Roy Smart Date: Fri, 13 Nov 2026 06:39:32 -0700 Subject: [PATCH 2/2] Require fiasco 0.9, and address the review of `contribution_function_line()` fiasco 0.9.0 takes the ratio of protons to electrons as an argument of `fiasco.Ion`, and `next_ion()` passes it on, so the ion that fiasco builds to recombine from no longer walks the whole database. It also computes the ratio as an ion is built unless it is given one, and the ratio is now a property, so priming it through `__dict__` does nothing. - `contribution_function()` sets a ratio it is given through the property, which also reaches the ion it recombines from. - `contribution_function_line()` and `lines()` give the ratio to each ion as it is built. `lines()` broadcasts it against the temperature first, so that a ratio which does not fit fails rather than skipping every ion. - `ions()` gives each ion a ratio it never reads, so that listing the database does not walk it once for each of five hundred ions. From the review of `contribution_function_line()`: - The default tolerance is a hundredth of a milliangstrom, not half of one. CHIANTI lists some wavelengths to a tenth of a milliangstrom, and many pairs of transitions half a milliangstrom apart, so half a milliangstrom could take in a neighbor or not depending on rounding. No two distinct wavelengths of one ion in the database are closer than a tenth of a milliangstrom. - Every line is matched to its transitions before any ion is solved, so that a wavelength with no transition fails at once. - The lines are grouped by the ion rather than by its name, so that "O 5" and "O V" are solved once. - The result is allocated before anything is solved, so that no lines at all is an empty result rather than outputs of None. - A scalar density is the same density at every temperature and adds no axis, and a density on an axis of its own keeps the name of that axis. A density along the lines, or along the temperature and another axis, is an error. - An empty temperature is an error of its own. - The inputs of the result are a copy, which can be written. - The docstring says what the arguments of fiasco may not do under `size_chunk`, and names the line of Mg X in the example correctly. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BYjDL98znSud1yFh9chnkP --- pyproject.toml | 2 +- utu/spectrum/_lines.py | 208 +++++++++++++++++++----------- utu/spectrum/_tests/test_lines.py | 192 ++++++++++++++++++++++++--- 3 files changed, 311 insertions(+), 91 deletions(-) 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/_lines.py b/utu/spectrum/_lines.py index a6e69c1..273e84c 100644 --- a/utu/spectrum/_lines.py +++ b/utu/spectrum/_lines.py @@ -123,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) @@ -193,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 -------- @@ -241,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)) @@ -293,7 +299,7 @@ def contribution_function_line( density: u.Quantity | na.AbstractScalar, axis_temperature: str = "temperature", proton_electron_ratio: None | u.Quantity | na.AbstractScalar = None, - tolerance: u.Quantity = 0.5 * u.mAA, + tolerance: u.Quantity = 0.01 * u.mAA, size_chunk: None | int = None, **kwargs: object, ) -> na.FunctionArray: @@ -310,38 +316,50 @@ def contribution_function_line( 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. 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`. + 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. Give it, and ``wavelength``, along axes of - their own to compute several lines at once. An ion with more than - one of the lines is built once, and solved once at each temperature. + ``"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, which may share the axis of the - temperature or have one of its own, as in - :func:`contribution_function`. + 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. Pass it to compute lines over one grid of - temperatures more than once without paying for it again. + 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. CHIANTI lists its wavelengths to the milliangstrom, so the - default is half of one. + 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 @@ -349,18 +367,18 @@ def contribution_function_line( 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. It does cost time: - :mod:`fiasco` builds the ion it recombines from anew for every chunk, - and that ion computes its own ratio of protons to electrons, which - walks the whole database again. + few at a time changes nothing in the result. kwargs - Additional arguments passed to :class:`fiasco.Ion` and to - :func:`fiasco.proton_electron_ratio`. + 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 brighter of the two lines of :math:`\mathrm{Mg\,X}` beside it. + the line of :math:`\mathrm{Mg\,X}` nearest it. .. jupyter-execute:: @@ -406,6 +424,8 @@ def contribution_function_line( 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 @@ -421,9 +441,63 @@ def contribution_function_line( f"{axis_temperature!r}." ) ion = ion.broadcast_to(shape) - wavelength = wavelength.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 @@ -439,51 +513,30 @@ def contribution_function_line( axes=(axis_temperature,), ) - axis_transition = "_transition" - result = None - - for name in np.unique(ion.ndarray): - # The lines of this ion, and the transitions which make up each of - # them. The transitions are found in the first chunk and kept, since - # their wavelengths do not depend on the temperature. - indices = [i for i in na.ndindex(shape) if ion[i].ndarray == name] - transitions = None - + for key, selection in selections.items(): for start in range(0, num_temperature, size_chunk): chunk = {axis_temperature: slice(start, start + size_chunk)} - t = temperature[chunk] g = contribution_function( - ion=fiasco.Ion(str(name), t.ndarray, **kwargs), + 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, - proton_electron_ratio=proton_electron_ratio[chunk], ) - if transitions is None: - transitions = [] - for index in indices: - w = wavelength[index].ndarray - near = np.abs(g.inputs.ndarray - w) < tolerance - if not np.any(near): - raise ValueError( - f"CHIANTI lists no transition of {name} within " - f"{tolerance} of {w}." - ) - transitions.append( - na.ScalarArray(np.flatnonzero(near), axes=axis_transition) - ) - - if result is None: - shape_result = { - a: n for a, n in g.outputs.shape.items() if a != axis_transition - } - shape_result[axis_temperature] = num_temperature - result = na.ScalarArray.zeros(shape_result | shape) << g.outputs.unit - - for index, transition in zip(indices, transitions): - line = g.outputs[{axis_transition: 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( @@ -551,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 @@ -588,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 = [] @@ -607,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 a97769f..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) @@ -298,8 +326,8 @@ def test_lines_ions( @needs_database def test_contribution_function_line(proton_electron_ratio: u.Quantity) -> None: """ - Each line is the sum of the transitions of its ion within half a - milliangstrom of its wavelength. + 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, @@ -317,14 +345,17 @@ def test_contribution_function_line(proton_electron_ratio: u.Quantity) -> None: 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), + ion=fiasco.Ion( + ion_line[index].ndarray.item(), + temperature.ndarray, + proton_electron_ratio=proton_electron_ratio, + ), density=density, axis_temperature="temperature", axis="transition", - proton_electron_ratio=proton_electron_ratio, ) w = wavelength_line[index].ndarray - near = np.abs(g.inputs.ndarray - w) < 0.5 * u.mAA + 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)) @@ -401,9 +432,118 @@ def test_contribution_function_line_scalar(proton_electron_ratio: u.Quantity) -> 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.""" + """ + 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",), @@ -419,18 +559,27 @@ def test_contribution_function_line_grid(proton_electron_ratio: u.Quantity) -> N ) expected = utu.spectrum.contribution_function( - ion=fiasco.Ion("O 5", temperature.ndarray), + ion=fiasco.Ion( + "O 5", + temperature.ndarray, + proton_electron_ratio=proton_electron_ratio, + ), density=density_grid, axis_temperature="temperature", axis="transition", - proton_electron_ratio=proton_electron_ratio, ) - near = np.abs(expected.inputs - wavelength_line[{"line": 0}]) < 0.5 * u.mAA + 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) - assert np.all(result.outputs[{"line": 0}] == expected.outputs[index]) + 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 @@ -455,11 +604,20 @@ def test_contribution_function_line_missing( 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: