plotastrodata 1.11.0__tar.gz → 1.11.1__tar.gz
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.
- {plotastrodata-1.11.0/plotastrodata.egg-info → plotastrodata-1.11.1}/PKG-INFO +2 -2
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/README.md +1 -1
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/plotastrodata/__init__.py +1 -1
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/plotastrodata/_type_utils.py +7 -3
- plotastrodata-1.11.1/plotastrodata/_validation_utils.py +70 -0
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/plotastrodata/analysis_utils.py +195 -147
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/plotastrodata/coord_utils.py +8 -7
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/plotastrodata/fft_utils.py +4 -3
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/plotastrodata/fits_utils.py +47 -26
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/plotastrodata/fitting_utils.py +46 -31
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/plotastrodata/noise_utils.py +24 -15
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/plotastrodata/other_utils.py +3 -0
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/plotastrodata/plot_utils.py +440 -315
- {plotastrodata-1.11.0 → plotastrodata-1.11.1/plotastrodata.egg-info}/PKG-INFO +2 -2
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/plotastrodata.egg-info/SOURCES.txt +1 -0
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/LICENSE +0 -0
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/MANIFEST.in +0 -0
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/plotastrodata/const_utils.py +0 -0
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/plotastrodata/ext_utils.py +0 -0
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/plotastrodata/los_utils.py +0 -0
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/plotastrodata/matrix_utils.py +0 -0
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/plotastrodata.egg-info/dependency_links.txt +0 -0
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/plotastrodata.egg-info/not-zip-safe +0 -0
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/plotastrodata.egg-info/requires.txt +0 -0
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/plotastrodata.egg-info/top_level.txt +0 -0
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/setup.cfg +0 -0
- {plotastrodata-1.11.0 → plotastrodata-1.11.1}/setup.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: plotastrodata
|
|
3
|
-
Version: 1.11.
|
|
3
|
+
Version: 1.11.1
|
|
4
4
|
Summary: plotastrodata is a tool for astronomers to create figures from FITS files and perform fundamental data analyses with ease.
|
|
5
5
|
Home-page: https://github.com/yusukeaso-astron/plotastrodata
|
|
6
6
|
Download-URL: https://github.com/yusukeaso-astron/plotastrodata
|
|
@@ -102,7 +102,7 @@ More examples and the complete API reference are available in the [online docume
|
|
|
102
102
|
|
|
103
103
|
## Conventions and Limitations
|
|
104
104
|
|
|
105
|
-
See [Conventions and usage notes](docs/conventions.rst) for data formats, coordinate and angle conventions, runtime types, and
|
|
105
|
+
See [Conventions and usage notes](docs/conventions.rst) for data formats, coordinate and angle conventions, runtime types, input validation, and usage limitations.
|
|
106
106
|
|
|
107
107
|
## Author
|
|
108
108
|
|
|
@@ -73,7 +73,7 @@ More examples and the complete API reference are available in the [online docume
|
|
|
73
73
|
|
|
74
74
|
## Conventions and Limitations
|
|
75
75
|
|
|
76
|
-
See [Conventions and usage notes](docs/conventions.rst) for data formats, coordinate and angle conventions, runtime types, and
|
|
76
|
+
See [Conventions and usage notes](docs/conventions.rst) for data formats, coordinate and angle conventions, runtime types, input validation, and usage limitations.
|
|
77
77
|
|
|
78
78
|
## Author
|
|
79
79
|
|
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""Annotated numeric types and output-boundary precision helpers.
|
|
2
|
+
|
|
3
|
+
Pydantic field coercion and preservation of computed output types are separate
|
|
4
|
+
from the noncoercing input checks in _validation_utils. A 0D array is not
|
|
5
|
+
implicitly a scalar: _normalize_float unwraps one only when the caller
|
|
6
|
+
explicitly requests scalar output.
|
|
7
|
+
"""
|
|
2
8
|
|
|
3
9
|
from dataclasses import field
|
|
4
10
|
import numpy as np
|
|
@@ -30,8 +36,6 @@ BeamInput = np.ndarray | list[RealScalar | None] | tuple[RealScalar | None,
|
|
|
30
36
|
ValidatedBeamTriple = list[ValidatedFloat | None]
|
|
31
37
|
ValidatedBeams = ValidatedBeamTriple | list[ValidatedBeamTriple]
|
|
32
38
|
|
|
33
|
-
|
|
34
|
-
|
|
35
39
|
_FloatNormalizationInput = int | float | np.integer | np.floating | np.ndarray
|
|
36
40
|
_FloatNormalizationResult = int | float | np.integer | np.longdouble | np.ndarray
|
|
37
41
|
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Shared input validation without coercion or changes to numeric precision."""
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _is_zero_dimensional_array(value: Any) -> bool:
|
|
8
|
+
"""Identify a NumPy 0D array without conversion or scalar extraction.
|
|
9
|
+
|
|
10
|
+
This shape predicate does not decide whether a caller accepts the value.
|
|
11
|
+
NumPy scalar objects are not arrays and return False.
|
|
12
|
+
"""
|
|
13
|
+
return isinstance(value, np.ndarray) and value.ndim == 0
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _is_uniform_spacing(steps: np.ndarray,
|
|
17
|
+
reference: int | float | np.integer | np.floating
|
|
18
|
+
) -> bool:
|
|
19
|
+
"""Compare intervals with a caller-selected reference (rtol=1e-5, atol=0).
|
|
20
|
+
|
|
21
|
+
Callers validate shape, finiteness, and allowed direction separately.
|
|
22
|
+
They choose the first interval or mean as appropriate for the operation.
|
|
23
|
+
No input arrays or intermediate scalar precision are changed.
|
|
24
|
+
"""
|
|
25
|
+
return bool(np.allclose(steps, reference, rtol=1e-5, atol=0))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _is_finite_real_scalar(value: Any) -> bool:
|
|
29
|
+
"""Accept finite Python/NumPy real numeric scalars without coercion.
|
|
30
|
+
|
|
31
|
+
Accept int, float, np.integer, and np.floating, excluding booleans.
|
|
32
|
+
Arrays (including 0D), complex values, strings, and other objects are
|
|
33
|
+
rejected. Return a Python bool and preserve extended floating precision.
|
|
34
|
+
"""
|
|
35
|
+
if (isinstance(value, bool)
|
|
36
|
+
or not isinstance(value, (int, float, np.integer, np.floating))):
|
|
37
|
+
return False
|
|
38
|
+
# Integers are finite; np.isfinite cannot handle arbitrary-size Python ints.
|
|
39
|
+
if isinstance(value, (int, np.integer)):
|
|
40
|
+
return True
|
|
41
|
+
return bool(np.isfinite(value))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _is_positive_real_scalar(value: Any) -> bool:
|
|
45
|
+
"""Require finite scalar form and strict positivity without coercion.
|
|
46
|
+
|
|
47
|
+
Return a Python bool; preserve the finite check's extended precision
|
|
48
|
+
and rejection of booleans, complex values, and arrays (including 0D).
|
|
49
|
+
"""
|
|
50
|
+
return _is_finite_real_scalar(value) and bool(value > 0)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _require_positive_real_scalar(value: Any, name: str) -> None:
|
|
54
|
+
"""Raise ValueError for invalid positive scalar input, without coercion."""
|
|
55
|
+
if not _is_positive_real_scalar(value):
|
|
56
|
+
raise ValueError(f'{name} must be a finite positive real scalar.')
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _require_integer(value: Any, name: str, minimum: int = 1) -> None:
|
|
60
|
+
"""Require a Python/NumPy integer at or above minimum, excluding booleans.
|
|
61
|
+
|
|
62
|
+
Floating values (even integral ones) and arrays (including 0D) are
|
|
63
|
+
rejected. Accepted values are left unchanged; normalization belongs at
|
|
64
|
+
public output boundaries.
|
|
65
|
+
"""
|
|
66
|
+
if (isinstance(value, (bool, np.bool_))
|
|
67
|
+
or not isinstance(value, (int, np.integer)) or value < minimum):
|
|
68
|
+
req01 = {0: 'a nonnegative integer', 1: 'a positive integer'}
|
|
69
|
+
requirement = req01.get(minimum, f'an integer of at least {minimum}')
|
|
70
|
+
raise ValueError(f'{name} must be {requirement}.')
|
|
@@ -14,6 +14,11 @@ from typing import (Any, Callable, Literal,
|
|
|
14
14
|
TypeVar, ParamSpec, TypedDict)
|
|
15
15
|
|
|
16
16
|
from plotastrodata import const_utils as cu
|
|
17
|
+
from plotastrodata._validation_utils import (_require_integer,
|
|
18
|
+
_is_finite_real_scalar,
|
|
19
|
+
_is_positive_real_scalar,
|
|
20
|
+
_require_positive_real_scalar,
|
|
21
|
+
_is_zero_dimensional_array)
|
|
17
22
|
from plotastrodata._type_utils import (_normalize_float, _internal_field,
|
|
18
23
|
RealScalar, Position,
|
|
19
24
|
ValidatedFloat, BeamInput)
|
|
@@ -27,6 +32,25 @@ from plotastrodata.other_utils import (nearest_index, RGIxy, RGIxyv,
|
|
|
27
32
|
to4dim, trim)
|
|
28
33
|
|
|
29
34
|
|
|
35
|
+
def _profile_ellipses(ellipse: Any, nprof: int) -> np.ndarray:
|
|
36
|
+
"""Prepare one ellipse per profile without changing supplied array dtypes."""
|
|
37
|
+
if ellipse is None:
|
|
38
|
+
ellipses = np.zeros((nprof, 3))
|
|
39
|
+
else:
|
|
40
|
+
ellipses = np.asarray(ellipse)
|
|
41
|
+
if ellipses.shape == (3,):
|
|
42
|
+
ellipses = np.broadcast_to(ellipses, (nprof, 3))
|
|
43
|
+
elif ellipses.shape != (nprof, 3):
|
|
44
|
+
raise ValueError('ellipse must be one [major, minor, pa] triple'
|
|
45
|
+
+ ' or exactly one triple per position.')
|
|
46
|
+
if (ellipses.dtype.kind not in 'iuf'
|
|
47
|
+
or not np.all(np.isfinite(ellipses))
|
|
48
|
+
or np.any(ellipses[:, :2] < 0)):
|
|
49
|
+
raise ValueError('ellipse values must be finite real numbers'
|
|
50
|
+
+ ' with nonnegative major and minor sizes.')
|
|
51
|
+
return ellipses
|
|
52
|
+
|
|
53
|
+
|
|
30
54
|
def quadrantmean(data: np.ndarray, x: np.ndarray, y: np.ndarray,
|
|
31
55
|
quadrants: Literal['13', '24'] = '13'
|
|
32
56
|
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
@@ -76,13 +100,13 @@ def filled2d(data: np.ndarray, x: np.ndarray, y: np.ndarray,
|
|
|
76
100
|
x (np.ndarray): 1D array.
|
|
77
101
|
y (np.ndarray): 1D array.
|
|
78
102
|
n (int or np.integer, optional): How many times more the new grid is.
|
|
79
|
-
|
|
103
|
+
Must be a positive integer; booleans, floats, and arrays are
|
|
104
|
+
rejected. Defaults to 1.
|
|
80
105
|
|
|
81
106
|
Returns:
|
|
82
107
|
tuple: The interpolated (data, x, y).
|
|
83
108
|
"""
|
|
84
|
-
|
|
85
|
-
raise ValueError('n must be a positive integer.')
|
|
109
|
+
_require_integer(n, 'n')
|
|
86
110
|
xnew = np.linspace(x[0], x[-1], n * (len(x) - 1) + 1)
|
|
87
111
|
ynew = np.linspace(y[0], y[-1], n * (len(y) - 1) + 1)
|
|
88
112
|
d = RGIxy(y, x, data, np.meshgrid(ynew, xnew, indexing='ij'),
|
|
@@ -181,6 +205,8 @@ class AstroData():
|
|
|
181
205
|
lists of arrays (with optional None placeholders) or FITS paths and
|
|
182
206
|
per-dataset metadata lists internally. Initialization determines n;
|
|
183
207
|
AstroFrame.read performs metadata expansion and loading later.
|
|
208
|
+
Scalar and zero-dimensional datasets are rejected at initialization;
|
|
209
|
+
shape/grid requirements are checked during subsequent processing.
|
|
184
210
|
After a read with swapxy=True, data, x/y, and beam angles describe
|
|
185
211
|
the exchanged axes. Analysis and FITS writing use the current axis
|
|
186
212
|
order with their usual conventions; no swap history is retained.
|
|
@@ -224,17 +250,11 @@ class AstroData():
|
|
|
224
250
|
|
|
225
251
|
n = 0
|
|
226
252
|
if has_fits:
|
|
227
|
-
|
|
228
|
-
n = 1
|
|
229
|
-
else:
|
|
230
|
-
n = len(self.fitsimage)
|
|
253
|
+
n = len(fits_values)
|
|
231
254
|
self.data = None
|
|
232
255
|
if has_data:
|
|
233
256
|
if _is_data_list(self.data):
|
|
234
257
|
n = len(self.data)
|
|
235
|
-
elif (isinstance(self.data, list)
|
|
236
|
-
and not any(a is not None for a in self.data)):
|
|
237
|
-
n = 0
|
|
238
258
|
else:
|
|
239
259
|
self.data = np.asarray(self.data)
|
|
240
260
|
n = 1
|
|
@@ -286,21 +306,17 @@ class AstroData():
|
|
|
286
306
|
setattr(self, dt, int(spacing) if isinstance(spacing, np.integer)
|
|
287
307
|
else _normalize_float(spacing))
|
|
288
308
|
|
|
289
|
-
def
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
"""
|
|
293
|
-
|
|
294
|
-
Uses the current axis order, including after AstroFrame swaps x/y.
|
|
295
|
-
PV mode continues to treat the vertical axis as velocity.
|
|
309
|
+
def _prepare_binning(self, width: list[int | np.integer]
|
|
310
|
+
| tuple[int | np.integer, ...] | np.ndarray
|
|
311
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
312
|
+
"""Validate and clamp bin widths, returning data, shape, and factors.
|
|
296
313
|
|
|
297
|
-
|
|
298
|
-
width (list, tuple, or np.ndarray, optional): Number of channels,
|
|
299
|
-
y-pixels, and x-pixels for binning. Defaults to [1, 1, 1].
|
|
314
|
+
Preparation reports clamped widths without changing public attributes.
|
|
300
315
|
"""
|
|
301
|
-
if not 1 <= len(width) <= 3
|
|
302
|
-
or a < 1 for a in width):
|
|
316
|
+
if not 1 <= len(width) <= 3:
|
|
303
317
|
raise ValueError('width must contain one to three positive integers.')
|
|
318
|
+
for i, factor in enumerate(width):
|
|
319
|
+
_require_integer(factor, f'width[{i}]')
|
|
304
320
|
w = np.array([1] * (3 - len(width)) + list(width), dtype=int)
|
|
305
321
|
if self.pv:
|
|
306
322
|
w[1] = max(w[0], w[1])
|
|
@@ -311,6 +327,23 @@ class AstroData():
|
|
|
311
327
|
w = np.minimum(w, size[1:])
|
|
312
328
|
ws = ', '.join([f'{s:d}' for s in w])
|
|
313
329
|
print(f'width was changed to [{ws}].')
|
|
330
|
+
return data4d, size, w
|
|
331
|
+
|
|
332
|
+
def binning(self, width: list[int | np.integer]
|
|
333
|
+
| tuple[int | np.integer, ...] | np.ndarray = [1, 1, 1]
|
|
334
|
+
) -> None:
|
|
335
|
+
"""Binning up neighboring pixels in the v, y, and x domain.
|
|
336
|
+
|
|
337
|
+
Uses the current axis order, including after AstroFrame swaps x/y.
|
|
338
|
+
PV mode continues to treat the vertical axis as velocity.
|
|
339
|
+
|
|
340
|
+
Args:
|
|
341
|
+
width (list, tuple, or np.ndarray, optional): Number of channels,
|
|
342
|
+
y-pixels, and x-pixels for binning. Entries must be positive
|
|
343
|
+
Python/NumPy integer scalars; booleans, floats, and
|
|
344
|
+
array-valued entries are rejected. Defaults to [1, 1, 1].
|
|
345
|
+
"""
|
|
346
|
+
data4d, size, w = self._prepare_binning(width)
|
|
314
347
|
for axis, factor in zip(('v', 'y', 'x'), w):
|
|
315
348
|
if factor > 1 and getattr(self, axis) is None:
|
|
316
349
|
raise ValueError(f'Binning in the {axis}-axis requires'
|
|
@@ -480,8 +513,9 @@ class AstroData():
|
|
|
480
513
|
chan: int | np.integer | None = None) -> _Fit2DResult:
|
|
481
514
|
"""Fit a given 2D model function to self.data.
|
|
482
515
|
|
|
483
|
-
Requires finite, positive scalar sigma
|
|
484
|
-
|
|
516
|
+
Requires finite, positive real scalar sigma; booleans and arrays are
|
|
517
|
+
rejected. Missing beam sizes disable beam correction.
|
|
518
|
+
Likelihood scalars preserve extended precision.
|
|
485
519
|
|
|
486
520
|
Default keyword values:
|
|
487
521
|
kwargs_plotcorner: ``show=False`` and ``savefig=None``.
|
|
@@ -508,8 +542,7 @@ class AstroData():
|
|
|
508
542
|
(residual).
|
|
509
543
|
"""
|
|
510
544
|
d = self._fit_image(chan)
|
|
511
|
-
if
|
|
512
|
-
or not np.isfinite(self.sigma) or self.sigma <= 0):
|
|
545
|
+
if not _is_positive_real_scalar(self.sigma):
|
|
513
546
|
raise ValueError('fit2d requires finite, positive scalar sigma.')
|
|
514
547
|
x, y = np.meshgrid(self.x, self.y)
|
|
515
548
|
if d.shape != x.shape:
|
|
@@ -551,7 +584,9 @@ class AstroData():
|
|
|
551
584
|
) -> _GaussFit2DResult:
|
|
552
585
|
"""Fit a 2D Gaussian function to self.data using
|
|
553
586
|
fitting_utils.gaussfit2d(). With sigma=None, noise is estimated
|
|
554
|
-
from an initial fit.
|
|
587
|
+
from an initial fit. Supplied sigma must be a finite positive real
|
|
588
|
+
scalar; booleans and arrays are rejected. Missing beam sizes disable
|
|
589
|
+
beam correction.
|
|
555
590
|
|
|
556
591
|
Args:
|
|
557
592
|
chan (int): The channel number where the 2D Gaussian is
|
|
@@ -568,11 +603,7 @@ class AstroData():
|
|
|
568
603
|
z = self._fit_image(chan)
|
|
569
604
|
if z.shape != (len(self.y), len(self.x)):
|
|
570
605
|
raise ValueError('Selected image shape must match the x/y grids.')
|
|
571
|
-
if self.sigma is not None and (
|
|
572
|
-
not isinstance(self.sigma, (numbers.Real,
|
|
573
|
-
np.floating,
|
|
574
|
-
np.integer))
|
|
575
|
-
or not np.isfinite(self.sigma) or self.sigma <= 0):
|
|
606
|
+
if self.sigma is not None and not _is_positive_real_scalar(self.sigma):
|
|
576
607
|
raise ValueError('gaussfit2d requires finite, positive scalar'
|
|
577
608
|
+ ' sigma or None.')
|
|
578
609
|
# Automatic estimation is handled by the underlying fitter; there is
|
|
@@ -694,8 +725,8 @@ class AstroData():
|
|
|
694
725
|
ellipse (list, tuple, or np.ndarray, optional): One
|
|
695
726
|
[major, minor, pa] triple shared by all positions, or one
|
|
696
727
|
triple per position. None selects nearest pixels.
|
|
697
|
-
ninterp (int or np.integer, optional):
|
|
698
|
-
Defaults to 1.
|
|
728
|
+
ninterp (int or np.integer, optional): Positive interpolation factor.
|
|
729
|
+
Booleans, floats, and arrays are rejected. Defaults to 1.
|
|
699
730
|
flux (bool, optional): Jy/beam to Jy. Defaults to False.
|
|
700
731
|
gaussfit (bool, optional): Fit the profiles. Defaults to
|
|
701
732
|
False.
|
|
@@ -719,20 +750,7 @@ class AstroData():
|
|
|
719
750
|
nprof = len(xlist)
|
|
720
751
|
dtype = data.dtype if data.dtype.kind in 'fc' else np.dtype(float)
|
|
721
752
|
prof = np.empty((nprof, len(self.v)), dtype=dtype)
|
|
722
|
-
|
|
723
|
-
ellipses = np.zeros((nprof, 3))
|
|
724
|
-
else:
|
|
725
|
-
ellipses = np.asarray(ellipse)
|
|
726
|
-
if ellipses.shape == (3,):
|
|
727
|
-
ellipses = np.broadcast_to(ellipses, (nprof, 3))
|
|
728
|
-
elif ellipses.shape != (nprof, 3):
|
|
729
|
-
raise ValueError('ellipse must be one [major, minor, pa] triple '
|
|
730
|
-
'or exactly one triple per position.')
|
|
731
|
-
if (ellipses.dtype.kind not in 'iuf'
|
|
732
|
-
or not np.all(np.isfinite(ellipses))
|
|
733
|
-
or np.any(ellipses[:, :2] < 0)):
|
|
734
|
-
raise ValueError('ellipse values must be finite real numbers '
|
|
735
|
-
+ 'with nonnegative major and minor sizes.')
|
|
753
|
+
ellipses = _profile_ellipses(ellipse, nprof)
|
|
736
754
|
calc = np.sum if flux else np.mean
|
|
737
755
|
for i, (xc, yc, e) in enumerate(zip(xlist, ylist, ellipses)):
|
|
738
756
|
major, minor, pa = e
|
|
@@ -768,22 +786,23 @@ class AstroData():
|
|
|
768
786
|
self.beam = list(self.beam)
|
|
769
787
|
self.beam[2] = _normalize_float(self.beam[2] + pa)
|
|
770
788
|
|
|
771
|
-
def slice(self, length: float | np.floating
|
|
789
|
+
def slice(self, length: float | np.floating,
|
|
772
790
|
pa: float | np.floating = 0,
|
|
773
791
|
dx: float | np.floating | None = None, **kwargs: Any
|
|
774
792
|
) -> tuple[np.ndarray, np.ndarray]:
|
|
775
793
|
"""Get 1D slice with given a length and a position-angle.
|
|
776
794
|
|
|
777
795
|
Args:
|
|
778
|
-
length (float
|
|
796
|
+
length (float or np.floating): Required finite positive slice
|
|
797
|
+
length. Booleans and arrays are rejected.
|
|
779
798
|
pa (float, optional): Position angle in the unit of degree.
|
|
780
799
|
Defaults to 0.
|
|
781
|
-
dx (float, optional):
|
|
800
|
+
dx (float or np.floating, optional): Finite positive grid increment.
|
|
801
|
+
Booleans and arrays are rejected. None uses abs(self.dx).
|
|
782
802
|
|
|
783
803
|
Returns:
|
|
784
804
|
tuple: (positions, data). Data have shape (npositions,) for
|
|
785
|
-
images or (nchannels, npositions) for cubes
|
|
786
|
-
length=0 gives one position.
|
|
805
|
+
images or (nchannels, npositions) for cubes.
|
|
787
806
|
"""
|
|
788
807
|
if self.data.ndim not in (2, 3):
|
|
789
808
|
raise ValueError('slice() requires a 2D image or 3D cube.')
|
|
@@ -791,10 +810,8 @@ class AstroData():
|
|
|
791
810
|
dx = np.abs(self.dx)
|
|
792
811
|
if dx is None:
|
|
793
812
|
raise ValueError('slice() requires dx or an x grid with pixel size.')
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
if not np.isfinite(length) or length < 0:
|
|
797
|
-
raise ValueError('length must be finite and nonnegative.')
|
|
813
|
+
_require_positive_real_scalar(dx, 'dx')
|
|
814
|
+
_require_positive_real_scalar(length, 'length')
|
|
798
815
|
|
|
799
816
|
n = int(np.ceil(length / 2 / dx))
|
|
800
817
|
r = np.linspace(-n, n, 2 * n + 1) * dx
|
|
@@ -845,49 +862,25 @@ class AstroData():
|
|
|
845
862
|
raise ValueError('Writing a velocity axis requires coordinates'
|
|
846
863
|
+ ' and spacing.')
|
|
847
864
|
cv, dv = self.v[ck], self.dv
|
|
865
|
+
if (self.restfreq is not None
|
|
866
|
+
and (not _is_finite_real_scalar(self.restfreq)
|
|
867
|
+
or self.restfreq < 0)):
|
|
868
|
+
raise ValueError('restfreq must be finite and positive,'
|
|
869
|
+
+ ' or None/0.')
|
|
848
870
|
if self.restfreq is None or self.restfreq == 0:
|
|
849
871
|
warnings.warn('No valid restfreq. The velocity axis is saved as is.',
|
|
850
872
|
UserWarning)
|
|
851
873
|
else:
|
|
852
|
-
if not np.isfinite(self.restfreq) or self.restfreq < 0:
|
|
853
|
-
raise ValueError('restfreq must be finite and positive,'
|
|
854
|
-
+ ' or None/0.')
|
|
855
874
|
cv = (1 - cv / cu.c_kms) * self.restfreq
|
|
856
875
|
dv = -dv / cu.c_kms * self.restfreq
|
|
857
876
|
return (_normalize_float(cv, force_float=True),
|
|
858
877
|
_normalize_float(dv, force_float=True))
|
|
859
878
|
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
header: Header | dict[str, Any] | None = None) -> None:
|
|
863
|
-
"""Write a single image or cube, overwriting an existing file.
|
|
864
|
-
|
|
865
|
-
Spatial axes use degrees, undoing any distance scaling applied by
|
|
866
|
-
AstroFrame.read. Known sky centers use celestial coordinates;
|
|
867
|
-
otherwise spatial axes are linear angular offsets. PV spatial axes
|
|
868
|
-
are also angular offsets. Spectral axes use Hz
|
|
869
|
-
when restfreq is known, otherwise radio velocity in km/s.
|
|
870
|
-
|
|
871
|
-
Axis roles follow the current data order. A prior swapxy is not
|
|
872
|
-
undone; PV output still treats x as position and y/v as velocity.
|
|
879
|
+
def _spatial_fits_header(self, h: dict[str, Any]) -> None:
|
|
880
|
+
"""Add spatial WCS cards in degrees for the current axis order.
|
|
873
881
|
|
|
874
|
-
|
|
875
|
-
serialized as Python floats, which can narrow extended precision.
|
|
876
|
-
Missing required grid spacing raises ValueError.
|
|
882
|
+
Header values are export scalars; in-memory grids retain precision.
|
|
877
883
|
"""
|
|
878
|
-
if (not isinstance(self.data, np.ndarray)
|
|
879
|
-
or self.data.ndim not in (2, 3)):
|
|
880
|
-
raise ValueError('writetofits requires a single 2D image'
|
|
881
|
-
+ ' or 3D cube.')
|
|
882
|
-
if not np.isfinite(self.dist) or self.dist <= 0:
|
|
883
|
-
raise ValueError('dist must be finite and positive.')
|
|
884
|
-
# Retain non-coordinate metadata; rebuild WCS for processed data.
|
|
885
|
-
h = dict(self.fitsheader.items()) if self.fitsheader is not None else {}
|
|
886
|
-
for key in list(h):
|
|
887
|
-
if (re.match(r'^(NAXIS|CTYPE|CUNIT|CRPIX|CRVAL|CDELT|CROTA)\d*$', key)
|
|
888
|
-
or re.match(r'^(PC|CD|PV|PS)\d+_\d+$', key)
|
|
889
|
-
or key in ('WCSAXES', 'LONPOLE', 'LATPOLE')):
|
|
890
|
-
del h[key]
|
|
891
884
|
ci = nearest_index(self.x)
|
|
892
885
|
celestial = self.center is not None and not self.pv
|
|
893
886
|
if celestial:
|
|
@@ -913,17 +906,37 @@ class AstroData():
|
|
|
913
906
|
h.update(CTYPE2='LINEAR', CUNIT2='deg')
|
|
914
907
|
self._put_header(h, 'y', cj + 1, self.y[cj] / self.dist / 3600,
|
|
915
908
|
self.dy / self.dist / 3600)
|
|
909
|
+
|
|
910
|
+
def _spectral_fits_header(self, h: dict[str, Any]) -> None:
|
|
911
|
+
"""Add frequency or velocity cards to the cube/PV spectral axis."""
|
|
912
|
+
if self.v is None:
|
|
913
|
+
raise ValueError('A cube or PV image requires'
|
|
914
|
+
+ ' velocity coordinates.')
|
|
915
|
+
ck = nearest_index(self.v)
|
|
916
|
+
cv, dv = self._get_cvdv_in_freq(ck)
|
|
917
|
+
axis = 2 if self.pv else 3
|
|
918
|
+
frequency = self.restfreq is not None and self.restfreq != 0
|
|
919
|
+
h[f'CTYPE{axis}'] = 'FREQ' if frequency else 'VRAD'
|
|
920
|
+
h[f'CUNIT{axis}'] = 'Hz' if frequency else 'km/s'
|
|
921
|
+
self._put_header(h, 'v', ck + 1, cv, dv)
|
|
922
|
+
|
|
923
|
+
def _build_fits_header(self) -> dict[str, Any]:
|
|
924
|
+
"""Rebuild processed WCS and metadata in a separate export payload.
|
|
925
|
+
|
|
926
|
+
Numeric FITS cards may narrow extended precision to Python floats.
|
|
927
|
+
PV output uses original sky-beam metadata when available.
|
|
928
|
+
"""
|
|
929
|
+
# Retain non-coordinate metadata; rebuild WCS for processed data.
|
|
930
|
+
h = dict(self.fitsheader.items()) if self.fitsheader is not None else {}
|
|
931
|
+
for key in list(h):
|
|
932
|
+
onenumkeys = r'^(NAXIS|CTYPE|CUNIT|CRPIX|CRVAL|CDELT|CROTA)\d*$'
|
|
933
|
+
twonumkeys = r'^(PC|CD|PV|PS)\d+_\d+$'
|
|
934
|
+
if (re.match(onenumkeys, key) or re.match(twonumkeys, key)
|
|
935
|
+
or key in ('WCSAXES', 'LONPOLE', 'LATPOLE')):
|
|
936
|
+
del h[key]
|
|
937
|
+
self._spatial_fits_header(h)
|
|
916
938
|
if self.pv or self.data.ndim == 3:
|
|
917
|
-
|
|
918
|
-
raise ValueError('A cube or PV image requires'
|
|
919
|
-
+ ' velocity coordinates.')
|
|
920
|
-
ck = nearest_index(self.v)
|
|
921
|
-
cv, dv = self._get_cvdv_in_freq(ck)
|
|
922
|
-
axis = 2 if self.pv else 3
|
|
923
|
-
frequency = self.restfreq is not None and self.restfreq != 0
|
|
924
|
-
h[f'CTYPE{axis}'] = 'FREQ' if frequency else 'VRAD'
|
|
925
|
-
h[f'CUNIT{axis}'] = 'Hz' if frequency else 'km/s'
|
|
926
|
-
self._put_header(h, 'v', ck + 1, cv, dv)
|
|
939
|
+
self._spectral_fits_header(h)
|
|
927
940
|
beam = self.beam_org if self.pv else self.beam
|
|
928
941
|
if beam is not None and None not in beam:
|
|
929
942
|
h['BMAJ'] = float(beam[0] / self.dist / 3600)
|
|
@@ -939,6 +952,32 @@ class AstroData():
|
|
|
939
952
|
h['BUNIT'] = self.bunit
|
|
940
953
|
if self.restfreq is not None and self.restfreq > 0:
|
|
941
954
|
h['RESTFRQ'] = float(self.restfreq)
|
|
955
|
+
return h
|
|
956
|
+
|
|
957
|
+
@_need_multipixels
|
|
958
|
+
def writetofits(self, fitsimage: str | PathLike[str] = 'out.fits',
|
|
959
|
+
header: Header | dict[str, Any] | None = None) -> None:
|
|
960
|
+
"""Write a single image or cube, overwriting an existing file.
|
|
961
|
+
|
|
962
|
+
Spatial axes use degrees, undoing any distance scaling applied by
|
|
963
|
+
AstroFrame.read. Known sky centers use celestial coordinates;
|
|
964
|
+
otherwise spatial axes are linear angular offsets. PV spatial axes
|
|
965
|
+
are also angular offsets. Spectral axes use Hz
|
|
966
|
+
when restfreq is known, otherwise radio velocity in km/s.
|
|
967
|
+
|
|
968
|
+
Axis roles follow the current data order. A prior swapxy is not
|
|
969
|
+
undone; PV output still treats x as position and y/v as velocity.
|
|
970
|
+
|
|
971
|
+
header optionally overrides generated cards. Numeric FITS cards are
|
|
972
|
+
serialized as Python floats, which can narrow extended precision.
|
|
973
|
+
Missing required grid spacing raises ValueError.
|
|
974
|
+
"""
|
|
975
|
+
if (not isinstance(self.data, np.ndarray)
|
|
976
|
+
or self.data.ndim not in (2, 3)):
|
|
977
|
+
raise ValueError('writetofits requires a single 2D image'
|
|
978
|
+
+ ' or 3D cube.')
|
|
979
|
+
_require_positive_real_scalar(self.dist, 'dist')
|
|
980
|
+
h = self._build_fits_header()
|
|
942
981
|
h.update(header or {})
|
|
943
982
|
data2fits(d=self.data, h=h, fitsimage=str(fitsimage))
|
|
944
983
|
|
|
@@ -973,6 +1012,50 @@ ASTRODATA_ARGS = ['fitsimage', 'data', 'Tb', 'sigma', 'center', 'restfreq',
|
|
|
973
1012
|
_Grid = list[np.ndarray | None]
|
|
974
1013
|
|
|
975
1014
|
|
|
1015
|
+
def _validate_shared_grid(expected_grid: _Grid, actual_grid: _Grid,
|
|
1016
|
+
dataset: int) -> None:
|
|
1017
|
+
"""Require matching processed grids, including missing axes (rtol=1e-7, atol=0)."""
|
|
1018
|
+
for name, expected, actual in zip(('x', 'y', 'v'),
|
|
1019
|
+
expected_grid, actual_grid):
|
|
1020
|
+
same = expected is None and actual is None
|
|
1021
|
+
if expected is not None and actual is not None:
|
|
1022
|
+
same = (expected.shape == actual.shape
|
|
1023
|
+
and np.allclose(expected, actual,
|
|
1024
|
+
rtol=1e-7, atol=0))
|
|
1025
|
+
if not same:
|
|
1026
|
+
raise ValueError(f'Dataset {dataset} has a different'
|
|
1027
|
+
+ f' processed {name} grid; datasets'
|
|
1028
|
+
+ ' in one AstroData must share'
|
|
1029
|
+
+ ' coordinate grids.')
|
|
1030
|
+
|
|
1031
|
+
|
|
1032
|
+
def _prepare_positions(poslist: Position | list[Position]
|
|
1033
|
+
| tuple[Position, ...]
|
|
1034
|
+
) -> list[Position] | tuple[Position, ...] | np.ndarray:
|
|
1035
|
+
"""Prepare a position collection without coercing mixed inputs or scalars."""
|
|
1036
|
+
def is_pair(value: Any) -> bool:
|
|
1037
|
+
return (isinstance(value, (list, tuple, np.ndarray))
|
|
1038
|
+
and not _is_zero_dimensional_array(value)
|
|
1039
|
+
and len(value) == 2
|
|
1040
|
+
and all(isinstance(v, (numbers.Real, np.integer, np.floating))
|
|
1041
|
+
for v in value))
|
|
1042
|
+
|
|
1043
|
+
if isinstance(poslist, str):
|
|
1044
|
+
poslist = [poslist]
|
|
1045
|
+
elif (isinstance(poslist, (list, tuple, np.ndarray))
|
|
1046
|
+
and not _is_zero_dimensional_array(poslist)):
|
|
1047
|
+
# Test elements without converting a mixed collection to an array.
|
|
1048
|
+
if is_pair(poslist):
|
|
1049
|
+
poslist = [poslist]
|
|
1050
|
+
else:
|
|
1051
|
+
raise ValueError('Each position must be a string or a numeric pair.')
|
|
1052
|
+
for position in poslist:
|
|
1053
|
+
if not isinstance(position, str) and not is_pair(position):
|
|
1054
|
+
raise ValueError('Each numeric position must contain'
|
|
1055
|
+
+ ' two real scalars.')
|
|
1056
|
+
return poslist
|
|
1057
|
+
|
|
1058
|
+
|
|
976
1059
|
@pydantic_dataclass(config=ConfigDict(arbitrary_types_allowed=True))
|
|
977
1060
|
class AstroFrame():
|
|
978
1061
|
"""Parameter set to limit and reshape the data in the AstroData
|
|
@@ -1079,11 +1162,13 @@ class AstroFrame():
|
|
|
1079
1162
|
Args:
|
|
1080
1163
|
poslist: One sky-coordinate string or numeric pair, or a list,
|
|
1081
1164
|
tuple, or array of positions. Mixed strings and pairs are
|
|
1082
|
-
supported.
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
the
|
|
1165
|
+
supported. Zero-dimensional arrays are rejected, including
|
|
1166
|
+
zero-dimensional string arrays. Sky-coordinate strings require
|
|
1167
|
+
a center; their angular offsets are multiplied by dist and
|
|
1168
|
+
exchanged when swapxy=True. xflip and yflip affect only
|
|
1169
|
+
the display, without changing these sky offsets.
|
|
1170
|
+
Numeric pairs are fractions of the displayed axis limits
|
|
1171
|
+
and are not exchanged by swapxy.
|
|
1087
1172
|
|
|
1088
1173
|
Returns:
|
|
1089
1174
|
np.ndarray: Coordinates with shape (2, N), including (2, 1)
|
|
@@ -1093,32 +1178,7 @@ class AstroFrame():
|
|
|
1093
1178
|
ValueError: If a numeric position is not a pair of real scalars,
|
|
1094
1179
|
or sky coordinates are supplied without a center.
|
|
1095
1180
|
"""
|
|
1096
|
-
|
|
1097
|
-
return (isinstance(value, (list, tuple, np.ndarray))
|
|
1098
|
-
and not (isinstance(value, np.ndarray) and value.ndim == 0)
|
|
1099
|
-
and len(value) == 2
|
|
1100
|
-
and all(isinstance(v, (numbers.Real,
|
|
1101
|
-
np.integer,
|
|
1102
|
-
np.floating))
|
|
1103
|
-
for v in value))
|
|
1104
|
-
|
|
1105
|
-
if isinstance(poslist, str):
|
|
1106
|
-
poslist = [poslist]
|
|
1107
|
-
elif isinstance(poslist, np.ndarray) and poslist.ndim == 0:
|
|
1108
|
-
raise ValueError('Each position must be a string or a numeric pair.')
|
|
1109
|
-
elif isinstance(poslist, (list, tuple, np.ndarray)):
|
|
1110
|
-
# Test elements without converting a mixed collection to an array.
|
|
1111
|
-
if (len(poslist) == 2
|
|
1112
|
-
and all(isinstance(v, (numbers.Real,
|
|
1113
|
-
np.integer,
|
|
1114
|
-
np.floating)) for v in poslist)):
|
|
1115
|
-
poslist = [poslist]
|
|
1116
|
-
else:
|
|
1117
|
-
raise ValueError('Each position must be a string or a numeric pair.')
|
|
1118
|
-
for position in poslist:
|
|
1119
|
-
if not isinstance(position, str) and not is_pair(position):
|
|
1120
|
-
raise ValueError('Each numeric position must contain'
|
|
1121
|
-
+ ' two real scalars.')
|
|
1181
|
+
poslist = _prepare_positions(poslist)
|
|
1122
1182
|
if self.center is None and any(isinstance(p, str) for p in poslist):
|
|
1123
1183
|
clsname = type(self).__name__
|
|
1124
1184
|
raise ValueError(f'{clsname}.pos2xy() requires "center"'
|
|
@@ -1334,11 +1394,11 @@ class AstroFrame():
|
|
|
1334
1394
|
|
|
1335
1395
|
Args:
|
|
1336
1396
|
d (AstroData): Dataclass for the add_* input.
|
|
1337
|
-
xskip, yskip (int or np.integer):
|
|
1397
|
+
xskip, yskip (int or np.integer): Positive spatial pixel skips.
|
|
1398
|
+
Booleans, floats, and arrays are rejected. Defaults to 1.
|
|
1338
1399
|
"""
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
raise ValueError('xskip and yskip must be positive integers.')
|
|
1400
|
+
_require_integer(xskip, 'xskip')
|
|
1401
|
+
_require_integer(yskip, 'yskip')
|
|
1342
1402
|
d.dist = self.dist
|
|
1343
1403
|
self.xskip = int(xskip)
|
|
1344
1404
|
self.yskip = int(yskip)
|
|
@@ -1361,19 +1421,7 @@ class AstroFrame():
|
|
|
1361
1421
|
if shared_grid is None:
|
|
1362
1422
|
shared_grid = [None if a is None else a.copy() for a in current]
|
|
1363
1423
|
else:
|
|
1364
|
-
|
|
1365
|
-
shared_grid,
|
|
1366
|
-
current):
|
|
1367
|
-
same = expected is None and actual is None
|
|
1368
|
-
if expected is not None and actual is not None:
|
|
1369
|
-
same = (expected.shape == actual.shape
|
|
1370
|
-
and np.allclose(expected, actual,
|
|
1371
|
-
rtol=1e-7, atol=0))
|
|
1372
|
-
if not same:
|
|
1373
|
-
raise ValueError(f'Dataset {i} has a different'
|
|
1374
|
-
+ f' processed {name} grid; datasets'
|
|
1375
|
-
+ ' in one AstroData must share'
|
|
1376
|
-
+ ' coordinate grids.')
|
|
1424
|
+
_validate_shared_grid(shared_grid, current, i)
|
|
1377
1425
|
for name in ASTRODATA_ARGS + ['beam']:
|
|
1378
1426
|
setattr(d, name, _scalar_if_single(getattr(d, name), d.n))
|
|
1379
1427
|
if self.swapxy:
|