plotastrodata 1.12.2__py3-none-any.whl → 1.13.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- plotastrodata/__init__.py +1 -1
- plotastrodata/analysis_utils.py +145 -10
- plotastrodata/plot_utils.py +2 -1
- plotastrodata/pngpdf_utils.py +267 -0
- plotastrodata/script_utils.py +50 -7
- {plotastrodata-1.12.2.dist-info → plotastrodata-1.13.0.dist-info}/METADATA +27 -3
- {plotastrodata-1.12.2.dist-info → plotastrodata-1.13.0.dist-info}/RECORD +10 -9
- {plotastrodata-1.12.2.dist-info → plotastrodata-1.13.0.dist-info}/WHEEL +0 -0
- {plotastrodata-1.12.2.dist-info → plotastrodata-1.13.0.dist-info}/licenses/LICENSE +0 -0
- {plotastrodata-1.12.2.dist-info → plotastrodata-1.13.0.dist-info}/top_level.txt +0 -0
plotastrodata/__init__.py
CHANGED
plotastrodata/analysis_utils.py
CHANGED
|
@@ -25,6 +25,7 @@ from plotastrodata._type_utils import (
|
|
|
25
25
|
from plotastrodata._validation_utils import (
|
|
26
26
|
_is_finite_real_scalar,
|
|
27
27
|
_is_positive_real_scalar,
|
|
28
|
+
_is_uniform_spacing,
|
|
28
29
|
_is_zero_dimensional_array,
|
|
29
30
|
_require_integer,
|
|
30
31
|
_require_positive_real_scalar,
|
|
@@ -41,6 +42,69 @@ from plotastrodata.other_utils import (
|
|
|
41
42
|
)
|
|
42
43
|
|
|
43
44
|
|
|
45
|
+
def _validate_moment_cube(data: np.ndarray, v: np.ndarray,
|
|
46
|
+
sigma: RealScalar, dv: RealScalar) -> None:
|
|
47
|
+
"""Validate a moment cube and its velocity/noise metadata without coercion.
|
|
48
|
+
|
|
49
|
+
Preserve input arrays and numerical precision. NaNs in data are allowed,
|
|
50
|
+
but reject infinities, unsuitable shapes, noise, and velocity spacing.
|
|
51
|
+
"""
|
|
52
|
+
if not isinstance(data, np.ndarray):
|
|
53
|
+
raise TypeError('moment requires data to be a NumPy array.')
|
|
54
|
+
if (data.ndim != 3 or 0 in data.shape
|
|
55
|
+
or data.dtype.kind not in 'iuf'
|
|
56
|
+
or np.any(np.isinf(data))):
|
|
57
|
+
raise ValueError('moment requires a nonempty real 3D cube'
|
|
58
|
+
+ ' without infinities.')
|
|
59
|
+
if not isinstance(v, np.ndarray):
|
|
60
|
+
raise TypeError('moment requires v to be a NumPy array.')
|
|
61
|
+
if (v.ndim != 1 or v.size != data.shape[0]
|
|
62
|
+
or v.dtype.kind not in 'iuf'
|
|
63
|
+
or not np.all(np.isfinite(v))):
|
|
64
|
+
raise ValueError('v must be a finite real 1D grid matching'
|
|
65
|
+
+ ' the number of channels.')
|
|
66
|
+
if not _is_positive_real_scalar(sigma):
|
|
67
|
+
raise ValueError('moment requires finite positive scalar sigma.')
|
|
68
|
+
if not _is_finite_real_scalar(dv) or dv == 0:
|
|
69
|
+
raise ValueError('moment requires finite nonzero scalar dv.')
|
|
70
|
+
if v.size > 1:
|
|
71
|
+
steps = np.diff(v.astype(np.result_type(v.dtype, float)))
|
|
72
|
+
if (not (np.all(steps > 0) or np.all(steps < 0))
|
|
73
|
+
or not _is_uniform_spacing(steps, steps[0])
|
|
74
|
+
or not _is_uniform_spacing(np.abs(steps), abs(dv))):
|
|
75
|
+
raise ValueError('v must be monotonic and uniformly spaced'
|
|
76
|
+
+ ' with spacing magnitude abs(dv).')
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _validate_moment_inputs(data: np.ndarray, v: np.ndarray,
|
|
80
|
+
sigma: RealScalar, dv: RealScalar,
|
|
81
|
+
vmask: np.ndarray | None,
|
|
82
|
+
threshold_cube: RealScalar,
|
|
83
|
+
threshold_mom0: RealScalar) -> np.ndarray:
|
|
84
|
+
"""Validate moment inputs and return a nonempty Boolean channel mask.
|
|
85
|
+
|
|
86
|
+
Check the cube before thresholds and selection, preserving validation
|
|
87
|
+
order and error messages. Return a supplied mask unchanged, or a new
|
|
88
|
+
all-True mask when omitted. Inputs and their dtypes are unchanged.
|
|
89
|
+
"""
|
|
90
|
+
_validate_moment_cube(data, v, sigma, dv)
|
|
91
|
+
for name, value in (('threshold_cube', threshold_cube),
|
|
92
|
+
('threshold_mom0', threshold_mom0)):
|
|
93
|
+
if not _is_finite_real_scalar(value) or value < 0:
|
|
94
|
+
raise ValueError(f'{name} must be a finite nonnegative'
|
|
95
|
+
+ ' real scalar.')
|
|
96
|
+
if vmask is None:
|
|
97
|
+
vmask = np.ones(v.size, dtype=bool)
|
|
98
|
+
elif not isinstance(vmask, np.ndarray):
|
|
99
|
+
raise TypeError('vmask must be a NumPy Boolean array or None.')
|
|
100
|
+
if (vmask.dtype.kind != 'b' or vmask.shape != v.shape
|
|
101
|
+
or not np.any(vmask)):
|
|
102
|
+
raise ValueError('vmask must be a 1D Boolean array matching v'
|
|
103
|
+
+ ' and selecting at least one channel.')
|
|
104
|
+
|
|
105
|
+
return vmask
|
|
106
|
+
|
|
107
|
+
|
|
44
108
|
def _profile_ellipses(ellipse: Any, nprof: int) -> np.ndarray:
|
|
45
109
|
"""Prepare one ellipse per profile without changing supplied array dtypes."""
|
|
46
110
|
if ellipse is None:
|
|
@@ -707,24 +771,24 @@ class AstroData():
|
|
|
707
771
|
if dataformask is None:
|
|
708
772
|
dataformask = self.data
|
|
709
773
|
if len(includepix) not in [0, 2] or len(excludepix) not in [0, 2]:
|
|
710
|
-
raise ValueError(
|
|
711
|
-
|
|
774
|
+
raise ValueError('includepix and excludepix must be empty'
|
|
775
|
+
+ ' or [min, max].')
|
|
712
776
|
if np.ndim(self.data) > np.ndim(dataformask):
|
|
713
777
|
print('The mask is broadcasted.')
|
|
714
778
|
try:
|
|
715
779
|
mask = np.broadcast_to(dataformask, np.shape(self.data))
|
|
716
780
|
except ValueError as exc:
|
|
717
|
-
raise ValueError(
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
781
|
+
raise ValueError('dataformask must be broadcastable'
|
|
782
|
+
' to the data shape;'
|
|
783
|
+
+ f' got {np.shape(dataformask)}'
|
|
784
|
+
+ f' and {np.shape(self.data)}.') from exc
|
|
721
785
|
else:
|
|
722
786
|
mask = dataformask
|
|
723
787
|
if np.shape(self.data) != np.shape(mask):
|
|
724
|
-
raise ValueError(
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
788
|
+
raise ValueError('dataformask must have the same shape as data'
|
|
789
|
+
+ ' after broadcasting;'
|
|
790
|
+
+ f' got {np.shape(dataformask)}'
|
|
791
|
+
+ f' and {np.shape(self.data)}.')
|
|
728
792
|
|
|
729
793
|
if ((len(includepix) == 2 or len(excludepix) == 2)
|
|
730
794
|
and self.data.dtype.kind in 'biu'):
|
|
@@ -734,6 +798,77 @@ class AstroData():
|
|
|
734
798
|
if len(excludepix) == 2:
|
|
735
799
|
self.data[(excludepix[0] < mask) * (mask < excludepix[1])] = np.nan
|
|
736
800
|
|
|
801
|
+
def moment(self, vmask: np.ndarray | None = None,
|
|
802
|
+
threshold_cube: RealScalar = 3,
|
|
803
|
+
threshold_mom0: RealScalar = 3) -> None:
|
|
804
|
+
"""Store integrated intensity, mean velocity, and velocity dispersion.
|
|
805
|
+
|
|
806
|
+
Uses the current data axis order (v, y, x), including after a
|
|
807
|
+
swapped read. Requires a nonempty real 3D cube, a finite 1D velocity
|
|
808
|
+
grid matching its first axis, finite positive scalar sigma, and
|
|
809
|
+
finite nonzero scalar dv. Multiple channels must be uniformly
|
|
810
|
+
spaced with spacing magnitude abs(dv) (relative tolerance 1e-5).
|
|
811
|
+
NaNs in the cube are ignored; infinities are rejected.
|
|
812
|
+
|
|
813
|
+
Args:
|
|
814
|
+
vmask (np.ndarray or None, optional): 1D Boolean array with one
|
|
815
|
+
entry per channel. True selects a channel. None selects all
|
|
816
|
+
channels; at least one must be selected.
|
|
817
|
+
threshold_cube (RealScalar, optional): Finite nonnegative noise
|
|
818
|
+
multiple used to select intensities for moments 1 and 2.
|
|
819
|
+
Values equal to the threshold survive. Defaults to 3.
|
|
820
|
+
threshold_mom0 (RealScalar, optional): Finite nonnegative
|
|
821
|
+
multiple of sigma_mom0 below which moments 1 and 2 are
|
|
822
|
+
masked. Values equal to the threshold survive. Defaults to 3.
|
|
823
|
+
Both thresholds accept Python/NumPy real scalars, excluding
|
|
824
|
+
booleans and arrays.
|
|
825
|
+
|
|
826
|
+
Returns:
|
|
827
|
+
None: Stores mom0, mom1, and mom2 as (y, x) NumPy arrays.
|
|
828
|
+
mom0 sums selected intensities times abs(dv), without cube
|
|
829
|
+
thresholding. mom1 is the intensity-weighted velocity; mom2 is
|
|
830
|
+
the weighted standard deviation, not FWHM. Both are NaN where
|
|
831
|
+
mom0 fails its threshold or no positive weight survives.
|
|
832
|
+
All-NaN spectra have mom0=0. sigma_mom0 is
|
|
833
|
+
sqrt(number of selected channels) * sigma * abs(dv), assuming
|
|
834
|
+
independent channel noise, even where data are NaN. It is a
|
|
835
|
+
Python float, except np.longdouble retains extended precision.
|
|
836
|
+
mom0 and sigma_mom0 use intensity times velocity units; mom1
|
|
837
|
+
and mom2 use the units of v. Input arrays are not modified.
|
|
838
|
+
|
|
839
|
+
Raises:
|
|
840
|
+
TypeError: data, v, or a supplied vmask is not a NumPy array.
|
|
841
|
+
ValueError: Shapes, numeric values, channel selection, noise,
|
|
842
|
+
spacing, or thresholds do not satisfy the requirements.
|
|
843
|
+
"""
|
|
844
|
+
vmask = _validate_moment_inputs(self.data, self.v, self.sigma, self.dv,
|
|
845
|
+
vmask, threshold_cube, threshold_mom0)
|
|
846
|
+
data = np.where(vmask[:, None, None], self.data, 0)
|
|
847
|
+
dv = abs(self.dv)
|
|
848
|
+
mom0 = np.nansum(data, axis=0) * dv
|
|
849
|
+
sigma_mom0 = np.sqrt(np.count_nonzero(vmask)) * self.sigma * dv
|
|
850
|
+
if (isinstance(self.sigma, np.longdouble)
|
|
851
|
+
or isinstance(dv, np.longdouble)):
|
|
852
|
+
sigma_mom0 = np.longdouble(sigma_mom0)
|
|
853
|
+
sigma_mom0 = _normalize_float(sigma_mom0)
|
|
854
|
+
w = np.where(data >= threshold_cube * self.sigma, data, 0)
|
|
855
|
+
total = np.sum(w, axis=0)
|
|
856
|
+
w = np.divide(w, total,
|
|
857
|
+
out=np.zeros_like(w, dtype=np.result_type(w, float)),
|
|
858
|
+
where=total > 0)
|
|
859
|
+
mask = (mom0 < threshold_mom0 * sigma_mom0) | (total <= 0)
|
|
860
|
+
|
|
861
|
+
def wmean(x: np.ndarray) -> np.ndarray:
|
|
862
|
+
return np.where(mask, np.nan, np.nansum(w * x, axis=0))
|
|
863
|
+
|
|
864
|
+
v = self.v[:, None, None]
|
|
865
|
+
mom1 = wmean(v)
|
|
866
|
+
mom2 = np.sqrt(wmean((v - mom1)**2))
|
|
867
|
+
self.mom0: np.ndarray = mom0
|
|
868
|
+
self.mom1: np.ndarray = mom1
|
|
869
|
+
self.mom2: np.ndarray = mom2
|
|
870
|
+
self.sigma_mom0: float | np.longdouble = sigma_mom0
|
|
871
|
+
|
|
737
872
|
def _gfit_profile(self, prof: np.ndarray, gaussfit: bool
|
|
738
873
|
) -> dict[str, list[np.ndarray]]:
|
|
739
874
|
if not gaussfit:
|
plotastrodata/plot_utils.py
CHANGED
|
@@ -2773,7 +2773,8 @@ def plot3d(levels: RealSequence = (3, 6, 12),
|
|
|
2773
2773
|
import plotly.graph_objs as go
|
|
2774
2774
|
from skimage import measure
|
|
2775
2775
|
except ImportError as exc:
|
|
2776
|
-
raise ImportError('plot3d() requires plotly and
|
|
2776
|
+
raise ImportError('plot3d() requires plotly and'
|
|
2777
|
+
+ ' scikit-image.') from exc
|
|
2777
2778
|
d = kwargs2instance(AstroData, kwargs)
|
|
2778
2779
|
f.read(d, xskip, yskip)
|
|
2779
2780
|
cube = _prepare_surface_cube(d)
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
"""Compose PNG images or first PDF pages using the same grid geometry.
|
|
2
|
+
|
|
3
|
+
Sizes are rounded to whole layout units (pixels for PNG, points for PDF).
|
|
4
|
+
PDF composition uses the required pypdf dependency, imported only when used.
|
|
5
|
+
"""
|
|
6
|
+
from contextlib import ExitStack
|
|
7
|
+
from os import PathLike
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Sequence
|
|
10
|
+
|
|
11
|
+
from PIL import Image
|
|
12
|
+
|
|
13
|
+
from plotastrodata._type_utils import RealScalar
|
|
14
|
+
from plotastrodata._validation_utils import (
|
|
15
|
+
_is_finite_real_scalar,
|
|
16
|
+
_is_positive_real_scalar,
|
|
17
|
+
_require_integer,
|
|
18
|
+
_require_positive_real_scalar,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
PathInput = str | PathLike[str]
|
|
23
|
+
ScaleInput = Sequence[RealScalar] | Sequence[Sequence[RealScalar]] | None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _inputs(file_list: Sequence[PathInput], output_file: PathInput,
|
|
27
|
+
columns: int, padding: RealScalar, scale_factors: ScaleInput,
|
|
28
|
+
suffix: str
|
|
29
|
+
) -> tuple[list[Path], Path, int, int, list[RealScalar]]:
|
|
30
|
+
"""Validate shared options without opening files and normalize their types.
|
|
31
|
+
|
|
32
|
+
Return input Paths, the output Path, integer columns and padding, and
|
|
33
|
+
one real scalar scale per input (preserving extended precision).
|
|
34
|
+
Flatten nested scales in row-major order, filling missing entries with
|
|
35
|
+
1.0 and validating unused entries as well.
|
|
36
|
+
Reject output paths that resolve to an input or have the wrong suffix.
|
|
37
|
+
"""
|
|
38
|
+
if isinstance(file_list, (str, PathLike)):
|
|
39
|
+
raise TypeError('file_list must be a sequence of paths')
|
|
40
|
+
files = [Path(f) for f in file_list]
|
|
41
|
+
if not files:
|
|
42
|
+
raise ValueError('file_list is empty')
|
|
43
|
+
_require_integer(columns, 'columns')
|
|
44
|
+
if not _is_finite_real_scalar(padding) or padding < 0:
|
|
45
|
+
raise ValueError('padding must be a finite nonnegative real scalar')
|
|
46
|
+
if padding != int(padding):
|
|
47
|
+
raise ValueError('padding must be a whole number of layout units')
|
|
48
|
+
output = Path(output_file)
|
|
49
|
+
if output.suffix.lower() != suffix:
|
|
50
|
+
raise ValueError(f'output_file must end in {suffix}')
|
|
51
|
+
if any(output.resolve() == f.resolve() for f in files):
|
|
52
|
+
raise ValueError('output_file must differ from every input file')
|
|
53
|
+
scales = _scale_factors(scale_factors, len(files), int(columns))
|
|
54
|
+
return files, output, int(columns), int(padding), scales
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _grid_scales(values: Sequence[Sequence[RealScalar]], item_count: int,
|
|
58
|
+
columns: int) -> list[RealScalar]:
|
|
59
|
+
"""Flatten a partial scale grid, validating even unused final-row cells.
|
|
60
|
+
|
|
61
|
+
Missing entries default to 1.0; supplied real scalar precision is retained.
|
|
62
|
+
"""
|
|
63
|
+
rows = (item_count + columns - 1) // columns
|
|
64
|
+
if len(values) > rows:
|
|
65
|
+
raise ValueError('too many scale-factor rows')
|
|
66
|
+
scales: list[RealScalar] = [1.0] * item_count
|
|
67
|
+
for r, row in enumerate(values):
|
|
68
|
+
if isinstance(row, (str, bytes)) or isinstance(row, RealScalar):
|
|
69
|
+
raise ValueError('scale_factors must be flat numbers'
|
|
70
|
+
+ ' or a nested grid')
|
|
71
|
+
row = list(row)
|
|
72
|
+
if len(row) > columns:
|
|
73
|
+
raise ValueError('too many scale-factor columns')
|
|
74
|
+
for c, value in enumerate(row):
|
|
75
|
+
_require_positive_real_scalar(value, 'scale factor')
|
|
76
|
+
index = r * columns + c
|
|
77
|
+
if index < item_count:
|
|
78
|
+
scales[index] = value
|
|
79
|
+
return scales
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _scale_factors(scale_factors: ScaleInput, item_count: int,
|
|
83
|
+
columns: int) -> list[RealScalar]:
|
|
84
|
+
"""Validate flat or nested factors and return one scale per input.
|
|
85
|
+
|
|
86
|
+
None gives unit scales. Flat sequences require exactly item_count values;
|
|
87
|
+
nested grids may omit entries. Preserve supplied scalar precision.
|
|
88
|
+
"""
|
|
89
|
+
if scale_factors is None:
|
|
90
|
+
return [1.0] * item_count
|
|
91
|
+
values = list(scale_factors)
|
|
92
|
+
if not values:
|
|
93
|
+
raise ValueError('scale_factors must not be empty')
|
|
94
|
+
if all(isinstance(v, RealScalar) for v in values):
|
|
95
|
+
if len(values) != item_count:
|
|
96
|
+
raise ValueError('flat scale_factors must have one value per input')
|
|
97
|
+
for value in values:
|
|
98
|
+
_require_positive_real_scalar(value, 'scale factor')
|
|
99
|
+
return values
|
|
100
|
+
return _grid_scales(values, item_count, columns)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _layout(sizes: Sequence[tuple[RealScalar, RealScalar]], columns: int,
|
|
104
|
+
padding: int, scales: Sequence[RealScalar]
|
|
105
|
+
) -> tuple[tuple[int, int], list[tuple[int, int, int, int]]]:
|
|
106
|
+
"""Return canvas (width, height) and row-major (x, y, width, height) items.
|
|
107
|
+
|
|
108
|
+
Scale source sizes and round to whole units, with a minimum of one.
|
|
109
|
+
Size each column/row to its largest item and omit wholly unused columns.
|
|
110
|
+
Coordinates start at the top left; integer centering leaves odd spare
|
|
111
|
+
units on the right/bottom. Padding separates neighboring cells only.
|
|
112
|
+
"""
|
|
113
|
+
columns = min(columns, len(sizes))
|
|
114
|
+
rows = (len(sizes) + columns - 1) // columns
|
|
115
|
+
widths, heights = [0] * columns, [0] * rows
|
|
116
|
+
drawn = []
|
|
117
|
+
for i, ((w, h), scale) in enumerate(zip(sizes, scales)):
|
|
118
|
+
if not all(_is_positive_real_scalar(v)
|
|
119
|
+
for v in (w, h, w * scale, h * scale)):
|
|
120
|
+
raise ValueError('input and scaled dimensions must be'
|
|
121
|
+
+ ' positive and finite')
|
|
122
|
+
dw, dh = w * scale, h * scale
|
|
123
|
+
cw, ch = max(1, round(dw)), max(1, round(dh))
|
|
124
|
+
drawn.append((cw, ch))
|
|
125
|
+
widths[i % columns] = max(widths[i % columns], cw)
|
|
126
|
+
heights[i // columns] = max(heights[i // columns], ch)
|
|
127
|
+
xs, ys = [], []
|
|
128
|
+
for sizes_, positions in ((widths, xs), (heights, ys)):
|
|
129
|
+
position = 0
|
|
130
|
+
for size in sizes_:
|
|
131
|
+
positions.append(position)
|
|
132
|
+
position += size + padding
|
|
133
|
+
cells = []
|
|
134
|
+
for i, (w, h) in enumerate(drawn):
|
|
135
|
+
r, c = divmod(i, columns)
|
|
136
|
+
cells.append((xs[c] + (widths[c] - w) // 2,
|
|
137
|
+
ys[r] + (heights[r] - h) // 2, w, h))
|
|
138
|
+
return (sum(widths) + padding * (columns - 1),
|
|
139
|
+
sum(heights) + padding * (rows - 1)), cells
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def concat_pngs(file_list: Sequence[PathInput], output_file: PathInput,
|
|
143
|
+
columns: int, padding: RealScalar = 0, *,
|
|
144
|
+
scale_factors: ScaleInput = None,
|
|
145
|
+
background: tuple[int, int, int, int]
|
|
146
|
+
| tuple[int, int, int] | str = 'white',
|
|
147
|
+
resample: Image.Resampling | int = Image.Resampling.LANCZOS
|
|
148
|
+
) -> None:
|
|
149
|
+
"""Concatenate PNG images into one grid PNG.
|
|
150
|
+
|
|
151
|
+
Images fill rows from left to right. Each input is scaled directly and
|
|
152
|
+
rounded to whole pixels, with a minimum size of one pixel per dimension.
|
|
153
|
+
Rows and columns fit their largest scaled item. Images are centered,
|
|
154
|
+
leaving any odd spare pixel on the right/bottom. Unused cells are blank;
|
|
155
|
+
entirely unused columns are omitted. No input content is cropped.
|
|
156
|
+
All opened images are closed, including on failure.
|
|
157
|
+
|
|
158
|
+
Args:
|
|
159
|
+
file_list (Sequence[PathInput]): Input PNG paths in row-major order.
|
|
160
|
+
output_file (PathInput): Output path ending in .png. Must differ
|
|
161
|
+
from every input path.
|
|
162
|
+
columns (int): Positive number of grid columns.
|
|
163
|
+
padding (RealScalar, optional): Finite nonnegative whole-number
|
|
164
|
+
space between neighboring cells, in pixels. Defaults to 0.
|
|
165
|
+
scale_factors (ScaleInput, optional): Positive finite multipliers,
|
|
166
|
+
given as a flat sequence with one value per image or a nested
|
|
167
|
+
grid. Missing grid entries default to 1.0. Unused final-row
|
|
168
|
+
entries are validated but have no effect. Defaults to None,
|
|
169
|
+
which uses 1.0 for every image.
|
|
170
|
+
background (tuple[int, int, int, int] | tuple[int, int, int] | str,
|
|
171
|
+
optional): Canvas color. Use (255, 255, 255, 0) for transparent
|
|
172
|
+
output. Defaults to 'white'.
|
|
173
|
+
resample (Image.Resampling | int, optional): Resizing filter. Defaults
|
|
174
|
+
to Image.Resampling.LANCZOS.
|
|
175
|
+
|
|
176
|
+
Returns:
|
|
177
|
+
None: The composed image is saved to output_file.
|
|
178
|
+
"""
|
|
179
|
+
files, output, columns, padding, scales = _inputs(
|
|
180
|
+
file_list, output_file, columns, padding, scale_factors, '.png')
|
|
181
|
+
with ExitStack() as stack:
|
|
182
|
+
images = []
|
|
183
|
+
for filename in files:
|
|
184
|
+
source = stack.enter_context(Image.open(filename))
|
|
185
|
+
if source.format != 'PNG':
|
|
186
|
+
raise ValueError(f'Input is not PNG: {filename}')
|
|
187
|
+
images.append(stack.enter_context(source.convert('RGBA')))
|
|
188
|
+
sizes = [im.size for im in images]
|
|
189
|
+
size, cells = _layout(sizes, columns, padding, scales)
|
|
190
|
+
canvas = stack.enter_context(Image.new('RGBA', size, background))
|
|
191
|
+
for image, (x, y, w, h) in zip(images, cells):
|
|
192
|
+
with image.resize((w, h), resample=resample) as resized:
|
|
193
|
+
canvas.alpha_composite(resized, dest=(x, y))
|
|
194
|
+
canvas.save(output, format='PNG')
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def concat_pdfs(file_list: Sequence[PathInput], output_file: PathInput,
|
|
198
|
+
columns: int, padding: RealScalar = 0, *,
|
|
199
|
+
scale_factors: ScaleInput = None) -> None:
|
|
200
|
+
"""Concatenate the first page of each PDF into one grid PDF page.
|
|
201
|
+
|
|
202
|
+
Uses the same direct scaling, whole-unit rounding, row/column sizing,
|
|
203
|
+
and centering rules as concat_pngs, with PDF points replacing pixels.
|
|
204
|
+
Matching numeric source dimensions give matching grid geometry; PNG DPI
|
|
205
|
+
metadata is ignored. PDF content preserves its aspect ratio within the
|
|
206
|
+
rounded cells. Text and vectors remain PDF content. Page rotations and
|
|
207
|
+
crop-box offsets are normalized before placement. The background is
|
|
208
|
+
unpainted, and interactive annotations are omitted.
|
|
209
|
+
All readers and streams are closed, including on failure.
|
|
210
|
+
|
|
211
|
+
Args:
|
|
212
|
+
file_list (Sequence[PathInput]): Input paths to unencrypted PDFs
|
|
213
|
+
with at least one page, in row-major order. Only the first page
|
|
214
|
+
of each file is used.
|
|
215
|
+
output_file (PathInput): Output path ending in .pdf. Must differ
|
|
216
|
+
from every input path.
|
|
217
|
+
columns (int): Positive number of grid columns.
|
|
218
|
+
padding (RealScalar, optional): Finite nonnegative whole-number
|
|
219
|
+
space between neighboring cells, in PDF points. Defaults to 0.
|
|
220
|
+
scale_factors (ScaleInput, optional): Positive finite multipliers,
|
|
221
|
+
given as a flat sequence with one value per PDF or a nested
|
|
222
|
+
grid. Missing grid entries default to 1.0. Unused final-row
|
|
223
|
+
entries are validated but have no effect. Defaults to None,
|
|
224
|
+
which uses 1.0 for every PDF.
|
|
225
|
+
|
|
226
|
+
Returns:
|
|
227
|
+
None: The composed page is saved to output_file.
|
|
228
|
+
"""
|
|
229
|
+
files, output, columns, padding, scales = _inputs(
|
|
230
|
+
file_list, output_file, columns, padding, scale_factors, '.pdf')
|
|
231
|
+
try:
|
|
232
|
+
from pypdf import PdfReader, PdfWriter, Transformation
|
|
233
|
+
except ImportError as exc:
|
|
234
|
+
raise ImportError('concat_pdfs() requires pypdf.') from exc
|
|
235
|
+
with ExitStack() as stack:
|
|
236
|
+
pages = []
|
|
237
|
+
source_writer = PdfWriter()
|
|
238
|
+
stack.callback(source_writer.close)
|
|
239
|
+
for filename in files:
|
|
240
|
+
stream = stack.enter_context(filename.open('rb'))
|
|
241
|
+
reader = PdfReader(stream)
|
|
242
|
+
stack.callback(reader.close)
|
|
243
|
+
if reader.is_encrypted:
|
|
244
|
+
raise ValueError(f'Encrypted PDF is unsupported: {filename}')
|
|
245
|
+
if not reader.pages:
|
|
246
|
+
raise ValueError(f'PDF has no pages: {filename}')
|
|
247
|
+
page = source_writer.add_page(reader.pages[0])
|
|
248
|
+
page.transfer_rotation_to_content()
|
|
249
|
+
pages.append(page)
|
|
250
|
+
sizes = [(float(p.cropbox.width), float(p.cropbox.height))
|
|
251
|
+
for p in pages]
|
|
252
|
+
size, cells = _layout(sizes, columns, padding, scales)
|
|
253
|
+
writer = PdfWriter()
|
|
254
|
+
stack.callback(writer.close)
|
|
255
|
+
canvas = writer.add_blank_page(width=size[0], height=size[1])
|
|
256
|
+
for page, (x, y, w, h) in zip(pages, cells):
|
|
257
|
+
box = page.cropbox
|
|
258
|
+
# Fit uniformly into the rounded rectangle; retain vector aspect ratio.
|
|
259
|
+
scale = min(w / float(box.width), h / float(box.height))
|
|
260
|
+
dx = (w - float(box.width) * scale) / 2
|
|
261
|
+
dy = (h - float(box.height) * scale) / 2
|
|
262
|
+
transform = (Transformation().translate(-float(box.left), -float(box.bottom))
|
|
263
|
+
.scale(scale).translate(x + dx, size[1] - y - h + dy))
|
|
264
|
+
page.pop('/Annots', None)
|
|
265
|
+
canvas.merge_transformed_page(page, transform, expand=False)
|
|
266
|
+
with output.open('wb') as stream:
|
|
267
|
+
writer.write(stream)
|
plotastrodata/script_utils.py
CHANGED
|
@@ -158,7 +158,7 @@ p.savefig({str(output.with_suffix('.png'))!r}, show=False)
|
|
|
158
158
|
def generate_cube_script(fitsimage: str | Path,
|
|
159
159
|
output: str | Path | None = None,
|
|
160
160
|
*, overwrite: bool = False) -> Path:
|
|
161
|
-
"""Write noise,
|
|
161
|
+
"""Write noise, line-profile, channel-map, and moment-map plotting code.
|
|
162
162
|
|
|
163
163
|
Use the existing AstroData, AstroFrame, Noise, plotprofile, and
|
|
164
164
|
PlotAstroData APIs, following the line-profile and 3D channel-map
|
|
@@ -217,11 +217,26 @@ def generate_cube_script(fitsimage: str | Path,
|
|
|
217
217
|
PB-corrected data about the FITS reference center. The generated
|
|
218
218
|
noise visualization still uses the full spatial footprint.
|
|
219
219
|
|
|
220
|
-
|
|
220
|
+
Channel maps use stretch='log' and show=False, with default fonts,
|
|
221
221
|
beams, contours, and channel layout. Edit these choices directly.
|
|
222
222
|
Channel-map pages are saved beside the script as <script stem>.png;
|
|
223
223
|
multiple pages receive _0, _1, ... suffixes before .png, following
|
|
224
224
|
PlotAstroData.savefig. Existing figures may be overwritten.
|
|
225
|
+
|
|
226
|
+
After channel maps, the cropped cube calls AstroData.moment
|
|
227
|
+
with 3-sigma cube and integrated-intensity thresholds. Two separate
|
|
228
|
+
figures show moments 1 and 2 with linear colors and moment-0 contours
|
|
229
|
+
at [3, 6, 12, 24, 48, 96] times sigma_mom0. Moment 1 uses a blue-red
|
|
230
|
+
colormap; both colorbars use cbformat='%.1f'. They are saved as
|
|
231
|
+
<script stem>_mom1.png and
|
|
232
|
+
<script stem>_mom2.png beside the script. Moment ranges follow the
|
|
233
|
+
crop frame; changing that frame changes the moment calculation.
|
|
234
|
+
After calculation, d_crop is reused as a 2D image: data and sigma
|
|
235
|
+
are replaced for each contour/color call through d_crop.todict().
|
|
236
|
+
The moment arrays remain NumPy arrays, and sigma_mom0 is a Python
|
|
237
|
+
float except that np.longdouble retains extended precision. The
|
|
238
|
+
final data is the mom2 array, sigma is None, and v is None. The
|
|
239
|
+
original cube d is unchanged.
|
|
225
240
|
"""
|
|
226
241
|
if not isinstance(overwrite, bool):
|
|
227
242
|
raise TypeError('overwrite must be a boolean.')
|
|
@@ -256,13 +271,13 @@ n.plot_histogram(savefig={str(output.with_name(output.stem + '_noise.png'))!r},
|
|
|
256
271
|
d.sigma = n.std # A float number in the data unit is acceptable.
|
|
257
272
|
|
|
258
273
|
# Line profile
|
|
259
|
-
|
|
260
|
-
|
|
274
|
+
d_crop = AstroData(**d.todict())
|
|
275
|
+
f_crop = AstroFrame(rmax={rmax!r}, # Estimated spatial half-width (arcsec); adjust as needed.
|
|
261
276
|
vmin={vmin!r}, vmax={vmax!r}, # Estimated velocity range (km/s); adjust as needed.
|
|
262
277
|
)
|
|
263
|
-
|
|
264
|
-
plotprofile(**
|
|
265
|
-
ellipse=[4 *
|
|
278
|
+
f_crop.read(d_crop)
|
|
279
|
+
plotprofile(**d_crop.todict(), xlist=[0], ylist=[0],
|
|
280
|
+
ellipse=[4 * f_crop.rmax, 4 * f_crop.rmax, 0], # Circle enclosing the cropped square.
|
|
266
281
|
flux=True,
|
|
267
282
|
savefig={str(output.with_name(output.stem + '_profile.png'))!r},
|
|
268
283
|
show=False,
|
|
@@ -277,6 +292,34 @@ p.add_color(**d.todict(), stretch='log')
|
|
|
277
292
|
p.add_contour(**d.todict(), colors='r')
|
|
278
293
|
p.set_axis()
|
|
279
294
|
p.savefig({str(output.with_suffix('.png'))!r}, show=False)
|
|
295
|
+
|
|
296
|
+
# Moment maps over the crop frame's spatial and velocity ranges
|
|
297
|
+
d_crop.moment(threshold_cube=3, threshold_mom0=3) # Noise multiples; adjust as needed.
|
|
298
|
+
d_crop.v = None # The moment maps are 2D images.
|
|
299
|
+
|
|
300
|
+
# Moment 1 with moment-0 contours
|
|
301
|
+
p = PlotAstroData(rmax=f_crop.rmax, center=d_crop.center)
|
|
302
|
+
d_crop.data = d_crop.mom0
|
|
303
|
+
d_crop.sigma = d_crop.sigma_mom0 # sigma * abs(dv) * sqrt(number of channels).
|
|
304
|
+
p.add_contour(**d_crop.todict(), levels=[3, 6, 12, 24, 48, 96], colors='k')
|
|
305
|
+
d_crop.data = d_crop.mom1
|
|
306
|
+
d_crop.sigma = None
|
|
307
|
+
p.add_color(**d_crop.todict(), stretch='linear', cmap='RdBu_r', cbformat='%.1f',
|
|
308
|
+
cblabel=r'Moment 1 (km s$^{{-1}}$)')
|
|
309
|
+
p.set_axis_radec(nticksminor=5)
|
|
310
|
+
p.savefig({str(output.with_name(output.stem + '_mom1.png'))!r}, show=False)
|
|
311
|
+
|
|
312
|
+
# Moment 2 with moment-0 contours
|
|
313
|
+
p = PlotAstroData(rmax=f_crop.rmax, center=d_crop.center)
|
|
314
|
+
d_crop.data = d_crop.mom0
|
|
315
|
+
d_crop.sigma = d_crop.sigma_mom0 # sigma * abs(dv) * sqrt(number of channels).
|
|
316
|
+
p.add_contour(**d_crop.todict(), levels=[3, 6, 12, 24, 48, 96], colors='k')
|
|
317
|
+
d_crop.data = d_crop.mom2
|
|
318
|
+
d_crop.sigma = None
|
|
319
|
+
p.add_color(**d_crop.todict(), stretch='linear', cbformat='%.1f',
|
|
320
|
+
cblabel=r'Moment 2 (km s$^{{-1}}$)')
|
|
321
|
+
p.set_axis_radec(nticksminor=5)
|
|
322
|
+
p.savefig({str(output.with_name(output.stem + '_mom2.png'))!r}, show=False)
|
|
280
323
|
"""
|
|
281
324
|
_write_script(source, output, overwrite=overwrite)
|
|
282
325
|
return output
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: plotastrodata
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.13.0
|
|
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
|
|
@@ -21,6 +21,7 @@ Requires-Dist: pillow
|
|
|
21
21
|
Requires-Dist: plotly
|
|
22
22
|
Requires-Dist: ptemcee
|
|
23
23
|
Requires-Dist: pydantic>=2
|
|
24
|
+
Requires-Dist: pypdf>=6.21.2
|
|
24
25
|
Requires-Dist: scikit-image
|
|
25
26
|
Requires-Dist: scipy
|
|
26
27
|
Requires-Dist: tqdm
|
|
@@ -106,7 +107,10 @@ with three significant digits for editing.
|
|
|
106
107
|
For a spectral cube, use `generate_cube_script("cube.fits", output="cube.py")`
|
|
107
108
|
from the same module. It generates an edge-channel noise visualization, a flux-integrated line
|
|
108
109
|
profile and 3D channel maps over estimated spatial and velocity ranges,
|
|
109
|
-
with intrinsic channel spacing.
|
|
110
|
+
with intrinsic channel spacing. Two further single-panel figures show moments
|
|
111
|
+
1 and 2 in linear colors with moment-0 contours and colorbar ticks to one
|
|
112
|
+
decimal place; moment 1 uses a blue-red colormap. The moments use the shared crop and are saved as
|
|
113
|
+
`<script stem>_mom1.png` and `<script stem>_mom2.png`. The flux profile assumes Jy/beam data with beam metadata.
|
|
110
114
|
Noise and range estimation in both generators assume PB-corrected intensities.
|
|
111
115
|
Both generators return an absolute pathlib.Path and write the script
|
|
112
116
|
without executing it.
|
|
@@ -121,6 +125,25 @@ PB correction. The array-based function is `noise_utils.estimate_ranges`,
|
|
|
121
125
|
with the same `pbcor` option and optional `sigma`. Here, `rmax` is a symmetric
|
|
122
126
|
spatial half-width; 2D images return `None` for both velocity limits.
|
|
123
127
|
|
|
128
|
+
## Combining saved figures
|
|
129
|
+
|
|
130
|
+
Use `concat_pngs` or `concat_pdfs` to place saved figures in a grid:
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
from plotastrodata.pngpdf_utils import concat_pngs, concat_pdfs
|
|
134
|
+
|
|
135
|
+
concat_pngs(["a.png", "b.png"], "grid.png", columns=2, padding=10)
|
|
136
|
+
concat_pdfs(["a.pdf", "b.pdf"], "grid.pdf", columns=2, padding=10)
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Both use direct scaling, whole-unit rounding, and centered placement. Padding
|
|
140
|
+
is measured in pixels for PNG and points for PDF; PNG DPI metadata is ignored.
|
|
141
|
+
Matching numeric source dimensions produce matching grid geometry. Optional
|
|
142
|
+
`scale_factors` accepts one multiplier per input or a nested grid with missing
|
|
143
|
+
entries defaulting to 1. PDF grids use only the first page of each unencrypted
|
|
144
|
+
input and preserve vector content. PNG supports transparent backgrounds.
|
|
145
|
+
Pillow and pypdf are installed with plotastrodata.
|
|
146
|
+
|
|
124
147
|
## Requirement
|
|
125
148
|
|
|
126
149
|
* Python >= 3.11
|
|
@@ -131,10 +154,11 @@ spatial half-width; 2D images return `None` for both velocity limits.
|
|
|
131
154
|
* ffmpeg (only for movie)
|
|
132
155
|
* matplotlib
|
|
133
156
|
* numpy >= 2.0
|
|
134
|
-
* pillow (only for RGB figures)
|
|
157
|
+
* pillow (only for RGB figures and PNG grids)
|
|
135
158
|
* plotly (only for html cube)
|
|
136
159
|
* ptemcee (only for fitting)
|
|
137
160
|
* pydantic >= 2
|
|
161
|
+
* pypdf >= 6.21.2 (only for PDF grids)
|
|
138
162
|
* scikit-image (only for html cube)
|
|
139
163
|
* scipy
|
|
140
164
|
* tqdm (only for fitting)
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
plotastrodata/__init__.py,sha256=
|
|
1
|
+
plotastrodata/__init__.py,sha256=VebpYlZRDs2S8Wa6sTXBPMyYnlZkVAFayJ515HMy4Kw,87
|
|
2
2
|
plotastrodata/_type_utils.py,sha256=e-k_r6DA_K790Ttpz3-ZMFJgFD8pOFc2e3kUm8X4Apo,4199
|
|
3
3
|
plotastrodata/_validation_utils.py,sha256=FOIOgzrP1vwuDfjqCMvYcp4yMdRjQUMtZWE-BnUXBgA,2924
|
|
4
|
-
plotastrodata/analysis_utils.py,sha256=
|
|
4
|
+
plotastrodata/analysis_utils.py,sha256=FVeSPgD67niCvWPydecOuGEyQ5MNL5AmD3riEWOmHyg,73298
|
|
5
5
|
plotastrodata/const_utils.py,sha256=8TCxHkV6P62XDGLK-t50O7P8ME10cjCS9S2DmPgi4hI,4789
|
|
6
6
|
plotastrodata/coord_utils.py,sha256=0jOhLIBlUZKpHbF7o6Tvroq-ezoTLADHeR1j4v1xvGQ,9854
|
|
7
7
|
plotastrodata/ext_utils.py,sha256=mi84yKu-T0lXkIk-9Fme0h5CwBu-_n3cCubLIia7tbo,5715
|
|
@@ -12,10 +12,11 @@ plotastrodata/los_utils.py,sha256=Q239z__C-kvzb0NR6NyGB-21quBl6KLhE2GdRMhMwn4,81
|
|
|
12
12
|
plotastrodata/matrix_utils.py,sha256=H6Ad9Sn8itsi0FU2D70Sb_SSJ4xmprYGueYYrIqotOY,2462
|
|
13
13
|
plotastrodata/noise_utils.py,sha256=LfpAEcKiX8afOwSaXvECboiTt2LUhecLfLCeAq4L_eo,23808
|
|
14
14
|
plotastrodata/other_utils.py,sha256=Kjh_PYfsm09-GZ2ezq7TpMxkvgSTzRf1nvtE9lby8vE,21788
|
|
15
|
-
plotastrodata/plot_utils.py,sha256=
|
|
16
|
-
plotastrodata/
|
|
17
|
-
plotastrodata
|
|
18
|
-
plotastrodata-1.
|
|
19
|
-
plotastrodata-1.
|
|
20
|
-
plotastrodata-1.
|
|
21
|
-
plotastrodata-1.
|
|
15
|
+
plotastrodata/plot_utils.py,sha256=pWF-AhM7KZfjCW9rqhd9Xcsg5qvHHVF0Qahr0XOaCeo,128476
|
|
16
|
+
plotastrodata/pngpdf_utils.py,sha256=70KV7FQWRgSaU0r-a4gpKjNRveSY8026YcKvUXiY2sM,12502
|
|
17
|
+
plotastrodata/script_utils.py,sha256=F5d20-DcmwGCUdQWZXE-DYuOryJEbhUGZBBWwo2BnL4,15649
|
|
18
|
+
plotastrodata-1.13.0.dist-info/licenses/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
|
|
19
|
+
plotastrodata-1.13.0.dist-info/METADATA,sha256=24D8JPItWZWr4qb_K4w-6Vn0uGQ0T5QcOUifYyP8B-c,7046
|
|
20
|
+
plotastrodata-1.13.0.dist-info/WHEEL,sha256=YLJXdYXQ2FQ0Uqn2J-6iEIC-3iOey8lH3xCtvFLkd8Q,91
|
|
21
|
+
plotastrodata-1.13.0.dist-info/top_level.txt,sha256=mv2FRRtreGAUE_UF_Z_TYj_NZLECJqkQx7ErkA_Rttg,14
|
|
22
|
+
plotastrodata-1.13.0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|