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
|
@@ -0,0 +1,636 @@
|
|
|
1
|
+
"""Primary beam models that weight each input"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import functools
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import TYPE_CHECKING, Any, NamedTuple
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
from astropy.constants import c as speed_of_light
|
|
11
|
+
from astropy.io import fits
|
|
12
|
+
from scipy.ndimage import map_coordinates
|
|
13
|
+
|
|
14
|
+
from patchwork.coordinates import offsets, unit_vectors
|
|
15
|
+
from patchwork.logging import logger
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from numpy.typing import ArrayLike, NDArray
|
|
19
|
+
|
|
20
|
+
from patchwork.io import ImageInfo
|
|
21
|
+
from patchwork.options import PrimaryBeamOptions
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def direction_cosines(
|
|
25
|
+
ra0_deg: float, dec0_deg: float, ra_deg: ArrayLike, dec_deg: ArrayLike
|
|
26
|
+
) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
|
|
27
|
+
"""The offsets (l to the east, m to the north) of sky positions from a centre, as direction cosines."""
|
|
28
|
+
return offsets((ra0_deg, dec0_deg), unit_vectors(ra_deg, dec_deg))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class GaussianBeam(NamedTuple):
|
|
32
|
+
"""A circular Gaussian primary beam"""
|
|
33
|
+
|
|
34
|
+
fwhm_rad: float
|
|
35
|
+
"""Full width at half maximum in radians"""
|
|
36
|
+
|
|
37
|
+
def response(
|
|
38
|
+
self, east: NDArray[np.float64], north: NDArray[np.float64]
|
|
39
|
+
) -> NDArray[np.float64]:
|
|
40
|
+
"""The response at offsets from the beam centre, given as direction cosines."""
|
|
41
|
+
offset = np.arcsin(np.clip(np.hypot(east, north), 0.0, 1.0))
|
|
42
|
+
return np.asarray(np.exp(-4 * np.log(2) * offset**2 / self.fwhm_rad**2))
|
|
43
|
+
|
|
44
|
+
def support_radius(self, cutoff: float) -> float | None:
|
|
45
|
+
"""The offset in radians beyond which the response is below ``cutoff``, or None if it never is."""
|
|
46
|
+
if cutoff <= 0:
|
|
47
|
+
return None
|
|
48
|
+
return float(
|
|
49
|
+
self.fwhm_rad * np.sqrt(np.log(1 / min(cutoff, 1.0)) / (4 * np.log(2)))
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class PatternTaps(NamedTuple):
|
|
54
|
+
"""Where positions fall on the grid of a holography cube: the four pixels around each, and their weights in linear interpolation"""
|
|
55
|
+
|
|
56
|
+
indices: NDArray[np.intp]
|
|
57
|
+
"""Flat indices into the grid of the four pixels around each position, shaped (4, n)"""
|
|
58
|
+
weights: NDArray[np.float64]
|
|
59
|
+
"""The weight of each of the four pixels, shaped (4, n), which is 0 for positions off the grid"""
|
|
60
|
+
shape: tuple[int, ...]
|
|
61
|
+
"""The shape of the positions"""
|
|
62
|
+
|
|
63
|
+
def sample(self, plane: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
64
|
+
"""Interpolate a plane of the grid at the positions."""
|
|
65
|
+
flat = plane.ravel()
|
|
66
|
+
values = self.weights[0] * flat[self.indices[0]]
|
|
67
|
+
for tap in range(1, 4):
|
|
68
|
+
values += self.weights[tap] * flat[self.indices[tap]]
|
|
69
|
+
return np.asarray(values.reshape(self.shape), dtype=np.float64)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def bilinear_taps(
|
|
73
|
+
pixels: NDArray[np.float64], grid_shape: tuple[int, ...], shape: tuple[int, ...]
|
|
74
|
+
) -> PatternTaps:
|
|
75
|
+
"""The taps that interpolate a grid linearly at (y, x) pixels, as ``scipy.ndimage.map_coordinates`` does with ``order=1`` and ``mode="constant"``.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
pixels (NDArray[np.float64]): Zero-based (y, x) positions, shaped (2, n)
|
|
79
|
+
grid_shape (tuple[int, ...]): The (ny, nx) shape of the grid
|
|
80
|
+
shape (tuple[int, ...]): The shape the n positions take
|
|
81
|
+
|
|
82
|
+
Returns:
|
|
83
|
+
PatternTaps: The taps, which give 0 for positions off the grid
|
|
84
|
+
"""
|
|
85
|
+
ny, nx = grid_shape
|
|
86
|
+
y, x = pixels
|
|
87
|
+
on_grid = (y >= 0) & (y <= ny - 1) & (x >= 0) & (x <= nx - 1)
|
|
88
|
+
y, x = np.where(on_grid, y, 0.0), np.where(on_grid, x, 0.0)
|
|
89
|
+
# The upper corner is the last pixel's own, so a position on the last row or column uses it
|
|
90
|
+
y_low = np.minimum(np.floor(y), max(ny - 2, 0)).astype(np.intp)
|
|
91
|
+
x_low = np.minimum(np.floor(x), max(nx - 2, 0)).astype(np.intp)
|
|
92
|
+
y_fraction, x_fraction = y - y_low, x - x_low
|
|
93
|
+
low = y_low * nx + x_low
|
|
94
|
+
y_step, x_step = min(1, ny - 1) * nx, min(1, nx - 1)
|
|
95
|
+
return PatternTaps(
|
|
96
|
+
indices=np.array([low, low + x_step, low + y_step, low + y_step + x_step]),
|
|
97
|
+
weights=np.array(
|
|
98
|
+
[
|
|
99
|
+
(1 - y_fraction) * (1 - x_fraction),
|
|
100
|
+
(1 - y_fraction) * x_fraction,
|
|
101
|
+
y_fraction * (1 - x_fraction),
|
|
102
|
+
y_fraction * x_fraction,
|
|
103
|
+
]
|
|
104
|
+
)
|
|
105
|
+
* on_grid,
|
|
106
|
+
shape=shape,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class HolographyBeam(NamedTuple):
|
|
111
|
+
"""One beam of a holography cube at one frequency"""
|
|
112
|
+
|
|
113
|
+
plane: NDArray[np.float64]
|
|
114
|
+
"""The (y, x) response, normalised to 1 at the beam centre unless used as the cube stores it"""
|
|
115
|
+
pixel_scale_rad: tuple[float, float]
|
|
116
|
+
"""Signed pixel size along x and y in radians (CDELT1, CDELT2)"""
|
|
117
|
+
centre_pixel: tuple[float, float]
|
|
118
|
+
"""Zero-based (x, y) pixel of the beam centre"""
|
|
119
|
+
alpha_rad: float
|
|
120
|
+
"""Rotation of the feeds from the frame the cube was measured in"""
|
|
121
|
+
scale: float
|
|
122
|
+
"""Frequency of the image over the frequency of the plane, by which offsets are scaled as the beam widens with wavelength"""
|
|
123
|
+
leakage: NDArray[np.float64] | None = None
|
|
124
|
+
"""The fractional leakage of Stokes I into (Q, U, V), shaped (3, y, x), if it was read"""
|
|
125
|
+
frame_rotation_rad: float = 0.0
|
|
126
|
+
"""Position angle, east of north at the beam centre, of the direction the input's polarisation is referenced to"""
|
|
127
|
+
cutoff_scale: float = 1.0
|
|
128
|
+
"""The response a cutoff is a fraction of: 1, the beam centre, or the peak of the plane when the beam is used as the cube stores it"""
|
|
129
|
+
|
|
130
|
+
def _pattern_pixels(
|
|
131
|
+
self, east: NDArray[np.float64], north: NDArray[np.float64]
|
|
132
|
+
) -> NDArray[np.float64]:
|
|
133
|
+
"""The (y, x) pixels of the cube at offsets from the beam centre."""
|
|
134
|
+
rotation = self.alpha_rad + self.frame_rotation_rad
|
|
135
|
+
cos_rotation, sin_rotation = np.cos(rotation), np.sin(rotation)
|
|
136
|
+
x = east * cos_rotation - north * sin_rotation
|
|
137
|
+
y = east * sin_rotation + north * cos_rotation
|
|
138
|
+
|
|
139
|
+
radius = np.hypot(x, y)
|
|
140
|
+
offset = np.arcsin(np.clip(radius, 0.0, 1.0))
|
|
141
|
+
with np.errstate(invalid="ignore", divide="ignore"):
|
|
142
|
+
stretch = np.where(
|
|
143
|
+
radius > 0, np.sin(self.scale * offset) / radius, self.scale
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
x_pixel = x * stretch / self.pixel_scale_rad[0] + self.centre_pixel[0]
|
|
147
|
+
y_pixel = y * stretch / self.pixel_scale_rad[1] + self.centre_pixel[1]
|
|
148
|
+
return np.array([np.ravel(y_pixel), np.ravel(x_pixel)])
|
|
149
|
+
|
|
150
|
+
def taps(
|
|
151
|
+
self, east: NDArray[np.float64], north: NDArray[np.float64]
|
|
152
|
+
) -> PatternTaps:
|
|
153
|
+
"""Where offsets from the beam centre, given as direction cosines, fall on the grid of the cube."""
|
|
154
|
+
return bilinear_taps(
|
|
155
|
+
self._pattern_pixels(east, north), self.plane.shape, np.shape(east)
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
def response(
|
|
159
|
+
self,
|
|
160
|
+
east: NDArray[np.float64],
|
|
161
|
+
north: NDArray[np.float64],
|
|
162
|
+
taps: PatternTaps | None = None,
|
|
163
|
+
) -> NDArray[np.float64]:
|
|
164
|
+
"""The response at offsets from the beam centre, given as direction cosines, or at ``taps`` found for them. It is 0 off the cube."""
|
|
165
|
+
return (self.taps(east, north) if taps is None else taps).sample(self.plane)
|
|
166
|
+
|
|
167
|
+
def leakage_response(
|
|
168
|
+
self,
|
|
169
|
+
east: NDArray[np.float64],
|
|
170
|
+
north: NDArray[np.float64],
|
|
171
|
+
taps: PatternTaps | None = None,
|
|
172
|
+
include_v: bool = True,
|
|
173
|
+
) -> NDArray[np.float64]:
|
|
174
|
+
"""The fractional (Q, U, V) leakage at offsets from the beam centre, with Q and U in the frame of the input.
|
|
175
|
+
|
|
176
|
+
The leakage is rotated with the feeds, by ``alpha_rad``.
|
|
177
|
+
Without ``include_v`` only Q and U are given.
|
|
178
|
+
|
|
179
|
+
Raises:
|
|
180
|
+
ValueError: Raised if the leakage was not read from the cube
|
|
181
|
+
"""
|
|
182
|
+
if self.leakage is None:
|
|
183
|
+
msg = "The leakage of this holography beam was not read"
|
|
184
|
+
raise ValueError(msg)
|
|
185
|
+
taps = self.taps(east, north) if taps is None else taps
|
|
186
|
+
q, u = taps.sample(self.leakage[0]), taps.sample(self.leakage[1])
|
|
187
|
+
cos_2alpha, sin_2alpha = np.cos(2 * self.alpha_rad), np.sin(2 * self.alpha_rad)
|
|
188
|
+
leakage = [q * cos_2alpha - u * sin_2alpha, q * sin_2alpha + u * cos_2alpha]
|
|
189
|
+
if include_v:
|
|
190
|
+
leakage.append(taps.sample(self.leakage[2]))
|
|
191
|
+
return np.array(leakage)
|
|
192
|
+
|
|
193
|
+
def reaches(self, cutoff: float) -> NDArray[np.bool_]:
|
|
194
|
+
"""The pixels of the plane at or above ``cutoff`` of ``cutoff_scale``, or above 0 when ``cutoff`` is not positive."""
|
|
195
|
+
if cutoff > 0:
|
|
196
|
+
return np.asarray(self.plane >= cutoff * self.cutoff_scale)
|
|
197
|
+
return np.asarray(self.plane > 0)
|
|
198
|
+
|
|
199
|
+
def pixel_offsets(
|
|
200
|
+
self, y: NDArray[np.float64], x: NDArray[np.float64], scale: float
|
|
201
|
+
) -> tuple[NDArray[np.float64], NDArray[np.float64]] | None:
|
|
202
|
+
"""The offsets (east, north) from the beam centre, as direction cosines, that ``taps`` places on (y, x) pixels at a frequency scale, or None if some lie a quarter of the sky or more away."""
|
|
203
|
+
grid_x = (x - self.centre_pixel[0]) * self.pixel_scale_rad[0]
|
|
204
|
+
grid_y = (y - self.centre_pixel[1]) * self.pixel_scale_rad[1]
|
|
205
|
+
radius = np.hypot(grid_x, grid_y)
|
|
206
|
+
offset = np.arcsin(np.clip(radius, 0.0, 1.0)) / scale
|
|
207
|
+
if np.any(offset >= np.pi / 2):
|
|
208
|
+
return None
|
|
209
|
+
with np.errstate(invalid="ignore", divide="ignore"):
|
|
210
|
+
shrink = np.where(radius > 0, np.sin(offset) / radius, 0.0)
|
|
211
|
+
rotation = self.alpha_rad + self.frame_rotation_rad
|
|
212
|
+
cos_rotation, sin_rotation = np.cos(rotation), np.sin(rotation)
|
|
213
|
+
x, y = grid_x * shrink, grid_y * shrink
|
|
214
|
+
return x * cos_rotation + y * sin_rotation, y * cos_rotation - x * sin_rotation
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
PrimaryBeam = GaussianBeam | HolographyBeam
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def gaussian_beam(
|
|
221
|
+
frequency_hz: float, aperture_m: float = 12.0, fwhm_scaling: float = 1.09
|
|
222
|
+
) -> GaussianBeam:
|
|
223
|
+
"""The Gaussian beam of a dish, with a FWHM of ``fwhm_scaling`` wavelengths over the dish diameter."""
|
|
224
|
+
wavelength_m = speed_of_light.value / frequency_hz
|
|
225
|
+
return GaussianBeam(fwhm_rad=fwhm_scaling * wavelength_m / aperture_m)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
@functools.lru_cache(maxsize=128)
|
|
229
|
+
def usable_planes(
|
|
230
|
+
holography_cube: Path, beam_number: int
|
|
231
|
+
) -> tuple[NDArray[np.float64], NDArray[np.int64], NDArray[np.float64]]:
|
|
232
|
+
"""The frequency of every plane of a beam of a holography cube, which planes respond at the beam centre, and that response.
|
|
233
|
+
|
|
234
|
+
Only the pixels around the centre of every plane are read. The result is
|
|
235
|
+
kept, as every channel of every input that uses the beam needs it.
|
|
236
|
+
|
|
237
|
+
Raises:
|
|
238
|
+
ValueError: Raised if the beam centre is near the cube edge, or the beam has no usable planes
|
|
239
|
+
"""
|
|
240
|
+
with fits.open(holography_cube, memmap=True) as hdul:
|
|
241
|
+
header = hdul[0].header
|
|
242
|
+
data = hdul[0].data
|
|
243
|
+
beam = data[beam_number] if data.ndim == 5 else data[beam_number][None]
|
|
244
|
+
n_freq, ny, nx = beam.shape[1:]
|
|
245
|
+
|
|
246
|
+
x0, y0 = header["CRPIX1"] - 1, header["CRPIX2"] - 1
|
|
247
|
+
if min(x0, nx - 1 - x0, y0, ny - 1 - y0) < 2:
|
|
248
|
+
msg = (
|
|
249
|
+
f"The beam centre (CRPIX) of {holography_cube} is at pixel ({x0 + 1}, {y0 + 1}) "
|
|
250
|
+
f"of a {nx}x{ny} grid, too close to its edge"
|
|
251
|
+
)
|
|
252
|
+
raise ValueError(msg)
|
|
253
|
+
|
|
254
|
+
x_low, y_low = int(np.floor(x0)), int(np.floor(y0))
|
|
255
|
+
around = np.nan_to_num(
|
|
256
|
+
np.asarray(
|
|
257
|
+
beam[0, :, y_low : y_low + 2, x_low : x_low + 2], dtype=np.float64
|
|
258
|
+
)
|
|
259
|
+
)
|
|
260
|
+
freqs_hz = (
|
|
261
|
+
header["CRVAL3"]
|
|
262
|
+
+ (np.arange(n_freq) + 1 - header["CRPIX3"]) * header["CDELT3"]
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
centre = map_coordinates(
|
|
266
|
+
around,
|
|
267
|
+
np.array(
|
|
268
|
+
[
|
|
269
|
+
np.arange(n_freq),
|
|
270
|
+
np.full(n_freq, y0 - y_low),
|
|
271
|
+
np.full(n_freq, x0 - x_low),
|
|
272
|
+
]
|
|
273
|
+
),
|
|
274
|
+
order=1,
|
|
275
|
+
)
|
|
276
|
+
usable = np.flatnonzero(centre > 0)
|
|
277
|
+
if usable.size == 0:
|
|
278
|
+
msg = f"Beam {beam_number} of {holography_cube} has no usable response"
|
|
279
|
+
raise ValueError(msg)
|
|
280
|
+
return np.asarray(freqs_hz, dtype=np.float64), usable, centre
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def nearest_planes(
|
|
284
|
+
holography_cube: Path, beam_number: int, frequencies_hz: ArrayLike
|
|
285
|
+
) -> tuple[NDArray[np.int64], NDArray[np.float64]]:
|
|
286
|
+
"""The usable plane of a beam of a holography cube nearest each frequency, and the frequency of that plane."""
|
|
287
|
+
freqs_hz, usable, _ = usable_planes(Path(holography_cube), beam_number)
|
|
288
|
+
wanted = np.reshape(np.asarray(frequencies_hz, dtype=np.float64), (-1, 1))
|
|
289
|
+
nearest = usable[np.argmin(np.abs(freqs_hz[usable] - wanted), axis=1)]
|
|
290
|
+
return nearest, freqs_hz[nearest]
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def load_holography_beam(
|
|
294
|
+
holography_cube: Path,
|
|
295
|
+
beam_number: int,
|
|
296
|
+
frequency_hz: float,
|
|
297
|
+
alpha_rad: float = 0.0,
|
|
298
|
+
leakage: bool = False,
|
|
299
|
+
normalise_leakage: bool = True,
|
|
300
|
+
frame_rotation_rad: float = 0.0,
|
|
301
|
+
normalise: bool = True,
|
|
302
|
+
) -> HolographyBeam:
|
|
303
|
+
"""Read one beam of a holography cube at the plane nearest a frequency.
|
|
304
|
+
|
|
305
|
+
The spatial axes are offsets about the beam centre, so only CRPIX and CDELT
|
|
306
|
+
are used. NaNs count as no response, planes with no response
|
|
307
|
+
at the beam centre (such as flagged channels) are skipped, and the beam is
|
|
308
|
+
scaled by the ratio of the image and plane frequencies, as the beam widens
|
|
309
|
+
with wavelength.
|
|
310
|
+
|
|
311
|
+
Args:
|
|
312
|
+
holography_cube (Path): Cube with axes (beam, stokes, freq, dec, ra), or (beam, freq, dec, ra)
|
|
313
|
+
beam_number (int): Zero-based beam to read
|
|
314
|
+
frequency_hz (float): Frequency of the image the beam weights
|
|
315
|
+
alpha_rad (float, optional): Rotation of the feeds from the frame the cube was measured in. Defaults to 0.0.
|
|
316
|
+
leakage (bool, optional): Also read the fractional leakage of Stokes I into Q, U and V. Defaults to False.
|
|
317
|
+
normalise_leakage (bool, optional): Remove the leakage at the beam centre, as calibration does. Defaults to True.
|
|
318
|
+
frame_rotation_rad (float, optional): Position angle at the beam centre of the direction the input's polarisation is referenced to. Defaults to 0.0.
|
|
319
|
+
normalise (bool, optional): Scale the beam to 1 at its centre, where calibration sets the gain. Otherwise it is used as the cube stores it, and a cutoff is measured from its peak. Defaults to True.
|
|
320
|
+
|
|
321
|
+
Raises:
|
|
322
|
+
ValueError: Raised if the beam centre is near the cube edge, the beam has no usable planes, or leakage is asked of a cube without Stokes planes
|
|
323
|
+
|
|
324
|
+
Returns:
|
|
325
|
+
HolographyBeam: The beam
|
|
326
|
+
"""
|
|
327
|
+
freqs_hz, _, centre = usable_planes(Path(holography_cube), beam_number)
|
|
328
|
+
nearest = int(nearest_planes(holography_cube, beam_number, frequency_hz)[0][0])
|
|
329
|
+
with fits.open(holography_cube, memmap=True) as hdul:
|
|
330
|
+
header = hdul[0].header
|
|
331
|
+
data = hdul[0].data
|
|
332
|
+
beam = data[beam_number] if data.ndim == 5 else data[beam_number][None]
|
|
333
|
+
if leakage and beam.shape[0] < 4:
|
|
334
|
+
msg = f"{holography_cube} has no Stokes planes to read the leakage from"
|
|
335
|
+
raise ValueError(msg)
|
|
336
|
+
x0, y0 = header["CRPIX1"] - 1, header["CRPIX2"] - 1
|
|
337
|
+
plane = np.nan_to_num(np.asarray(beam[0, nearest], dtype=np.float64))
|
|
338
|
+
leakage_planes = None
|
|
339
|
+
if leakage:
|
|
340
|
+
leakage_planes = np.nan_to_num(
|
|
341
|
+
np.asarray(beam[1:4, nearest], dtype=np.float64)
|
|
342
|
+
)
|
|
343
|
+
if normalise_leakage:
|
|
344
|
+
at_centre = map_coordinates(
|
|
345
|
+
leakage_planes,
|
|
346
|
+
np.array([np.arange(3), np.full(3, y0), np.full(3, x0)]),
|
|
347
|
+
order=1,
|
|
348
|
+
)
|
|
349
|
+
leakage_planes -= at_centre[:, None, None]
|
|
350
|
+
|
|
351
|
+
logger.debug(
|
|
352
|
+
f"Using plane {nearest} at {freqs_hz[nearest] / 1e6:.2f} MHz of beam {beam_number}"
|
|
353
|
+
)
|
|
354
|
+
return HolographyBeam(
|
|
355
|
+
plane=plane / centre[nearest] if normalise else plane,
|
|
356
|
+
pixel_scale_rad=(
|
|
357
|
+
float(np.radians(header["CDELT1"])),
|
|
358
|
+
float(np.radians(header["CDELT2"])),
|
|
359
|
+
),
|
|
360
|
+
centre_pixel=(float(x0), float(y0)),
|
|
361
|
+
alpha_rad=alpha_rad,
|
|
362
|
+
scale=float(frequency_hz / freqs_hz[nearest]),
|
|
363
|
+
leakage=leakage_planes,
|
|
364
|
+
frame_rotation_rad=frame_rotation_rad,
|
|
365
|
+
cutoff_scale=1.0 if normalise else float(np.max(plane)),
|
|
366
|
+
)
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
@functools.lru_cache(maxsize=512)
|
|
370
|
+
def _cached_holography_beam(
|
|
371
|
+
holography_cube: Path,
|
|
372
|
+
beam_number: int,
|
|
373
|
+
frequency_hz: float,
|
|
374
|
+
alpha_rad: float,
|
|
375
|
+
leakage: bool,
|
|
376
|
+
normalise_leakage: bool,
|
|
377
|
+
frame_rotation_rad: float,
|
|
378
|
+
normalise: bool,
|
|
379
|
+
) -> HolographyBeam:
|
|
380
|
+
"""A holography beam, kept so that each worker reads a plane once."""
|
|
381
|
+
return load_holography_beam(
|
|
382
|
+
holography_cube,
|
|
383
|
+
beam_number,
|
|
384
|
+
frequency_hz,
|
|
385
|
+
alpha_rad=alpha_rad,
|
|
386
|
+
leakage=leakage,
|
|
387
|
+
normalise_leakage=normalise_leakage,
|
|
388
|
+
frame_rotation_rad=frame_rotation_rad,
|
|
389
|
+
normalise=normalise,
|
|
390
|
+
)
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
class BeamModel(NamedTuple):
|
|
394
|
+
"""The primary beam of an input at the frequency of each of its channels.
|
|
395
|
+
|
|
396
|
+
It is small enough to send to every worker, which build the beam of a
|
|
397
|
+
channel when it is needed, reading holography planes as they go.
|
|
398
|
+
"""
|
|
399
|
+
|
|
400
|
+
options: PrimaryBeamOptions
|
|
401
|
+
"""The beam model"""
|
|
402
|
+
frequencies_hz: tuple[float, ...]
|
|
403
|
+
"""The frequency of each channel"""
|
|
404
|
+
beam_number: int | None = None
|
|
405
|
+
"""The beam of the holography cube"""
|
|
406
|
+
leakage: bool = False
|
|
407
|
+
"""Whether the polarisation leakage is read"""
|
|
408
|
+
normalise_leakage: bool = True
|
|
409
|
+
"""Whether the leakage at the beam centre is removed"""
|
|
410
|
+
frame_rotation_rad: float = 0.0
|
|
411
|
+
"""Position angle at the beam centre of the direction the input's polarisation is referenced to"""
|
|
412
|
+
|
|
413
|
+
def channel(self, index: int) -> PrimaryBeam:
|
|
414
|
+
"""The primary beam of one channel."""
|
|
415
|
+
frequency = self.frequencies_hz[index]
|
|
416
|
+
if self.options.pb_model == "gaussian":
|
|
417
|
+
return gaussian_beam(
|
|
418
|
+
frequency, self.options.aperture_m, self.options.fwhm_scaling
|
|
419
|
+
)
|
|
420
|
+
return _cached_holography_beam(
|
|
421
|
+
Path(str(self.options.holography_cube)),
|
|
422
|
+
int(self.beam_number or 0),
|
|
423
|
+
frequency,
|
|
424
|
+
self.options.holography_alpha_rad,
|
|
425
|
+
self.leakage,
|
|
426
|
+
self.normalise_leakage,
|
|
427
|
+
self.frame_rotation_rad,
|
|
428
|
+
self.options.holography_scale == "centre",
|
|
429
|
+
)
|
|
430
|
+
|
|
431
|
+
def responses(
|
|
432
|
+
self, channels: range, east: NDArray[np.float64], north: NDArray[np.float64]
|
|
433
|
+
) -> NDArray[np.float64]:
|
|
434
|
+
"""The response of each channel at offsets from the beam centre, shaped ``(channel, *east.shape)``."""
|
|
435
|
+
if self.options.pb_model == "gaussian":
|
|
436
|
+
offset = np.arcsin(np.clip(np.hypot(east, north), 0.0, 1.0)) ** 2
|
|
437
|
+
fwhms = np.array([self.channel(index).fwhm_rad for index in channels]) # type: ignore[union-attr]
|
|
438
|
+
return np.asarray(
|
|
439
|
+
np.exp(
|
|
440
|
+
-4 * np.log(2) * offset / fwhms.reshape(-1, *[1] * offset.ndim) ** 2
|
|
441
|
+
)
|
|
442
|
+
)
|
|
443
|
+
beams = self._holography_beams(channels)
|
|
444
|
+
return np.array(
|
|
445
|
+
[
|
|
446
|
+
beam.response(east, north, taps)
|
|
447
|
+
for beam, taps in zip(
|
|
448
|
+
beams, _shared_taps(beams, east, north), strict=True
|
|
449
|
+
)
|
|
450
|
+
]
|
|
451
|
+
)
|
|
452
|
+
|
|
453
|
+
def leakage_responses(
|
|
454
|
+
self,
|
|
455
|
+
channels: range,
|
|
456
|
+
east: NDArray[np.float64],
|
|
457
|
+
north: NDArray[np.float64],
|
|
458
|
+
include_v: bool = True,
|
|
459
|
+
) -> NDArray[np.float64]:
|
|
460
|
+
"""The fractional (Q, U, V) leakage of each channel, shaped ``(channel, 3, *east.shape)``, or without V ``(channel, 2, *east.shape)``."""
|
|
461
|
+
beams = self._holography_beams(channels)
|
|
462
|
+
return np.array(
|
|
463
|
+
[
|
|
464
|
+
beam.leakage_response(east, north, taps, include_v=include_v)
|
|
465
|
+
for beam, taps in zip(
|
|
466
|
+
beams, _shared_taps(beams, east, north), strict=True
|
|
467
|
+
)
|
|
468
|
+
]
|
|
469
|
+
)
|
|
470
|
+
|
|
471
|
+
def cutoff_scales(self, channels: range) -> NDArray[np.float64]:
|
|
472
|
+
"""The response a cutoff is a fraction of in each channel: 1, or the peak of a holography beam used as the cube stores it."""
|
|
473
|
+
if self.options.pb_model != "holography":
|
|
474
|
+
return np.ones(len(channels))
|
|
475
|
+
return np.array(
|
|
476
|
+
[beam.cutoff_scale for beam in self._holography_beams(channels)]
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
def plane_frequencies_hz(self) -> NDArray[np.float64] | None:
|
|
480
|
+
"""The frequency of the holography plane each channel's beam is read from, or None if it is not a holography beam."""
|
|
481
|
+
if self.options.pb_model != "holography":
|
|
482
|
+
return None
|
|
483
|
+
return nearest_planes(
|
|
484
|
+
Path(str(self.options.holography_cube)),
|
|
485
|
+
int(self.beam_number or 0),
|
|
486
|
+
self.frequencies_hz,
|
|
487
|
+
)[1]
|
|
488
|
+
|
|
489
|
+
def _holography_beams(self, channels: range) -> list[HolographyBeam]:
|
|
490
|
+
"""The holography beam of each channel."""
|
|
491
|
+
beams = [self.channel(index) for index in channels]
|
|
492
|
+
holography = [beam for beam in beams if isinstance(beam, HolographyBeam)]
|
|
493
|
+
if len(holography) != len(beams):
|
|
494
|
+
msg = "Only holography beams carry polarisation leakage"
|
|
495
|
+
raise ValueError(msg)
|
|
496
|
+
return holography
|
|
497
|
+
|
|
498
|
+
def reach(
|
|
499
|
+
self, cutoff: float
|
|
500
|
+
) -> tuple[NDArray[np.float64], NDArray[np.float64]] | None:
|
|
501
|
+
"""Offsets (east, north) from the beam centre, as direction cosines, whose bounding box on a frame holds every position where some channel reaches ``cutoff``.
|
|
502
|
+
|
|
503
|
+
A Gaussian beam reaches a circle. A holography beam reaches the pixels of
|
|
504
|
+
its planes at or above the cutoff, which differ from channel to channel
|
|
505
|
+
when the beam fills its grid. No offsets are given if no channel reaches
|
|
506
|
+
the cutoff, and None if the response never falls below it.
|
|
507
|
+
"""
|
|
508
|
+
channels = range(len(self.frequencies_hz))
|
|
509
|
+
if self.options.pb_model == "gaussian":
|
|
510
|
+
radii = [self.channel(index).support_radius(cutoff) for index in channels] # type: ignore[union-attr]
|
|
511
|
+
if any(radius is None for radius in radii):
|
|
512
|
+
return None
|
|
513
|
+
# Points on a circle bound a polygon inside it, which falls short of the
|
|
514
|
+
# circle by many pixels for a wide beam. On a circle larger by
|
|
515
|
+
# 1 / cos(pi / samples) the polygon's edges touch the true circle
|
|
516
|
+
samples = 64
|
|
517
|
+
radius = max(radius for radius in radii if radius is not None) / np.cos(
|
|
518
|
+
np.pi / samples
|
|
519
|
+
)
|
|
520
|
+
if radius >= np.pi / 2:
|
|
521
|
+
return None
|
|
522
|
+
angles = np.linspace(0, 2 * np.pi, samples, endpoint=False)
|
|
523
|
+
return np.sin(radius) * np.sin(angles), np.sin(radius) * np.cos(angles)
|
|
524
|
+
|
|
525
|
+
groups: dict[tuple[Any, ...], list[HolographyBeam]] = {}
|
|
526
|
+
# The reach needs only the Stokes I planes, not the leakage
|
|
527
|
+
for beam in self._replace(leakage=False)._holography_beams(channels):
|
|
528
|
+
rotation = beam.alpha_rad + beam.frame_rotation_rad
|
|
529
|
+
key = (beam.plane.shape, beam.pixel_scale_rad, beam.centre_pixel, rotation)
|
|
530
|
+
groups.setdefault(key, []).append(beam)
|
|
531
|
+
east, north = [], []
|
|
532
|
+
for group in groups.values():
|
|
533
|
+
y, x = np.nonzero(np.any([beam.reaches(cutoff) for beam in group], axis=0))
|
|
534
|
+
# A response interpolated between pixels reaches the cutoff only within a
|
|
535
|
+
# pixel of one that does, and each pixel lies furthest from the centre,
|
|
536
|
+
# in the same direction, at the smallest scale
|
|
537
|
+
corners = group[0].pixel_offsets(
|
|
538
|
+
np.ravel(y[:, None] + np.array([-1.0, -1.0, 1.0, 1.0])),
|
|
539
|
+
np.ravel(x[:, None] + np.array([-1.0, 1.0, -1.0, 1.0])),
|
|
540
|
+
scale=min(beam.scale for beam in group),
|
|
541
|
+
)
|
|
542
|
+
if corners is None:
|
|
543
|
+
return None
|
|
544
|
+
east.append(corners[0])
|
|
545
|
+
north.append(corners[1])
|
|
546
|
+
if not any(len(values) for values in east):
|
|
547
|
+
return np.zeros(0), np.zeros(0)
|
|
548
|
+
# The centre too, so the box spans every direction out from it
|
|
549
|
+
return np.concatenate([[0.0], *east]), np.concatenate([[0.0], *north])
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def _shared_taps(
|
|
553
|
+
beams: list[HolographyBeam],
|
|
554
|
+
east: NDArray[np.float64],
|
|
555
|
+
north: NDArray[np.float64],
|
|
556
|
+
) -> list[PatternTaps]:
|
|
557
|
+
"""The taps of each beam of one input at offsets, found once for all the channels that share a frequency scale.
|
|
558
|
+
|
|
559
|
+
The beams of an input differ only in their planes and scale, so channels at
|
|
560
|
+
the frequencies of the planes, as ASKAP cubes have, all share one set.
|
|
561
|
+
"""
|
|
562
|
+
found: dict[float, PatternTaps] = {}
|
|
563
|
+
taps = []
|
|
564
|
+
for beam in beams:
|
|
565
|
+
# Scales a part in 10^9 apart move a position by far less than a pixel
|
|
566
|
+
key = round(beam.scale, 9)
|
|
567
|
+
if key not in found:
|
|
568
|
+
found[key] = beam.taps(east, north)
|
|
569
|
+
taps.append(found[key])
|
|
570
|
+
return taps
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def beam_model(
|
|
574
|
+
options: PrimaryBeamOptions,
|
|
575
|
+
info: ImageInfo,
|
|
576
|
+
leakage: bool = False,
|
|
577
|
+
normalise_leakage: bool = True,
|
|
578
|
+
frame_rotation_rad: float = 0.0,
|
|
579
|
+
) -> BeamModel | None:
|
|
580
|
+
"""The primary beam model of an input, or None when no beam model is used.
|
|
581
|
+
|
|
582
|
+
Args:
|
|
583
|
+
options (PrimaryBeamOptions): The beam model to build
|
|
584
|
+
info (ImageInfo): The input the beam belongs to
|
|
585
|
+
leakage (bool, optional): Also read the polarisation leakage, which needs a holography beam. Defaults to False.
|
|
586
|
+
normalise_leakage (bool, optional): Remove the leakage at the beam centre. Defaults to True.
|
|
587
|
+
frame_rotation_rad (float, optional): Position angle at the beam centre of the direction the input's polarisation is referenced to. Defaults to 0.0.
|
|
588
|
+
|
|
589
|
+
Raises:
|
|
590
|
+
ValueError: Raised if the input lacks the frequency or beam number the model needs, or leakage is asked of a beam without it
|
|
591
|
+
|
|
592
|
+
Returns:
|
|
593
|
+
BeamModel | None: The primary beam model of the input
|
|
594
|
+
"""
|
|
595
|
+
if leakage and options.pb_model != "holography":
|
|
596
|
+
msg = "Removing polarisation leakage needs the holography primary beam"
|
|
597
|
+
raise ValueError(msg)
|
|
598
|
+
if options.pb_model == "none":
|
|
599
|
+
return None
|
|
600
|
+
if not info.frequencies_hz:
|
|
601
|
+
msg = f"The frequency of {info.path} is unknown, and the primary beam needs it"
|
|
602
|
+
raise ValueError(msg)
|
|
603
|
+
if options.pb_model == "holography" and (
|
|
604
|
+
options.holography_cube is None or info.beam_number is None
|
|
605
|
+
):
|
|
606
|
+
msg = f"The holography beam of {info.path} needs a holography cube and a beam number"
|
|
607
|
+
raise ValueError(msg)
|
|
608
|
+
|
|
609
|
+
model = BeamModel(
|
|
610
|
+
options=options,
|
|
611
|
+
frequencies_hz=info.frequencies_hz,
|
|
612
|
+
beam_number=info.beam_number,
|
|
613
|
+
leakage=leakage,
|
|
614
|
+
normalise_leakage=normalise_leakage,
|
|
615
|
+
frame_rotation_rad=frame_rotation_rad,
|
|
616
|
+
)
|
|
617
|
+
model.channel(0) # Fail now, rather than on a worker, if the beam cannot be built
|
|
618
|
+
return model
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
def make_primary_beam(
|
|
622
|
+
options: PrimaryBeamOptions,
|
|
623
|
+
info: ImageInfo,
|
|
624
|
+
leakage: bool = False,
|
|
625
|
+
normalise_leakage: bool = True,
|
|
626
|
+
frame_rotation_rad: float = 0.0,
|
|
627
|
+
) -> PrimaryBeam | None:
|
|
628
|
+
"""The primary beam of the first channel of an input, or None when no beam model is used."""
|
|
629
|
+
model = beam_model(options, info, leakage, normalise_leakage, frame_rotation_rad)
|
|
630
|
+
return None if model is None else model.channel(0)
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
def pb_rotation_from_pol_axis(pol_axis_rad: float) -> float:
|
|
634
|
+
"""The holography beam rotation of a field, from the polarisation axis of its measurement set."""
|
|
635
|
+
# Holography cubes are measured with the feeds at -45 degrees
|
|
636
|
+
return pol_axis_rad + np.pi / 4
|
patchwork/py.typed
ADDED
|
File without changes
|