plotastrodata 1.12.0__tar.gz → 1.12.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.12.0/plotastrodata.egg-info → plotastrodata-1.12.1}/PKG-INFO +5 -6
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/README.md +4 -5
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/plotastrodata/__init__.py +1 -1
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/plotastrodata/noise_utils.py +3 -1
- plotastrodata-1.12.1/plotastrodata/script_utils.py +595 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1/plotastrodata.egg-info}/PKG-INFO +5 -6
- plotastrodata-1.12.0/plotastrodata/script_utils.py +0 -302
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/LICENSE +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/MANIFEST.in +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/plotastrodata/_type_utils.py +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/plotastrodata/_validation_utils.py +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/plotastrodata/analysis_utils.py +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/plotastrodata/const_utils.py +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/plotastrodata/coord_utils.py +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/plotastrodata/ext_utils.py +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/plotastrodata/fft_utils.py +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/plotastrodata/fits_utils.py +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/plotastrodata/fitting_utils.py +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/plotastrodata/los_utils.py +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/plotastrodata/matrix_utils.py +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/plotastrodata/other_utils.py +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/plotastrodata/plot_utils.py +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/plotastrodata.egg-info/SOURCES.txt +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/plotastrodata.egg-info/dependency_links.txt +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/plotastrodata.egg-info/not-zip-safe +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/plotastrodata.egg-info/requires.txt +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/plotastrodata.egg-info/top_level.txt +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/setup.cfg +0 -0
- {plotastrodata-1.12.0 → plotastrodata-1.12.1}/setup.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: plotastrodata
|
|
3
|
-
Version: 1.12.
|
|
3
|
+
Version: 1.12.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
|
|
@@ -101,13 +101,12 @@ Review the inline values, then run `python image.py`. The script uses existing
|
|
|
101
101
|
library APIs to visualize a hist-pbcor noise fit, fit a 2D Gaussian and report
|
|
102
102
|
its sky center and east/north uncertainties, and plot a logarithmic image
|
|
103
103
|
with contours, a beam, and RA/Dec axes. It saves separate noise and image PNGs.
|
|
104
|
-
Noise estimation uses the full image. Fitting and plotting
|
|
105
|
-
|
|
106
|
-
The estimated rmax is written inline for editing.
|
|
104
|
+
Noise estimation uses the full image. Fitting and plotting ranges are estimated automatically and written inline
|
|
105
|
+
with three significant digits for editing.
|
|
107
106
|
For a spectral cube, use `generate_cube_script("cube.fits", output="cube.py")`
|
|
108
107
|
from the same module. It generates an edge-channel noise visualization, a flux-integrated line
|
|
109
|
-
profile
|
|
110
|
-
channel spacing. The flux profile assumes Jy/beam data with beam metadata.
|
|
108
|
+
profile and 3D channel maps over estimated spatial and velocity ranges,
|
|
109
|
+
with intrinsic channel spacing. The flux profile assumes Jy/beam data with beam metadata.
|
|
111
110
|
Both generators return an absolute pathlib.Path and write the script
|
|
112
111
|
without executing it.
|
|
113
112
|
See the [script-generation guide](docs/script_generation.rst).
|
|
@@ -72,13 +72,12 @@ Review the inline values, then run `python image.py`. The script uses existing
|
|
|
72
72
|
library APIs to visualize a hist-pbcor noise fit, fit a 2D Gaussian and report
|
|
73
73
|
its sky center and east/north uncertainties, and plot a logarithmic image
|
|
74
74
|
with contours, a beam, and RA/Dec axes. It saves separate noise and image PNGs.
|
|
75
|
-
Noise estimation uses the full image. Fitting and plotting
|
|
76
|
-
|
|
77
|
-
The estimated rmax is written inline for editing.
|
|
75
|
+
Noise estimation uses the full image. Fitting and plotting ranges are estimated automatically and written inline
|
|
76
|
+
with three significant digits for editing.
|
|
78
77
|
For a spectral cube, use `generate_cube_script("cube.fits", output="cube.py")`
|
|
79
78
|
from the same module. It generates an edge-channel noise visualization, a flux-integrated line
|
|
80
|
-
profile
|
|
81
|
-
channel spacing. The flux profile assumes Jy/beam data with beam metadata.
|
|
79
|
+
profile and 3D channel maps over estimated spatial and velocity ranges,
|
|
80
|
+
with intrinsic channel spacing. The flux profile assumes Jy/beam data with beam metadata.
|
|
82
81
|
Both generators return an absolute pathlib.Path and write the script
|
|
83
82
|
without executing it.
|
|
84
83
|
See the [script-generation guide](docs/script_generation.rst).
|
|
@@ -126,7 +126,9 @@ def gauss_pbcor(x: float | np.floating | np.ndarray,
|
|
|
126
126
|
The variable of the probability density.
|
|
127
127
|
s (float): Standard deviation of the Gaussian noise.
|
|
128
128
|
m (float): Mean of the Gaussian noise.
|
|
129
|
-
R (float):
|
|
129
|
+
R (float): Dimensionless outer radius r_out / r_p, where r_p is
|
|
130
|
+
the primary-beam half-width at half maximum (HWHM). The
|
|
131
|
+
primary-beam response at radius r is 2**(-(r / r_p)**2).
|
|
130
132
|
|
|
131
133
|
Returns:
|
|
132
134
|
float or np.longdouble or np.ndarray: Probability density.
|
|
@@ -0,0 +1,595 @@
|
|
|
1
|
+
"""Generate short, editable plotting scripts using existing plotastrodata APIs."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
from astropy.io import fits
|
|
6
|
+
from astropy.wcs import WCS
|
|
7
|
+
from astropy.wcs.utils import proj_plane_pixel_scales
|
|
8
|
+
from scipy import ndimage
|
|
9
|
+
|
|
10
|
+
from plotastrodata._type_utils import RealScalar, RealSequence, _normalize_float
|
|
11
|
+
from plotastrodata._validation_utils import (
|
|
12
|
+
_is_uniform_spacing,
|
|
13
|
+
_require_positive_real_scalar,
|
|
14
|
+
)
|
|
15
|
+
from plotastrodata.analysis_utils import AstroData, AstroFrame
|
|
16
|
+
from plotastrodata.noise_utils import Noise
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _multiply_pb(data: np.ndarray, x: np.ndarray, y: np.ndarray,
|
|
20
|
+
R: float | np.integer | np.floating,
|
|
21
|
+
r_out: float | np.integer | np.floating) -> np.ndarray:
|
|
22
|
+
"""Multiply an image or cube by an approximate Gaussian primary beam.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
data: Numeric array with shape (ny, nx) or (nchan, ny, nx).
|
|
26
|
+
x: Finite real 1D x offsets from the assumed PB center, length nx.
|
|
27
|
+
y: Finite real 1D y offsets from the assumed PB center, length ny.
|
|
28
|
+
R: Positive dimensionless outer radius r_out / r_p from gauss_pbcor
|
|
29
|
+
(Noise.popt[2]), where r_p is the primary-beam HWHM.
|
|
30
|
+
r_out: Positive outer radius of the footprint used for the noise fit,
|
|
31
|
+
in the same spatial units as x and y. It is supplied explicitly,
|
|
32
|
+
not inferred from the array shape or the plotting crop.
|
|
33
|
+
|
|
34
|
+
Returns:
|
|
35
|
+
np.ndarray: New array of the same shape, multiplied by
|
|
36
|
+
B(x, y) = 2**(-R**2 * ((x/r_out)**2 + (y/r_out)**2)).
|
|
37
|
+
One spatial pattern is broadcast across all channels. Inputs are
|
|
38
|
+
not modified and nonfinite data pixels are not filled or removed.
|
|
39
|
+
NumPy determines the arithmetic dtype; integer data can become
|
|
40
|
+
floating point, and extended precision is retained without casting.
|
|
41
|
+
|
|
42
|
+
Raises:
|
|
43
|
+
TypeError: data is not a NumPy array.
|
|
44
|
+
ValueError: Shapes, coordinate values, or PB parameters are unsuitable.
|
|
45
|
+
|
|
46
|
+
Notes:
|
|
47
|
+
Applying this to PB-corrected data approximately restores the
|
|
48
|
+
pre-correction intensities. The assumed circular beam and center
|
|
49
|
+
are intended for range estimation, not calibrated PB reconstruction.
|
|
50
|
+
"""
|
|
51
|
+
if not isinstance(data, np.ndarray):
|
|
52
|
+
raise TypeError('data must be a NumPy array.')
|
|
53
|
+
if (data.ndim not in (2, 3) or 0 in data.shape
|
|
54
|
+
or not np.issubdtype(data.dtype, np.number)):
|
|
55
|
+
raise ValueError('data must be a nonempty numeric 2D or 3D array.')
|
|
56
|
+
x, y = np.asarray(x), np.asarray(y)
|
|
57
|
+
for coordinate, length, name in ((x, data.shape[-1], 'x'),
|
|
58
|
+
(y, data.shape[-2], 'y')):
|
|
59
|
+
if (coordinate.ndim != 1 or len(coordinate) != length
|
|
60
|
+
or coordinate.dtype.kind not in 'iuf'
|
|
61
|
+
or not np.all(np.isfinite(coordinate))):
|
|
62
|
+
raise ValueError(f'{name} must be a finite real 1D coordinate array'
|
|
63
|
+
+ ' matching the spatial data axis.')
|
|
64
|
+
_require_positive_real_scalar(R, 'R')
|
|
65
|
+
_require_positive_real_scalar(r_out, 'r_out')
|
|
66
|
+
radius_squared = (x[None, :] / r_out)**2 + (y[:, None] / r_out)**2
|
|
67
|
+
pattern = np.exp2(-R**2 * radius_squared)
|
|
68
|
+
return data * pattern
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _validate_range_inputs(data: np.ndarray, x: np.ndarray, y: np.ndarray,
|
|
72
|
+
sigma: RealScalar, v: np.ndarray | None
|
|
73
|
+
) -> tuple[np.ndarray,
|
|
74
|
+
np.ndarray,
|
|
75
|
+
np.ndarray | None]:
|
|
76
|
+
"""Validate range-estimator inputs and return the coordinate arrays.
|
|
77
|
+
|
|
78
|
+
Preserve array dtypes and leave all inputs unchanged. Reject unsuitable
|
|
79
|
+
dimensions, noise values, coordinates, and image/cube velocity arguments.
|
|
80
|
+
"""
|
|
81
|
+
if not isinstance(data, np.ndarray):
|
|
82
|
+
raise TypeError('data must be a NumPy array.')
|
|
83
|
+
if (data.ndim not in (2, 3) or data.dtype.kind not in 'iuf'
|
|
84
|
+
or any(length < 2 for length in data.shape)):
|
|
85
|
+
raise ValueError('data must be a real 2D or 3D array with at least'
|
|
86
|
+
+ ' two samples on every axis.')
|
|
87
|
+
_require_positive_real_scalar(sigma, 'sigma')
|
|
88
|
+
x, y = np.asarray(x), np.asarray(y)
|
|
89
|
+
axes = [(x, data.shape[-1], 'x'), (y, data.shape[-2], 'y')]
|
|
90
|
+
if data.ndim == 3:
|
|
91
|
+
if v is None:
|
|
92
|
+
raise ValueError('v is required for a cube.')
|
|
93
|
+
v = np.asarray(v)
|
|
94
|
+
axes.append((v, data.shape[0], 'v'))
|
|
95
|
+
elif v is not None:
|
|
96
|
+
raise ValueError('v must be omitted for a 2D image.')
|
|
97
|
+
for coordinate, length, name in axes:
|
|
98
|
+
if (coordinate.ndim != 1 or len(coordinate) != length
|
|
99
|
+
or coordinate.dtype.kind not in 'iuf'
|
|
100
|
+
or not np.all(np.isfinite(coordinate))):
|
|
101
|
+
raise ValueError(f'{name} must be a finite real 1D coordinate array'
|
|
102
|
+
+ ' matching its data axis.')
|
|
103
|
+
steps = np.diff(coordinate)
|
|
104
|
+
if steps[0] == 0 or not _is_uniform_spacing(steps, steps[0]):
|
|
105
|
+
raise ValueError(f'{name} must have nonzero uniform spacing.')
|
|
106
|
+
return x, y, v
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _range_beam_settings(beam: RealSequence | None, dx: RealScalar, dy: RealScalar
|
|
110
|
+
) -> tuple[RealScalar, RealScalar]:
|
|
111
|
+
"""Return minimum spatial footprint in pixels and spatial padding.
|
|
112
|
+
|
|
113
|
+
Use a Gaussian beam area and the larger FWHM when beam lengths are
|
|
114
|
+
provided, otherwise one pixel. Internal numeric precision is retained.
|
|
115
|
+
"""
|
|
116
|
+
minimum_pixels = 1
|
|
117
|
+
padding = max(dx, dy)
|
|
118
|
+
if beam is not None:
|
|
119
|
+
sizes = np.asarray(beam)
|
|
120
|
+
if sizes.ndim != 1 or sizes.size not in (2, 3):
|
|
121
|
+
raise ValueError('beam must contain [major, minor]'
|
|
122
|
+
+ ' or [major, minor, pa].')
|
|
123
|
+
for size in sizes[:2]:
|
|
124
|
+
_require_positive_real_scalar(size, 'beam FWHM')
|
|
125
|
+
minimum_pixels = np.ceil(np.pi * sizes[0] * sizes[1]
|
|
126
|
+
/ (4 * np.log(2) * dx * dy))
|
|
127
|
+
padding = max(sizes[:2])
|
|
128
|
+
|
|
129
|
+
return minimum_pixels, padding
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _find_emission_bounds(data: np.ndarray, sigma: RealScalar,
|
|
133
|
+
minimum_pixels: RealScalar
|
|
134
|
+
) -> tuple[slice, ...] | None:
|
|
135
|
+
"""Return union bounding slices for qualified emission, or None.
|
|
136
|
+
|
|
137
|
+
Keep all face-connected 3-sigma components with a 5-sigma seed and the
|
|
138
|
+
minimum projected spatial footprint. Cubes also require two adjacent
|
|
139
|
+
channels. Input arrays are not modified.
|
|
140
|
+
"""
|
|
141
|
+
structure = ndimage.generate_binary_structure(data.ndim, 1)
|
|
142
|
+
mask = np.isfinite(data) & (data >= 3 * sigma)
|
|
143
|
+
labels, _ = ndimage.label(mask, structure=structure)
|
|
144
|
+
del mask
|
|
145
|
+
lower = list(data.shape)
|
|
146
|
+
upper = [0] * data.ndim
|
|
147
|
+
found = False
|
|
148
|
+
for component_id, region in enumerate(ndimage.find_objects(labels), start=1):
|
|
149
|
+
if region is None:
|
|
150
|
+
continue
|
|
151
|
+
component = labels[region] == component_id
|
|
152
|
+
if not np.any((data[region] >= 5 * sigma) & component):
|
|
153
|
+
continue
|
|
154
|
+
if data.ndim == 3:
|
|
155
|
+
if region[0].stop - region[0].start < 2:
|
|
156
|
+
continue
|
|
157
|
+
spatial = np.any(component, axis=0)
|
|
158
|
+
else:
|
|
159
|
+
spatial = component
|
|
160
|
+
if np.count_nonzero(spatial) < minimum_pixels:
|
|
161
|
+
continue
|
|
162
|
+
found = True
|
|
163
|
+
for axis, extent in enumerate(region):
|
|
164
|
+
lower[axis] = min(lower[axis], extent.start)
|
|
165
|
+
upper[axis] = max(upper[axis], extent.stop)
|
|
166
|
+
|
|
167
|
+
if not found:
|
|
168
|
+
return None
|
|
169
|
+
return tuple(slice(lo, hi) for lo, hi in zip(lower, upper))
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _estimate_ranges(data: np.ndarray, x: np.ndarray, y: np.ndarray,
|
|
173
|
+
sigma: RealScalar, *, v: np.ndarray | None = None,
|
|
174
|
+
beam: RealSequence | None = None
|
|
175
|
+
) -> tuple[float | np.longdouble,
|
|
176
|
+
float | np.longdouble | None,
|
|
177
|
+
float | np.longdouble | None]:
|
|
178
|
+
"""Estimate spatial and velocity limits from positive emission.
|
|
179
|
+
|
|
180
|
+
Args:
|
|
181
|
+
data: Real numeric image (ny, nx) or cube (nchan, ny, nx), with
|
|
182
|
+
approximately uniform noise, for example after _multiply_pb.
|
|
183
|
+
Nonfinite values are excluded from detection.
|
|
184
|
+
x: Finite, uniformly spaced 1D x offsets from the intended center.
|
|
185
|
+
y: Finite, uniformly spaced 1D y offsets from the intended center.
|
|
186
|
+
Both spatial axes require at least two samples and may descend.
|
|
187
|
+
sigma: Finite positive scalar noise level in the data units.
|
|
188
|
+
v: Finite, uniformly spaced channel coordinates, required for a
|
|
189
|
+
cube and omitted for an image. At least two channels are needed.
|
|
190
|
+
beam: Optional [major, minor] FWHM lengths, or [major, minor, pa].
|
|
191
|
+
Lengths use the same units as x and y; pa is unused. Without a
|
|
192
|
+
beam, the minimum footprint is one pixel and padding is one
|
|
193
|
+
spatial pixel rather than one beam FWHM.
|
|
194
|
+
|
|
195
|
+
Returns:
|
|
196
|
+
tuple: (rmax, vmin, vmax). Computed scalars are Python floats,
|
|
197
|
+
except np.longdouble results retain extended precision. An image
|
|
198
|
+
returns None for both velocity limits. A cube returns numerical
|
|
199
|
+
velocity limits in ascending order even for a descending v axis.
|
|
200
|
+
Inputs and their array dtypes are unchanged.
|
|
201
|
+
|
|
202
|
+
Raises:
|
|
203
|
+
TypeError: data is not a NumPy array.
|
|
204
|
+
ValueError: Data, axes, noise, beam, or the centered finite region
|
|
205
|
+
are unsuitable.
|
|
206
|
+
|
|
207
|
+
Notes:
|
|
208
|
+
Face-connected components at or above 3*sigma survive only when they
|
|
209
|
+
contain a 5*sigma seed and cover at least one Gaussian beam area
|
|
210
|
+
in projected spatial pixels. Cube components must also span two
|
|
211
|
+
adjacent channels. All qualifying components are retained.
|
|
212
|
+
|
|
213
|
+
For each spatial axis, average the absolute values of the two
|
|
214
|
+
emission endpoints; take the larger x/y average and add the major
|
|
215
|
+
beam FWHM. Thus asymmetric emission uses mean absolute extent,
|
|
216
|
+
not maximum distance, and its farthest edge may lie outside the
|
|
217
|
+
symmetric field. Clip rmax to the centered finite footprint.
|
|
218
|
+
Velocity limits include two extra channels on each side, clipped
|
|
219
|
+
to the available channels, without skipping or binning.
|
|
220
|
+
|
|
221
|
+
With no qualifying component, use the centered finite footprint
|
|
222
|
+
and full velocity range. Spatial pixels with any nonfinite cube
|
|
223
|
+
channel restrict that footprint, with a pixel margin as in the
|
|
224
|
+
script generators. Thresholds assume a zero noise baseline; subtract
|
|
225
|
+
a fitted noise mean from data before calling if appropriate.
|
|
226
|
+
This helper does not fit noise or apply a PB.
|
|
227
|
+
"""
|
|
228
|
+
x, y, v = _validate_range_inputs(data, x, y, sigma, v)
|
|
229
|
+
dx, dy = abs(x[1] - x[0]), abs(y[1] - y[0])
|
|
230
|
+
minimum_pixels, padding = _range_beam_settings(beam, dx, dy)
|
|
231
|
+
|
|
232
|
+
footprint = AstroData(data=data, x=x, y=y, sigma=None)
|
|
233
|
+
footprint.dx, footprint.dy = dx, dy
|
|
234
|
+
full_radius = max((abs(x[0]) + abs(x[-1]) + dx) / 2,
|
|
235
|
+
(abs(y[0]) + abs(y[-1]) + dy) / 2)
|
|
236
|
+
available_radius = _get_valid_radius(footprint, full_radius)
|
|
237
|
+
bounds = _find_emission_bounds(data, sigma, minimum_pixels)
|
|
238
|
+
rmax = available_radius
|
|
239
|
+
if bounds is not None:
|
|
240
|
+
rx = (abs(x[bounds[-1].start]) + abs(x[bounds[-1].stop - 1])) / 2
|
|
241
|
+
ry = (abs(y[bounds[-2].start]) + abs(y[bounds[-2].stop - 1])) / 2
|
|
242
|
+
rmax = min(max(rx, ry) + padding, available_radius)
|
|
243
|
+
rmax = _normalize_float(rmax, force_float=True)
|
|
244
|
+
if v is None:
|
|
245
|
+
return rmax, None, None
|
|
246
|
+
first = max(bounds[0].start - 2, 0) if bounds is not None else 0
|
|
247
|
+
last = (min(bounds[0].stop + 1, len(v) - 1)
|
|
248
|
+
if bounds is not None else len(v) - 1)
|
|
249
|
+
return (rmax,
|
|
250
|
+
_normalize_float(min(v[first], v[last]), force_float=True),
|
|
251
|
+
_normalize_float(max(v[first], v[last]), force_float=True))
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _estimate_pb_ranges(image: AstroData
|
|
255
|
+
) -> tuple[float | np.longdouble,
|
|
256
|
+
float | np.longdouble | None,
|
|
257
|
+
float | np.longdouble | None]:
|
|
258
|
+
"""Fit PB-corrected noise and estimate emission ranges for loaded data.
|
|
259
|
+
|
|
260
|
+
image must contain one real 2D image or 3D cube already read by
|
|
261
|
+
AstroFrame, with spatial coordinates, pixel sizes, and cube velocities.
|
|
262
|
+
Fit hist-pbcor to the full image or the first and last cube channels.
|
|
263
|
+
Infer r_out from the equivalent circular area of the finite noise
|
|
264
|
+
footprint, averaging the two sampled channel areas for a cube.
|
|
265
|
+
|
|
266
|
+
Multiply a temporary array by the approximate PB from the fitted R,
|
|
267
|
+
subtract the fitted noise mean, and pass it to _estimate_ranges with
|
|
268
|
+
the fitted noise standard deviation and available beam metadata.
|
|
269
|
+
Missing beam lengths select the estimator's pixel-based defaults.
|
|
270
|
+
The AstroData object, its arrays, and the input FITS file are unchanged.
|
|
271
|
+
|
|
272
|
+
Return (rmax, vmin, vmax), with None velocity limits for an image.
|
|
273
|
+
Scalar results are Python floats, except np.longdouble results retain
|
|
274
|
+
extended precision. The selection rules and fallback are those of
|
|
275
|
+
_estimate_ranges. Errors from noise fitting, PB weighting, and range
|
|
276
|
+
estimation propagate from the underlying helpers.
|
|
277
|
+
"""
|
|
278
|
+
if not isinstance(image.data, np.ndarray) or image.data.ndim not in (2, 3):
|
|
279
|
+
raise ValueError('Expected a loaded 2D image or 3D cube.')
|
|
280
|
+
if image.data.ndim == 2:
|
|
281
|
+
noise_data = image.data
|
|
282
|
+
pixels = np.count_nonzero(np.isfinite(noise_data))
|
|
283
|
+
else:
|
|
284
|
+
noise_data = image.data[[0, -1]]
|
|
285
|
+
pixels = np.mean(np.count_nonzero(np.isfinite(noise_data), axis=(1, 2)))
|
|
286
|
+
noise = Noise(data=noise_data, sigma='hist-pbcor')
|
|
287
|
+
noise.gen_histogram()
|
|
288
|
+
noise.fit_histogram()
|
|
289
|
+
r_out = np.sqrt(pixels * abs(image.dx * image.dy) / np.pi)
|
|
290
|
+
del noise_data
|
|
291
|
+
weighted = _multiply_pb(image.data, image.x, image.y,
|
|
292
|
+
R=noise.popt[2], r_out=r_out)
|
|
293
|
+
weighted -= noise.mean
|
|
294
|
+
beam = image.beam if None not in image.beam[:2] else None
|
|
295
|
+
return _estimate_ranges(weighted, image.x, image.y, noise.std,
|
|
296
|
+
v=image.v if image.data.ndim == 3 else None,
|
|
297
|
+
beam=beam)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _validate_fits_image(fitsimage: str | Path, *, ndim: int = 2) -> None:
|
|
301
|
+
"""Validate the header of a primary-HDU RA/Dec image or spectral cube.
|
|
302
|
+
|
|
303
|
+
Internal callers use ndim=2 for an image or ndim=3 for a cube.
|
|
304
|
+
Higher axes must be singleton. Read only the header and return None.
|
|
305
|
+
Raise ValueError for unsuitable axes or nonpositive/nonfinite spatial
|
|
306
|
+
pixel scales. No data pixels are loaded or modified.
|
|
307
|
+
"""
|
|
308
|
+
with fits.open(fitsimage, memmap=True) as hdus:
|
|
309
|
+
h = hdus[0].header
|
|
310
|
+
n = int(h.get('NAXIS', 0))
|
|
311
|
+
if (n < ndim or h.get('NAXIS1', 0) < 2 or h.get('NAXIS2', 0) < 2
|
|
312
|
+
or any(h[f'NAXIS{i}'] != 1 for i in range(ndim + 1, n + 1))
|
|
313
|
+
or not str(h.get('CTYPE1', '')).upper().startswith('RA')
|
|
314
|
+
or not str(h.get('CTYPE2', '')).upper().startswith('DEC')):
|
|
315
|
+
raise ValueError(f'Expected a {ndim}D RA/Dec image'
|
|
316
|
+
+ ' in the primary FITS HDU.')
|
|
317
|
+
if ndim == 3 and (
|
|
318
|
+
h.get('NAXIS3', 0) < 2
|
|
319
|
+
or not str(h.get('CTYPE3', '')).upper().startswith(
|
|
320
|
+
('FREQ', 'VRAD', 'VELO', 'VOPT', 'FELO'))
|
|
321
|
+
or str(h.get('CUNIT3', '')).strip().upper() not in
|
|
322
|
+
('HZ', 'M/S', 'KM/S')):
|
|
323
|
+
raise ValueError('Expected at least two frequency'
|
|
324
|
+
+ ' or velocity channels on the third FITS axis,'
|
|
325
|
+
+ ' in Hz, m/s, or km/s.')
|
|
326
|
+
scales = proj_plane_pixel_scales(WCS(h, naxis=2, fix=False).celestial)
|
|
327
|
+
if not np.all(np.isfinite(scales)) or np.any(scales <= 0):
|
|
328
|
+
raise ValueError('Expected finite positive spatial pixel scales.')
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _get_valid_radius(image: AstroData, rmax: RealScalar
|
|
332
|
+
) -> float | np.longdouble:
|
|
333
|
+
"""Reduce a half-width to exclude nonfinite pixels, with a pixel margin.
|
|
334
|
+
|
|
335
|
+
image must contain one 2D image or 3D cube already read by AstroFrame,
|
|
336
|
+
with spatial coordinates and pixel spacings. rmax uses those same
|
|
337
|
+
spatial units. For cubes, a
|
|
338
|
+
spatial pixel is invalid if any channel is nonfinite. Return the
|
|
339
|
+
half-width as a Python float, preserving np.longdouble results as an
|
|
340
|
+
extended-precision exception; emission-size selection is left to the caller.
|
|
341
|
+
Raise ValueError if no sufficiently large centered finite region remains.
|
|
342
|
+
"""
|
|
343
|
+
if image.data.ndim == 2:
|
|
344
|
+
valid = np.isfinite(image.data)
|
|
345
|
+
else:
|
|
346
|
+
valid = np.ones(image.data.shape[-2:], dtype=bool)
|
|
347
|
+
for channel in image.data:
|
|
348
|
+
valid &= np.isfinite(channel)
|
|
349
|
+
invalid_y, invalid_x = np.nonzero(~valid)
|
|
350
|
+
if invalid_x.size:
|
|
351
|
+
nearest_invalid = np.min(np.maximum(np.abs(image.x[invalid_x]),
|
|
352
|
+
np.abs(image.y[invalid_y])))
|
|
353
|
+
margin = max(abs(image.dx), abs(image.dy))
|
|
354
|
+
rmax = min(rmax, nearest_invalid - margin)
|
|
355
|
+
if not np.isfinite(rmax) or rmax <= margin:
|
|
356
|
+
raise ValueError('No centered finite spatial region large enough.')
|
|
357
|
+
return _normalize_float(rmax, force_float=True)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _write_script(source: str, output: Path, *, overwrite: bool = False
|
|
361
|
+
) -> None:
|
|
362
|
+
"""Check Python syntax and write source, creating parent directories.
|
|
363
|
+
|
|
364
|
+
Compilation does not execute the source. Existing scripts raise
|
|
365
|
+
FileExistsError unless overwrite is True. SyntaxError is raised before
|
|
366
|
+
directories or files are created when source is invalid. Other I/O
|
|
367
|
+
errors propagate. output is a Path; return None.
|
|
368
|
+
"""
|
|
369
|
+
compile(source, str(output), 'exec')
|
|
370
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
371
|
+
with output.open('w' if overwrite else 'x') as stream:
|
|
372
|
+
stream.write(source)
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def generate_image_script(fitsimage: str | Path,
|
|
376
|
+
output: str | Path | None = None,
|
|
377
|
+
*, overwrite: bool = False) -> Path:
|
|
378
|
+
"""Write an editable noise, Gaussian-fit, and 2D image plotting script.
|
|
379
|
+
|
|
380
|
+
Generation reads the primary FITS image, fits its noise histogram, and
|
|
381
|
+
estimates an emission-based fitting region. It does not execute the
|
|
382
|
+
generated script or modify the input FITS file.
|
|
383
|
+
The generated script uses the existing AstroData, AstroFrame, Noise,
|
|
384
|
+
and PlotAstroData APIs directly, following example.py.
|
|
385
|
+
|
|
386
|
+
Args:
|
|
387
|
+
fitsimage (str | Path): A primary-HDU RA/Dec image with at least
|
|
388
|
+
two pixels on each spatial axis. Any higher axes must be singleton.
|
|
389
|
+
output (str | Path | None): Script path with a .py suffix. Defaults
|
|
390
|
+
to <input stem>_image.py in the current working directory.
|
|
391
|
+
Relative paths are resolved at generation time.
|
|
392
|
+
overwrite (bool): Allow replacing an existing script. Defaults to
|
|
393
|
+
False. This option does not control figure overwriting.
|
|
394
|
+
|
|
395
|
+
Returns:
|
|
396
|
+
Path: Absolute path of the written script.
|
|
397
|
+
|
|
398
|
+
Raises:
|
|
399
|
+
TypeError: overwrite is not a Python bool.
|
|
400
|
+
ValueError: The output path, image axes, spatial pixel scales, or
|
|
401
|
+
centered finite fitting region are unsuitable.
|
|
402
|
+
FileExistsError: The script exists and overwrite is False.
|
|
403
|
+
OSError: The input cannot be read or the script cannot be written.
|
|
404
|
+
|
|
405
|
+
Notes:
|
|
406
|
+
Generation estimates rmax and writes it directly into the fitting
|
|
407
|
+
and plotting frames, rounded to three significant digits as a
|
|
408
|
+
Python float literal with an inline comment. Edit it in the script
|
|
409
|
+
to change either field; no runtime range-selection helper is added.
|
|
410
|
+
|
|
411
|
+
The generated script reads the full image with sigma=None, fits
|
|
412
|
+
a hist-pbcor noise model, and saves <script stem>_noise.png. It then
|
|
413
|
+
reads a separate cropped image with the fitted noise level and calls
|
|
414
|
+
gaussfit2d(progressbar=True). It prints the sky center and east/north
|
|
415
|
+
position uncertainties in arcsec, then centers the 2D image on the
|
|
416
|
+
fitted sky position and saves <script stem>.png.
|
|
417
|
+
Both PNGs are beside the script and follow the existing plotting
|
|
418
|
+
methods' overwrite behavior. Noise statistics print with .3e format.
|
|
419
|
+
Changing the generated noise fit does not recompute the inline range.
|
|
420
|
+
Plotting uses stretch='log', show=False, and the default fonts,
|
|
421
|
+
beam, and contour levels. Edit these choices directly in the script.
|
|
422
|
+
"""
|
|
423
|
+
if not isinstance(overwrite, bool):
|
|
424
|
+
raise TypeError('overwrite must be a boolean.')
|
|
425
|
+
fitsimage = Path(fitsimage).resolve()
|
|
426
|
+
output = Path(output or f'{fitsimage.stem}_image.py').resolve()
|
|
427
|
+
if output.suffix != '.py':
|
|
428
|
+
raise ValueError('output must have a .py suffix.')
|
|
429
|
+
_validate_fits_image(fitsimage)
|
|
430
|
+
image = AstroData(fitsimage=str(fitsimage), sigma=None)
|
|
431
|
+
AstroFrame().read(image)
|
|
432
|
+
rmax, _, _ = _estimate_pb_ranges(image)
|
|
433
|
+
rmax = float(f'{rmax:.3g}')
|
|
434
|
+
source = f'''
|
|
435
|
+
from plotastrodata.analysis_utils import AstroData, AstroFrame
|
|
436
|
+
from plotastrodata.noise_utils import Noise
|
|
437
|
+
from plotastrodata.plot_utils import PlotAstroData
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
# Read the image
|
|
441
|
+
d = AstroData(fitsimage={str(fitsimage)!r}, sigma=None) # Estimate noise below.
|
|
442
|
+
f = AstroFrame()
|
|
443
|
+
f.read(d)
|
|
444
|
+
|
|
445
|
+
# Noise visualization
|
|
446
|
+
n = Noise(data=d.data, sigma='hist-pbcor')
|
|
447
|
+
n.gen_histogram()
|
|
448
|
+
n.fit_histogram()
|
|
449
|
+
print(f'Noise (mean, std): {{n.mean:.3e}}, {{n.std:.3e}}')
|
|
450
|
+
n.plot_histogram(savefig={str(output.with_name(output.stem + '_noise.png'))!r}, show=False)
|
|
451
|
+
|
|
452
|
+
d.sigma = n.std # A float number in the data unit is acceptable.
|
|
453
|
+
|
|
454
|
+
# 2D Gaussian fitting
|
|
455
|
+
d_fit = AstroData(fitsimage={str(fitsimage)!r}, sigma=d.sigma)
|
|
456
|
+
f_fit = AstroFrame(rmax={rmax!r}) # Estimated from PB-weighted emission (arcsec); adjust the fit region here.
|
|
457
|
+
f_fit.read(d_fit)
|
|
458
|
+
fit = d_fit.gaussfit2d(progressbar=True)
|
|
459
|
+
print('Gaussian center:', fit['center'])
|
|
460
|
+
print('Center uncertainties (east, north; arcsec):', fit['perr'][1:3])
|
|
461
|
+
|
|
462
|
+
# 2D image
|
|
463
|
+
p = PlotAstroData(rmax={rmax!r}, center=fit['center']) # Estimated from PB-weighted emission (arcsec); adjust as needed.
|
|
464
|
+
p.add_color(**d.todict(), stretch='log')
|
|
465
|
+
p.add_contour(**d.todict(), colors='r')
|
|
466
|
+
p.set_axis_radec(nticksminor=5)
|
|
467
|
+
p.savefig({str(output.with_suffix('.png'))!r}, show=False)
|
|
468
|
+
'''
|
|
469
|
+
_write_script(source, output, overwrite=overwrite)
|
|
470
|
+
return output
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def generate_cube_script(fitsimage: str | Path,
|
|
474
|
+
output: str | Path | None = None,
|
|
475
|
+
*, overwrite: bool = False) -> Path:
|
|
476
|
+
"""Write noise, integrated line-profile, and 3D channel-map plotting code.
|
|
477
|
+
|
|
478
|
+
Use the existing AstroData, AstroFrame, Noise, plotprofile, and
|
|
479
|
+
PlotAstroData APIs, following the line-profile and 3D channel-map
|
|
480
|
+
sections of example.py. Generation reads the FITS header and cube
|
|
481
|
+
pixels, fits edge-channel noise, and estimates emission ranges. It does
|
|
482
|
+
not execute the generated script or modify the input FITS file.
|
|
483
|
+
|
|
484
|
+
Args:
|
|
485
|
+
fitsimage (str | Path): Primary-HDU RA/Dec spectral cube with at least
|
|
486
|
+
two pixels on each spatial axis and two frequency or velocity
|
|
487
|
+
channels on axis 3, in Hz, m/s, or km/s. Higher axes must be
|
|
488
|
+
singleton. Running the generated flux profile assumes Jy/beam
|
|
489
|
+
intensities and requires a complete beam and spatial pixel sizes.
|
|
490
|
+
output (str | Path | None): Script path with a .py suffix. Defaults
|
|
491
|
+
to <input stem>_cube.py in the current working directory.
|
|
492
|
+
Relative input and output paths are resolved at generation time.
|
|
493
|
+
overwrite (bool): Permit replacing an existing script. Defaults to
|
|
494
|
+
False. This does not control figure overwriting.
|
|
495
|
+
|
|
496
|
+
Returns:
|
|
497
|
+
Path: Absolute path of the written script.
|
|
498
|
+
|
|
499
|
+
Raises:
|
|
500
|
+
TypeError: overwrite is not a Python bool.
|
|
501
|
+
ValueError: The output suffix, cube axes, spatial pixel scales, or
|
|
502
|
+
centered finite spatial region are unsuitable.
|
|
503
|
+
FileExistsError: The script exists and overwrite is False.
|
|
504
|
+
OSError: The input cannot be read or the script cannot be written.
|
|
505
|
+
|
|
506
|
+
Notes:
|
|
507
|
+
The script reads the full cube with sigma=None. Noise uses
|
|
508
|
+
edge,hist-pbcor (first and last spectral channels); the fitted
|
|
509
|
+
standard deviation is reused for colors and contours. Statistics
|
|
510
|
+
print with .3e format and the histogram is saved as
|
|
511
|
+
<script stem>_noise.png beside the script.
|
|
512
|
+
|
|
513
|
+
A separate AstroData instance reuses the loaded cube and is read
|
|
514
|
+
through AstroFrame to crop it to the estimated spatial and velocity
|
|
515
|
+
ranges, written directly in the script with inline comments.
|
|
516
|
+
plotprofile integrates flux over that crop with a circle whose
|
|
517
|
+
diameter is four times rmax, enclosing the entire square. Flux
|
|
518
|
+
integration assumes Jy/beam intensities and requires beam metadata
|
|
519
|
+
and spatial pixel sizes. The single-panel profile is saved as
|
|
520
|
+
<script stem>_profile.png at intrinsic channel spacing.
|
|
521
|
+
|
|
522
|
+
Generation estimates rmax, vmin, and vmax and writes them into
|
|
523
|
+
both frames as Python float literals rounded to three significant
|
|
524
|
+
digits, with inline comments. Edit them in the generated script
|
|
525
|
+
to change the profile or channel-map region. Changing its noise
|
|
526
|
+
fit does not recompute these values.
|
|
527
|
+
|
|
528
|
+
Both profile and channel maps use the selected ranges at intrinsic
|
|
529
|
+
channel spacing, without skipping or binning. They plot original
|
|
530
|
+
PB-corrected data about the FITS reference center. The generated
|
|
531
|
+
noise visualization still uses the full spatial footprint.
|
|
532
|
+
|
|
533
|
+
The script sets stretch='log' and show=False, with default fonts,
|
|
534
|
+
beams, contours, and channel layout. Edit these choices directly.
|
|
535
|
+
Channel-map pages are saved beside the script as <script stem>.png;
|
|
536
|
+
multiple pages receive _0, _1, ... suffixes before .png, following
|
|
537
|
+
PlotAstroData.savefig. Existing figures may be overwritten.
|
|
538
|
+
"""
|
|
539
|
+
if not isinstance(overwrite, bool):
|
|
540
|
+
raise TypeError('overwrite must be a boolean.')
|
|
541
|
+
fitsimage = Path(fitsimage).resolve()
|
|
542
|
+
output = Path(output or f'{fitsimage.stem}_cube.py').resolve()
|
|
543
|
+
if output.suffix != '.py':
|
|
544
|
+
raise ValueError('output must have a .py suffix.')
|
|
545
|
+
_validate_fits_image(fitsimage, ndim=3)
|
|
546
|
+
cube = AstroData(fitsimage=str(fitsimage), sigma=None)
|
|
547
|
+
AstroFrame().read(cube)
|
|
548
|
+
rmax, vmin, vmax = _estimate_pb_ranges(cube)
|
|
549
|
+
rmax = float(f'{rmax:.3g}')
|
|
550
|
+
vmin, vmax = float(f'{vmin:.3g}'), float(f'{vmax:.3g}')
|
|
551
|
+
source = f"""
|
|
552
|
+
from plotastrodata.analysis_utils import AstroData, AstroFrame
|
|
553
|
+
from plotastrodata.noise_utils import Noise
|
|
554
|
+
from plotastrodata.plot_utils import PlotAstroData, plotprofile
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
# Read the cube
|
|
558
|
+
d = AstroData(fitsimage={str(fitsimage)!r}, sigma=None) # Estimate noise below.
|
|
559
|
+
f = AstroFrame()
|
|
560
|
+
f.read(d)
|
|
561
|
+
|
|
562
|
+
# Noise visualization
|
|
563
|
+
n = Noise(data=d.data, sigma='edge,hist-pbcor') # First and last channels; adjust if they contain emission.
|
|
564
|
+
n.gen_histogram()
|
|
565
|
+
n.fit_histogram()
|
|
566
|
+
print(f'Noise (mean, std): {{n.mean:.3e}}, {{n.std:.3e}}')
|
|
567
|
+
n.plot_histogram(savefig={str(output.with_name(output.stem + '_noise.png'))!r}, show=False)
|
|
568
|
+
|
|
569
|
+
d.sigma = n.std # A float number in the data unit is acceptable.
|
|
570
|
+
|
|
571
|
+
# Line profile
|
|
572
|
+
d_profile = AstroData(**d.todict())
|
|
573
|
+
f_profile = AstroFrame(rmax={rmax!r}, # Estimated spatial half-width (arcsec); adjust as needed.
|
|
574
|
+
vmin={vmin!r}, vmax={vmax!r}, # Estimated velocity range (km/s); adjust as needed.
|
|
575
|
+
)
|
|
576
|
+
f_profile.read(d_profile)
|
|
577
|
+
plotprofile(**d_profile.todict(), xlist=[0], ylist=[0],
|
|
578
|
+
ellipse=[4 * f_profile.rmax, 4 * f_profile.rmax, 0], # Circle enclosing the cropped square.
|
|
579
|
+
flux=True,
|
|
580
|
+
savefig={str(output.with_name(output.stem + '_profile.png'))!r},
|
|
581
|
+
show=False,
|
|
582
|
+
)
|
|
583
|
+
|
|
584
|
+
# 3D channel maps
|
|
585
|
+
p = PlotAstroData(v=d.v, center=d.center,
|
|
586
|
+
rmax={rmax!r}, # Estimated spatial half-width (arcsec); adjust as needed.
|
|
587
|
+
vmin={vmin!r}, vmax={vmax!r}, # Estimated velocity range (km/s); adjust as needed.
|
|
588
|
+
)
|
|
589
|
+
p.add_color(**d.todict(), stretch='log')
|
|
590
|
+
p.add_contour(**d.todict(), colors='r')
|
|
591
|
+
p.set_axis()
|
|
592
|
+
p.savefig({str(output.with_suffix('.png'))!r}, show=False)
|
|
593
|
+
"""
|
|
594
|
+
_write_script(source, output, overwrite=overwrite)
|
|
595
|
+
return output
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: plotastrodata
|
|
3
|
-
Version: 1.12.
|
|
3
|
+
Version: 1.12.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
|
|
@@ -101,13 +101,12 @@ Review the inline values, then run `python image.py`. The script uses existing
|
|
|
101
101
|
library APIs to visualize a hist-pbcor noise fit, fit a 2D Gaussian and report
|
|
102
102
|
its sky center and east/north uncertainties, and plot a logarithmic image
|
|
103
103
|
with contours, a beam, and RA/Dec axes. It saves separate noise and image PNGs.
|
|
104
|
-
Noise estimation uses the full image. Fitting and plotting
|
|
105
|
-
|
|
106
|
-
The estimated rmax is written inline for editing.
|
|
104
|
+
Noise estimation uses the full image. Fitting and plotting ranges are estimated automatically and written inline
|
|
105
|
+
with three significant digits for editing.
|
|
107
106
|
For a spectral cube, use `generate_cube_script("cube.fits", output="cube.py")`
|
|
108
107
|
from the same module. It generates an edge-channel noise visualization, a flux-integrated line
|
|
109
|
-
profile
|
|
110
|
-
channel spacing. The flux profile assumes Jy/beam data with beam metadata.
|
|
108
|
+
profile and 3D channel maps over estimated spatial and velocity ranges,
|
|
109
|
+
with intrinsic channel spacing. The flux profile assumes Jy/beam data with beam metadata.
|
|
111
110
|
Both generators return an absolute pathlib.Path and write the script
|
|
112
111
|
without executing it.
|
|
113
112
|
See the [script-generation guide](docs/script_generation.rst).
|
|
@@ -1,302 +0,0 @@
|
|
|
1
|
-
"""Generate short, editable plotting scripts using existing plotastrodata APIs."""
|
|
2
|
-
from pathlib import Path
|
|
3
|
-
|
|
4
|
-
import numpy as np
|
|
5
|
-
from astropy.io import fits
|
|
6
|
-
from astropy.wcs import WCS
|
|
7
|
-
from astropy.wcs.utils import proj_plane_pixel_scales
|
|
8
|
-
|
|
9
|
-
from plotastrodata.analysis_utils import AstroData, AstroFrame
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
def _get_image_radius(fitsimage: str | Path, *, ndim: int = 2) -> float:
|
|
13
|
-
"""Validate a primary-HDU RA/Dec image or cube and return its half-width.
|
|
14
|
-
|
|
15
|
-
Read only the header. The result is half the larger image dimension
|
|
16
|
-
in arcsec, using projected WCS pixel scales, as a Python float.
|
|
17
|
-
Internal callers use ndim=2 for an image or ndim=3 for a spectral
|
|
18
|
-
cube. Higher axes must be singleton. Raise ValueError for unsuitable axes or spatial pixel scales.
|
|
19
|
-
"""
|
|
20
|
-
with fits.open(fitsimage, memmap=True) as hdus:
|
|
21
|
-
h = hdus[0].header
|
|
22
|
-
n = int(h.get('NAXIS', 0))
|
|
23
|
-
if (n < ndim or h.get('NAXIS1', 0) < 2 or h.get('NAXIS2', 0) < 2
|
|
24
|
-
or any(h[f'NAXIS{i}'] != 1 for i in range(ndim + 1, n + 1))
|
|
25
|
-
or not str(h.get('CTYPE1', '')).upper().startswith('RA')
|
|
26
|
-
or not str(h.get('CTYPE2', '')).upper().startswith('DEC')):
|
|
27
|
-
raise ValueError(f'Expected a {ndim}D RA/Dec image'
|
|
28
|
-
+ ' in the primary FITS HDU.')
|
|
29
|
-
if ndim == 3 and (
|
|
30
|
-
h.get('NAXIS3', 0) < 2
|
|
31
|
-
or not str(h.get('CTYPE3', '')).upper().startswith(
|
|
32
|
-
('FREQ', 'VRAD', 'VELO', 'VOPT', 'FELO'))
|
|
33
|
-
or str(h.get('CUNIT3', '')).strip().upper() not in
|
|
34
|
-
('HZ', 'M/S', 'KM/S')):
|
|
35
|
-
raise ValueError('Expected at least two frequency'
|
|
36
|
-
+ ' or velocity channels on the third FITS axis,'
|
|
37
|
-
+ ' in Hz, m/s, or km/s.')
|
|
38
|
-
scales = proj_plane_pixel_scales(WCS(h, naxis=2, fix=False).celestial)
|
|
39
|
-
rmax = max(h['NAXIS1'] * scales[0], h['NAXIS2'] * scales[1]) * 3600 / 2
|
|
40
|
-
if not np.isfinite(rmax) or rmax <= 0:
|
|
41
|
-
raise ValueError('Expected finite positive spatial pixel scales.')
|
|
42
|
-
return float(rmax)
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
def _get_valid_radius(image: AstroData, rmax: float) -> float:
|
|
46
|
-
"""Reduce a half-width to exclude nonfinite pixels, with a pixel margin.
|
|
47
|
-
|
|
48
|
-
image must contain one 2D image or 3D cube already read by AstroFrame,
|
|
49
|
-
with spatial coordinates and pixel spacings. rmax uses those same
|
|
50
|
-
spatial units. For cubes, a
|
|
51
|
-
spatial pixel is invalid if any channel is nonfinite. Return the
|
|
52
|
-
half-width as a Python float; quarter-size scaling is left to the caller.
|
|
53
|
-
Raise ValueError if no sufficiently large centered finite region remains.
|
|
54
|
-
"""
|
|
55
|
-
if image.data.ndim == 2:
|
|
56
|
-
valid = np.isfinite(image.data)
|
|
57
|
-
else:
|
|
58
|
-
valid = np.ones(image.data.shape[-2:], dtype=bool)
|
|
59
|
-
for channel in image.data:
|
|
60
|
-
valid &= np.isfinite(channel)
|
|
61
|
-
invalid_y, invalid_x = np.nonzero(~valid)
|
|
62
|
-
if invalid_x.size:
|
|
63
|
-
nearest_invalid = np.min(np.maximum(np.abs(image.x[invalid_x]),
|
|
64
|
-
np.abs(image.y[invalid_y])))
|
|
65
|
-
margin = max(abs(image.dx), abs(image.dy))
|
|
66
|
-
rmax = min(rmax, nearest_invalid - margin)
|
|
67
|
-
if not np.isfinite(rmax) or rmax <= margin:
|
|
68
|
-
raise ValueError('No centered finite spatial region large enough.')
|
|
69
|
-
return float(rmax)
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
def _write_script(source: str, output: Path, *, overwrite: bool = False
|
|
73
|
-
) -> None:
|
|
74
|
-
"""Check Python syntax and write source, creating parent directories.
|
|
75
|
-
|
|
76
|
-
Compilation does not execute the source. Existing scripts raise
|
|
77
|
-
FileExistsError unless overwrite is True. SyntaxError is raised before
|
|
78
|
-
directories or files are created when source is invalid. Other I/O
|
|
79
|
-
errors propagate. output is a Path; return None.
|
|
80
|
-
"""
|
|
81
|
-
compile(source, str(output), 'exec')
|
|
82
|
-
output.parent.mkdir(parents=True, exist_ok=True)
|
|
83
|
-
with output.open('w' if overwrite else 'x') as stream:
|
|
84
|
-
stream.write(source)
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
def generate_image_script(fitsimage: str | Path,
|
|
88
|
-
output: str | Path | None = None,
|
|
89
|
-
*, overwrite: bool = False) -> Path:
|
|
90
|
-
"""Write an editable noise, Gaussian-fit, and 2D image plotting script.
|
|
91
|
-
|
|
92
|
-
Generation reads the primary FITS image to estimate a finite fitting
|
|
93
|
-
region, but does not execute the script or modify the input file.
|
|
94
|
-
The generated script uses the existing AstroData, AstroFrame, Noise,
|
|
95
|
-
and PlotAstroData APIs directly, following example.py.
|
|
96
|
-
|
|
97
|
-
Args:
|
|
98
|
-
fitsimage (str | Path): A primary-HDU RA/Dec image with at least
|
|
99
|
-
two pixels on each spatial axis. Any higher axes must be singleton.
|
|
100
|
-
output (str | Path | None): Script path with a .py suffix. Defaults
|
|
101
|
-
to <input stem>_image.py in the current working directory.
|
|
102
|
-
Relative paths are resolved at generation time.
|
|
103
|
-
overwrite (bool): Allow replacing an existing script. Defaults to
|
|
104
|
-
False. This option does not control figure overwriting.
|
|
105
|
-
|
|
106
|
-
Returns:
|
|
107
|
-
Path: Absolute path of the written script.
|
|
108
|
-
|
|
109
|
-
Raises:
|
|
110
|
-
TypeError: overwrite is not a Python bool.
|
|
111
|
-
ValueError: The output path, image axes, spatial pixel scales, or
|
|
112
|
-
centered finite fitting region are unsuitable.
|
|
113
|
-
FileExistsError: The script exists and overwrite is False.
|
|
114
|
-
OSError: The input cannot be read or the script cannot be written.
|
|
115
|
-
|
|
116
|
-
Notes:
|
|
117
|
-
The initial half-width is half the larger image dimension in arcsec,
|
|
118
|
-
using projected WCS pixel scales. If nonfinite pixels are present,
|
|
119
|
-
it is reduced to a square around the FITS reference position that
|
|
120
|
-
excludes them, with one spatial pixel of margin. That half-width
|
|
121
|
-
is divided by four and rounded to eight significant digits for the
|
|
122
|
-
inline Python float used by the fitting frame and plotting frame.
|
|
123
|
-
Thus the full field width is one quarter of the initial valid width.
|
|
124
|
-
This is a footprint estimate, not a measurement of source emission.
|
|
125
|
-
|
|
126
|
-
The generated script reads the full image with sigma=None, fits
|
|
127
|
-
a hist-pbcor noise model, and saves <script stem>_noise.png. It then
|
|
128
|
-
reads a separate cropped image with the fitted noise level and calls
|
|
129
|
-
gaussfit2d(progressbar=True). It prints the sky center and east/north
|
|
130
|
-
position uncertainties in arcsec, then centers the 2D image on the
|
|
131
|
-
fitted sky position and saves <script stem>.png.
|
|
132
|
-
Both PNGs are beside the script and follow the existing plotting
|
|
133
|
-
methods' overwrite behavior. Noise statistics print with .3e format.
|
|
134
|
-
Plotting uses stretch='log', show=False, and the default fonts,
|
|
135
|
-
beam, and contour levels. Edit these choices directly in the script.
|
|
136
|
-
"""
|
|
137
|
-
if not isinstance(overwrite, bool):
|
|
138
|
-
raise TypeError('overwrite must be a boolean.')
|
|
139
|
-
fitsimage = Path(fitsimage).resolve()
|
|
140
|
-
output = Path(output or f'{fitsimage.stem}_image.py').resolve()
|
|
141
|
-
if output.suffix != '.py':
|
|
142
|
-
raise ValueError('output must have a .py suffix.')
|
|
143
|
-
rmax = _get_image_radius(fitsimage)
|
|
144
|
-
image = AstroData(fitsimage=str(fitsimage), sigma=None)
|
|
145
|
-
AstroFrame().read(image)
|
|
146
|
-
rmax = _get_valid_radius(image, rmax)
|
|
147
|
-
rmax = float(f'{rmax / 4:.8g}')
|
|
148
|
-
source = f'''
|
|
149
|
-
from plotastrodata.analysis_utils import AstroData, AstroFrame
|
|
150
|
-
from plotastrodata.noise_utils import Noise
|
|
151
|
-
from plotastrodata.plot_utils import PlotAstroData
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
# Read the image
|
|
155
|
-
d = AstroData(fitsimage={str(fitsimage)!r}, sigma=None) # Estimate noise below.
|
|
156
|
-
f = AstroFrame()
|
|
157
|
-
f.read(d)
|
|
158
|
-
|
|
159
|
-
# Noise visualization
|
|
160
|
-
n = Noise(data=d.data, sigma='hist-pbcor')
|
|
161
|
-
n.gen_histogram()
|
|
162
|
-
n.fit_histogram()
|
|
163
|
-
print(f'Noise (mean, std): {{n.mean:.3e}}, {{n.std:.3e}}')
|
|
164
|
-
n.plot_histogram(savefig={str(output.with_name(output.stem + '_noise.png'))!r}, show=False)
|
|
165
|
-
|
|
166
|
-
d.sigma = n.std # A float number in the data unit is acceptable.
|
|
167
|
-
|
|
168
|
-
# 2D Gaussian fitting
|
|
169
|
-
d_fit = AstroData(fitsimage={str(fitsimage)!r}, sigma=d.sigma)
|
|
170
|
-
f_fit = AstroFrame(rmax={rmax!r}) # One quarter of the valid half-width in arcsec; adjust the fit region here.
|
|
171
|
-
f_fit.read(d_fit)
|
|
172
|
-
fit = d_fit.gaussfit2d(progressbar=True)
|
|
173
|
-
print('Gaussian center:', fit['center'])
|
|
174
|
-
print('Center uncertainties (east, north; arcsec):', fit['perr'][1:3])
|
|
175
|
-
|
|
176
|
-
# 2D image
|
|
177
|
-
p = PlotAstroData(rmax={rmax!r}, center=fit['center']) # One quarter of the valid half-width in arcsec; adjust as needed.
|
|
178
|
-
p.add_color(**d.todict(), stretch='log', cblabel=d.bunit)
|
|
179
|
-
p.add_contour(**d.todict(), colors='r')
|
|
180
|
-
p.set_axis_radec(nticksminor=5)
|
|
181
|
-
p.savefig({str(output.with_suffix('.png'))!r}, show=False)
|
|
182
|
-
'''
|
|
183
|
-
_write_script(source, output, overwrite=overwrite)
|
|
184
|
-
return output
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
def generate_cube_script(fitsimage: str | Path,
|
|
188
|
-
output: str | Path | None = None,
|
|
189
|
-
*, overwrite: bool = False) -> Path:
|
|
190
|
-
"""Write noise, integrated line-profile, and 3D channel-map plotting code.
|
|
191
|
-
|
|
192
|
-
Use the existing AstroData, AstroFrame, Noise, plotprofile, and
|
|
193
|
-
PlotAstroData APIs, following the line-profile and 3D channel-map
|
|
194
|
-
sections of example.py. Generation reads
|
|
195
|
-
the FITS header and cube pixels, but does not execute the script.
|
|
196
|
-
|
|
197
|
-
Args:
|
|
198
|
-
fitsimage (str | Path): Primary-HDU RA/Dec spectral cube with at least
|
|
199
|
-
two pixels on each spatial axis and two frequency or velocity
|
|
200
|
-
channels on axis 3, in Hz, m/s, or km/s. Higher axes must be
|
|
201
|
-
singleton. Running the generated flux profile assumes Jy/beam
|
|
202
|
-
intensities and requires a complete beam and spatial pixel sizes.
|
|
203
|
-
output (str | Path | None): Script path with a .py suffix. Defaults
|
|
204
|
-
to <input stem>_cube.py in the current working directory.
|
|
205
|
-
Relative input and output paths are resolved at generation time.
|
|
206
|
-
overwrite (bool): Permit replacing an existing script. Defaults to
|
|
207
|
-
False. This does not control figure overwriting.
|
|
208
|
-
|
|
209
|
-
Returns:
|
|
210
|
-
Path: Absolute path of the written script.
|
|
211
|
-
|
|
212
|
-
Raises:
|
|
213
|
-
TypeError: overwrite is not a Python bool.
|
|
214
|
-
ValueError: The output suffix, cube axes, spatial pixel scales, or
|
|
215
|
-
centered finite spatial region are unsuitable.
|
|
216
|
-
FileExistsError: The script exists and overwrite is False.
|
|
217
|
-
OSError: The input cannot be read or the script cannot be written.
|
|
218
|
-
|
|
219
|
-
Notes:
|
|
220
|
-
The script reads the full cube with sigma=None. Noise uses
|
|
221
|
-
edge,hist-pbcor (first and last spectral channels); the fitted
|
|
222
|
-
standard deviation is reused for colors and contours. Statistics
|
|
223
|
-
print with .3e format and the histogram is saved as
|
|
224
|
-
<script stem>_noise.png beside the script.
|
|
225
|
-
|
|
226
|
-
A separate AstroData instance reuses the loaded cube and is read
|
|
227
|
-
through AstroFrame to crop it to the spatial quarter-size.
|
|
228
|
-
plotprofile integrates flux over that crop with a circle whose
|
|
229
|
-
diameter is four times rmax, enclosing the entire square. Flux
|
|
230
|
-
integration assumes Jy/beam intensities and requires beam metadata
|
|
231
|
-
and spatial pixel sizes. The single-panel profile is saved as
|
|
232
|
-
<script stem>_profile.png at intrinsic channel spacing.
|
|
233
|
-
|
|
234
|
-
Channel maps use the full spectral range at intrinsic channel
|
|
235
|
-
spacing, without skipping or binning. Spatial rmax starts from
|
|
236
|
-
half the larger image dimension in arcsec. A spatial pixel is
|
|
237
|
-
invalid if any channel there is nonfinite. If invalid pixels exist,
|
|
238
|
-
the centered square is reduced to exclude them with one spatial
|
|
239
|
-
pixel of margin. This valid half-width is divided by four and
|
|
240
|
-
rounded to eight significant digits as an inline Python float
|
|
241
|
-
for the profile crop and channel maps. The full field width is one
|
|
242
|
-
quarter of the estimated valid width. This estimates the footprint,
|
|
243
|
-
not the source emission. Both regions use the FITS reference center;
|
|
244
|
-
noise uses the full cube.
|
|
245
|
-
|
|
246
|
-
The script sets stretch='log' and show=False, with default fonts,
|
|
247
|
-
beams, contours, and channel layout. Edit these choices directly.
|
|
248
|
-
Channel-map pages are saved beside the script as <script stem>.png;
|
|
249
|
-
multiple pages receive _0, _1, ... suffixes before .png, following
|
|
250
|
-
PlotAstroData.savefig. Existing figures may be overwritten.
|
|
251
|
-
"""
|
|
252
|
-
if not isinstance(overwrite, bool):
|
|
253
|
-
raise TypeError('overwrite must be a boolean.')
|
|
254
|
-
fitsimage = Path(fitsimage).resolve()
|
|
255
|
-
output = Path(output or f'{fitsimage.stem}_cube.py').resolve()
|
|
256
|
-
if output.suffix != '.py':
|
|
257
|
-
raise ValueError('output must have a .py suffix.')
|
|
258
|
-
rmax = _get_image_radius(fitsimage, ndim=3)
|
|
259
|
-
cube = AstroData(fitsimage=str(fitsimage), sigma=None)
|
|
260
|
-
AstroFrame().read(cube)
|
|
261
|
-
rmax = _get_valid_radius(cube, rmax)
|
|
262
|
-
rmax = float(f'{rmax / 4:.8g}')
|
|
263
|
-
source = f"""
|
|
264
|
-
from plotastrodata.analysis_utils import AstroData, AstroFrame
|
|
265
|
-
from plotastrodata.noise_utils import Noise
|
|
266
|
-
from plotastrodata.plot_utils import PlotAstroData, plotprofile
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
# Read the cube
|
|
270
|
-
d = AstroData(fitsimage={str(fitsimage)!r}, sigma=None) # Estimate noise below.
|
|
271
|
-
f = AstroFrame()
|
|
272
|
-
f.read(d)
|
|
273
|
-
|
|
274
|
-
# Noise visualization
|
|
275
|
-
n = Noise(data=d.data, sigma='edge,hist-pbcor') # First and last channels; adjust if they contain emission.
|
|
276
|
-
n.gen_histogram()
|
|
277
|
-
n.fit_histogram()
|
|
278
|
-
print(f'Noise (mean, std): {{n.mean:.3e}}, {{n.std:.3e}}')
|
|
279
|
-
n.plot_histogram(savefig={str(output.with_name(output.stem + '_noise.png'))!r}, show=False)
|
|
280
|
-
|
|
281
|
-
d.sigma = n.std # A float number in the data unit is acceptable.
|
|
282
|
-
|
|
283
|
-
# Line profile
|
|
284
|
-
d_profile = AstroData(**d.todict())
|
|
285
|
-
f_profile = AstroFrame(rmax={rmax!r}) # One quarter of the valid half-width in arcsec; adjust as needed.
|
|
286
|
-
f_profile.read(d_profile)
|
|
287
|
-
plotprofile(**d_profile.todict(), xlist=[0], ylist=[0],
|
|
288
|
-
ellipse=[4 * f_profile.rmax, 4 * f_profile.rmax, 0], # Circle enclosing the cropped square.
|
|
289
|
-
flux=True,
|
|
290
|
-
savefig={str(output.with_name(output.stem + '_profile.png'))!r},
|
|
291
|
-
show=False,
|
|
292
|
-
)
|
|
293
|
-
|
|
294
|
-
# 3D channel maps
|
|
295
|
-
p = PlotAstroData(v=d.v, rmax={rmax!r}, center=d.center) # One quarter of the valid half-width in arcsec; adjust as needed.
|
|
296
|
-
p.add_color(**d.todict(), stretch='log', cblabel=d.bunit)
|
|
297
|
-
p.add_contour(**d.todict(), colors='r')
|
|
298
|
-
p.set_axis()
|
|
299
|
-
p.savefig({str(output.with_suffix('.png'))!r}, show=False)
|
|
300
|
-
"""
|
|
301
|
-
_write_script(source, output, overwrite=overwrite)
|
|
302
|
-
return output
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|