plotastrodata 1.13.0__py3-none-any.whl → 1.13.2__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.
- plotastrodata/__init__.py +1 -1
- plotastrodata/_ptemcee_compat.py +37 -0
- plotastrodata/analysis_utils.py +100 -47
- plotastrodata/coord_utils.py +2 -2
- plotastrodata/fft_utils.py +4 -4
- plotastrodata/fits_utils.py +7 -7
- plotastrodata/fitting_utils.py +171 -59
- plotastrodata/noise_utils.py +11 -11
- plotastrodata/other_utils.py +5 -5
- plotastrodata/plot_utils.py +32 -32
- plotastrodata/pngpdf_utils.py +168 -45
- plotastrodata/script_utils.py +3 -3
- {plotastrodata-1.13.0.dist-info → plotastrodata-1.13.2.dist-info}/METADATA +8 -2
- plotastrodata-1.13.2.dist-info/RECORD +23 -0
- {plotastrodata-1.13.0.dist-info → plotastrodata-1.13.2.dist-info}/WHEEL +1 -1
- plotastrodata-1.13.0.dist-info/RECORD +0 -22
- {plotastrodata-1.13.0.dist-info → plotastrodata-1.13.2.dist-info}/licenses/LICENSE +0 -0
- {plotastrodata-1.13.0.dist-info → plotastrodata-1.13.2.dist-info}/top_level.txt +0 -0
plotastrodata/__init__.py
CHANGED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Parallel-tempering compatibility, loaded only when selected."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import ptemcee
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class _PTSampler(ptemcee.Sampler):
|
|
8
|
+
"""Support ptemcee 1.0's sampler on NumPy without the np.float alias.
|
|
9
|
+
|
|
10
|
+
Only reset and likelihood evaluation need the obsolete alias. Keep
|
|
11
|
+
their behavior while using float for the sampler's float64 buffers.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
def reset(self, random=None, betas=None, time=None) -> None:
|
|
15
|
+
"""Clear stored samples, counters, and current sampling state."""
|
|
16
|
+
for name in ('_chain', '_logposterior', '_loglikelihood',
|
|
17
|
+
'_beta_history', '_p0', '_logposterior0',
|
|
18
|
+
'_loglikelihood0'):
|
|
19
|
+
setattr(self, name, None)
|
|
20
|
+
self._time = 0 if time is None else time
|
|
21
|
+
if betas is not None:
|
|
22
|
+
self._betas = betas
|
|
23
|
+
if random is not None:
|
|
24
|
+
self._random = random
|
|
25
|
+
self.nswap = np.zeros(self.ntemps, dtype=float)
|
|
26
|
+
self.nswap_accepted = np.zeros(self.ntemps, dtype=float)
|
|
27
|
+
self.nprop = np.zeros((self.ntemps, self.nwalkers), dtype=float)
|
|
28
|
+
self.nprop_accepted = np.zeros_like(self.nprop)
|
|
29
|
+
|
|
30
|
+
def _evaluate(self, ps: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
31
|
+
"""Evaluate likelihood and prior for every temperature and walker."""
|
|
32
|
+
map_function = map if self.pool is None else self.pool.map
|
|
33
|
+
results = list(map_function(self._likeprior,
|
|
34
|
+
ps.reshape((-1, self.dim))))
|
|
35
|
+
values = np.asarray(results, dtype=float)
|
|
36
|
+
shape = (self.ntemps, -1)
|
|
37
|
+
return values[:, 0].reshape(shape), values[:, 1].reshape(shape)
|
plotastrodata/analysis_utils.py
CHANGED
|
@@ -4,7 +4,8 @@ import warnings
|
|
|
4
4
|
from dataclasses import dataclass, field
|
|
5
5
|
from functools import wraps
|
|
6
6
|
from os import PathLike
|
|
7
|
-
from typing import Any, Callable, Literal,
|
|
7
|
+
from typing import (Any, Callable, Literal,
|
|
8
|
+
ParamSpec, TypedDict, TypeVar)
|
|
8
9
|
|
|
9
10
|
import numpy as np
|
|
10
11
|
from astropy.io.fits import Header
|
|
@@ -33,7 +34,7 @@ from plotastrodata._validation_utils import (
|
|
|
33
34
|
from plotastrodata.coord_utils import _getframe, coord2xy, rel2abs, xy2coord
|
|
34
35
|
from plotastrodata.fits_utils import FitsData, Jy2K, data2fits
|
|
35
36
|
from plotastrodata.fitting_utils import (
|
|
36
|
-
EmceeCorner, gaussfit1d, gaussfit2d, gaussian2d
|
|
37
|
+
EmceeCorner, gaussfit1d, gaussfit2d, gaussian2d, gaussian_deconvolve
|
|
37
38
|
)
|
|
38
39
|
from plotastrodata.matrix_utils import Mfac, Mrot, dot2d
|
|
39
40
|
from plotastrodata.noise_utils import estimate_ranges, estimate_rms
|
|
@@ -55,14 +56,14 @@ def _validate_moment_cube(data: np.ndarray, v: np.ndarray,
|
|
|
55
56
|
or data.dtype.kind not in 'iuf'
|
|
56
57
|
or np.any(np.isinf(data))):
|
|
57
58
|
raise ValueError('moment requires a nonempty real 3D cube'
|
|
58
|
-
|
|
59
|
+
' without infinities.')
|
|
59
60
|
if not isinstance(v, np.ndarray):
|
|
60
61
|
raise TypeError('moment requires v to be a NumPy array.')
|
|
61
62
|
if (v.ndim != 1 or v.size != data.shape[0]
|
|
62
63
|
or v.dtype.kind not in 'iuf'
|
|
63
64
|
or not np.all(np.isfinite(v))):
|
|
64
65
|
raise ValueError('v must be a finite real 1D grid matching'
|
|
65
|
-
|
|
66
|
+
' the number of channels.')
|
|
66
67
|
if not _is_positive_real_scalar(sigma):
|
|
67
68
|
raise ValueError('moment requires finite positive scalar sigma.')
|
|
68
69
|
if not _is_finite_real_scalar(dv) or dv == 0:
|
|
@@ -73,7 +74,7 @@ def _validate_moment_cube(data: np.ndarray, v: np.ndarray,
|
|
|
73
74
|
or not _is_uniform_spacing(steps, steps[0])
|
|
74
75
|
or not _is_uniform_spacing(np.abs(steps), abs(dv))):
|
|
75
76
|
raise ValueError('v must be monotonic and uniformly spaced'
|
|
76
|
-
|
|
77
|
+
' with spacing magnitude abs(dv).')
|
|
77
78
|
|
|
78
79
|
|
|
79
80
|
def _validate_moment_inputs(data: np.ndarray, v: np.ndarray,
|
|
@@ -92,7 +93,7 @@ def _validate_moment_inputs(data: np.ndarray, v: np.ndarray,
|
|
|
92
93
|
('threshold_mom0', threshold_mom0)):
|
|
93
94
|
if not _is_finite_real_scalar(value) or value < 0:
|
|
94
95
|
raise ValueError(f'{name} must be a finite nonnegative'
|
|
95
|
-
|
|
96
|
+
' real scalar.')
|
|
96
97
|
if vmask is None:
|
|
97
98
|
vmask = np.ones(v.size, dtype=bool)
|
|
98
99
|
elif not isinstance(vmask, np.ndarray):
|
|
@@ -100,7 +101,7 @@ def _validate_moment_inputs(data: np.ndarray, v: np.ndarray,
|
|
|
100
101
|
if (vmask.dtype.kind != 'b' or vmask.shape != v.shape
|
|
101
102
|
or not np.any(vmask)):
|
|
102
103
|
raise ValueError('vmask must be a 1D Boolean array matching v'
|
|
103
|
-
|
|
104
|
+
' and selecting at least one channel.')
|
|
104
105
|
|
|
105
106
|
return vmask
|
|
106
107
|
|
|
@@ -115,12 +116,12 @@ def _profile_ellipses(ellipse: Any, nprof: int) -> np.ndarray:
|
|
|
115
116
|
ellipses = np.broadcast_to(ellipses, (nprof, 3))
|
|
116
117
|
elif ellipses.shape != (nprof, 3):
|
|
117
118
|
raise ValueError('ellipse must be one [major, minor, pa] triple'
|
|
118
|
-
|
|
119
|
+
' or exactly one triple per position.')
|
|
119
120
|
if (ellipses.dtype.kind not in 'iuf'
|
|
120
121
|
or not np.all(np.isfinite(ellipses))
|
|
121
122
|
or np.any(ellipses[:, :2] < 0)):
|
|
122
123
|
raise ValueError('ellipse values must be finite real numbers'
|
|
123
|
-
|
|
124
|
+
' with nonnegative major and minor sizes.')
|
|
124
125
|
return ellipses
|
|
125
126
|
|
|
126
127
|
|
|
@@ -200,7 +201,7 @@ def _need_multipixels(method: Callable[_MethodArgs, _MethodResult]
|
|
|
200
201
|
singlepixel = cls.dx is None or cls.dy is None
|
|
201
202
|
if singlepixel:
|
|
202
203
|
raise ValueError(f'{method.__name__}() requires at least'
|
|
203
|
-
|
|
204
|
+
' two x and y pixels.')
|
|
204
205
|
return method(*args, **kwargs)
|
|
205
206
|
return wrapper
|
|
206
207
|
|
|
@@ -229,7 +230,15 @@ class _Fit2DResult(TypedDict):
|
|
|
229
230
|
residual: np.ndarray
|
|
230
231
|
|
|
231
232
|
|
|
232
|
-
class
|
|
233
|
+
class _GaussianDeconvolutionResult(TypedDict):
|
|
234
|
+
deconvolved: tuple[float | np.longdouble,
|
|
235
|
+
float | np.longdouble,
|
|
236
|
+
float | np.longdouble] | None
|
|
237
|
+
deconvolution_status: Literal['success', 'unresolved',
|
|
238
|
+
'missing_beam', 'unsupported_pv']
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
class _GaussFit2DResult(_GaussianDeconvolutionResult):
|
|
233
242
|
popt: np.ndarray
|
|
234
243
|
perr: np.ndarray
|
|
235
244
|
model: np.ndarray
|
|
@@ -335,8 +344,8 @@ class AstroData():
|
|
|
335
344
|
for i, data in enumerate(datasets):
|
|
336
345
|
if data is not None and np.ndim(data) == 0:
|
|
337
346
|
raise ValueError(f'Dataset {i} must be an array '
|
|
338
|
-
|
|
339
|
-
|
|
347
|
+
'with spatial axes, not a scalar'
|
|
348
|
+
' or zero-dimensional array.')
|
|
340
349
|
self.n = n
|
|
341
350
|
self.fitsimage_org = None
|
|
342
351
|
self.sigma_org = None
|
|
@@ -350,7 +359,7 @@ class AstroData():
|
|
|
350
359
|
return
|
|
351
360
|
if grid is None:
|
|
352
361
|
raise ValueError(f'Binning in the {t}-axis requires'
|
|
353
|
-
|
|
362
|
+
f' a {t} coordinate array.')
|
|
354
363
|
|
|
355
364
|
dt = f'd{t}'
|
|
356
365
|
sep = getattr(self, dt)
|
|
@@ -420,17 +429,17 @@ class AstroData():
|
|
|
420
429
|
for axis, factor in zip(('v', 'y', 'x'), w):
|
|
421
430
|
if factor > 1 and getattr(self, axis) is None:
|
|
422
431
|
raise ValueError(f'Binning in the {axis}-axis requires'
|
|
423
|
-
|
|
432
|
+
' a coordinate array.')
|
|
424
433
|
velocity_binning = (not self.pv and w[0] > 1) or (self.pv and w[1] > 1)
|
|
425
434
|
if velocity_binning and isinstance(self.sigma, str):
|
|
426
435
|
raise ValueError('Estimate sigma before velocity binning,'
|
|
427
|
-
|
|
436
|
+
' or set sigma=None.')
|
|
428
437
|
self.data = data4d
|
|
429
438
|
if velocity_binning:
|
|
430
439
|
width_v = w[1] if self.pv else w[0]
|
|
431
440
|
if self.sigma is not None:
|
|
432
441
|
print(f'sigma has been divided by sqrt({width_v:d})'
|
|
433
|
-
|
|
442
|
+
' because of binning in the v-axis.')
|
|
434
443
|
self.sigma = _normalize_float(self.sigma / np.sqrt(width_v))
|
|
435
444
|
if (not self.pv and w[1] > 1) or w[2] > 1:
|
|
436
445
|
print('Binning in the x- or y-axis does not update sigma.')
|
|
@@ -494,7 +503,7 @@ class AstroData():
|
|
|
494
503
|
bmaj, bmin, bpa = self.beam
|
|
495
504
|
if not np.all(np.isfinite([bmaj, bmin, bpa])) or not 0 < bmin <= bmaj:
|
|
496
505
|
raise ValueError('circularbeam requires finite beam values'
|
|
497
|
-
|
|
506
|
+
' with major >= minor > 0.')
|
|
498
507
|
if bmaj == bmin:
|
|
499
508
|
return
|
|
500
509
|
self.rotate(-bpa)
|
|
@@ -571,7 +580,7 @@ class AstroData():
|
|
|
571
580
|
raise ValueError('Fitting requires finite, nonzero pixel sizes.')
|
|
572
581
|
factor = np.pi * sizes[0] * sizes[1] / (4 * np.log(2) * area)
|
|
573
582
|
print('In the fitting, sigma is multiplied by sqrt(pixel-per-beam)'
|
|
574
|
-
|
|
583
|
+
' to account for beam noise correlation.')
|
|
575
584
|
return factor
|
|
576
585
|
|
|
577
586
|
@_need_multipixels
|
|
@@ -624,7 +633,7 @@ class AstroData():
|
|
|
624
633
|
result = model(p, x, y)
|
|
625
634
|
if not isinstance(result, np.ndarray) or result.shape != d.shape:
|
|
626
635
|
raise ValueError('model must return an ndarray matching'
|
|
627
|
-
|
|
636
|
+
' the selected image shape.')
|
|
628
637
|
return result
|
|
629
638
|
|
|
630
639
|
def logl(p: np.ndarray) -> float | np.floating:
|
|
@@ -688,6 +697,34 @@ class AstroData():
|
|
|
688
697
|
return estimate_ranges(self.data, self.x, self.y, self.sigma,
|
|
689
698
|
v=v, beam=self.beam, pbcor=pbcor)
|
|
690
699
|
|
|
700
|
+
def _validate_deconvolution_beam(self) -> None:
|
|
701
|
+
"""Reject invalid spatial beam metadata before running the fit."""
|
|
702
|
+
if not self.pv:
|
|
703
|
+
if (not isinstance(self.beam, (list, tuple, np.ndarray))
|
|
704
|
+
or np.shape(self.beam) != (3,)):
|
|
705
|
+
raise ValueError('Deconvolution requires a three-entry beam.')
|
|
706
|
+
if all(v is not None for v in self.beam):
|
|
707
|
+
if (not all(_is_finite_real_scalar(v) for v in self.beam)
|
|
708
|
+
or any(v < 0 for v in self.beam[:2])):
|
|
709
|
+
raise ValueError('Deconvolution requires finite beam values'
|
|
710
|
+
' and nonnegative widths.')
|
|
711
|
+
|
|
712
|
+
def _deconvolve_gaussian_fit(self, shape: np.ndarray
|
|
713
|
+
) -> _GaussianDeconvolutionResult:
|
|
714
|
+
"""Describe intrinsic shape availability without changing the fit."""
|
|
715
|
+
if self.pv:
|
|
716
|
+
return {'deconvolved': None,
|
|
717
|
+
'deconvolution_status': 'unsupported_pv'}
|
|
718
|
+
if any(v is None for v in self.beam):
|
|
719
|
+
return {'deconvolved': None,
|
|
720
|
+
'deconvolution_status': 'missing_beam'}
|
|
721
|
+
try:
|
|
722
|
+
intrinsic = gaussian_deconvolve(shape, self.beam)
|
|
723
|
+
except ValueError:
|
|
724
|
+
return {'deconvolved': None,
|
|
725
|
+
'deconvolution_status': 'unresolved'}
|
|
726
|
+
return {'deconvolved': intrinsic, 'deconvolution_status': 'success'}
|
|
727
|
+
|
|
691
728
|
@_need_multipixels
|
|
692
729
|
def gaussfit2d(self, chan: int | np.integer | None = None,
|
|
693
730
|
*, progressbar: bool = False) -> _GaussFit2DResult:
|
|
@@ -708,14 +745,30 @@ class AstroData():
|
|
|
708
745
|
the best 2D Gaussian array (model), the residual from the
|
|
709
746
|
model (residual), and the coordinates of the best-fit center
|
|
710
747
|
(center). The fitted spatial offsets are divided by dist before
|
|
711
|
-
conversion to sky coordinates.
|
|
748
|
+
conversion to sky coordinates. All these observed-fit outputs
|
|
749
|
+
retain their observed-fit meaning. Deconvolution is always
|
|
750
|
+
attempted for spatial images and cube channels using self.beam.
|
|
751
|
+
The deconvolved result is a (major FWHM, minor FWHM, PA) tuple
|
|
752
|
+
or None; deconvolution_status is success, unresolved (no Gaussian
|
|
753
|
+
solution), missing_beam (any beam entry is None), or unsupported_pv.
|
|
754
|
+
Successful zero-width limiting solutions are allowed. Scalars are
|
|
755
|
+
Python floats, preserving extended-precision NumPy floating
|
|
756
|
+
scalars. No intrinsic uncertainties or upper limits are computed;
|
|
757
|
+
perr remains the observed-fit uncertainty.
|
|
758
|
+
|
|
759
|
+
Notes:
|
|
760
|
+
The fit and self.beam must use the same length units and current
|
|
761
|
+
coordinate frame. PA is measured from +y toward +x. The processed
|
|
762
|
+
beam is used directly after swapxy; display flips need no angle
|
|
763
|
+
correction. Invalid complete beam metadata raises ValueError.
|
|
712
764
|
"""
|
|
765
|
+
self._validate_deconvolution_beam()
|
|
713
766
|
z = self._fit_image(chan)
|
|
714
767
|
if z.shape != (len(self.y), len(self.x)):
|
|
715
768
|
raise ValueError('Selected image shape must match the x/y grids.')
|
|
716
769
|
if self.sigma is not None and not _is_positive_real_scalar(self.sigma):
|
|
717
770
|
raise ValueError('gaussfit2d requires finite, positive scalar'
|
|
718
|
-
|
|
771
|
+
' sigma or None.')
|
|
719
772
|
# Automatic estimation is handled by the underlying fitter; there is
|
|
720
773
|
# no supplied sigma to scale in that case.
|
|
721
774
|
sigma = None
|
|
@@ -733,9 +786,9 @@ class AstroData():
|
|
|
733
786
|
coordorg=self.center)
|
|
734
787
|
else:
|
|
735
788
|
newcenter = None
|
|
736
|
-
return {'popt': popt, 'perr': perr,
|
|
737
|
-
'
|
|
738
|
-
|
|
789
|
+
return {'popt': popt, 'perr': perr, 'model': model,
|
|
790
|
+
'residual': residual, 'center': newcenter,
|
|
791
|
+
**self._deconvolve_gaussian_fit(popt[3:6])}
|
|
739
792
|
|
|
740
793
|
def histogram(self, **kwargs: Any) -> tuple[np.ndarray, np.ndarray]:
|
|
741
794
|
"""Output histogram of self.data using numpy.histogram. This
|
|
@@ -772,7 +825,7 @@ class AstroData():
|
|
|
772
825
|
dataformask = self.data
|
|
773
826
|
if len(includepix) not in [0, 2] or len(excludepix) not in [0, 2]:
|
|
774
827
|
raise ValueError('includepix and excludepix must be empty'
|
|
775
|
-
|
|
828
|
+
' or [min, max].')
|
|
776
829
|
if np.ndim(self.data) > np.ndim(dataformask):
|
|
777
830
|
print('The mask is broadcasted.')
|
|
778
831
|
try:
|
|
@@ -780,15 +833,15 @@ class AstroData():
|
|
|
780
833
|
except ValueError as exc:
|
|
781
834
|
raise ValueError('dataformask must be broadcastable'
|
|
782
835
|
' to the data shape;'
|
|
783
|
-
|
|
784
|
-
|
|
836
|
+
f' got {np.shape(dataformask)}'
|
|
837
|
+
f' and {np.shape(self.data)}.') from exc
|
|
785
838
|
else:
|
|
786
839
|
mask = dataformask
|
|
787
840
|
if np.shape(self.data) != np.shape(mask):
|
|
788
841
|
raise ValueError('dataformask must have the same shape as data'
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
842
|
+
' after broadcasting;'
|
|
843
|
+
f' got {np.shape(dataformask)}'
|
|
844
|
+
f' and {np.shape(self.data)}.')
|
|
792
845
|
|
|
793
846
|
if ((len(includepix) == 2 or len(excludepix) == 2)
|
|
794
847
|
and self.data.dtype.kind in 'biu'):
|
|
@@ -1042,16 +1095,16 @@ class AstroData():
|
|
|
1042
1095
|
"""Convert velocity reference and spacing, preserving scalar precision."""
|
|
1043
1096
|
if self.v is None or self.dv is None:
|
|
1044
1097
|
raise ValueError('Writing a velocity axis requires coordinates'
|
|
1045
|
-
|
|
1098
|
+
' and spacing.')
|
|
1046
1099
|
cv, dv = self.v[ck], self.dv
|
|
1047
1100
|
if (self.restfreq is not None
|
|
1048
1101
|
and (not _is_finite_real_scalar(self.restfreq)
|
|
1049
1102
|
or self.restfreq < 0)):
|
|
1050
1103
|
raise ValueError('restfreq must be finite and positive,'
|
|
1051
|
-
|
|
1104
|
+
' or None/0.')
|
|
1052
1105
|
if self.restfreq is None or self.restfreq == 0:
|
|
1053
1106
|
warnings.warn('No valid restfreq.'
|
|
1054
|
-
|
|
1107
|
+
' The velocity axis is saved as is.',
|
|
1055
1108
|
UserWarning)
|
|
1056
1109
|
else:
|
|
1057
1110
|
cv = (1 - cv / cu.c_kms) * self.restfreq
|
|
@@ -1094,7 +1147,7 @@ class AstroData():
|
|
|
1094
1147
|
"""Add frequency or velocity cards to the cube/PV spectral axis."""
|
|
1095
1148
|
if self.v is None:
|
|
1096
1149
|
raise ValueError('A cube or PV image requires'
|
|
1097
|
-
|
|
1150
|
+
' velocity coordinates.')
|
|
1098
1151
|
ck = nearest_index(self.v)
|
|
1099
1152
|
cv, dv = self._get_cvdv_in_freq(ck)
|
|
1100
1153
|
axis = 2 if self.pv else 3
|
|
@@ -1127,7 +1180,7 @@ class AstroData():
|
|
|
1127
1180
|
h['BPA'] = float(beam[2])
|
|
1128
1181
|
elif self.pv and not all(k in h for k in ('BMAJ', 'BMIN', 'BPA')):
|
|
1129
1182
|
warnings.warn('Original sky beam unavailable;'
|
|
1130
|
-
|
|
1183
|
+
' omitting FITS beam metadata.',
|
|
1131
1184
|
UserWarning)
|
|
1132
1185
|
for key in ('BMAJ', 'BMIN', 'BPA'):
|
|
1133
1186
|
h.pop(key, None)
|
|
@@ -1158,7 +1211,7 @@ class AstroData():
|
|
|
1158
1211
|
if (not isinstance(self.data, np.ndarray)
|
|
1159
1212
|
or self.data.ndim not in (2, 3)):
|
|
1160
1213
|
raise ValueError('writetofits requires a single 2D image'
|
|
1161
|
-
|
|
1214
|
+
' or 3D cube.')
|
|
1162
1215
|
_require_positive_real_scalar(self.dist, 'dist')
|
|
1163
1216
|
h = self._build_fits_header()
|
|
1164
1217
|
h.update(header or {})
|
|
@@ -1207,9 +1260,9 @@ def _validate_shared_grid(expected_grid: _Grid, actual_grid: _Grid,
|
|
|
1207
1260
|
rtol=1e-7, atol=0))
|
|
1208
1261
|
if not same:
|
|
1209
1262
|
raise ValueError(f'Dataset {dataset} has a different'
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1263
|
+
f' processed {name} grid; datasets'
|
|
1264
|
+
' in one AstroData must share'
|
|
1265
|
+
' coordinate grids.')
|
|
1213
1266
|
|
|
1214
1267
|
|
|
1215
1268
|
def _prepare_positions(poslist: Position | list[Position]
|
|
@@ -1235,7 +1288,7 @@ def _prepare_positions(poslist: Position | list[Position]
|
|
|
1235
1288
|
for position in poslist:
|
|
1236
1289
|
if not isinstance(position, str) and not is_pair(position):
|
|
1237
1290
|
raise ValueError('Each numeric position must contain'
|
|
1238
|
-
|
|
1291
|
+
' two real scalars.')
|
|
1239
1292
|
return poslist
|
|
1240
1293
|
|
|
1241
1294
|
|
|
@@ -1365,9 +1418,9 @@ class AstroFrame():
|
|
|
1365
1418
|
if self.center is None and any(isinstance(p, str) for p in poslist):
|
|
1366
1419
|
clsname = type(self).__name__
|
|
1367
1420
|
raise ValueError(f'{clsname}.pos2xy() requires "center"'
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1421
|
+
' when poslist contains sky-coordinate strings.'
|
|
1422
|
+
' Set "center" explicitly or "fitsimage"'
|
|
1423
|
+
' from which the center can be determined.')
|
|
1371
1424
|
x, y = [None] * len(poslist), [None] * len(poslist)
|
|
1372
1425
|
for i, p in enumerate(poslist):
|
|
1373
1426
|
if isinstance(p, str):
|
|
@@ -1499,8 +1552,8 @@ class AstroFrame():
|
|
|
1499
1552
|
dx = d.dy if self.swapxy else d.dx
|
|
1500
1553
|
if dx is None:
|
|
1501
1554
|
raise ValueError('Brightness-temperature conversion requires'
|
|
1502
|
-
|
|
1503
|
-
|
|
1555
|
+
' beam sizes or at least two spatial pixels'
|
|
1556
|
+
' to determine pixel size.')
|
|
1504
1557
|
header.update(CDELT1=dx / self.dist / 3600, CUNIT1='deg')
|
|
1505
1558
|
factor = Jy2K(header=header)
|
|
1506
1559
|
d.data[i] = d.data[i] * factor
|
|
@@ -1609,4 +1662,4 @@ class AstroFrame():
|
|
|
1609
1662
|
setattr(d, name, _scalar_if_single(getattr(d, name), d.n))
|
|
1610
1663
|
if self.swapxy:
|
|
1611
1664
|
print('x and y axes have been swapped; subsequent AstroData'
|
|
1612
|
-
|
|
1665
|
+
' operations use the current axis order.')
|
plotastrodata/coord_utils.py
CHANGED
|
@@ -57,7 +57,7 @@ def _getframe(coord: str | list | tuple | np.ndarray, *, as_frame: bool = False
|
|
|
57
57
|
for i, value in enumerate(values.flat):
|
|
58
58
|
if not isinstance(value, str):
|
|
59
59
|
raise ValueError('Coordinates must be strings'
|
|
60
|
-
|
|
60
|
+
' in a rectangular collection.')
|
|
61
61
|
parts = value.split()
|
|
62
62
|
hasframe = len(parts) == 3
|
|
63
63
|
parsed.append(f'{parts[1]} {parts[2]}' if hasframe else value)
|
|
@@ -152,7 +152,7 @@ def xy2coord(xy: list | tuple | np.ndarray,
|
|
|
152
152
|
offsets = np.asarray(xy)
|
|
153
153
|
if offsets.ndim == 0 or offsets.shape[0] != 2:
|
|
154
154
|
raise ValueError('xy must have shape (2, ...)'
|
|
155
|
-
|
|
155
|
+
' with matching coordinate shapes.')
|
|
156
156
|
shape = offsets.shape[1:]
|
|
157
157
|
if offsets.size == 0:
|
|
158
158
|
return np.empty(shape, dtype=str)
|
plotastrodata/fft_utils.py
CHANGED
|
@@ -120,17 +120,17 @@ def _ifft_xsize(nfreq: int, u: np.ndarray | None, dx: float,
|
|
|
120
120
|
"""Resolve inverse-transform length without resizing the spectrum."""
|
|
121
121
|
if nfreq < 2:
|
|
122
122
|
raise ValueError('Inverse centering requires at least'
|
|
123
|
-
|
|
123
|
+
' two x-frequency samples.')
|
|
124
124
|
if u is not None and (np.ndim(u) != 1 or len(u) != nfreq):
|
|
125
125
|
raise ValueError(f'u must be a 1D grid with {nfreq} points, matching '
|
|
126
|
-
|
|
126
|
+
'the number of x-frequency samples in F.')
|
|
127
127
|
if nx is not None:
|
|
128
128
|
if not rfft:
|
|
129
129
|
raise ValueError('nx is only supported when rfft=True.')
|
|
130
130
|
_require_integer(nx, 'nx', minimum=2)
|
|
131
131
|
if int(nx) // 2 + 1 != nfreq:
|
|
132
132
|
raise ValueError(f'nx={nx} must satisfy nx // 2 + 1 == {nfreq}, '
|
|
133
|
-
|
|
133
|
+
'the number of x-frequency samples in F.')
|
|
134
134
|
return int(nx)
|
|
135
135
|
if not rfft:
|
|
136
136
|
return nfreq
|
|
@@ -480,7 +480,7 @@ def findindex(u: np.ndarray | None = None, v: np.ndarray | None = None,
|
|
|
480
480
|
return None
|
|
481
481
|
if grid is None or np.ndim(grid) != 1 or len(grid) < 2:
|
|
482
482
|
raise ValueError(f'{name} observations require a 1D {name} grid '
|
|
483
|
-
|
|
483
|
+
'with at least two points.')
|
|
484
484
|
step = grid[1] - grid[0]
|
|
485
485
|
if not np.isfinite(step) or step == 0:
|
|
486
486
|
raise ValueError(f'{name} grid spacing must be finite and nonzero.')
|
plotastrodata/fits_utils.py
CHANGED
|
@@ -79,12 +79,12 @@ def Jy2K(header: fits.Header | dict[str, Any] | None = None,
|
|
|
79
79
|
bmaj, bmin, freq = _jy2k_metadata(header, bmaj, bmin, restfreq)
|
|
80
80
|
if freq is None:
|
|
81
81
|
raise ValueError('Brightness-temperature conversion requires restfreq'
|
|
82
|
-
|
|
82
|
+
' or a RESTFREQ/RESTFRQ header value.')
|
|
83
83
|
_require_positive_real_scalar(freq, 'restfreq')
|
|
84
84
|
if not _is_positive_real_scalar(bmaj) or not _is_positive_real_scalar(bmin):
|
|
85
85
|
raise ValueError('Brightness-temperature conversion requires finite,'
|
|
86
|
-
|
|
87
|
-
|
|
86
|
+
' positive bmaj and bmin values'
|
|
87
|
+
' or equivalent FITS header metadata.')
|
|
88
88
|
omega = bmaj * bmin * units.arcsec**2 * np.pi / 4. / np.log(2.)
|
|
89
89
|
equiv = units.brightness_temperature(freq * units.Hz, beam_area=omega)
|
|
90
90
|
T = (1 * units.Jy / units.beam).to(units.K, equivalencies=equiv)
|
|
@@ -234,7 +234,7 @@ class FitsData:
|
|
|
234
234
|
h, d = self.hdu.header, self.hdu.data
|
|
235
235
|
if d is None:
|
|
236
236
|
raise ValueError(f'Primary HDU in {self.fitsimage!s}'
|
|
237
|
-
|
|
237
|
+
' contains no data.')
|
|
238
238
|
if drop:
|
|
239
239
|
d = np.squeeze(d)
|
|
240
240
|
if Tb:
|
|
@@ -281,7 +281,7 @@ class FitsData:
|
|
|
281
281
|
rho_b = np.arctan2(np.abs(cd12), -np.sign(cd12) * cd22)
|
|
282
282
|
if (drho := np.abs(np.degrees(rho_a - rho_b))) > 1.0:
|
|
283
283
|
print('Angles from (CD21, CD11) and (CD12, CD22)'
|
|
284
|
-
|
|
284
|
+
f' are different by {drho:.2} degrees.')
|
|
285
285
|
crota2 = (rho_a + rho_b) / 2.
|
|
286
286
|
sin_rho = np.sin(crota2)
|
|
287
287
|
cos_rho = np.cos(crota2)
|
|
@@ -368,7 +368,7 @@ class FitsData:
|
|
|
368
368
|
if restfreq is None:
|
|
369
369
|
freq = np.mean(v)
|
|
370
370
|
print('restfreq is assumed to be'
|
|
371
|
-
|
|
371
|
+
' the mean channel frequency.')
|
|
372
372
|
else:
|
|
373
373
|
freq = restfreq
|
|
374
374
|
if freq == 0:
|
|
@@ -383,7 +383,7 @@ class FitsData:
|
|
|
383
383
|
v = v - vsys
|
|
384
384
|
case _:
|
|
385
385
|
print(f'Unknown CUNIT3 {cunitv} found.'
|
|
386
|
-
|
|
386
|
+
' v is read as is.')
|
|
387
387
|
dv = None if len(v) <= 1 else _normalize_float(v[1] - v[0])
|
|
388
388
|
self.v, self.dv = v, dv
|
|
389
389
|
|