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.
- askap_patchwork-0.1.0.dist-info/METADATA +179 -0
- askap_patchwork-0.1.0.dist-info/RECORD +33 -0
- askap_patchwork-0.1.0.dist-info/WHEEL +4 -0
- askap_patchwork-0.1.0.dist-info/entry_points.txt +4 -0
- askap_patchwork-0.1.0.dist-info/licenses/LICENSE +28 -0
- patchwork/__init__.py +11 -0
- patchwork/__main__.py +8 -0
- patchwork/_version.py +24 -0
- patchwork/_version.pyi +2 -0
- patchwork/cli.py +60 -0
- patchwork/combine.py +146 -0
- patchwork/convolve.py +534 -0
- patchwork/coordinates.py +222 -0
- patchwork/frame.py +439 -0
- patchwork/fused.py +618 -0
- patchwork/fused_kernels.py +695 -0
- patchwork/io.py +668 -0
- patchwork/logging.py +62 -0
- patchwork/mosaic.py +546 -0
- patchwork/numba_kernels.py +203 -0
- patchwork/options.py +211 -0
- patchwork/pipeline/__init__.py +3 -0
- patchwork/pipeline/cluster.py +73 -0
- patchwork/pipeline/flow.py +143 -0
- patchwork/plan.py +818 -0
- patchwork/polarisation.py +178 -0
- patchwork/primary_beam.py +636 -0
- patchwork/py.typed +0 -0
- patchwork/resample.py +267 -0
- patchwork/rotate.py +319 -0
- patchwork/tile.py +344 -0
- patchwork/weights.py +175 -0
- patchwork/write.py +502 -0
patchwork/coordinates.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""Sky positions as unit vectors, and the mapping of output pixels onto inputs.
|
|
2
|
+
|
|
3
|
+
Unit vectors behave everywhere on the sphere, including at the poles where RA is
|
|
4
|
+
undefined, so sky geometry is done with them rather than with RA and Dec.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import TYPE_CHECKING, NamedTuple
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
from astropy.wcs.utils import proj_plane_pixel_scales
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from astropy.wcs import WCS
|
|
16
|
+
from numpy.typing import ArrayLike, NDArray
|
|
17
|
+
|
|
18
|
+
from patchwork.io import Slices
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def unit_vectors(ra_deg: ArrayLike, dec_deg: ArrayLike) -> NDArray[np.float64]:
|
|
22
|
+
"""Cartesian unit vectors, along a new leading axis, of sky positions in degrees."""
|
|
23
|
+
ra, dec = np.radians(ra_deg), np.radians(dec_deg)
|
|
24
|
+
return np.array([np.cos(dec) * np.cos(ra), np.cos(dec) * np.sin(ra), np.sin(dec)])
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def ra_dec(
|
|
28
|
+
vectors: NDArray[np.float64],
|
|
29
|
+
) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
|
|
30
|
+
"""The RA and Dec in degrees of unit vectors along the leading axis."""
|
|
31
|
+
x, y, z = vectors
|
|
32
|
+
return np.degrees(np.arctan2(y, x)) % 360, np.degrees(np.arctan2(z, np.hypot(x, y)))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def east_north(
|
|
36
|
+
ra_deg: float, dec_deg: float
|
|
37
|
+
) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
|
|
38
|
+
"""Unit vectors pointing east and north at a sky position."""
|
|
39
|
+
ra, dec = np.radians(ra_deg), np.radians(dec_deg)
|
|
40
|
+
east = np.array([-np.sin(ra), np.cos(ra), 0.0])
|
|
41
|
+
north = np.array(
|
|
42
|
+
[-np.sin(dec) * np.cos(ra), -np.sin(dec) * np.sin(ra), np.cos(dec)]
|
|
43
|
+
)
|
|
44
|
+
return east, north
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def offsets(
|
|
48
|
+
centre: tuple[float, float], vectors: NDArray[np.float64]
|
|
49
|
+
) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
|
|
50
|
+
"""The offsets (east, north) of positions from a centre, as direction cosines."""
|
|
51
|
+
east, north = east_north(*centre)
|
|
52
|
+
return np.tensordot(east, vectors, axes=1), np.tensordot(north, vectors, axes=1)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def offset_vectors(
|
|
56
|
+
centre: tuple[float, float], east: NDArray[np.float64], north: NDArray[np.float64]
|
|
57
|
+
) -> NDArray[np.float64]:
|
|
58
|
+
"""The unit vectors of positions at offsets (east, north) from a centre, as direction cosines, on the centre's side of the sky."""
|
|
59
|
+
east_axis, north_axis = east_north(*centre)
|
|
60
|
+
towards = np.sqrt(np.clip(1 - east**2 - north**2, 0.0, None))
|
|
61
|
+
return np.asarray(
|
|
62
|
+
np.multiply.outer(unit_vectors(*centre), towards)
|
|
63
|
+
+ np.multiply.outer(east_axis, east)
|
|
64
|
+
+ np.multiply.outer(north_axis, north)
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _linear_weights(
|
|
69
|
+
positions: NDArray[np.float64], nodes: NDArray[np.float64]
|
|
70
|
+
) -> NDArray[np.float64]:
|
|
71
|
+
"""The matrix that linearly interpolates values on nodes onto positions."""
|
|
72
|
+
return np.stack(
|
|
73
|
+
[np.interp(positions, nodes, column) for column in np.eye(len(nodes))], axis=1
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _between_nodes(
|
|
78
|
+
y_weights: NDArray[np.float64],
|
|
79
|
+
values: NDArray[np.float64],
|
|
80
|
+
x_weights: NDArray[np.float64],
|
|
81
|
+
) -> NDArray[np.float64]:
|
|
82
|
+
"""Interpolate values on a grid of nodes, shaped (..., ny_nodes, nx_nodes), with weight matrices."""
|
|
83
|
+
return np.asarray(y_weights @ values @ x_weights.T)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _nodes(start: int, stop: int, step: int) -> NDArray[np.float64]:
|
|
87
|
+
"""Positions every ``step`` pixels from ``start``, always including the last pixel."""
|
|
88
|
+
return np.unique(np.append(np.arange(start, stop, step), stop - 1)).astype(
|
|
89
|
+
np.float64
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _between(nodes: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
94
|
+
"""Positions halfway between nodes, where interpolation is checked, or the node itself when there is only one."""
|
|
95
|
+
return (nodes[:-1] + nodes[1:]) / 2 if len(nodes) > 1 else nodes
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _normalised(vectors: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
99
|
+
"""Vectors along the leading axis scaled to unit length."""
|
|
100
|
+
return np.asarray(vectors / np.linalg.norm(vectors, axis=0))
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class TileCoordinates(NamedTuple):
|
|
104
|
+
"""The sky positions of the pixels of a tile, and what is needed to map them onto inputs.
|
|
105
|
+
|
|
106
|
+
Coordinates are found exactly on a coarse grid of nodes and interpolated
|
|
107
|
+
between them, which is far cheaper than a full transform per pixel. The
|
|
108
|
+
interpolation is checked halfway between the nodes, and every pixel is
|
|
109
|
+
transformed exactly where it misses by more than the tolerance.
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
vectors: NDArray[np.float64]
|
|
113
|
+
"""Unit vectors of every pixel of the tile, shaped (3, ny, nx)"""
|
|
114
|
+
node_world: NDArray[np.float64]
|
|
115
|
+
"""The (RA, Dec) of the nodes, shaped (2, ny_nodes, nx_nodes)"""
|
|
116
|
+
check_world: NDArray[np.float64]
|
|
117
|
+
"""The (RA, Dec) between the nodes, where the interpolation is checked"""
|
|
118
|
+
y_weights: NDArray[np.float64]
|
|
119
|
+
"""Interpolates node rows onto the rows of the tile"""
|
|
120
|
+
x_weights: NDArray[np.float64]
|
|
121
|
+
"""Interpolates node columns onto the columns of the tile"""
|
|
122
|
+
y_check_weights: NDArray[np.float64]
|
|
123
|
+
"""Interpolates node rows onto the rows between them"""
|
|
124
|
+
x_check_weights: NDArray[np.float64]
|
|
125
|
+
"""Interpolates node columns onto the columns between them"""
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def tile_coordinates(
|
|
129
|
+
wcs: WCS, tile: Slices, step: int = 16, tolerance: float = 1e-3
|
|
130
|
+
) -> TileCoordinates:
|
|
131
|
+
"""Find the sky positions of the pixels of a tile of a frame.
|
|
132
|
+
|
|
133
|
+
Args:
|
|
134
|
+
wcs (WCS): Celestial WCS of the frame
|
|
135
|
+
tile (Slices): The (y, x) region of the frame
|
|
136
|
+
step (int, optional): Spacing in pixels of the nodes the coordinates are found exactly on. 1 finds every pixel exactly. Defaults to 16.
|
|
137
|
+
tolerance (float, optional): Largest error in pixels of the frame of interpolated positions. Defaults to 1e-3.
|
|
138
|
+
|
|
139
|
+
Returns:
|
|
140
|
+
TileCoordinates: The coordinates of the tile
|
|
141
|
+
"""
|
|
142
|
+
ys, xs = tile
|
|
143
|
+
y_pixels = np.arange(ys.start, ys.stop, dtype=np.float64)
|
|
144
|
+
x_pixels = np.arange(xs.start, xs.stop, dtype=np.float64)
|
|
145
|
+
y_nodes = _nodes(ys.start, ys.stop, max(step, 1))
|
|
146
|
+
x_nodes = _nodes(xs.start, xs.stop, max(step, 1))
|
|
147
|
+
y_check, x_check = _between(y_nodes), _between(x_nodes)
|
|
148
|
+
|
|
149
|
+
node_world = np.array(wcs.pixel_to_world_values(*np.meshgrid(x_nodes, y_nodes)))
|
|
150
|
+
check_world = np.array(wcs.pixel_to_world_values(*np.meshgrid(x_check, y_check)))
|
|
151
|
+
y_weights = _linear_weights(y_pixels, y_nodes)
|
|
152
|
+
x_weights = _linear_weights(x_pixels, x_nodes)
|
|
153
|
+
y_check_weights = _linear_weights(y_check, y_nodes)
|
|
154
|
+
x_check_weights = _linear_weights(x_check, x_nodes)
|
|
155
|
+
|
|
156
|
+
vectors = None
|
|
157
|
+
if (
|
|
158
|
+
step > 1
|
|
159
|
+
and np.all(np.isfinite(node_world))
|
|
160
|
+
and np.all(np.isfinite(check_world))
|
|
161
|
+
):
|
|
162
|
+
node_vectors = unit_vectors(*node_world)
|
|
163
|
+
predicted = _normalised(
|
|
164
|
+
_between_nodes(y_check_weights, node_vectors, x_check_weights)
|
|
165
|
+
)
|
|
166
|
+
# The chord between unit vectors is their separation in radians
|
|
167
|
+
error = np.linalg.norm(predicted - unit_vectors(*check_world), axis=0)
|
|
168
|
+
pixel_rad = np.radians(np.min(proj_plane_pixel_scales(wcs)))
|
|
169
|
+
if np.max(error) <= tolerance * pixel_rad:
|
|
170
|
+
vectors = _normalised(_between_nodes(y_weights, node_vectors, x_weights))
|
|
171
|
+
if vectors is None:
|
|
172
|
+
world = np.array(wcs.pixel_to_world_values(*np.meshgrid(x_pixels, y_pixels)))
|
|
173
|
+
vectors = unit_vectors(*world)
|
|
174
|
+
|
|
175
|
+
return TileCoordinates(
|
|
176
|
+
vectors=vectors,
|
|
177
|
+
node_world=node_world,
|
|
178
|
+
check_world=check_world,
|
|
179
|
+
y_weights=y_weights,
|
|
180
|
+
x_weights=x_weights,
|
|
181
|
+
y_check_weights=y_check_weights,
|
|
182
|
+
x_check_weights=x_check_weights,
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def map_to_input(
|
|
187
|
+
coordinates: TileCoordinates,
|
|
188
|
+
wcs: WCS,
|
|
189
|
+
region: Slices,
|
|
190
|
+
tolerance: float = 1e-3,
|
|
191
|
+
) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
|
|
192
|
+
"""The pixel positions in an input of a region of a tile.
|
|
193
|
+
|
|
194
|
+
The positions are interpolated from the nodes of the tile, unless that
|
|
195
|
+
misses the exact positions between the nodes by more than ``tolerance``
|
|
196
|
+
pixels, or the input cannot be reached from every node, in which case every
|
|
197
|
+
pixel is found exactly.
|
|
198
|
+
|
|
199
|
+
Args:
|
|
200
|
+
coordinates (TileCoordinates): The coordinates of the tile
|
|
201
|
+
wcs (WCS): Celestial WCS of the input
|
|
202
|
+
region (Slices): The (y, x) region of the tile, relative to the tile
|
|
203
|
+
tolerance (float, optional): Largest error in pixels of interpolated positions. Defaults to 1e-3.
|
|
204
|
+
|
|
205
|
+
Returns:
|
|
206
|
+
tuple[NDArray[np.float64], NDArray[np.float64]]: Zero-based x and y positions in the input
|
|
207
|
+
"""
|
|
208
|
+
rows, columns = region
|
|
209
|
+
nodes = np.array(wcs.world_to_pixel_values(*coordinates.node_world))
|
|
210
|
+
if np.all(np.isfinite(nodes)) and coordinates.check_world.size:
|
|
211
|
+
exact = np.array(wcs.world_to_pixel_values(*coordinates.check_world))
|
|
212
|
+
predicted = _between_nodes(
|
|
213
|
+
coordinates.y_check_weights, nodes, coordinates.x_check_weights
|
|
214
|
+
)
|
|
215
|
+
if np.max(np.abs(predicted - exact)) <= tolerance:
|
|
216
|
+
x, y = _between_nodes(
|
|
217
|
+
coordinates.y_weights[rows], nodes, coordinates.x_weights[columns]
|
|
218
|
+
)
|
|
219
|
+
return x, y
|
|
220
|
+
|
|
221
|
+
x, y = wcs.world_to_pixel_values(*ra_dec(coordinates.vectors[:, rows, columns]))
|
|
222
|
+
return np.asarray(x), np.asarray(y)
|
patchwork/frame.py
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
"""The output frame of a mosaic: its pixel grid, coordinates and tiles"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from argparse import ArgumentParser, Namespace
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import TYPE_CHECKING, Literal, NamedTuple
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
from astropy.io import fits
|
|
11
|
+
from astropy.wcs import WCS
|
|
12
|
+
from astropy.wcs.utils import proj_plane_pixel_area
|
|
13
|
+
from capn_crunch import add_options_to_parser, create_options_from_parser
|
|
14
|
+
|
|
15
|
+
from patchwork.coordinates import east_north, offsets, ra_dec, unit_vectors
|
|
16
|
+
from patchwork.io import Slices, celestial_wcs, read_image_info, spectral_axis
|
|
17
|
+
from patchwork.logging import logger, setup_logging
|
|
18
|
+
from patchwork.options import FrameOptions
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from numpy.typing import NDArray
|
|
22
|
+
|
|
23
|
+
from patchwork.io import ImageInfo
|
|
24
|
+
|
|
25
|
+
BoundingBox = tuple[int, int, int, int]
|
|
26
|
+
"""A (y_low, y_high, x_low, x_high) inclusive region of the frame in pixels"""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Frame(NamedTuple):
|
|
30
|
+
"""The pixel grid of a mosaic"""
|
|
31
|
+
|
|
32
|
+
wcs: WCS
|
|
33
|
+
"""Celestial WCS of the frame"""
|
|
34
|
+
shape: tuple[int, int]
|
|
35
|
+
"""The (ny, nx) shape of the frame"""
|
|
36
|
+
|
|
37
|
+
def header(
|
|
38
|
+
self, reference: fits.Header | None = None, channels: slice | None = None
|
|
39
|
+
) -> fits.Header:
|
|
40
|
+
"""The header of the frame, keeping the non-celestial axes of a reference header.
|
|
41
|
+
|
|
42
|
+
Those axes are made a single pixel long, except a FREQ axis when
|
|
43
|
+
``channels`` are given, which then holds those channels.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
reference (fits.Header | None, optional): Header whose non-celestial axes are kept. Defaults to None.
|
|
47
|
+
channels (slice | None, optional): The channels of the reference FREQ axis the frame holds. Defaults to None, a single plane.
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
fits.Header: The header
|
|
51
|
+
"""
|
|
52
|
+
extra_axes = [] if reference is None else list(range(3, reference["NAXIS"] + 1))
|
|
53
|
+
spectral = (
|
|
54
|
+
None if reference is None or channels is None else spectral_axis(reference)
|
|
55
|
+
)
|
|
56
|
+
header = fits.Header()
|
|
57
|
+
header["NAXIS"] = 2 + len(extra_axes)
|
|
58
|
+
header["NAXIS1"] = self.shape[1]
|
|
59
|
+
header["NAXIS2"] = self.shape[0]
|
|
60
|
+
for axis in extra_axes:
|
|
61
|
+
header[f"NAXIS{axis}"] = 1
|
|
62
|
+
|
|
63
|
+
header.update(self.wcs.to_header())
|
|
64
|
+
header["WCSAXES"] = header["NAXIS"]
|
|
65
|
+
if reference is None:
|
|
66
|
+
return header
|
|
67
|
+
|
|
68
|
+
keys = [
|
|
69
|
+
f"{key}{axis}"
|
|
70
|
+
for axis in extra_axes
|
|
71
|
+
for key in ("CTYPE", "CRVAL", "CDELT", "CRPIX", "CUNIT")
|
|
72
|
+
]
|
|
73
|
+
for key in (*keys, "RESTFRQ", "SPECSYS"):
|
|
74
|
+
if key in reference:
|
|
75
|
+
header[key] = reference[key]
|
|
76
|
+
if spectral is not None and channels is not None:
|
|
77
|
+
start, stop, _ = channels.indices(int(reference[f"NAXIS{spectral}"]))
|
|
78
|
+
header[f"NAXIS{spectral}"] = stop - start
|
|
79
|
+
header[f"CRPIX{spectral}"] = reference.get(f"CRPIX{spectral}", 1.0) - start
|
|
80
|
+
return header
|
|
81
|
+
|
|
82
|
+
def crop(self, box: BoundingBox) -> Frame:
|
|
83
|
+
"""The part of the frame within a bounding box, on the same grid."""
|
|
84
|
+
wcs = self.wcs.deepcopy()
|
|
85
|
+
wcs.wcs.crpix = wcs.wcs.crpix - [box[2], box[0]]
|
|
86
|
+
wcs.wcs.set()
|
|
87
|
+
return Frame(wcs=wcs, shape=(box[1] - box[0] + 1, box[3] - box[2] + 1))
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def union_of_boxes(boxes: list[BoundingBox | None]) -> BoundingBox | None:
|
|
91
|
+
"""The smallest bounding box that holds every box, or None if there are none."""
|
|
92
|
+
present = [box for box in boxes if box is not None]
|
|
93
|
+
if not present:
|
|
94
|
+
return None
|
|
95
|
+
return (
|
|
96
|
+
min(box[0] for box in present),
|
|
97
|
+
max(box[1] for box in present),
|
|
98
|
+
min(box[2] for box in present),
|
|
99
|
+
max(box[3] for box in present),
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def shift_box(box: BoundingBox | None, origin: BoundingBox) -> BoundingBox | None:
|
|
104
|
+
"""A bounding box relative to the corner of another."""
|
|
105
|
+
if box is None:
|
|
106
|
+
return None
|
|
107
|
+
return (
|
|
108
|
+
box[0] - origin[0],
|
|
109
|
+
box[1] - origin[0],
|
|
110
|
+
box[2] - origin[2],
|
|
111
|
+
box[3] - origin[2],
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def boundary_pixels(shape: tuple[int, int], samples: int = 32) -> NDArray[np.float64]:
|
|
116
|
+
"""Zero-based (x, y) pixels along the outer edges of an image, with ``samples`` per edge."""
|
|
117
|
+
ny, nx = shape
|
|
118
|
+
xs = np.linspace(-0.5, nx - 0.5, samples)
|
|
119
|
+
ys = np.linspace(-0.5, ny - 0.5, samples)
|
|
120
|
+
x = np.concatenate([xs, xs, np.full(samples, -0.5), np.full(samples, nx - 0.5)])
|
|
121
|
+
y = np.concatenate([np.full(samples, -0.5), np.full(samples, ny - 0.5), ys, ys])
|
|
122
|
+
return np.array([x, y])
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def footprint_world(info: ImageInfo) -> NDArray[np.float64]:
|
|
126
|
+
"""The (RA, Dec) in degrees along the edges of an image."""
|
|
127
|
+
x, y = boundary_pixels(info.shape)
|
|
128
|
+
return np.array(info.wcs.pixel_to_world_values(x, y))
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def image_centre(info: ImageInfo) -> tuple[float, float]:
|
|
132
|
+
"""The (RA, Dec) in degrees of the central pixel of an image."""
|
|
133
|
+
ny, nx = info.shape
|
|
134
|
+
ra, dec = info.wcs.pixel_to_world_values(nx // 2, ny // 2)
|
|
135
|
+
return float(ra), float(dec)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def central_index(infos: list[ImageInfo]) -> int:
|
|
139
|
+
"""The index of the input whose centre is nearest the mean centre of all inputs."""
|
|
140
|
+
centres = np.array([image_centre(info) for info in infos])
|
|
141
|
+
vectors = unit_vectors(centres[:, 0], centres[:, 1])
|
|
142
|
+
mean = np.mean(vectors, axis=1)
|
|
143
|
+
return int(np.argmax(mean @ vectors))
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def new_wcs(
|
|
147
|
+
centre: tuple[float, float], pixel_scale_deg: float, projection: str = "SIN"
|
|
148
|
+
) -> WCS:
|
|
149
|
+
"""A north-up celestial WCS centred on a position, with its reference pixel at the origin."""
|
|
150
|
+
wcs = WCS(naxis=2)
|
|
151
|
+
wcs.wcs.ctype = [f"RA---{projection}", f"DEC--{projection}"]
|
|
152
|
+
wcs.wcs.crval = [centre[0] % 360, centre[1]]
|
|
153
|
+
wcs.wcs.cdelt = [-pixel_scale_deg, pixel_scale_deg]
|
|
154
|
+
wcs.wcs.crpix = [1.0, 1.0]
|
|
155
|
+
wcs.wcs.radesys = "ICRS"
|
|
156
|
+
wcs.wcs.set()
|
|
157
|
+
return wcs
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def cover_inputs(wcs: WCS, infos: list[ImageInfo]) -> Frame:
|
|
161
|
+
"""Shift and size a WCS so that its frame just covers every input."""
|
|
162
|
+
pixels = np.concatenate(
|
|
163
|
+
[np.array(wcs.world_to_pixel_values(*footprint_world(info))) for info in infos],
|
|
164
|
+
axis=1,
|
|
165
|
+
)
|
|
166
|
+
pixels = pixels[:, np.all(np.isfinite(pixels), axis=0)]
|
|
167
|
+
# Edges that land on pixel edges only through round-off do not add a pixel
|
|
168
|
+
x_low, y_low = np.floor(np.min(pixels, axis=1) + 0.5 + 1e-6).astype(int)
|
|
169
|
+
x_high, y_high = np.ceil(np.max(pixels, axis=1) - 0.5 - 1e-6).astype(int)
|
|
170
|
+
|
|
171
|
+
wcs = wcs.deepcopy()
|
|
172
|
+
wcs.wcs.crpix = wcs.wcs.crpix - [x_low, y_low]
|
|
173
|
+
wcs.wcs.set()
|
|
174
|
+
return Frame(wcs=wcs, shape=(int(y_high - y_low + 1), int(x_high - x_low + 1)))
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def reference_frame(
|
|
178
|
+
infos: list[ImageInfo],
|
|
179
|
+
reference_index: int | None = None,
|
|
180
|
+
centre: tuple[float, float] | None = None,
|
|
181
|
+
projection: str = "SIN",
|
|
182
|
+
) -> Frame:
|
|
183
|
+
"""A frame on the pixel grid of one input that covers every input.
|
|
184
|
+
|
|
185
|
+
The grid is that of ``reference_index``, or of the central input. Given a
|
|
186
|
+
``centre``, a north-up grid with the pixel scale of the reference input is
|
|
187
|
+
centred there instead.
|
|
188
|
+
|
|
189
|
+
Args:
|
|
190
|
+
infos (list[ImageInfo]): The inputs to cover
|
|
191
|
+
reference_index (int | None, optional): The input whose grid is used. Defaults to None, the central input.
|
|
192
|
+
centre (tuple[float, float] | None, optional): (RA, Dec) in degrees of a new frame centre. Defaults to None.
|
|
193
|
+
projection (str, optional): Projection used when ``centre`` is given. Defaults to "SIN".
|
|
194
|
+
|
|
195
|
+
Returns:
|
|
196
|
+
Frame: The frame of the mosaic
|
|
197
|
+
"""
|
|
198
|
+
index = central_index(infos) if reference_index is None else reference_index
|
|
199
|
+
logger.info(f"Using the grid of {infos[index].path}")
|
|
200
|
+
wcs = infos[index].wcs.deepcopy()
|
|
201
|
+
if centre is not None:
|
|
202
|
+
scale = float(np.sqrt(proj_plane_pixel_area(wcs)))
|
|
203
|
+
wcs = new_wcs(centre=centre, pixel_scale_deg=scale, projection=projection)
|
|
204
|
+
return cover_inputs(wcs=wcs, infos=infos)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _most_covered_range(
|
|
208
|
+
lows: NDArray[np.float64], highs: NDArray[np.float64]
|
|
209
|
+
) -> tuple[float, float]:
|
|
210
|
+
"""The range most inputs cover along one axis: the lower and upper edges that the most inputs reach past, counting an input once for starting below an edge and once for ending above it."""
|
|
211
|
+
count_low = np.sum(lows[:, None] > lows[None, :], axis=1) + np.sum(
|
|
212
|
+
highs[None, :] > lows[:, None], axis=1
|
|
213
|
+
)
|
|
214
|
+
count_high = np.sum(highs[None, :] > highs[:, None], axis=1) + np.sum(
|
|
215
|
+
highs[:, None] > lows[None, :], axis=1
|
|
216
|
+
)
|
|
217
|
+
return float(lows[np.argmax(count_low)]), float(highs[np.argmax(count_high)])
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def fitted_centre(
|
|
221
|
+
infos: list[ImageInfo], centre_type: Literal["all", "most"] = "all"
|
|
222
|
+
) -> tuple[float, float]:
|
|
223
|
+
"""The centre of a fitted frame: the middle of all inputs, or of the region most of them cover.
|
|
224
|
+
|
|
225
|
+
Ranges of RA and Dec break down towards a pole, where an input can span
|
|
226
|
+
every RA. The ranges are instead those of offsets in a plane tangent to the
|
|
227
|
+
sky at the mean centre of the inputs, which behave the same everywhere on
|
|
228
|
+
the sky.
|
|
229
|
+
|
|
230
|
+
Args:
|
|
231
|
+
infos (list[ImageInfo]): The inputs
|
|
232
|
+
centre_type (Literal["all", "most"], optional): Centre on all inputs, or on the region most of them cover. Defaults to "all".
|
|
233
|
+
|
|
234
|
+
Returns:
|
|
235
|
+
tuple[float, float]: The (RA, Dec) of the centre in degrees
|
|
236
|
+
"""
|
|
237
|
+
centres = unit_vectors(*np.array([image_centre(info) for info in infos]).T)
|
|
238
|
+
mean = np.mean(centres, axis=1)
|
|
239
|
+
tangent_ra, tangent_dec = ra_dec(mean / np.linalg.norm(mean))
|
|
240
|
+
tangent_point = (float(tangent_ra), float(tangent_dec))
|
|
241
|
+
|
|
242
|
+
footprints = [
|
|
243
|
+
np.array(offsets(tangent_point, unit_vectors(*footprint_world(info))))
|
|
244
|
+
for info in infos
|
|
245
|
+
]
|
|
246
|
+
lows = np.array([np.min(footprint, axis=1) for footprint in footprints])
|
|
247
|
+
highs = np.array([np.max(footprint, axis=1) for footprint in footprints])
|
|
248
|
+
if centre_type == "all":
|
|
249
|
+
east, north = (np.min(lows, axis=0) + np.max(highs, axis=0)) / 2
|
|
250
|
+
else:
|
|
251
|
+
east, north = (
|
|
252
|
+
np.mean(_most_covered_range(lows[:, axis], highs[:, axis]))
|
|
253
|
+
for axis in range(2)
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
east_vector, north_vector = east_north(*tangent_point)
|
|
257
|
+
centre = (
|
|
258
|
+
east * east_vector
|
|
259
|
+
+ north * north_vector
|
|
260
|
+
+ np.sqrt(max(1 - east**2 - north**2, 0.0)) * unit_vectors(*tangent_point)
|
|
261
|
+
)
|
|
262
|
+
ra, dec = ra_dec(centre)
|
|
263
|
+
return float(ra), float(dec)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def fitted_frame(infos: list[ImageInfo], options: FrameOptions) -> Frame:
|
|
267
|
+
"""A new north-up frame fitted to every input.
|
|
268
|
+
|
|
269
|
+
The pixel scale is the median, minimum or maximum of the input pixel scales,
|
|
270
|
+
and the centre is the middle of all inputs or of the region most of them
|
|
271
|
+
cover (see ``fitted_centre``). Unless an image size is given the frame is
|
|
272
|
+
sized to cover every input.
|
|
273
|
+
|
|
274
|
+
Args:
|
|
275
|
+
infos (list[ImageInfo]): The inputs to cover
|
|
276
|
+
options (FrameOptions): How the frame is fitted
|
|
277
|
+
|
|
278
|
+
Returns:
|
|
279
|
+
Frame: The frame of the mosaic
|
|
280
|
+
"""
|
|
281
|
+
if options.pixel_scale_arcsec is not None:
|
|
282
|
+
scale = options.pixel_scale_arcsec / 3600
|
|
283
|
+
else:
|
|
284
|
+
scales = [float(np.sqrt(proj_plane_pixel_area(info.wcs))) for info in infos]
|
|
285
|
+
percentile = {"min": 0, "median": 50, "max": 100}[options.pixel_scale_type]
|
|
286
|
+
scale = float(np.percentile(scales, percentile))
|
|
287
|
+
|
|
288
|
+
centre = options.centre or fitted_centre(infos, options.centre_type)
|
|
289
|
+
logger.info(
|
|
290
|
+
f"Fitted frame centred on {centre} with {scale * 3600:.3f} arcsec pixels"
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
wcs = new_wcs(centre=centre, pixel_scale_deg=scale, projection=options.projection)
|
|
294
|
+
if options.image_size is None:
|
|
295
|
+
return cover_inputs(wcs=wcs, infos=infos)
|
|
296
|
+
|
|
297
|
+
nx, ny = options.image_size
|
|
298
|
+
wcs.wcs.crpix = [(nx + 1) / 2, (ny + 1) / 2]
|
|
299
|
+
wcs.wcs.set()
|
|
300
|
+
return Frame(wcs=wcs, shape=(ny, nx))
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def frame_from_header(header: fits.Header | str | Path) -> Frame:
|
|
304
|
+
"""The frame described by a FITS header, or by the header of a FITS file."""
|
|
305
|
+
if not isinstance(header, fits.Header):
|
|
306
|
+
header = fits.getheader(header)
|
|
307
|
+
return Frame(
|
|
308
|
+
wcs=celestial_wcs(header), shape=(int(header["NAXIS2"]), int(header["NAXIS1"]))
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def build_frame(infos: list[ImageInfo], options: FrameOptions) -> Frame:
|
|
313
|
+
"""The frame of a mosaic of the inputs."""
|
|
314
|
+
if options.frame_type == "fit":
|
|
315
|
+
return fitted_frame(infos=infos, options=options)
|
|
316
|
+
return reference_frame(
|
|
317
|
+
infos=infos,
|
|
318
|
+
reference_index=options.reference_index,
|
|
319
|
+
centre=options.centre,
|
|
320
|
+
projection=options.projection,
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def world_bounding_box(
|
|
325
|
+
frame: Frame, world: NDArray[np.float64], margin: int = 2
|
|
326
|
+
) -> BoundingBox | None:
|
|
327
|
+
"""The region of the frame that encloses (RA, Dec) points, grown by a margin, or None if it misses the frame."""
|
|
328
|
+
pixels = np.array(frame.wcs.world_to_pixel_values(*world))
|
|
329
|
+
pixels = pixels[:, np.all(np.isfinite(pixels), axis=0)]
|
|
330
|
+
if pixels.size == 0:
|
|
331
|
+
return None
|
|
332
|
+
|
|
333
|
+
ny, nx = frame.shape
|
|
334
|
+
x_low, y_low = np.floor(np.min(pixels, axis=1)).astype(int) - margin
|
|
335
|
+
x_high, y_high = np.ceil(np.max(pixels, axis=1)).astype(int) + margin
|
|
336
|
+
box = (
|
|
337
|
+
max(int(y_low), 0),
|
|
338
|
+
min(int(y_high), ny - 1),
|
|
339
|
+
max(int(x_low), 0),
|
|
340
|
+
min(int(x_high), nx - 1),
|
|
341
|
+
)
|
|
342
|
+
if box[0] > box[1] or box[2] > box[3]:
|
|
343
|
+
return None
|
|
344
|
+
return box
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def input_bounding_box(
|
|
348
|
+
frame: Frame, info: ImageInfo, margin: int = 2
|
|
349
|
+
) -> BoundingBox | None:
|
|
350
|
+
"""The region of the frame an input covers, grown by a margin, or None if it covers none of it."""
|
|
351
|
+
return world_bounding_box(frame, footprint_world(info), margin=margin)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def intersect_boxes(
|
|
355
|
+
first: BoundingBox | None, second: BoundingBox | None
|
|
356
|
+
) -> BoundingBox | None:
|
|
357
|
+
"""The region two bounding boxes share, or None if they share none."""
|
|
358
|
+
if first is None or second is None:
|
|
359
|
+
return None
|
|
360
|
+
box = (
|
|
361
|
+
max(first[0], second[0]),
|
|
362
|
+
min(first[1], second[1]),
|
|
363
|
+
max(first[2], second[2]),
|
|
364
|
+
min(first[3], second[3]),
|
|
365
|
+
)
|
|
366
|
+
if box[0] > box[1] or box[2] > box[3]:
|
|
367
|
+
return None
|
|
368
|
+
return box
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def tiles(frame: Frame, tile_size: int = 512) -> list[Slices]:
|
|
372
|
+
"""Split a frame into square (y, x) tiles of up to ``tile_size`` pixels."""
|
|
373
|
+
ny, nx = frame.shape
|
|
374
|
+
return [
|
|
375
|
+
(slice(y, min(y + tile_size, ny)), slice(x, min(x + tile_size, nx)))
|
|
376
|
+
for y in range(0, ny, tile_size)
|
|
377
|
+
for x in range(0, nx, tile_size)
|
|
378
|
+
]
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def strips(frame: Frame, tile_size: int = 512) -> list[Slices]:
|
|
382
|
+
"""Split a frame into strips of whole rows, each about as large as a square tile of ``tile_size`` pixels.
|
|
383
|
+
|
|
384
|
+
Each strip of a channel is one run of bytes in a FITS file, so tasks
|
|
385
|
+
writing neighbouring strips share at most the blocks at their ends.
|
|
386
|
+
"""
|
|
387
|
+
ny, nx = frame.shape
|
|
388
|
+
rows = max(1, -(-(tile_size**2) // nx))
|
|
389
|
+
return [(slice(y, min(y + rows, ny)), slice(0, nx)) for y in range(0, ny, rows)]
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def tile_region(tile: Slices, box: BoundingBox | None) -> Slices | None:
|
|
393
|
+
"""The part of a tile within a bounding box, relative to the tile, or None if they share no pixels."""
|
|
394
|
+
if box is None:
|
|
395
|
+
return None
|
|
396
|
+
ys, xs = tile
|
|
397
|
+
y_low, y_high = max(ys.start, box[0]), min(ys.stop - 1, box[1])
|
|
398
|
+
x_low, x_high = max(xs.start, box[2]), min(xs.stop - 1, box[3])
|
|
399
|
+
if y_low > y_high or x_low > x_high:
|
|
400
|
+
return None
|
|
401
|
+
return (
|
|
402
|
+
slice(y_low - ys.start, y_high - ys.start + 1),
|
|
403
|
+
slice(x_low - xs.start, x_high - xs.start + 1),
|
|
404
|
+
)
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def get_parser(parser: ArgumentParser | None = None) -> ArgumentParser:
|
|
408
|
+
"""The parser of the ``frame`` command."""
|
|
409
|
+
if parser is None:
|
|
410
|
+
parser = ArgumentParser(
|
|
411
|
+
description="Construct the output frame of a mosaic without making it"
|
|
412
|
+
)
|
|
413
|
+
parser.add_argument(
|
|
414
|
+
"images", nargs="+", type=Path, help="The images the frame covers"
|
|
415
|
+
)
|
|
416
|
+
parser.add_argument(
|
|
417
|
+
"--output",
|
|
418
|
+
type=Path,
|
|
419
|
+
default=None,
|
|
420
|
+
help="Text file the frame header is written to. If not given it is printed",
|
|
421
|
+
)
|
|
422
|
+
return add_options_to_parser(parser=parser, options_class=FrameOptions)
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def cli(args: Namespace | None = None) -> None:
|
|
426
|
+
"""Run the ``frame`` command."""
|
|
427
|
+
setup_logging()
|
|
428
|
+
args = get_parser().parse_args() if args is None else args
|
|
429
|
+
infos = [read_image_info(image) for image in args.images]
|
|
430
|
+
frame = build_frame(
|
|
431
|
+
infos,
|
|
432
|
+
create_options_from_parser(parser_namespace=args, options_class=FrameOptions),
|
|
433
|
+
)
|
|
434
|
+
header = frame.header(infos[0].header)
|
|
435
|
+
if args.output is None:
|
|
436
|
+
logger.info(f"Frame header:\n{header.tostring(sep=chr(10)).strip()}")
|
|
437
|
+
else:
|
|
438
|
+
header.totextfile(args.output, overwrite=True)
|
|
439
|
+
logger.info(f"Written the frame header to {args.output}")
|