askap-patchwork 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,179 @@
1
+ Metadata-Version: 2.5
2
+ Name: askap-patchwork
3
+ Version: 0.1.0
4
+ Summary: The pirate quilt.
5
+ Project-URL: Homepage, https://github.com/flint-crew/patchwork
6
+ Project-URL: Bug Tracker, https://github.com/flint-crew/patchwork/issues
7
+ Project-URL: Discussions, https://github.com/flint-crew/patchwork/discussions
8
+ Project-URL: Changelog, https://github.com/flint-crew/patchwork/releases
9
+ Author-email: Tim Galvin <tim.galvin@csiro.au>
10
+ License-Expression: BSD-3-Clause
11
+ License-File: LICENSE
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Topic :: Scientific/Engineering
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.11
25
+ Requires-Dist: astropy>=7.2.0
26
+ Requires-Dist: capn-crunch>=1.2.0
27
+ Requires-Dist: dask[distributed]>=2025.1.0
28
+ Requires-Dist: numpy>=2.0.0
29
+ Requires-Dist: pyyaml>=6.0
30
+ Requires-Dist: radio-beam>=0.3.9
31
+ Requires-Dist: scipy
32
+ Provides-Extra: numba
33
+ Requires-Dist: numba>=0.61; extra == 'numba'
34
+ Provides-Extra: zarr
35
+ Requires-Dist: zarr>=3; extra == 'zarr'
36
+ Description-Content-Type: text/markdown
37
+
38
+ # Patchwork
39
+
40
+ [![Actions Status][actions-badge]][actions-link]
41
+ [![Documentation Status][rtd-badge]][rtd-link]
42
+ [![PyPI version][pypi-version]][pypi-link]
43
+ [![PyPI platforms][pypi-platforms]][pypi-link]
44
+ [![Coverage][coverage-badge]][coverage-link]
45
+
46
+ <!-- SPHINX-START -->
47
+
48
+ <!-- prettier-ignore-start -->
49
+ [actions-badge]: https://github.com/flint-crew/patchwork/workflows/CI/badge.svg
50
+ [actions-link]: https://github.com/flint-crew/patchwork/actions
51
+ [pypi-link]: https://pypi.org/project/askap-patchwork/
52
+ [pypi-platforms]: https://img.shields.io/pypi/pyversions/askap-patchwork
53
+ [pypi-version]: https://img.shields.io/pypi/v/askap-patchwork
54
+ [rtd-badge]: https://readthedocs.org/projects/askap-patchwork/badge/?version=latest
55
+ [rtd-link]: https://askap-patchwork.readthedocs.io/en/latest/?badge=latest
56
+ [coverage-badge]: https://codecov.io/github/flint-crew/patchwork/branch/main/graph/badge.svg
57
+ [coverage-link]: https://codecov.io/github/flint-crew/patchwork
58
+
59
+ <!-- prettier-ignore-end -->
60
+
61
+ The pirate quilt!
62
+
63
+ patchwork is a Python library and set of command-line tools for linear
64
+ mosaicking of radio images. Each image is resampled onto a common pixel grid,
65
+ weighted by its primary beam and its noise, and added to the mosaic. The images
66
+ can first be convolved to a common restoring beam.
67
+
68
+ The library uses numpy and astropy, and a separate pipeline runs the same steps
69
+ on a dask cluster.
70
+
71
+ ![A pirate ship sailing at night under patchwork sails](docs/_static/patchwork.svg)
72
+
73
+ ## Documentation
74
+
75
+ The documentation is on
76
+ [Read the Docs](https://askap-patchwork.readthedocs.io/).
77
+
78
+ ## Usage
79
+
80
+ ```bash
81
+ # Convolve a set of beam images to their common restoring beam and mosaic
82
+ # them, weighting by a Gaussian primary beam and their noise
83
+ patchwork mosaic beam*.fits --convolve natural --output-base field
84
+
85
+ # Or only convolve them, writing beam*.conv.fits
86
+ patchwork convolve beam*.fits
87
+
88
+ # Or rotate Q and U cubes referenced to north at the boresight to north at each
89
+ # pixel, writing beam*.rot.fits with their frame recorded in the header
90
+ patchwork rotate beam*.{q,u}.fits --frame-centre 12.5 -81.0
91
+
92
+ # Mosaic Stokes I, Q and U together, rotating Q and U into the frame of the
93
+ # mosaic and removing the leakage of Stokes I with an ASKAP holography cube
94
+ patchwork mosaic beam*.{i,q,u}.fits --remove-leakage \
95
+ --pb-model holography --holography-cube akpb.iquv.cube.fits \
96
+ --frame-centre 12.5 -81.0 --output-base field
97
+
98
+ # Cubes are mosaicked in the same way, here each with its weights log, and
99
+ # every channel convolved to a common beam first, in eight processes
100
+ patchwork mosaic beam*.{i,q,u}.cube.fits --weights beam*.{i,q,u}.weights.txt \
101
+ --frame-centre 12.5 -81.0 --convolve natural --output-base field \
102
+ --max-workers 8 --processes
103
+
104
+ # patchwork-pipeline takes the same arguments, and spreads the work over a
105
+ # dask cluster: a local one, or one described in a YAML file
106
+ patchwork-pipeline beam*.{i,q,u}.cube.fits --weights beam*.{i,q,u}.weights.txt \
107
+ --frame-centre 12.5 -81.0 --convolve natural --output-base field \
108
+ --cluster-config slurm.yaml
109
+ ```
110
+
111
+ `patchwork` runs on one machine, with `--max-workers` threads, or processes with
112
+ `--processes`, and does not use dask. `patchwork-pipeline` does the same work,
113
+ convolution included, on a dask cluster.
114
+
115
+ Images and cubes are given as one list: each one's Stokes parameter is read from
116
+ its header, and those on one pixel grid are taken to be one beam. The mosaics
117
+ are labelled by Stokes parameter, such as `field.i.mosaic.fits` and
118
+ `field.qu.weight.fits`, or `field.i.cube.fits` for cubes.
119
+
120
+ Two dependencies are optional: numba, which speeds up the resampling, and zarr,
121
+ which is needed for zarr output.
122
+
123
+ ```bash
124
+ pip install "askap-patchwork[numba,zarr]"
125
+ ```
126
+
127
+ ## Installation
128
+
129
+ Releases are on PyPI:
130
+
131
+ ```bash
132
+ # PyPI release
133
+ pip install askap-patchwork
134
+ ```
135
+
136
+ To install the latest commit from GitHub:
137
+
138
+ ```bash
139
+ # Direct git install (latest push)
140
+ pip install git+https://github.com/flint-crew/patchwork.git
141
+ ```
142
+
143
+ Or from a local clone:
144
+
145
+ ```bash
146
+ git clone https://github.com/flint-crew/patchwork.git
147
+ cd patchwork
148
+ pip install -e .
149
+ ```
150
+
151
+ With [uv](https://docs.astral.sh/uv/), `uv sync` installs the versions pinned in
152
+ `uv.lock`:
153
+
154
+ ```bash
155
+ git clone https://github.com/flint-crew/patchwork.git
156
+ cd patchwork
157
+ uv venv
158
+ uv sync
159
+ ```
160
+
161
+ ## Contributions
162
+
163
+ Report problems and propose changes through GitHub issues and pull requests.
164
+
165
+ To install the development tools:
166
+
167
+ ```bash
168
+ git clone https://github.com/flint-crew/patchwork.git
169
+ cd patchwork
170
+ pip install -e . --group dev # --group needs pip 25.1 or newer
171
+ ```
172
+
173
+ Or, using `uv`:
174
+
175
+ ```bash
176
+ git clone https://github.com/flint-crew/patchwork.git
177
+ cd patchwork
178
+ uv sync --group dev
179
+ ```
@@ -0,0 +1,33 @@
1
+ patchwork/__init__.py,sha256=qG4L7tVFWJMFzI10B8aMNHTEmHb0qKFdJzjD8ZlZdLc,205
2
+ patchwork/__main__.py,sha256=1qPPWDHeYVYnupHjgtLReZGXhZ3iG9wm6kryVH0IGg0,179
3
+ patchwork/_version.py,sha256=n_5vdJsPNu7wZ57LGuRL585uvll-hiuvZUBWzdG0RQU,520
4
+ patchwork/_version.pyi,sha256=o7uNL6MhuJoiqpEnriU7rBT6TmkJZA-i2qMoNz9YcgQ,82
5
+ patchwork/cli.py,sha256=BGUME7Su-QPDKJDGnvy1EKqRIRGElkrLTa2JxccHpyc,1971
6
+ patchwork/combine.py,sha256=XdkL43_uwGJwmI7N8M9zvgMYLjbCWNQIT4QfY2dE_14,5896
7
+ patchwork/convolve.py,sha256=o5rY1QyJiCCu7Vq7KuhCOFP5LKJVOvtebigKlooSWLM,20535
8
+ patchwork/coordinates.py,sha256=5TQPw_3upj5AbVOQS016I7HAUCMJKwyupZDHnySIwhU,8979
9
+ patchwork/frame.py,sha256=J-CArlMbXzf5c_ClbMTK37B5cage7A8ZsVIver_M0ak,16650
10
+ patchwork/fused.py,sha256=aWQV1LmYvZ8qXTfHFoPbFhIHlLepbeJFHBKbozZBN8A,24285
11
+ patchwork/fused_kernels.py,sha256=NYgUnopKY0N-X_t4oFb8jO7Yn0eggXejH0w-TaDd1gw,29038
12
+ patchwork/io.py,sha256=oBcJKXPM9afP9JbmcXH6ksM0qtRfxmDQHJ06C9QxRHY,25895
13
+ patchwork/logging.py,sha256=5ye-0uDE_pR09OtueEUzeRdBISdLpotu4xYEX-ovSUA,2157
14
+ patchwork/mosaic.py,sha256=tX-7_ZXbYHOhWfi9ATTbtWTZz1IkGIJk6-QKleRBV-w,21543
15
+ patchwork/numba_kernels.py,sha256=E6NHBmrYf3X0URj-HjTIUDEYWWJ1NUQCzp9OdS2zSKU,7666
16
+ patchwork/options.py,sha256=sUWXgL0ZbefZ_wla85BjV2BKg0lcC8udaDPXgmgkBbU,14086
17
+ patchwork/plan.py,sha256=PvZENQYfa_YrurGmGoJkKu4yN7qI-N-GAMb8gZD3l38,32928
18
+ patchwork/polarisation.py,sha256=rlHnQNRCxbVspLzixECQ0OZwy_EzEIBotW5Jx5TemDc,7512
19
+ patchwork/primary_beam.py,sha256=wMaaoDt7-28TIZ2XH5IfWfMwSA5VTchZ1kFAl1tMSYY,27400
20
+ patchwork/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
21
+ patchwork/resample.py,sha256=q0MwlarBEFhGhp1L4bfEk9ihBVyvxEh33hCoVfN_Y2Y,10674
22
+ patchwork/rotate.py,sha256=VoTY03zFNJ8JDlw69-_40Qp7KDq7cBTTshrRwrkTVww,13246
23
+ patchwork/tile.py,sha256=2ovWG7Wu6-KySBDa1fsWTSvP_0ORqWNLbUkNuukubKU,13283
24
+ patchwork/weights.py,sha256=sC4UVyE3LG-ZWO1CmSufrrbYplIRRnujG2OPr0Clqm0,7372
25
+ patchwork/write.py,sha256=hZYcRKvc43OefCikbfxx9zTBelrx8StkXgJly7lZS5g,19643
26
+ patchwork/pipeline/__init__.py,sha256=E_QcCHOM6OsuJ-I-u0T3pZgiVOl8PbnfvE6Xsyg6DIU,110
27
+ patchwork/pipeline/cluster.py,sha256=tNmEpp_3CptZ5_59a-vLWVdG6BFpKUWvcEEFn9oCEI4,2720
28
+ patchwork/pipeline/flow.py,sha256=gO74QHXD2U77ksanXjCXZa1eup2c8PP8jwuwXUorIIY,5579
29
+ askap_patchwork-0.1.0.dist-info/METADATA,sha256=gNw5W9lOWVSCUlQcwaNb39fbEM9Xmdl14Yk4hiheMCg,6221
30
+ askap_patchwork-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
31
+ askap_patchwork-0.1.0.dist-info/entry_points.txt,sha256=fGAA8mBw4gmbPflBVeRSVHAE4oczTWAFhUVAORrcS68,142
32
+ askap_patchwork-0.1.0.dist-info/licenses/LICENSE,sha256=_jZTapMIOcgi0WpoRQsrKqfiwecDD_c2I9ZI93GQUUE,1497
33
+ askap_patchwork-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,4 @@
1
+ [console_scripts]
2
+ patchwork = patchwork.cli:cli
3
+ patchwork-cube = patchwork.pipeline.flow:cli
4
+ patchwork-pipeline = patchwork.pipeline.flow:cli
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, flint-crew
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
patchwork/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ """
2
+ Copyright (c) 2026 Tim Galvin. All rights reserved.
3
+
4
+ askap-patchwork: The pirate quilt.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from ._version import version as __version__
10
+
11
+ __all__ = ["__version__"]
patchwork/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Allows the ``patchwork`` CLI to be run with ``python -m patchwork``"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from patchwork.cli import cli
6
+
7
+ if __name__ == "__main__":
8
+ cli()
patchwork/_version.py ADDED
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.1.0'
22
+ __version_tuple__ = version_tuple = (0, 1, 0)
23
+
24
+ __commit_id__ = commit_id = None
patchwork/_version.pyi ADDED
@@ -0,0 +1,2 @@
1
+ version: str
2
+ version_tuple: tuple[int, int, int] | tuple[int, int, int, str, str]
patchwork/cli.py ADDED
@@ -0,0 +1,60 @@
1
+ """The ``patchwork`` command line interface. Each sub-command is configured by the
2
+ ``get_parser`` of its module, which is passed the sub-parser to add arguments to."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from argparse import ArgumentParser
7
+
8
+ from patchwork import convolve, frame, mosaic, rotate
9
+ from patchwork.logging import logger, setup_logging
10
+
11
+
12
+ def get_parser() -> ArgumentParser:
13
+ """The parser of the ``patchwork`` command."""
14
+ parser = ArgumentParser(description="Linear mosaicking of radio images.")
15
+ subparser = parser.add_subparsers(dest="mode", help="Operation mode of patchwork")
16
+
17
+ mosaic.get_parser(
18
+ parser=subparser.add_parser(
19
+ "mosaic",
20
+ help="Mosaic images onto a common frame, weighting each by its primary beam and noise.",
21
+ )
22
+ )
23
+ convolve.get_parser(
24
+ parser=subparser.add_parser(
25
+ "convolve",
26
+ help="Convolve images to a target beam, or to the smallest beam that encloses all of theirs.",
27
+ )
28
+ )
29
+ frame.get_parser(
30
+ parser=subparser.add_parser(
31
+ "frame",
32
+ help="Construct the output frame of a mosaic and write its header, without making the mosaic.",
33
+ )
34
+ )
35
+ rotate.get_parser(
36
+ parser=subparser.add_parser(
37
+ "rotate",
38
+ help="Rotate the Q and U of images or cubes from the frame they were imaged in to north at each pixel, recording it in their headers.",
39
+ )
40
+ )
41
+ return parser
42
+
43
+
44
+ def cli() -> None:
45
+ """Run the ``patchwork`` command."""
46
+ setup_logging()
47
+ parser = get_parser()
48
+ args = parser.parse_args()
49
+
50
+ if args.mode == "mosaic":
51
+ mosaic.cli(args=args)
52
+ elif args.mode == "convolve":
53
+ convolve.cli(args=args)
54
+ elif args.mode == "frame":
55
+ frame.cli(args=args)
56
+ elif args.mode == "rotate":
57
+ rotate.cli(args=args)
58
+ else:
59
+ logger.error(f"Supplied mode {args.mode} is not known. ")
60
+ parser.print_help()
patchwork/combine.py ADDED
@@ -0,0 +1,146 @@
1
+ """Linear combination of the resampled inputs of a tile"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Literal, NamedTuple
6
+
7
+ import numpy as np
8
+
9
+ if TYPE_CHECKING:
10
+ from collections.abc import Sequence
11
+
12
+ from numpy.typing import NDArray
13
+
14
+ CombineType = Literal["weighted", "average", "sum"]
15
+
16
+
17
+ class TileSums(NamedTuple):
18
+ """Running sums over the inputs of a tile, for a group of images that share a weight.
19
+
20
+ Each input contributes an estimate ``e`` of each image (its weighted image
21
+ over its weight) with a weight ``w``. A weighted mean needs only the sums of
22
+ ``w e`` and of ``w``, so the sums a plain mean or a sum also need are only
23
+ kept for those.
24
+ """
25
+
26
+ totals: tuple[NDArray[np.float64], ...]
27
+ """For each image, the sum of ``w e`` for a weighted mean, otherwise the sum of ``e``"""
28
+ weight: NDArray[np.float64]
29
+ """Sum of ``w``"""
30
+ inverse_weight: NDArray[np.float64] | None = None
31
+ """Sum of ``1 / w``, the summed variance, kept for a plain mean or a sum"""
32
+ n_inputs: NDArray[np.float64] | None = None
33
+ """Number of contributing inputs, kept for a plain mean or a sum"""
34
+
35
+ def region(self, index: tuple[slice, ...]) -> TileSums:
36
+ """The sums over part of the tile, as views that accumulate into these."""
37
+ return TileSums(
38
+ totals=tuple(total[index] for total in self.totals),
39
+ weight=self.weight[index],
40
+ inverse_weight=None
41
+ if self.inverse_weight is None
42
+ else self.inverse_weight[index],
43
+ n_inputs=None if self.n_inputs is None else self.n_inputs[index],
44
+ )
45
+
46
+
47
+ def empty_sums(
48
+ shape: tuple[int, ...], n_images: int = 1, combine_type: CombineType = "weighted"
49
+ ) -> TileSums:
50
+ """Sums of a tile no input has contributed to yet, for a group of ``n_images`` images."""
51
+ kept = combine_type != "weighted"
52
+ return TileSums(
53
+ totals=tuple(np.zeros(shape) for _ in range(n_images)),
54
+ weight=np.zeros(shape),
55
+ inverse_weight=np.zeros(shape) if kept else None,
56
+ n_inputs=np.zeros(shape) if kept else None,
57
+ )
58
+
59
+
60
+ def accumulate(
61
+ sums: TileSums,
62
+ images: Sequence[NDArray[np.float64]],
63
+ factor: NDArray[np.float64] | float,
64
+ weight: NDArray[np.float64],
65
+ combine_type: CombineType = "weighted",
66
+ ) -> None:
67
+ """Add the images of an input to the sums, wherever its weight is positive.
68
+
69
+ Each image contributes ``image * factor``, its weighted image, with weight
70
+ ``weight``, as ``patchwork.weights.weighting`` gives them.
71
+
72
+ Args:
73
+ sums (TileSums): The sums of the region of the tile the input covers
74
+ images (Sequence[NDArray[np.float64]]): The input's images of the group, in the order of the sums
75
+ factor (NDArray[np.float64] | float): What the images are multiplied by to weight them
76
+ weight (NDArray[np.float64]): The weight of the input at every pixel, which is 0 where it does not contribute
77
+ combine_type (CombineType, optional): How the inputs are combined. Defaults to "weighted".
78
+ """
79
+ contributes = np.isfinite(weight) & (weight > 0)
80
+ if combine_type == "weighted":
81
+ multiplier = factor
82
+ else:
83
+ if sums.inverse_weight is None or sums.n_inputs is None:
84
+ msg = f"Sums made for a weighted mean cannot be combined as {combine_type}"
85
+ raise ValueError(msg)
86
+ inverse = np.divide(1.0, weight, out=np.zeros(weight.shape), where=contributes)
87
+ multiplier = factor * inverse
88
+ np.add(sums.inverse_weight, inverse, out=sums.inverse_weight, where=contributes)
89
+ np.add(sums.n_inputs, 1.0, out=sums.n_inputs, where=contributes)
90
+ np.add(sums.weight, weight, out=sums.weight, where=contributes)
91
+
92
+ scaled = np.empty(contributes.shape)
93
+ for total, image in zip(sums.totals, images, strict=True):
94
+ np.multiply(image, multiplier, out=scaled)
95
+ np.add(total, scaled, out=total, where=contributes)
96
+
97
+
98
+ def finalise(
99
+ sums: TileSums, combine_type: CombineType = "weighted"
100
+ ) -> tuple[tuple[NDArray[np.float32], ...], NDArray[np.float32]]:
101
+ """The combined images of a group and their weight, which are NaN where no input contributed.
102
+
103
+ The weighted mean has the summed weight. The plain mean and the sum have the
104
+ inverse of their variance.
105
+
106
+ Args:
107
+ sums (TileSums): The sums over the inputs of a tile
108
+ combine_type (CombineType, optional): How to combine the inputs. Defaults to "weighted".
109
+
110
+ Returns:
111
+ tuple[tuple[NDArray[np.float32], ...], NDArray[np.float32]]: The images, and their weight
112
+ """
113
+
114
+ def blank() -> NDArray[np.float32]:
115
+ return np.full(sums.weight.shape, np.nan, dtype=np.float32)
116
+
117
+ if combine_type == "weighted":
118
+ covered = sums.weight > 0
119
+ images = tuple(
120
+ np.divide(total, sums.weight, out=blank(), where=covered)
121
+ for total in sums.totals
122
+ )
123
+ return images, _filled(sums.weight, covered)
124
+
125
+ if sums.inverse_weight is None or sums.n_inputs is None:
126
+ msg = f"Sums made for a weighted mean cannot be combined as {combine_type}"
127
+ raise ValueError(msg)
128
+ covered = sums.n_inputs > 0
129
+ with np.errstate(divide="ignore", invalid="ignore"):
130
+ if combine_type == "average":
131
+ images = tuple(
132
+ np.divide(total, sums.n_inputs, out=blank(), where=covered)
133
+ for total in sums.totals
134
+ )
135
+ weight = sums.n_inputs**2 / sums.inverse_weight
136
+ else:
137
+ images = tuple(_filled(total, covered) for total in sums.totals)
138
+ weight = 1.0 / sums.inverse_weight
139
+ return images, _filled(weight, covered)
140
+
141
+
142
+ def _filled(
143
+ values: NDArray[np.float64], covered: NDArray[np.bool]
144
+ ) -> NDArray[np.float32]:
145
+ """Values as float32, which are NaN where not covered."""
146
+ return np.where(covered, values, np.nan).astype(np.float32)