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,178 @@
1
+ """The frames that linear polarisation is referenced to, and the leakage of Stokes I into it.
2
+
3
+ Stokes Q and U describe a polarisation angle, measured east of a reference
4
+ direction. In a mosaic (by the IAU convention) that direction is north at each
5
+ pixel. An interferometric image instead references every pixel to one direction:
6
+ north at its phase centre, or for ASKAP at the boresight of the dish, carried
7
+ across the field as a fixed direction of the feeds. Away from that position
8
+ local north turns away from it, by roughly the offset times ``tan(Dec)``, so the
9
+ two frames part ways quickly towards a celestial pole. Each input is therefore
10
+ rotated from its own frame into the frame of the mosaic before it is combined.
11
+
12
+ The frame of an image can be recorded in its header, as patchwork records the
13
+ frame of its mosaics, with the keywords ``FRAME_KEYWORDS``.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from pathlib import Path
19
+ from typing import TYPE_CHECKING, NamedTuple
20
+
21
+ import numpy as np
22
+
23
+ from patchwork.coordinates import east_north, unit_vectors
24
+
25
+ if TYPE_CHECKING:
26
+ from astropy.io import fits
27
+ from numpy.typing import NDArray
28
+
29
+ STOKES_CODES = {"I": 1, "Q": 2, "U": 3, "V": 4}
30
+ """FITS codes of the Stokes parameters, as found on a STOKES axis"""
31
+
32
+ FRAME_KEYWORDS = ("POLFRAME", "POLRA", "POLDEC")
33
+ """The header keywords that record what the Q and U of an image are referenced to.
34
+ POLFRAME is NORTH (north at each pixel) or FIXED (north at POLRA, POLDEC, in
35
+ degrees, carried across the image)"""
36
+
37
+
38
+ class LinearFrame(NamedTuple):
39
+ """What the polarisation angles of an image are measured from"""
40
+
41
+ centre: tuple[float, float] | None = None
42
+ """The (RA, Dec) in degrees whose north the angles are measured from everywhere, or None if they are measured from north at each pixel"""
43
+
44
+ def describe(self) -> str:
45
+ """The frame in words."""
46
+ if self.centre is None:
47
+ return "north at each pixel"
48
+ return f"north at RA {self.centre[0]:.5f}, Dec {self.centre[1]:.5f}"
49
+
50
+ def matches(self, other: LinearFrame, tolerance_deg: float = 1 / 3600) -> bool:
51
+ """Whether two frames are the same, their positions no more than ``tolerance_deg`` apart."""
52
+ if self.centre is None or other.centre is None:
53
+ return self.centre is None and other.centre is None
54
+ chord = float(
55
+ np.linalg.norm(unit_vectors(*self.centre) - unit_vectors(*other.centre))
56
+ )
57
+ return bool(np.degrees(2 * np.arcsin(min(chord / 2, 1.0))) <= tolerance_deg)
58
+
59
+
60
+ NORTH = LinearFrame()
61
+ """Angles measured from north at each pixel, the IAU convention"""
62
+
63
+
64
+ def header_frame(
65
+ header: fits.Header, path: str | Path | None = None
66
+ ) -> LinearFrame | None:
67
+ """The frame the keywords of a header give the Q and U of its image, or None if it has none of them.
68
+
69
+ Args:
70
+ header (fits.Header): The header
71
+ path (str | Path | None, optional): The file the header is from, named in errors. Defaults to None.
72
+
73
+ Raises:
74
+ ValueError: Raised if the keywords do not describe a frame
75
+
76
+ Returns:
77
+ LinearFrame | None: The frame, or None if the header does not record one
78
+ """
79
+ if not any(key in header for key in FRAME_KEYWORDS):
80
+ return None
81
+ where = "" if path is None else f" of {Path(path)}"
82
+ kind = str(header.get("POLFRAME", "")).strip().upper()
83
+ if kind == "NORTH":
84
+ return NORTH
85
+ if kind != "FIXED":
86
+ msg = (
87
+ f"The header{where} has POLFRAME {header.get('POLFRAME')!r}, but it must be NORTH or FIXED"
88
+ if "POLFRAME" in header
89
+ else f"The header{where} has POLRA or POLDEC, but no POLFRAME to say what they mean"
90
+ )
91
+ raise ValueError(msg)
92
+ try:
93
+ ra, dec = float(header["POLRA"]), float(header["POLDEC"])
94
+ except (KeyError, TypeError, ValueError):
95
+ ra = dec = np.nan
96
+ if not (np.isfinite(ra) and np.isfinite(dec) and -90 <= dec <= 90):
97
+ msg = f"The header{where} has POLFRAME FIXED, but its POLRA and POLDEC are not a position"
98
+ raise ValueError(msg)
99
+ return LinearFrame((ra % 360, dec))
100
+
101
+
102
+ def write_frame_keywords(header: fits.Header, frame: LinearFrame) -> None:
103
+ """Record in a header what the Q and U of its image are referenced to, in place of any record there."""
104
+ remove_frame_keywords(header)
105
+ if frame.centre is None:
106
+ header["POLFRAME"] = ("NORTH", "Q,U angles from north at each pixel")
107
+ return
108
+ header["POLFRAME"] = ("FIXED", "Q,U angles from north at POLRA,POLDEC")
109
+ header["POLRA"] = (frame.centre[0], "[deg] RA of the north Q,U are from")
110
+ header["POLDEC"] = (frame.centre[1], "[deg] Dec of the north Q,U are from")
111
+
112
+
113
+ def remove_frame_keywords(header: fits.Header) -> None:
114
+ """Remove any record of the frame of Q and U from a header."""
115
+ for key in FRAME_KEYWORDS:
116
+ header.remove(key, ignore_missing=True, remove_all=True)
117
+
118
+
119
+ def frame_angle(
120
+ reference: tuple[float, float], vectors: NDArray[np.float64]
121
+ ) -> NDArray[np.float64]:
122
+ """The position angle, east of local north, at each position of the direction that is north at ``reference``.
123
+
124
+ The direction is the projection of north at the reference position onto the
125
+ sky at each position, which is how a fixed feed direction appears across a
126
+ field. It is 0 at the reference position, and its value at a pole is that of
127
+ the RA the pole is approached along.
128
+
129
+ Args:
130
+ reference (tuple[float, float]): The (RA, Dec) in degrees the frame is north at
131
+ vectors (NDArray[np.float64]): Unit vectors of the positions, along the leading axis
132
+
133
+ Returns:
134
+ NDArray[np.float64]: Position angles in radians
135
+ """
136
+ _, north = east_north(*reference)
137
+ x, y, z = vectors
138
+ # Unnormalised east (-y, x, 0) and north (-z x, -z y, x^2 + y^2) at each position
139
+ along_east = -north[0] * y + north[1] * x
140
+ along_north = -z * (north[0] * x + north[1] * y) + north[2] * (x**2 + y**2)
141
+ return np.asarray(np.arctan2(along_east, along_north))
142
+
143
+
144
+ def rotate_linear(
145
+ q: NDArray[np.float64], u: NDArray[np.float64], angle: NDArray[np.float64] | float
146
+ ) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
147
+ """Turn polarisation angles by ``angle`` radians east, which turns (Q, U) by twice it."""
148
+ cos_2angle, sin_2angle = np.cos(2 * angle), np.sin(2 * angle)
149
+ return q * cos_2angle - u * sin_2angle, q * sin_2angle + u * cos_2angle
150
+
151
+
152
+ def remove_leakage(
153
+ planes: tuple[NDArray[np.float64], ...],
154
+ stokes: tuple[int, ...],
155
+ stokes_i: NDArray[np.float64],
156
+ leakage: NDArray[np.float64],
157
+ ) -> tuple[NDArray[np.float64], ...]:
158
+ """Subtract the leakage of Stokes I from images of Q, U or V.
159
+
160
+ Args:
161
+ planes (tuple[NDArray[np.float64], ...]): The images, all in the frame of the input
162
+ stokes (tuple[int, ...]): The FITS Stokes code of each image
163
+ stokes_i (NDArray[np.float64]): The Stokes I image, still carrying the primary beam
164
+ leakage (NDArray[np.float64]): Fractional leakage into (Q, U, V), in the frame of the input
165
+
166
+ Raises:
167
+ ValueError: Raised if an image is not of Q, U or V
168
+
169
+ Returns:
170
+ tuple[NDArray[np.float64], ...]: The images with the leakage removed
171
+ """
172
+ if any(code not in (2, 3, 4) for code in stokes):
173
+ msg = f"Leakage is only removed from Q, U and V, not from Stokes codes {stokes}"
174
+ raise ValueError(msg)
175
+ return tuple(
176
+ plane - leakage[code - 2] * stokes_i
177
+ for plane, code in zip(planes, stokes, strict=True)
178
+ )