From 9fef403f16e9695a8805cb3db864c08c78329761 Mon Sep 17 00:00:00 2001 From: Roy Smart Date: Mon, 9 Nov 2026 06:49:41 -0700 Subject: [PATCH 1/2] Sum `utu.spectrum.synthesize()` as a matrix product, and add `axis_shift` for velocity-resolved emission measures `synthesize()` formed the product of the contribution function, the emission measure and the profile at every temperature and in every pixel, one bin of velocity at a time, and then summed it over temperature. For a map, building that product is most of the work, and it is not needed. Unless the profile varies from pixel to pixel, the spectral radiance per unit emission measure in each bin of temperature, the kernel, has no axes of the map, and the sum is a matrix product of the kernel and the emission measure. `synthesize()` now computes the kernel for every bin of velocity and every line at once, and sums it with the emission measure using `na.vecdot()`, which does that matrix product with BLAS. Where the profile does vary from pixel to pixel, the kernel is as large as the map, and it is computed in blocks of bins and of lines which fit in `_size_block` elements. That limit now bounds the kernel, not the product. The new `axis_shift` argument names an axis of `emission_measure` along which the plasma is binned by line-of-sight velocity, as in a velocity-resolved DEM. It is summed over as well as `axis_temperature`, each bin with the profile of its own `shift` and `width_nonthermal`. `emission_measure` must have that axis, and `velocity` must not vary along it. A velocity-resolved DEM of a MURaM active-region simulation, of shape (logT=24, vdop=33, x=1024, y=1024), now synthesizes in 8.4 s, with the 25 brightest lines of the ESIS-II passband in 64 bins of velocity. The old code took 4.8 s for one line on a 128 x 128 slice of it, which is about 2 hours for the whole cube and all the lines. The result agrees with a separately written single-precision contraction to 5e-7 of each line's peak. The sum is taken in the units of the spectral radiance per unit emission measure, so the result, which may be large, is never converted. This needs named-arrays 2.19 for `na.vecdot()`. New tests compare `axis_shift` with the sum of separate syntheses of its bins, check blocks of lines and of bins against a single block, with a shift which varies from pixel to pixel and a last block which is not full, and cover the new errors. A second example in the docstring synthesizes a velocity-resolved emission measure. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017xqpht97bF4FWsACAA4wQa --- pyproject.toml | 2 +- utu/spectrum/_synthesis.py | 234 +++++++++++++++++++------- utu/spectrum/_tests/test_synthesis.py | 88 +++++++++- 3 files changed, 254 insertions(+), 70 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 26883d3..0783c25 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,7 +20,7 @@ dependencies = [ "astropy", "matplotlib", "adjustText", - "named-arrays~=2.8", + "named-arrays~=2.19", "numba", "scipy", "fiasco~=0.8.2", diff --git a/utu/spectrum/_synthesis.py b/utu/spectrum/_synthesis.py index 79c6aec..d41d26c 100644 --- a/utu/spectrum/_synthesis.py +++ b/utu/spectrum/_synthesis.py @@ -1,5 +1,6 @@ """The spectral radiance of an optically thin plasma.""" +import math from typing import cast import astropy.constants @@ -14,13 +15,14 @@ _size_block = 2**25 """ -The most elements :func:`synthesize` puts in any one array along the way, a +The most elements of the kernel :func:`synthesize` computes at once, a quarter of a gigabyte in double precision. -The largest of them is the product of the contribution function, the -emission measure, and the profile of a block of lines in one bin of -velocity, at every temperature and in every pixel. The lines are synthesized -as many at a time as fit in this, and at least one. +The kernel is the spectral radiance of each line in each bin of velocity per +unit emission measure in each bin of temperature, and it is as large as the +map only where the profile varies from pixel to pixel. It is computed for as +many bins of velocity and lines at a time as fit in this, and at least one +of each. """ @@ -33,6 +35,7 @@ def synthesize( shift: u.Quantity | na.AbstractScalar = 0 * u.km / u.s, width_nonthermal: u.Quantity | na.AbstractScalar = 0 * u.km / u.s, axis_temperature: str = "temperature", + axis_shift: None | str = None, axis_velocity: str = "velocity", axis: str = "line", ) -> na.FunctionArray[na.DopplerVectorArray, na.AbstractScalar]: @@ -61,6 +64,16 @@ def synthesize( with :math:`m` the mass of the ion and :math:`\sigma_\mathrm{nt}` the nonthermal width. + An emission measure resolved in line-of-sight velocity as well as in + temperature, such as the velocity-resolved DEM of a simulation, is a sum + over both, each bin of velocity :math:`s` with a profile centered on its + own shift, + + .. math:: + + L(\lambda) = \frac{1}{4 \pi} \sum_T \sum_s G(T) \, + \mathrm{EM}(T, s) \, \phi(\lambda; T, s). + The radiance of each bin of velocity is the integral of the profile across it divided by its width in wavelength, not the profile sampled at its center. So the sum of the radiance over the bins is the radiance of @@ -88,8 +101,9 @@ def synthesize( emission_measure How much plasma there is in each bin of temperature, :math:`\int n_e n_H \, dh` through the column, along - `axis_temperature`. Every other axis is carried through to the - result, such as the two axes of a map. + `axis_temperature`, and in each bin of line-of-sight velocity too, + along `axis_shift`, if it is given. Every other axis is carried + through to the result, such as the two axes of a map. This is the emission measure of each bin, not the differential emission measure: a DEM per unit :math:`\log_{10} T`, such as @@ -103,8 +117,8 @@ def synthesize( velocities are away from the observer, to longer wavelengths. shift The line-of-sight velocity of the plasma. It may vary along any axis - of `emission_measure`, including `axis_temperature`, and along - `axis`. + of `emission_measure`, including `axis_temperature` and + `axis_shift`, and along `axis`. width_nonthermal The standard deviation of the nonthermal motions of the plasma along the line of sight. Often quoted instead as the most probable speed @@ -112,6 +126,14 @@ def synthesize( along the same axes as `shift`. axis_temperature The name of the axis of `temperature`, summed over. + axis_shift + The name of an axis of `emission_measure` along which the plasma is + binned by line-of-sight velocity, as in a velocity-resolved DEM, + summed over like `axis_temperature`. `shift` is then the velocity of + each bin, and `width_nonthermal` can hold the spread of velocities + within it, such as its width over :math:`\sqrt{12}`, the standard + deviation of a uniform distribution across it. If :obj:`None`, the + default, only `axis_temperature` is summed over. axis_velocity The name of the axis of `velocity`. axis @@ -124,17 +146,19 @@ def synthesize( : The spectral radiance of each line in each bin of velocity, along `axis`, `axis_velocity`, and every axis of the other arguments but - `axis_temperature`. The inputs are the vertices of the bins, as + `axis_temperature` and `axis_shift`. The inputs are the vertices of + the bins, as wavelengths with the rest wavelength of each line beside them. Raises ------ ValueError If `velocity` has no axis `axis_velocity` or varies along - `axis_temperature`, if `temperature` or the - outputs of `contribution` have no axis `axis_temperature`, if a - temperature is not positive, or if an argument varies along `axis` - differently than `contribution` does. + `axis_temperature` or `axis_shift`, if `temperature` or the + outputs of `contribution` have no axis `axis_temperature`, if + `emission_measure` has no axis `axis_shift`, if a temperature is + not positive, or if an argument varies along `axis` differently than + `contribution` does. Notes ----- @@ -145,12 +169,19 @@ def synthesize( left out, which in the transition region and the corona is a small fraction of a milliangstrom, and so is opacity. - The result is filled in one bin of velocity and one block of lines at a - time, with as many lines in a block as keep the largest array along the - way under :data:`_size_block` elements. So a map of many lines needs - little more memory than the result itself. Where the profile is the same - for every line, because none of `mass`, `shift`, and `width_nonthermal` - varies along `axis`, it is computed once for all of them. + The spectral radiance of each line per unit emission measure in each bin + of temperature, the kernel, is computed first, and then summed with the + emission measure over `axis_temperature` and `axis_shift` by + :func:`named_arrays.vecdot`. Unless the profile varies from pixel to + pixel, the kernel has no axes of the map, and the sum is a single matrix + product, so a map of many lines takes little more memory than the result + itself, and is many times faster than forming the product of the two. + Where the profile does vary from pixel to pixel, the kernel is as large + as the map, and is computed for as many bins of velocity and lines at a + time as fit in :data:`_size_block` elements. Where the profile is the + same for every line, because none of `mass`, `shift`, and + `width_nonthermal` varies along `axis`, it is computed once for all of + them. Examples -------- @@ -212,6 +243,41 @@ def synthesize( ax.set_xlabel(f"velocity ({u.km / u.s:latex_inline})") ax.set_ylabel(f"spectral radiance\n({result.outputs.unit:latex_inline})") ax.legend(title="shift"); + + The same plasma, resolved in line-of-sight velocity as well: half of it + at rest and a quarter in each of two bins :math:`40\,\mathrm{km\,s^{-1}}` + to either side, the plasma of each bin spread evenly across its width. + + .. jupyter-execute:: + + # the vertices of three bins of line-of-sight velocity + vertices = na.linspace(-60, 60, axis="vdop", num=4) * u.km / u.s + center = (vertices[dict(vdop=slice(1, None))] + vertices[dict(vdop=slice(None, -1))]) / 2 + width = np.diff(vertices, axis="vdop") + + fraction = na.ScalarArray(np.array([0.25, 0.5, 0.25]), axes="vdop") + + result = utu.spectrum.synthesize( + contribution=contribution, + temperature=temperature, + mass=ion.mass, + emission_measure=emission_measure * fraction, + velocity=na.linspace(-100, 100, axis="velocity", num=81) * u.km / u.s, + shift=center, + width_nonthermal=width / np.sqrt(12), + axis_temperature=axis, + axis_shift="vdop", + ) + + fig, ax = plt.subplots(figsize=(6, 4), constrained_layout=True) + na.plt.stairs( + result.inputs.velocity, + result.outputs, + ax=ax, + axis="velocity", + ) + ax.set_xlabel(f"velocity ({u.km / u.s:latex_inline})") + ax.set_ylabel(f"spectral radiance\n({result.outputs.unit:latex_inline})"); """ temperature = _scalar(temperature) mass = _scalar(mass) @@ -228,11 +294,24 @@ def synthesize( f"`velocity` must have the axis {axis_velocity!r}, " f"got {na.shape(velocity)}." ) - if axis_temperature in na.shape(velocity): - raise ValueError( - f"`velocity` must not vary along {axis_temperature!r}, which is " - f"summed over, got {na.shape(velocity)}." - ) + axis_sum = (axis_temperature,) + if axis_shift is not None: + if axis_shift in (axis_temperature, axis): + raise ValueError( + f"`axis_shift` must be an axis of its own, got {axis_shift!r}." + ) + if axis_shift not in na.shape(emission_measure): + raise ValueError( + f"`emission_measure` must have the axis {axis_shift!r}, " + f"got {na.shape(emission_measure)}." + ) + axis_sum = axis_sum + (axis_shift,) + for a in axis_sum: + if a in na.shape(velocity): + raise ValueError( + f"`velocity` must not vary along {a!r}, which is " + f"summed over, got {na.shape(velocity)}." + ) for name, a in dict(temperature=temperature, contribution=g).items(): if axis_temperature not in na.shape(a): raise ValueError( @@ -274,35 +353,57 @@ def synthesize( emission_measure, *profile.values(), ) - num_temperature = shape.pop(axis_temperature) + for a in axis_sum: + shape.pop(a) num_bin = shape[axis_velocity] - 1 shape[axis_velocity] = num_bin + # The kernel is summed with the emission measure as plain numbers, in + # the units which make the sum a spectral radiance, so that the result, + # which may be very large, is never converted. unit = u.erg / u.cm**2 / u.s / u.sr / u.AA - result = na.ScalarArray( - ndarray=np.zeros(tuple(shape.values())) << unit, - axes=tuple(shape), - ) - - # Enough lines at a time that the product of the contribution function, - # the emission measure, and the profile in one bin, at every temperature - # and in every pixel, stays under the size of a block. - size_line = num_temperature - for a, n in shape.items(): - if a not in (axis, axis_velocity): - size_line *= n - num_block = max(1, _size_block // size_line) + unit_kernel = unit / na.unit_normalized(emission_measure) + emission_measure = emission_measure.value + + # The kernel varies along every axis the contribution function and the + # profile do, which are the axes of the map only if the profile varies + # from pixel to pixel. As many lines at a time as fit in a block in one + # bin of velocity, and as many bins at a time as fit with them. + shape_kernel = na.shape_broadcasted(g, wavelength_rest, temperature, *profile.values()) + size = math.prod(n for a, n in shape_kernel.items() if a not in (axis, axis_velocity)) + num_line_block = num_line if num_line else 1 + if size * num_line_block > _size_block: + num_line_block = max(1, _size_block // size) + num_bin_block = max(1, _size_block // (size * num_line_block)) + + blocks_bin = [ + slice(k, min(k + num_bin_block, num_bin)) + for k in range(0, num_bin, num_bin_block) + ] if num_line is None: - blocks = [None] + blocks_line = [None] else: - blocks = [slice(i, i + num_block) for i in range(0, num_line, num_block)] + blocks_line = [ + slice(i, i + num_line_block) + for i in range(0, num_line, num_line_block) + ] + + # One block is the result itself, and any other number of them fills it. + single = len(blocks_bin) * len(blocks_line) == 1 + if not single: + result = na.ScalarArray( + ndarray=np.zeros(tuple(shape.values())) << unit, + axes=tuple(shape), + ) # The profile is the same for every line unless something it depends on - # varies along the axis of lines, and is then computed once per bin. + # varies along the axis of lines, and is then computed once per block of + # bins. shared = all(axis not in na.shape(a) for a in profile.values()) - for k in range(num_bin): - index_bin = {axis_velocity: slice(k, k + 2)} + for bins in blocks_bin: + # the vertices of the bins in this block + index_bin = {axis_velocity: slice(bins.start, bins.stop + 1)} if shared: fraction_shared = _fraction( @@ -311,7 +412,7 @@ def synthesize( axis_velocity=axis_velocity, ) - for block in blocks: + for block in blocks_line: index = {} if block is None else {axis: block} if shared: @@ -326,19 +427,27 @@ def synthesize( axis_velocity=axis_velocity, ) - radiance = g[index] * _select(emission_measure, index) * fraction - radiance = radiance.sum(axis_temperature) - - # The width of the bin in wavelength, which turns the radiance in - # it into a spectral radiance. The Doppler shift is linear in + # The width of each bin in wavelength, which turns the radiance + # in it into a spectral radiance. The Doppler shift is linear in # velocity, so this is exact, and does not take the difference of # two wavelengths which agree in most of their digits. width = np.diff(_select(velocity[index_bin], index), axis=axis_velocity) width = wavelength_rest[index] * width / astropy.constants.c - radiance = radiance / width / (4 * np.pi * u.sr) + kernel = g[index] * fraction / width / (4 * np.pi * u.sr) + kernel = kernel.to(unit_kernel).value - result[index | {axis_velocity: slice(k, k + 1)}] = radiance + radiance = na.vecdot( + kernel, + _select(emission_measure, index), + axis=axis_sum, + ) + radiance = radiance << unit + + if single: + result = radiance + else: + result[index | {axis_velocity: bins}] = radiance return na.FunctionArray( inputs=na.DopplerVectorArray.from_velocity( @@ -358,17 +467,18 @@ def _fraction( axis_velocity: str, ) -> na.AbstractScalar: """ - The fraction of the profile of a line which falls in one bin of velocity. + The fraction of the profile of a line which falls in each of a block of + bins of velocity. - `velocity` is the two vertices of the bin, along `axis_velocity`, and the - result keeps that axis, with one element. + `velocity` is the vertices of a block of bins, along `axis_velocity`, + and the result has one element fewer along that axis, one for each bin. The fraction is the difference of the cumulative distribution of the - profile at the two vertices. Far into either wing that distribution is - within rounding of zero or of one, and the difference of two values near - one loses every digit, so it is taken instead from the complementary - error function of the tail the bin is in, which keeps its relative - precision there. + profile at the two vertices of a bin. Far into either wing that + distribution is within rounding of zero or of one, and the difference of + two values near one loses every digit, so it is taken instead from the + complementary error function of the tail the bin is in, which keeps its + relative precision there. """ width = np.sqrt( astropy.constants.k_B * temperature / mass + np.square(width_nonthermal) @@ -377,8 +487,8 @@ def _fraction( z = (velocity - shift) / (np.sqrt(2) * width) z = z.to(u.dimensionless_unscaled).value - z0 = z[{axis_velocity: slice(0, 1)}] - z1 = z[{axis_velocity: slice(1, 2)}] + z0 = z[{axis_velocity: slice(None, -1)}] + z1 = z[{axis_velocity: slice(1, None)}] # +1 if the middle of the bin is above the center of the profile, -1 if # below, so that the error function is evaluated in its own tail diff --git a/utu/spectrum/_tests/test_synthesis.py b/utu/spectrum/_tests/test_synthesis.py index 5746a59..5e67f7d 100644 --- a/utu/spectrum/_tests/test_synthesis.py +++ b/utu/spectrum/_tests/test_synthesis.py @@ -277,8 +277,29 @@ def _rename(a: na.AbstractScalar) -> na.AbstractScalar: dict(mass=na.ScalarArray([20, 28, 32] * u.u, axes="line")), # a mass for each of two lines, given to one line dict(contribution=contribution[{"line": 0}]), + # bins of line-of-sight velocity which the emission measure lacks + dict(axis_shift="vdop"), + # bins of line-of-sight velocity along the axis of temperature + dict(axis_shift="temperature"), + # bins of the spectrum which change with the bins of line-of-sight + # velocity summed over + dict( + emission_measure=emission_measure * na.ScalarArray(np.ones(3), axes="vdop"), + velocity=velocity * na.linspace(1, 2, axis="vdop", num=3), + axis_shift="vdop", + ), + ], + ids=[ + "velocity", + "velocity-temperature", + "temperature", + "zero", + "mass", + "single", + "shift-missing", + "shift-temperature", + "velocity-shift", ], - ids=["velocity", "velocity-temperature", "temperature", "zero", "mass", "single"], ) def test_synthesize_error(kwargs: dict): with pytest.raises(ValueError): @@ -348,18 +369,71 @@ def test_synthesize_wings(): assert np.allclose(fraction, expected, rtol=1e-6) -def test_synthesize_blocks(monkeypatch: pytest.MonkeyPatch): - """A map synthesized a line at a time is the same map.""" +@pytest.mark.parametrize( + argnames="shift,size_block", + argvalues=[ + # The kernel of one line in one bin of velocity has an element at + # each of the six temperatures, and room for one of them is a line + # and a bin at a time. + (0 * u.km / u.s, 6), + # A shift which varies from pixel to pixel gives the kernel the three + # pixels of the map as well. + (na.ScalarArray([-20, 0, 30] * u.km / u.s, axes="x"), 6 * 3), + # Both lines in seven bins at a time, which leaves fewer bins in the + # last block. + (na.ScalarArray([-20, 0, 30] * u.km / u.s, axes="x"), 6 * 3 * 2 * 7), + ], + ids=["line", "map", "bins"], +) +def test_synthesize_blocks( + monkeypatch: pytest.MonkeyPatch, + shift: u.Quantity | na.AbstractScalar, + size_block: int, +) -> None: + """A map synthesized in blocks of lines and of bins is the same map.""" em = emission_measure * na.ScalarArray(np.array([1, 2, 3]), axes="x") - expected = _synthesize(emission_measure=em) + expected = _synthesize(emission_measure=em, shift=shift) - # room for one line at every temperature and in every pixel, and no more - monkeypatch.setattr(utu.spectrum._synthesis, "_size_block", 6 * 3) - result = _synthesize(emission_measure=em) + monkeypatch.setattr(utu.spectrum._synthesis, "_size_block", size_block) + result = _synthesize(emission_measure=em, shift=shift) + assert na.shape(result.outputs) == na.shape(expected.outputs) assert np.allclose(result.outputs, expected.outputs, rtol=1e-12) +def test_synthesize_axis_shift() -> None: + """ + An emission measure resolved in line-of-sight velocity is the plasma in + each of its bins of velocity, each at its own shift and width, added up. + """ + shift = na.ScalarArray([-40, 0, 25] * u.km / u.s, axes="vdop") + width = na.ScalarArray([10, 5, 15] * u.km / u.s, axes="vdop") + + em = emission_measure * na.ScalarArray(np.array([0.2, 0.5, 0.3]), axes="vdop") + em = em * na.ScalarArray(np.array([1, 2]), axes="x") + + result = _synthesize( + emission_measure=em, + shift=shift, + width_nonthermal=width, + axis_shift="vdop", + ) + + assert na.shape(result.outputs) == dict(line=2, velocity=800, x=2) + + expected = 0 + for i in range(3): + index = {"vdop": i} + part = _synthesize( + emission_measure=em[index], + shift=shift[index], + width_nonthermal=width[index], + ) + expected = expected + part.outputs + + assert np.allclose(result.outputs, expected, rtol=1e-12) + + @needs_database def test_synthesize_lines(): """The radiance of the lines is that :func:`utu.spectrum.lines` gives.""" From 187b78ac231625fb635bdef17bb7ca1d179f407e Mon Sep 17 00:00:00 2001 From: Roy Smart Date: Mon, 9 Nov 2026 09:10:54 -0700 Subject: [PATCH 2/2] Fix the review findings on `utu.spectrum.synthesize()` An emission measure with one element along `axis_shift` was broadcast against the shifts and summed, which counted its plasma once for each of them, three times over for three shifts. It now has to have as many elements along `axis_shift` as every other argument. `axis_shift` may not be `axis_velocity` either, which blamed the bins of velocity. The block size bounded only the kernel, not the radiance each block gives, which has every axis of the map of the emission measure. Two blocks of bins of a map along x, with the profile the same in every pixel, took 2.01 times the memory of the result, where main took 1.06. If the kernel of every line and bin fits in `_size_block`, the result is still computed in one piece. Otherwise the kernel and the radiance of a block are bounded together, which brings that case back to 1.06. An axis of the kernel with no elements no longer divides by zero. The result computed in one piece had its axes in the order `na.vecdot()` gives them, and the result computed in blocks in the order of the arguments, as on main. Both now have the order of the arguments, the one-piece result as a transposed view. The result computed in blocks is allocated from the first block, so it is uncertain if the block is, where it raised `TypeError`. The units of the kernel are converted before the fraction, which has every axis of the kernel, is multiplied in. The docstrings say that the kernel has axes of the map where the contribution function varies from pixel to pixel as well as the profile, that a Gaussian of the same variance approximates plasma spread evenly across a bin, and which errors `axis_shift` raises. The example takes the centers and the widths of its bins with `cell_centers()` and `volume_cell()`. `test_synthesize_blocks` now checks how many blocks each case is split into, the type of the result and the order of its axes, and covers an uncertain emission measure. New tests cover `axis_shift` in blocks, with a shift the same in every bin, equal to `axis_velocity` or `axis`, and with one bin of emission measure for three shifts, and a profile which varies along an axis with no elements. The changed files are formatted with black. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017xqpht97bF4FWsACAA4wQa --- utu/spectrum/_synthesis.py | 160 ++++++++++++++++++-------- utu/spectrum/_tests/test_synthesis.py | 137 ++++++++++++++++++++-- 2 files changed, 236 insertions(+), 61 deletions(-) diff --git a/utu/spectrum/_synthesis.py b/utu/spectrum/_synthesis.py index d41d26c..fd0586b 100644 --- a/utu/spectrum/_synthesis.py +++ b/utu/spectrum/_synthesis.py @@ -15,14 +15,16 @@ _size_block = 2**25 """ -The most elements of the kernel :func:`synthesize` computes at once, a -quarter of a gigabyte in double precision. +The most elements :func:`synthesize` computes at once, a quarter of a +gigabyte in double precision, where it computes the result in blocks. The kernel is the spectral radiance of each line in each bin of velocity per -unit emission measure in each bin of temperature, and it is as large as the -map only where the profile varies from pixel to pixel. It is computed for as -many bins of velocity and lines at a time as fit in this, and at least one -of each. +unit emission measure in each bin of temperature. If it fits in this for +every line and bin at once, the result is computed in one piece. Otherwise, +as where the profile or the contribution function varies from pixel to pixel +and the kernel is as large as the map, the kernel and the radiance it gives +are computed for as many bins of velocity and lines at a time as fit in +this, and at least one of each. """ @@ -131,8 +133,11 @@ def synthesize( binned by line-of-sight velocity, as in a velocity-resolved DEM, summed over like `axis_temperature`. `shift` is then the velocity of each bin, and `width_nonthermal` can hold the spread of velocities - within it, such as its width over :math:`\sqrt{12}`, the standard - deviation of a uniform distribution across it. If :obj:`None`, the + within it. The profile of each bin is a Gaussian, so plasma spread + evenly across a bin is approximated by a Gaussian of the same + variance, with a nonthermal width of the width of the bin over + :math:`\sqrt{12}`. `emission_measure` must have every element along + this axis that the other arguments have. If :obj:`None`, the default, only `axis_temperature` is summed over. axis_velocity The name of the axis of `velocity`. @@ -156,9 +161,10 @@ def synthesize( If `velocity` has no axis `axis_velocity` or varies along `axis_temperature` or `axis_shift`, if `temperature` or the outputs of `contribution` have no axis `axis_temperature`, if - `emission_measure` has no axis `axis_shift`, if a temperature is - not positive, or if an argument varies along `axis` differently than - `contribution` does. + `axis_shift` is `axis_temperature`, `axis_velocity`, or `axis`, if + `emission_measure` has no axis `axis_shift` or fewer elements along + it than another argument, if a temperature is not positive, or if an + argument varies along `axis` differently than `contribution` does. Notes ----- @@ -172,13 +178,14 @@ def synthesize( The spectral radiance of each line per unit emission measure in each bin of temperature, the kernel, is computed first, and then summed with the emission measure over `axis_temperature` and `axis_shift` by - :func:`named_arrays.vecdot`. Unless the profile varies from pixel to - pixel, the kernel has no axes of the map, and the sum is a single matrix - product, so a map of many lines takes little more memory than the result - itself, and is many times faster than forming the product of the two. - Where the profile does vary from pixel to pixel, the kernel is as large - as the map, and is computed for as many bins of velocity and lines at a - time as fit in :data:`_size_block` elements. Where the profile is the + :func:`named_arrays.vecdot`. Unless the profile or the contribution + function varies from pixel to pixel, the kernel has no axes of the map, + and the sum is a single matrix product, so a map of many lines takes + little more memory than the result itself, and is many times faster than + forming the product of the two. Where one of them does vary from pixel + to pixel, the kernel is as large as the map, and it and the radiance it + gives are computed for as many bins of velocity and lines at a time as + fit in :data:`_size_block` elements. Where the profile is the same for every line, because none of `mass`, `shift`, and `width_nonthermal` varies along `axis`, it is computed once for all of them. @@ -246,14 +253,16 @@ def synthesize( The same plasma, resolved in line-of-sight velocity as well: half of it at rest and a quarter in each of two bins :math:`40\,\mathrm{km\,s^{-1}}` - to either side, the plasma of each bin spread evenly across its width. + to either side. The plasma of each bin is spread evenly across its + width, which the profile approximates with a Gaussian of the same + variance. .. jupyter-execute:: # the vertices of three bins of line-of-sight velocity vertices = na.linspace(-60, 60, axis="vdop", num=4) * u.km / u.s - center = (vertices[dict(vdop=slice(1, None))] + vertices[dict(vdop=slice(None, -1))]) / 2 - width = np.diff(vertices, axis="vdop") + center = vertices.cell_centers("vdop") + width = vertices.volume_cell("vdop") fraction = na.ScalarArray(np.array([0.25, 0.5, 0.25]), axes="vdop") @@ -296,9 +305,10 @@ def synthesize( ) axis_sum = (axis_temperature,) if axis_shift is not None: - if axis_shift in (axis_temperature, axis): + if axis_shift in (axis_temperature, axis_velocity, axis): raise ValueError( - f"`axis_shift` must be an axis of its own, got {axis_shift!r}." + f"`axis_shift` must be an axis of its own, not `axis_temperature`, " + f"`axis_velocity`, or `axis`, got {axis_shift!r}." ) if axis_shift not in na.shape(emission_measure): raise ValueError( @@ -353,6 +363,19 @@ def synthesize( emission_measure, *profile.values(), ) + + # An emission measure with one element along `axis_shift` would be + # broadcast against the shifts and summed, counting its plasma once for + # each of them. + if axis_shift is not None: + num_shift = na.shape(emission_measure)[axis_shift] + if num_shift != shape[axis_shift]: + raise ValueError( + f"`emission_measure` must have as many elements along " + f"{axis_shift!r} as every other argument, {shape[axis_shift]}, " + f"got {num_shift}." + ) + for a in axis_sum: shape.pop(a) num_bin = shape[axis_velocity] - 1 @@ -366,35 +389,39 @@ def synthesize( emission_measure = emission_measure.value # The kernel varies along every axis the contribution function and the - # profile do, which are the axes of the map only if the profile varies - # from pixel to pixel. As many lines at a time as fit in a block in one - # bin of velocity, and as many bins at a time as fit with them. - shape_kernel = na.shape_broadcasted(g, wavelength_rest, temperature, *profile.values()) - size = math.prod(n for a, n in shape_kernel.items() if a not in (axis, axis_velocity)) - num_line_block = num_line if num_line else 1 - if size * num_line_block > _size_block: - num_line_block = max(1, _size_block // size) - num_bin_block = max(1, _size_block // (size * num_line_block)) - - blocks_bin = [ - slice(k, min(k + num_bin_block, num_bin)) - for k in range(0, num_bin, num_bin_block) - ] + # profile do, which are axes of the map only where one of them varies + # from pixel to pixel. If the kernel of every line in every bin of + # velocity fits in a block, the result is computed in one piece. + # Otherwise, as many lines at a time as fit in a block in one bin of + # velocity, with the radiance they give, and as many bins at a time as + # fit with them. + shape_kernel = na.shape_broadcasted( + g, wavelength_rest, temperature, *profile.values() + ) + size_kernel = math.prod( + n for a, n in shape_kernel.items() if a not in (axis, axis_velocity) + ) + size_radiance = math.prod( + n for a, n in shape.items() if a not in (axis, axis_velocity) + ) + num_line_all = 1 if num_line is None else num_line + if size_kernel * num_line_all * num_bin <= _size_block: + num_line_block = max(1, num_line_all) + num_bin_block = max(1, num_bin) + else: + size = size_kernel + size_radiance + num_line_block = max(1, min(num_line_all, _size_block // size)) + num_bin_block = max(1, _size_block // (size * num_line_block)) + + blocks_bin = _blocks(num_bin, num_bin_block) if num_line is None: blocks_line = [None] else: - blocks_line = [ - slice(i, i + num_line_block) - for i in range(0, num_line, num_line_block) - ] + blocks_line = _blocks(num_line, num_line_block) # One block is the result itself, and any other number of them fills it. single = len(blocks_bin) * len(blocks_line) == 1 - if not single: - result = na.ScalarArray( - ndarray=np.zeros(tuple(shape.values())) << unit, - axes=tuple(shape), - ) + result = None # The profile is the same for every line unless something it depends on # varies along the axis of lines, and is then computed once per block of @@ -434,21 +461,32 @@ def synthesize( width = np.diff(_select(velocity[index_bin], index), axis=axis_velocity) width = wavelength_rest[index] * width / astropy.constants.c - kernel = g[index] * fraction / width / (4 * np.pi * u.sr) - kernel = kernel.to(unit_kernel).value + # The units are converted before the fraction, which has every + # axis of the kernel, is multiplied in. + factor = g[index] / width / (4 * np.pi * u.sr) + kernel = factor.to(unit_kernel).value * fraction radiance = na.vecdot( kernel, _select(emission_measure, index), axis=axis_sum, ) - radiance = radiance << unit + radiance = np.transpose(radiance << unit, axes=tuple(shape)) if single: result = radiance else: + if result is None: + result = _allocate(radiance, shape) result[index | {axis_velocity: bins}] = radiance + # no lines, or no bins of velocity + if result is None: + result = na.ScalarArray( + ndarray=np.zeros(tuple(shape.values())) << unit, + axes=tuple(shape), + ) + return na.FunctionArray( inputs=na.DopplerVectorArray.from_velocity( velocity=velocity, @@ -500,6 +538,30 @@ def _fraction( return side * (erfc0 - erfc1) / 2 +def _blocks( + num: int, + num_block: int, +) -> list[slice]: + """ + Split `num` elements into blocks of `num_block` elements, the last of + which may have fewer. + """ + return [slice(k, min(k + num_block, num)) for k in range(0, num, num_block)] + + +def _allocate( + block: na.AbstractScalar, + shape: dict[str, int], +) -> na.AbstractScalar: + """ + An array of the type and the unit of a block of the result of + :func:`synthesize`, scalar or uncertain, with the shape of the whole + result, every element of which the blocks overwrite. + """ + first = {a: slice(0, 1) for a in na.shape(block)} + return na.broadcast_to(block[first], shape).copy() + + def _select( a: na.AbstractScalar, index: dict[str, slice], diff --git a/utu/spectrum/_tests/test_synthesis.py b/utu/spectrum/_tests/test_synthesis.py index 5e67f7d..84ff87c 100644 --- a/utu/spectrum/_tests/test_synthesis.py +++ b/utu/spectrum/_tests/test_synthesis.py @@ -1,3 +1,5 @@ +import math + import astropy.constants import astropy.units as u import fiasco @@ -279,8 +281,18 @@ def _rename(a: na.AbstractScalar) -> na.AbstractScalar: dict(contribution=contribution[{"line": 0}]), # bins of line-of-sight velocity which the emission measure lacks dict(axis_shift="vdop"), - # bins of line-of-sight velocity along the axis of temperature + # bins of line-of-sight velocity along the axis of temperature, of + # the spectrum, or of lines dict(axis_shift="temperature"), + dict(axis_shift="velocity"), + dict(axis_shift="line"), + # an emission measure in one bin of line-of-sight velocity, with a + # shift for each of three + dict( + emission_measure=emission_measure * na.ScalarArray(np.ones(1), axes="vdop"), + shift=na.ScalarArray([-40, 0, 25] * u.km / u.s, axes="vdop"), + axis_shift="vdop", + ), # bins of the spectrum which change with the bins of line-of-sight # velocity summed over dict( @@ -298,6 +310,9 @@ def _rename(a: na.AbstractScalar) -> na.AbstractScalar: "single", "shift-missing", "shift-temperature", + "shift-velocity", + "shift-line", + "shift-one", "velocity-shift", ], ) @@ -318,6 +333,15 @@ def test_synthesize_empty(): assert na.shape(result.outputs) == dict(line=0, velocity=800) +def test_synthesize_empty_map() -> None: + """A map with no pixels, along which the profile varies, is no pixels.""" + shift = na.ScalarArray(np.zeros(0) * u.km / u.s, axes="x") + + result = _synthesize(shift=shift) + + assert na.shape(result.outputs) == dict(line=2, x=0, velocity=800) + + def test_synthesize_broadcast(): """A mass with one element along the axis of lines is every line's.""" one = na.ScalarArray([20.18] * u.u, axes="line") @@ -369,39 +393,109 @@ def test_synthesize_wings(): assert np.allclose(fraction, expected, rtol=1e-6) +def _count_blocks(monkeypatch: pytest.MonkeyPatch) -> list[int]: + """ + Record how many blocks of bins and of lines :func:`utu.spectrum.synthesize` + splits the result into, by appending each number to the list returned. + """ + nums = [] + blocks = utu.spectrum._synthesis._blocks + + def _blocks(num: int, num_block: int) -> list[slice]: + """:func:`utu.spectrum._synthesis._blocks`, recorded.""" + result = blocks(num, num_block) + nums.append(len(result)) + return result + + monkeypatch.setattr(utu.spectrum._synthesis, "_blocks", _blocks) + return nums + + +# An emission measure along the three pixels of a map, and the same with +# uncertainty. +_em_map = emission_measure * na.ScalarArray(np.array([1, 2, 3]), axes="x") +_em_map_uncertain = na.UncertainScalarArray( + nominal=_em_map, + distribution=_em_map * na.ScalarArray(np.array([0.9, 1.2]), axes="_distribution"), +) + + @pytest.mark.parametrize( - argnames="shift,size_block", + argnames="em,shift,size_block,num_block", argvalues=[ # The kernel of one line in one bin of velocity has an element at - # each of the six temperatures, and room for one of them is a line - # and a bin at a time. - (0 * u.km / u.s, 6), + # each of the six temperatures, and the radiance it gives one at each + # of the three pixels, so room for nine is a line and a bin at a time. + (_em_map, 0 * u.km / u.s, 6 + 3, 2 * 800), # A shift which varies from pixel to pixel gives the kernel the three # pixels of the map as well. - (na.ScalarArray([-20, 0, 30] * u.km / u.s, axes="x"), 6 * 3), - # Both lines in seven bins at a time, which leaves fewer bins in the + ( + _em_map, + na.ScalarArray([-20, 0, 30] * u.km / u.s, axes="x"), + 6 * 3 + 3, + 2 * 800, + ), + # Both lines in seven bins at a time, which leaves two bins in the # last block. - (na.ScalarArray([-20, 0, 30] * u.km / u.s, axes="x"), 6 * 3 * 2 * 7), + ( + _em_map, + na.ScalarArray([-20, 0, 30] * u.km / u.s, axes="x"), + (6 * 3 + 3) * 2 * 7, + 115, + ), + # An uncertain emission measure is as uncertain in blocks. + ( + _em_map_uncertain, + na.ScalarArray([-20, 0, 30] * u.km / u.s, axes="x"), + (6 * 3 + 3) * 2 * 7, + 115, + ), ], - ids=["line", "map", "bins"], + ids=["line", "map", "bins", "uncertain"], ) def test_synthesize_blocks( monkeypatch: pytest.MonkeyPatch, + em: na.AbstractScalar, shift: u.Quantity | na.AbstractScalar, size_block: int, + num_block: int, ) -> None: - """A map synthesized in blocks of lines and of bins is the same map.""" - em = emission_measure * na.ScalarArray(np.array([1, 2, 3]), axes="x") + """ + A map synthesized in blocks of lines and of bins is the same map, of the + same type and with its axes in the same order, as in one piece. + """ + nums = _count_blocks(monkeypatch) expected = _synthesize(emission_measure=em, shift=shift) + assert math.prod(nums) == 1 + nums.clear() monkeypatch.setattr(utu.spectrum._synthesis, "_size_block", size_block) result = _synthesize(emission_measure=em, shift=shift) + assert math.prod(nums) == num_block + assert type(result.outputs) is type(expected.outputs) + assert result.outputs.axes == expected.outputs.axes assert na.shape(result.outputs) == na.shape(expected.outputs) + # the nominal values and the distributions, if uncertain assert np.allclose(result.outputs, expected.outputs, rtol=1e-12) -def test_synthesize_axis_shift() -> None: +@pytest.mark.parametrize( + argnames="size_block", + argvalues=[ + None, + # Both lines in seven bins at a time: the kernel of one line in one + # bin has an element at each of six temperatures in each of three + # bins of line-of-sight velocity, and the radiance one at each of + # two pixels. + (6 * 3 + 2) * 2 * 7, + ], + ids=["whole", "blocks"], +) +def test_synthesize_axis_shift( + monkeypatch: pytest.MonkeyPatch, + size_block: None | int, +) -> None: """ An emission measure resolved in line-of-sight velocity is the plasma in each of its bins of velocity, each at its own shift and width, added up. @@ -412,12 +506,16 @@ def test_synthesize_axis_shift() -> None: em = emission_measure * na.ScalarArray(np.array([0.2, 0.5, 0.3]), axes="vdop") em = em * na.ScalarArray(np.array([1, 2]), axes="x") + nums = _count_blocks(monkeypatch) + if size_block is not None: + monkeypatch.setattr(utu.spectrum._synthesis, "_size_block", size_block) result = _synthesize( emission_measure=em, shift=shift, width_nonthermal=width, axis_shift="vdop", ) + assert math.prod(nums) == (1 if size_block is None else 115) assert na.shape(result.outputs) == dict(line=2, velocity=800, x=2) @@ -434,6 +532,21 @@ def test_synthesize_axis_shift() -> None: assert np.allclose(result.outputs, expected, rtol=1e-12) +def test_synthesize_axis_shift_constant() -> None: + """ + Bins of line-of-sight velocity which all have the same shift and width + are the plasma in all of them at that shift and width. + """ + em = emission_measure * na.ScalarArray(np.array([0.2, 0.5, 0.3]), axes="vdop") + shift = 15 * u.km / u.s + + result = _synthesize(emission_measure=em, shift=shift, axis_shift="vdop") + expected = _synthesize(emission_measure=em.sum("vdop"), shift=shift) + + assert na.shape(result.outputs) == dict(line=2, velocity=800) + assert np.allclose(result.outputs, expected.outputs, rtol=1e-12) + + @needs_database def test_synthesize_lines(): """The radiance of the lines is that :func:`utu.spectrum.lines` gives."""