plotastrodata 1.12.3__tar.gz → 1.13.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.3/plotastrodata.egg-info → plotastrodata-1.13.1}/PKG-INFO +29 -2
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/README.md +27 -1
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata/__init__.py +1 -1
- plotastrodata-1.13.1/plotastrodata/_ptemcee_compat.py +37 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata/analysis_utils.py +66 -40
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata/fitting_utils.py +40 -48
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata/plot_utils.py +2 -1
- plotastrodata-1.13.1/plotastrodata/pngpdf_utils.py +390 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1/plotastrodata.egg-info}/PKG-INFO +29 -2
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata.egg-info/SOURCES.txt +2 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata.egg-info/requires.txt +1 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/setup.cfg +1 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/LICENSE +0 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/MANIFEST.in +0 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata/_type_utils.py +0 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata/_validation_utils.py +0 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata/const_utils.py +0 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata/coord_utils.py +0 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata/ext_utils.py +0 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata/fft_utils.py +0 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata/fits_utils.py +0 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata/los_utils.py +0 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata/matrix_utils.py +0 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata/noise_utils.py +0 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata/other_utils.py +0 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata/script_utils.py +0 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata.egg-info/dependency_links.txt +0 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata.egg-info/not-zip-safe +0 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/plotastrodata.egg-info/top_level.txt +0 -0
- {plotastrodata-1.12.3 → plotastrodata-1.13.1}/setup.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: plotastrodata
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.13.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
|
|
@@ -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
|
|
@@ -124,8 +125,33 @@ PB correction. The array-based function is `noise_utils.estimate_ranges`,
|
|
|
124
125
|
with the same `pbcor` option and optional `sigma`. Here, `rmax` is a symmetric
|
|
125
126
|
spatial half-width; 2D images return `None` for both velocity limits.
|
|
126
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
|
+
|
|
127
147
|
## Requirement
|
|
128
148
|
|
|
149
|
+
The fitting libraries below are installed by default, but imported only when
|
|
150
|
+
the corresponding feature is used: emcee for ordinary MCMC, ptemcee for
|
|
151
|
+
parallel tempering, corner for corner plots, dynesty for nested sampling,
|
|
152
|
+
and tqdm for fitting progress bars. When using the source directory directly,
|
|
153
|
+
these libraries are needed only for those features.
|
|
154
|
+
|
|
129
155
|
* Python >= 3.11
|
|
130
156
|
* astropy >= 7.2
|
|
131
157
|
* corner (only for fitting)
|
|
@@ -134,10 +160,11 @@ spatial half-width; 2D images return `None` for both velocity limits.
|
|
|
134
160
|
* ffmpeg (only for movie)
|
|
135
161
|
* matplotlib
|
|
136
162
|
* numpy >= 2.0
|
|
137
|
-
* pillow
|
|
163
|
+
* pillow
|
|
138
164
|
* plotly (only for html cube)
|
|
139
165
|
* ptemcee (only for fitting)
|
|
140
166
|
* pydantic >= 2
|
|
167
|
+
* pypdf >= 6.21.2 (only for PDF grids)
|
|
141
168
|
* scikit-image (only for html cube)
|
|
142
169
|
* scipy
|
|
143
170
|
* tqdm (only for fitting)
|
|
@@ -95,8 +95,33 @@ PB correction. The array-based function is `noise_utils.estimate_ranges`,
|
|
|
95
95
|
with the same `pbcor` option and optional `sigma`. Here, `rmax` is a symmetric
|
|
96
96
|
spatial half-width; 2D images return `None` for both velocity limits.
|
|
97
97
|
|
|
98
|
+
## Combining saved figures
|
|
99
|
+
|
|
100
|
+
Use `concat_pngs` or `concat_pdfs` to place saved figures in a grid:
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
from plotastrodata.pngpdf_utils import concat_pngs, concat_pdfs
|
|
104
|
+
|
|
105
|
+
concat_pngs(["a.png", "b.png"], "grid.png", columns=2, padding=10)
|
|
106
|
+
concat_pdfs(["a.pdf", "b.pdf"], "grid.pdf", columns=2, padding=10)
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Both use direct scaling, whole-unit rounding, and centered placement. Padding
|
|
110
|
+
is measured in pixels for PNG and points for PDF; PNG DPI metadata is ignored.
|
|
111
|
+
Matching numeric source dimensions produce matching grid geometry. Optional
|
|
112
|
+
`scale_factors` accepts one multiplier per input or a nested grid with missing
|
|
113
|
+
entries defaulting to 1. PDF grids use only the first page of each unencrypted
|
|
114
|
+
input and preserve vector content. PNG supports transparent backgrounds.
|
|
115
|
+
Pillow and pypdf are installed with plotastrodata.
|
|
116
|
+
|
|
98
117
|
## Requirement
|
|
99
118
|
|
|
119
|
+
The fitting libraries below are installed by default, but imported only when
|
|
120
|
+
the corresponding feature is used: emcee for ordinary MCMC, ptemcee for
|
|
121
|
+
parallel tempering, corner for corner plots, dynesty for nested sampling,
|
|
122
|
+
and tqdm for fitting progress bars. When using the source directory directly,
|
|
123
|
+
these libraries are needed only for those features.
|
|
124
|
+
|
|
100
125
|
* Python >= 3.11
|
|
101
126
|
* astropy >= 7.2
|
|
102
127
|
* corner (only for fitting)
|
|
@@ -105,10 +130,11 @@ spatial half-width; 2D images return `None` for both velocity limits.
|
|
|
105
130
|
* ffmpeg (only for movie)
|
|
106
131
|
* matplotlib
|
|
107
132
|
* numpy >= 2.0
|
|
108
|
-
* pillow
|
|
133
|
+
* pillow
|
|
109
134
|
* plotly (only for html cube)
|
|
110
135
|
* ptemcee (only for fitting)
|
|
111
136
|
* pydantic >= 2
|
|
137
|
+
* pypdf >= 6.21.2 (only for PDF grids)
|
|
112
138
|
* scikit-image (only for html cube)
|
|
113
139
|
* scipy
|
|
114
140
|
* tqdm (only for fitting)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Parallel-tempering compatibility, loaded only when selected."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import ptemcee
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class _PTSampler(ptemcee.Sampler):
|
|
8
|
+
"""Support ptemcee 1.0's sampler on NumPy without the np.float alias.
|
|
9
|
+
|
|
10
|
+
Only reset and likelihood evaluation need the obsolete alias. Keep
|
|
11
|
+
their behavior while using float for the sampler's float64 buffers.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
def reset(self, random=None, betas=None, time=None) -> None:
|
|
15
|
+
"""Clear stored samples, counters, and current sampling state."""
|
|
16
|
+
for name in ('_chain', '_logposterior', '_loglikelihood',
|
|
17
|
+
'_beta_history', '_p0', '_logposterior0',
|
|
18
|
+
'_loglikelihood0'):
|
|
19
|
+
setattr(self, name, None)
|
|
20
|
+
self._time = 0 if time is None else time
|
|
21
|
+
if betas is not None:
|
|
22
|
+
self._betas = betas
|
|
23
|
+
if random is not None:
|
|
24
|
+
self._random = random
|
|
25
|
+
self.nswap = np.zeros(self.ntemps, dtype=float)
|
|
26
|
+
self.nswap_accepted = np.zeros(self.ntemps, dtype=float)
|
|
27
|
+
self.nprop = np.zeros((self.ntemps, self.nwalkers), dtype=float)
|
|
28
|
+
self.nprop_accepted = np.zeros_like(self.nprop)
|
|
29
|
+
|
|
30
|
+
def _evaluate(self, ps: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
31
|
+
"""Evaluate likelihood and prior for every temperature and walker."""
|
|
32
|
+
map_function = map if self.pool is None else self.pool.map
|
|
33
|
+
results = list(map_function(self._likeprior,
|
|
34
|
+
ps.reshape((-1, self.dim))))
|
|
35
|
+
values = np.asarray(results, dtype=float)
|
|
36
|
+
shape = (self.ntemps, -1)
|
|
37
|
+
return values[:, 0].reshape(shape), values[:, 1].reshape(shape)
|
|
@@ -42,6 +42,69 @@ from plotastrodata.other_utils import (
|
|
|
42
42
|
)
|
|
43
43
|
|
|
44
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
|
+
|
|
45
108
|
def _profile_ellipses(ellipse: Any, nprof: int) -> np.ndarray:
|
|
46
109
|
"""Prepare one ellipse per profile without changing supplied array dtypes."""
|
|
47
110
|
if ellipse is None:
|
|
@@ -778,51 +841,14 @@ class AstroData():
|
|
|
778
841
|
ValueError: Shapes, numeric values, channel selection, noise,
|
|
779
842
|
spacing, or thresholds do not satisfy the requirements.
|
|
780
843
|
"""
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
if (self.data.ndim != 3 or 0 in self.data.shape
|
|
784
|
-
or self.data.dtype.kind not in 'iuf'
|
|
785
|
-
or np.any(np.isinf(self.data))):
|
|
786
|
-
raise ValueError('moment requires a nonempty real 3D cube'
|
|
787
|
-
+ ' without infinities.')
|
|
788
|
-
if not isinstance(self.v, np.ndarray):
|
|
789
|
-
raise TypeError('moment requires v to be a NumPy array.')
|
|
790
|
-
if (self.v.ndim != 1 or self.v.size != self.data.shape[0]
|
|
791
|
-
or self.v.dtype.kind not in 'iuf'
|
|
792
|
-
or not np.all(np.isfinite(self.v))):
|
|
793
|
-
raise ValueError('v must be a finite real 1D grid matching'
|
|
794
|
-
+ ' the number of channels.')
|
|
795
|
-
if not _is_positive_real_scalar(self.sigma):
|
|
796
|
-
raise ValueError('moment requires finite positive scalar sigma.')
|
|
797
|
-
if not _is_finite_real_scalar(self.dv) or self.dv == 0:
|
|
798
|
-
raise ValueError('moment requires finite nonzero scalar dv.')
|
|
799
|
-
if self.v.size > 1:
|
|
800
|
-
steps = np.diff(self.v.astype(np.result_type(self.v.dtype, float)))
|
|
801
|
-
if (not (np.all(steps > 0) or np.all(steps < 0))
|
|
802
|
-
or not _is_uniform_spacing(steps, steps[0])
|
|
803
|
-
or not _is_uniform_spacing(np.abs(steps), abs(self.dv))):
|
|
804
|
-
raise ValueError('v must be monotonic and uniformly spaced'
|
|
805
|
-
+ ' with spacing magnitude abs(dv).')
|
|
806
|
-
for name, value in (('threshold_cube', threshold_cube),
|
|
807
|
-
('threshold_mom0', threshold_mom0)):
|
|
808
|
-
if not _is_finite_real_scalar(value) or value < 0:
|
|
809
|
-
raise ValueError(f'{name} must be a finite nonnegative'
|
|
810
|
-
+ ' real scalar.')
|
|
811
|
-
if vmask is None:
|
|
812
|
-
vmask = np.ones(self.v.size, dtype=bool)
|
|
813
|
-
elif not isinstance(vmask, np.ndarray):
|
|
814
|
-
raise TypeError('vmask must be a NumPy Boolean array or None.')
|
|
815
|
-
if (vmask.dtype.kind != 'b' or vmask.shape != self.v.shape
|
|
816
|
-
or not np.any(vmask)):
|
|
817
|
-
raise ValueError('vmask must be a 1D Boolean array matching v'
|
|
818
|
-
+ ' and selecting at least one channel.')
|
|
819
|
-
|
|
844
|
+
vmask = _validate_moment_inputs(self.data, self.v, self.sigma, self.dv,
|
|
845
|
+
vmask, threshold_cube, threshold_mom0)
|
|
820
846
|
data = np.where(vmask[:, None, None], self.data, 0)
|
|
821
847
|
dv = abs(self.dv)
|
|
822
848
|
mom0 = np.nansum(data, axis=0) * dv
|
|
823
849
|
sigma_mom0 = np.sqrt(np.count_nonzero(vmask)) * self.sigma * dv
|
|
824
850
|
if (isinstance(self.sigma, np.longdouble)
|
|
825
|
-
|
|
851
|
+
or isinstance(dv, np.longdouble)):
|
|
826
852
|
sigma_mom0 = np.longdouble(sigma_mom0)
|
|
827
853
|
sigma_mom0 = _normalize_float(sigma_mom0)
|
|
828
854
|
w = np.where(data >= threshold_cube * self.sigma, data, 0)
|
|
@@ -1,23 +1,39 @@
|
|
|
1
|
+
"""Fitting utilities with sampling dependencies loaded on demand."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
1
5
|
import pickle
|
|
2
6
|
import warnings
|
|
3
7
|
from functools import partial
|
|
8
|
+
from importlib import import_module
|
|
4
9
|
from multiprocessing import Pool
|
|
5
|
-
from
|
|
10
|
+
from types import ModuleType
|
|
11
|
+
from typing import TYPE_CHECKING, Any, Callable
|
|
6
12
|
|
|
7
|
-
import corner
|
|
8
|
-
import emcee
|
|
9
13
|
import matplotlib.pyplot as plt
|
|
10
14
|
import numpy as np
|
|
11
|
-
import ptemcee
|
|
12
|
-
from dynesty import DynamicNestedSampler as DNS
|
|
13
15
|
from matplotlib.figure import Figure
|
|
14
|
-
from tqdm import tqdm
|
|
15
16
|
|
|
16
17
|
from plotastrodata._type_utils import _normalize_float
|
|
17
18
|
from plotastrodata._validation_utils import _require_integer
|
|
18
19
|
from plotastrodata.matrix_utils import Mrot, dot2d
|
|
19
20
|
from plotastrodata.other_utils import close_figure
|
|
20
21
|
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
import emcee
|
|
24
|
+
import ptemcee
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _import_fitting_package(name: str) -> ModuleType:
|
|
28
|
+
"""Import a selected dependency without masking broken installations."""
|
|
29
|
+
try:
|
|
30
|
+
return import_module(name)
|
|
31
|
+
except ModuleNotFoundError as exc:
|
|
32
|
+
if exc.name != name:
|
|
33
|
+
raise
|
|
34
|
+
raise ImportError(f'This fitting feature requires {name}.') from exc
|
|
35
|
+
|
|
36
|
+
|
|
21
37
|
global_bounds = None
|
|
22
38
|
bar = None
|
|
23
39
|
global_progressbar = True
|
|
@@ -37,39 +53,6 @@ def _validate_mcmc_run(nwalkersperdim: int | np.integer,
|
|
|
37
53
|
_require_integer(nwalkersperdim, 'nwalkersperdim', minimum=2)
|
|
38
54
|
|
|
39
55
|
|
|
40
|
-
class _PTSampler(ptemcee.Sampler):
|
|
41
|
-
"""Support ptemcee 1.0's sampler on NumPy without the np.float alias.
|
|
42
|
-
|
|
43
|
-
Only reset and likelihood evaluation need the obsolete alias. Keep
|
|
44
|
-
their behavior while using float for the sampler's float64 buffers.
|
|
45
|
-
"""
|
|
46
|
-
|
|
47
|
-
def reset(self, random=None, betas=None, time=None) -> None:
|
|
48
|
-
"""Clear stored samples, counters, and current sampling state."""
|
|
49
|
-
for name in ('_chain', '_logposterior', '_loglikelihood',
|
|
50
|
-
'_beta_history', '_p0', '_logposterior0',
|
|
51
|
-
'_loglikelihood0'):
|
|
52
|
-
setattr(self, name, None)
|
|
53
|
-
self._time = 0 if time is None else time
|
|
54
|
-
if betas is not None:
|
|
55
|
-
self._betas = betas
|
|
56
|
-
if random is not None:
|
|
57
|
-
self._random = random
|
|
58
|
-
self.nswap = np.zeros(self.ntemps, dtype=float)
|
|
59
|
-
self.nswap_accepted = np.zeros(self.ntemps, dtype=float)
|
|
60
|
-
self.nprop = np.zeros((self.ntemps, self.nwalkers), dtype=float)
|
|
61
|
-
self.nprop_accepted = np.zeros_like(self.nprop)
|
|
62
|
-
|
|
63
|
-
def _evaluate(self, ps: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
64
|
-
"""Evaluate likelihood and prior for every temperature and walker."""
|
|
65
|
-
map_function = map if self.pool is None else self.pool.map
|
|
66
|
-
results = list(map_function(self._likeprior,
|
|
67
|
-
ps.reshape((-1, self.dim))))
|
|
68
|
-
values = np.asarray(results, dtype=float)
|
|
69
|
-
shape = (self.ntemps, -1)
|
|
70
|
-
return values[:, 0].reshape(shape), values[:, 1].reshape(shape)
|
|
71
|
-
|
|
72
|
-
|
|
73
56
|
def _gaussian_log_likelihood(x: np.ndarray, model: Callable,
|
|
74
57
|
xdata: np.ndarray | list[np.ndarray]
|
|
75
58
|
| tuple[np.ndarray, ...],
|
|
@@ -229,6 +212,9 @@ class EmceeCorner():
|
|
|
229
212
|
) -> ptemcee.Sampler | emcee.EnsembleSampler:
|
|
230
213
|
"""Create and run the sampler, then return it."""
|
|
231
214
|
if pt:
|
|
215
|
+
_import_fitting_package("ptemcee")
|
|
216
|
+
from plotastrodata._ptemcee_compat import _PTSampler
|
|
217
|
+
|
|
232
218
|
sampler_cls = _PTSampler
|
|
233
219
|
sampler_kwargs = {'ntemps': ntemps,
|
|
234
220
|
'nwalkers': nwalkers, 'dim': self.dim,
|
|
@@ -238,11 +224,12 @@ class EmceeCorner():
|
|
|
238
224
|
try:
|
|
239
225
|
pickle.dumps(self.logl)
|
|
240
226
|
except (pickle.PicklingError, AttributeError, TypeError) as exc:
|
|
241
|
-
raise TypeError(
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
227
|
+
raise TypeError('logl and model must be pickleable'
|
|
228
|
+
+ ' when ncores > 1. Define them'
|
|
229
|
+
+ ' at module scope instead of inside'
|
|
230
|
+
+ ' another function.') from exc
|
|
245
231
|
|
|
232
|
+
emcee = _import_fitting_package("emcee")
|
|
246
233
|
sampler_cls = emcee.EnsembleSampler
|
|
247
234
|
sampler_kwargs = {'nwalkers': nwalkers, 'ndim': self.dim,
|
|
248
235
|
'log_prob_fn': _bounded_log_probability,
|
|
@@ -298,10 +285,11 @@ class EmceeCorner():
|
|
|
298
285
|
pos0: np.ndarray | None = None,
|
|
299
286
|
savechain: str | None = None, ncores: int | np.integer = 1,
|
|
300
287
|
grcheck: bool = False, pt: bool = False) -> None:
|
|
301
|
-
"""Perform
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
288
|
+
"""Perform MCMC fitting with emcee, or ptemcee for parallel tempering.
|
|
289
|
+
|
|
290
|
+
The selected sampler is imported only when used. tqdm is required
|
|
291
|
+
only when progressbar=True. Plot samples separately with plotcorner,
|
|
292
|
+
which loads corner on demand.
|
|
305
293
|
|
|
306
294
|
All run counts must be Python or NumPy integers; booleans and
|
|
307
295
|
floating values (even integral ones) and arrays, including 0D, are
|
|
@@ -345,6 +333,7 @@ class EmceeCorner():
|
|
|
345
333
|
active_bar = None
|
|
346
334
|
try:
|
|
347
335
|
if global_progressbar:
|
|
336
|
+
tqdm = _import_fitting_package("tqdm").tqdm
|
|
348
337
|
total = ntry * ntemps * nwalkers * (nsteps + 1) // ncores
|
|
349
338
|
active_bar = bar = tqdm(total=total)
|
|
350
339
|
active_bar.set_description('Within the ranges')
|
|
@@ -377,7 +366,7 @@ class EmceeCorner():
|
|
|
377
366
|
| np.ndarray | None = None,
|
|
378
367
|
savefig: dict | str | None = None,
|
|
379
368
|
show: bool = False) -> None:
|
|
380
|
-
"""Make the corner plot from self.samples.
|
|
369
|
+
"""Make the corner plot from self.samples, loading corner on demand.
|
|
381
370
|
|
|
382
371
|
Args:
|
|
383
372
|
labels (list, optional): Labels for the corner plot.
|
|
@@ -390,6 +379,7 @@ class EmceeCorner():
|
|
|
390
379
|
show (bool, optional): True means doing plt.show(). Defaults
|
|
391
380
|
to False.
|
|
392
381
|
"""
|
|
382
|
+
corner = _import_fitting_package("corner")
|
|
393
383
|
if labels is None:
|
|
394
384
|
labels = [f'Par {i:d}' for i in range(self.dim)]
|
|
395
385
|
if cornerrange is None:
|
|
@@ -638,6 +628,8 @@ class EmceeCorner():
|
|
|
638
628
|
nested sampling through dynesty. Evidence and error are Python
|
|
639
629
|
floats unless extended-precision scalar results must be preserved.
|
|
640
630
|
"""
|
|
631
|
+
DNS = _import_fitting_package("dynesty").DynamicNestedSampler
|
|
632
|
+
|
|
641
633
|
def prior_transform(u: np.ndarray) -> np.ndarray:
|
|
642
634
|
b0 = self.bounds[:, 0]
|
|
643
635
|
b1 = self.bounds[:, 1]
|
|
@@ -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,390 @@
|
|
|
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 TYPE_CHECKING, 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
|
+
if TYPE_CHECKING:
|
|
23
|
+
from pypdf import PageObject, PdfWriter
|
|
24
|
+
from pypdf.generic import IndirectObject, StreamObject
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
PathInput = str | PathLike[str]
|
|
28
|
+
ScaleInput = Sequence[RealScalar] | Sequence[Sequence[RealScalar]] | None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _inputs(file_list: Sequence[PathInput], output_file: PathInput,
|
|
32
|
+
columns: int, padding: RealScalar, scale_factors: ScaleInput,
|
|
33
|
+
suffix: str
|
|
34
|
+
) -> tuple[list[Path], Path, int, int, list[RealScalar]]:
|
|
35
|
+
"""Validate shared options without opening files and normalize their types.
|
|
36
|
+
|
|
37
|
+
Return input Paths, the output Path, integer columns and padding, and
|
|
38
|
+
one real scalar scale per input (preserving extended precision).
|
|
39
|
+
Flatten nested scales in row-major order, filling missing entries with
|
|
40
|
+
1.0 and validating unused entries as well.
|
|
41
|
+
Reject output paths that resolve to an input or have the wrong suffix.
|
|
42
|
+
"""
|
|
43
|
+
if isinstance(file_list, (str, PathLike)):
|
|
44
|
+
raise TypeError('file_list must be a sequence of paths')
|
|
45
|
+
files = [Path(f) for f in file_list]
|
|
46
|
+
if not files:
|
|
47
|
+
raise ValueError('file_list is empty')
|
|
48
|
+
_require_integer(columns, 'columns')
|
|
49
|
+
if not _is_finite_real_scalar(padding) or padding < 0:
|
|
50
|
+
raise ValueError('padding must be a finite nonnegative real scalar')
|
|
51
|
+
integer_padding = int(padding)
|
|
52
|
+
if padding != integer_padding:
|
|
53
|
+
raise ValueError('padding must be a whole number of layout units')
|
|
54
|
+
output = Path(output_file)
|
|
55
|
+
if output.suffix.lower() != suffix:
|
|
56
|
+
raise ValueError(f'output_file must end in {suffix}')
|
|
57
|
+
resolved_output = output.resolve()
|
|
58
|
+
if any(resolved_output == f.resolve() for f in files):
|
|
59
|
+
raise ValueError('output_file must differ from every input file')
|
|
60
|
+
columns = int(columns)
|
|
61
|
+
scales = _scale_factors(scale_factors, len(files), columns)
|
|
62
|
+
return files, output, columns, integer_padding, scales
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _grid_scales(values: Sequence[Sequence[RealScalar]], item_count: int,
|
|
66
|
+
columns: int) -> list[RealScalar]:
|
|
67
|
+
"""Flatten a partial scale grid, validating even unused final-row cells.
|
|
68
|
+
|
|
69
|
+
Missing entries default to 1.0; supplied real scalar precision is retained.
|
|
70
|
+
"""
|
|
71
|
+
rows = (item_count + columns - 1) // columns
|
|
72
|
+
if len(values) > rows:
|
|
73
|
+
raise ValueError('too many scale-factor rows')
|
|
74
|
+
scales: list[RealScalar] = [1.0] * item_count
|
|
75
|
+
for r, row in enumerate(values):
|
|
76
|
+
if isinstance(row, (str, bytes)) or isinstance(row, RealScalar):
|
|
77
|
+
raise ValueError('scale_factors must be flat numbers'
|
|
78
|
+
+ ' or a nested grid')
|
|
79
|
+
row = list(row)
|
|
80
|
+
if len(row) > columns:
|
|
81
|
+
raise ValueError('too many scale-factor columns')
|
|
82
|
+
for c, value in enumerate(row):
|
|
83
|
+
_require_positive_real_scalar(value, 'scale factor')
|
|
84
|
+
index = r * columns + c
|
|
85
|
+
if index < item_count:
|
|
86
|
+
scales[index] = value
|
|
87
|
+
return scales
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _scale_factors(scale_factors: ScaleInput, item_count: int,
|
|
91
|
+
columns: int) -> list[RealScalar]:
|
|
92
|
+
"""Validate flat or nested factors and return one scale per input.
|
|
93
|
+
|
|
94
|
+
None gives unit scales. Flat sequences require exactly item_count values;
|
|
95
|
+
nested grids may omit entries. Preserve supplied scalar precision.
|
|
96
|
+
"""
|
|
97
|
+
if scale_factors is None:
|
|
98
|
+
return [1.0] * item_count
|
|
99
|
+
values = list(scale_factors)
|
|
100
|
+
if not values:
|
|
101
|
+
raise ValueError('scale_factors must not be empty')
|
|
102
|
+
if all(isinstance(v, RealScalar) for v in values):
|
|
103
|
+
if len(values) != item_count:
|
|
104
|
+
raise ValueError('flat scale_factors must have one value per input')
|
|
105
|
+
for value in values:
|
|
106
|
+
_require_positive_real_scalar(value, 'scale factor')
|
|
107
|
+
return values
|
|
108
|
+
return _grid_scales(values, item_count, columns)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _layout(sizes: Sequence[tuple[RealScalar, RealScalar]], columns: int,
|
|
112
|
+
padding: int, scales: Sequence[RealScalar]
|
|
113
|
+
) -> tuple[tuple[int, int], list[tuple[int, int, int, int]]]:
|
|
114
|
+
"""Return canvas (width, height) and row-major (x, y, width, height) items.
|
|
115
|
+
|
|
116
|
+
Scale source sizes and round to whole units, with a minimum of one.
|
|
117
|
+
Size each column/row to its largest item and omit wholly unused columns.
|
|
118
|
+
Coordinates start at the top left; integer centering leaves odd spare
|
|
119
|
+
units on the right/bottom. Padding separates neighboring cells only.
|
|
120
|
+
"""
|
|
121
|
+
columns = min(columns, len(sizes))
|
|
122
|
+
rows = (len(sizes) + columns - 1) // columns
|
|
123
|
+
widths, heights = [0] * columns, [0] * rows
|
|
124
|
+
drawn = []
|
|
125
|
+
for i, ((w, h), scale) in enumerate(zip(sizes, scales)):
|
|
126
|
+
dw, dh = w * scale, h * scale
|
|
127
|
+
if not all(_is_positive_real_scalar(v)
|
|
128
|
+
for v in (w, h, dw, dh)):
|
|
129
|
+
raise ValueError('input and scaled dimensions must be'
|
|
130
|
+
+ ' positive and finite')
|
|
131
|
+
cw, ch = max(1, round(dw)), max(1, round(dh))
|
|
132
|
+
drawn.append((cw, ch))
|
|
133
|
+
widths[i % columns] = max(widths[i % columns], cw)
|
|
134
|
+
heights[i // columns] = max(heights[i // columns], ch)
|
|
135
|
+
xs, ys = [], []
|
|
136
|
+
for sizes_, positions in ((widths, xs), (heights, ys)):
|
|
137
|
+
position = 0
|
|
138
|
+
for size in sizes_:
|
|
139
|
+
positions.append(position)
|
|
140
|
+
position += size + padding
|
|
141
|
+
cells = []
|
|
142
|
+
for i, (w, h) in enumerate(drawn):
|
|
143
|
+
r, c = divmod(i, columns)
|
|
144
|
+
cells.append((xs[c] + (widths[c] - w) // 2,
|
|
145
|
+
ys[r] + (heights[r] - h) // 2, w, h))
|
|
146
|
+
return (sum(widths) + padding * (columns - 1),
|
|
147
|
+
sum(heights) + padding * (rows - 1)), cells
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def concat_pngs(file_list: Sequence[PathInput], output_file: PathInput,
|
|
151
|
+
columns: int, padding: RealScalar = 0, *,
|
|
152
|
+
scale_factors: ScaleInput = None,
|
|
153
|
+
background: tuple[int, int, int, int]
|
|
154
|
+
| tuple[int, int, int] | str = 'white',
|
|
155
|
+
resample: Image.Resampling | int = Image.Resampling.LANCZOS
|
|
156
|
+
) -> None:
|
|
157
|
+
"""Concatenate PNG images into one grid PNG.
|
|
158
|
+
|
|
159
|
+
Images fill rows from left to right. Each input is scaled directly and
|
|
160
|
+
rounded to whole pixels, with a minimum size of one pixel per dimension.
|
|
161
|
+
Rows and columns fit their largest scaled item. Images are centered,
|
|
162
|
+
leaving any odd spare pixel on the right/bottom. Unused cells are blank;
|
|
163
|
+
entirely unused columns are omitted. No input content is cropped.
|
|
164
|
+
All opened images are closed, including on failure.
|
|
165
|
+
|
|
166
|
+
Args:
|
|
167
|
+
file_list (Sequence[PathInput]): Input PNG paths in row-major order.
|
|
168
|
+
output_file (PathInput): Output path ending in .png. Must differ
|
|
169
|
+
from every input path.
|
|
170
|
+
columns (int): Positive number of grid columns.
|
|
171
|
+
padding (RealScalar, optional): Finite nonnegative whole-number
|
|
172
|
+
space between neighboring cells, in pixels. Defaults to 0.
|
|
173
|
+
scale_factors (ScaleInput, optional): Positive finite multipliers,
|
|
174
|
+
given as a flat sequence with one value per image or a nested
|
|
175
|
+
grid. Missing grid entries default to 1.0. Unused final-row
|
|
176
|
+
entries are validated but have no effect. Defaults to None,
|
|
177
|
+
which uses 1.0 for every image.
|
|
178
|
+
background (tuple[int, int, int, int] | tuple[int, int, int] | str,
|
|
179
|
+
optional): Canvas color. Use (255, 255, 255, 0) for transparent
|
|
180
|
+
output. Defaults to 'white'.
|
|
181
|
+
resample (Image.Resampling | int, optional): Resizing filter. Defaults
|
|
182
|
+
to Image.Resampling.LANCZOS.
|
|
183
|
+
|
|
184
|
+
Returns:
|
|
185
|
+
None: The composed image is saved to output_file.
|
|
186
|
+
"""
|
|
187
|
+
files, output, columns, padding, scales = _inputs(
|
|
188
|
+
file_list, output_file, columns, padding, scale_factors, '.png')
|
|
189
|
+
with ExitStack() as stack:
|
|
190
|
+
images = []
|
|
191
|
+
for filename in files:
|
|
192
|
+
source = stack.enter_context(Image.open(filename))
|
|
193
|
+
if source.format != 'PNG':
|
|
194
|
+
raise ValueError(f'Input is not PNG: {filename}')
|
|
195
|
+
image = (source if source.mode == 'RGBA' else
|
|
196
|
+
stack.enter_context(source.convert('RGBA')))
|
|
197
|
+
images.append(image)
|
|
198
|
+
sizes = [im.size for im in images]
|
|
199
|
+
size, cells = _layout(sizes, columns, padding, scales)
|
|
200
|
+
canvas = stack.enter_context(Image.new('RGBA', size, background))
|
|
201
|
+
for image, (x, y, w, h) in zip(images, cells):
|
|
202
|
+
if image.size == (w, h):
|
|
203
|
+
canvas.alpha_composite(image, dest=(x, y))
|
|
204
|
+
else:
|
|
205
|
+
with image.resize((w, h), resample=resample) as resized:
|
|
206
|
+
canvas.alpha_composite(resized, dest=(x, y))
|
|
207
|
+
canvas.save(output, format='PNG')
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _pdf_form_stream(page: "PageObject", writer: "PdfWriter") -> "StreamObject":
|
|
211
|
+
"""Copy a single content stream with its original encoding untouched.
|
|
212
|
+
|
|
213
|
+
Separate copies allow pages sharing a stream to have different form
|
|
214
|
+
geometry and resources. Multiple streams must be joined in sequence to
|
|
215
|
+
preserve graphics state; that fallback still uses pypdf's decode limits.
|
|
216
|
+
"""
|
|
217
|
+
from pypdf.generic import ArrayObject, DecodedStreamObject, NullObject
|
|
218
|
+
|
|
219
|
+
contents = page.get('/Contents')
|
|
220
|
+
contents = contents.get_object() if contents is not None else None
|
|
221
|
+
entries = contents if isinstance(contents, ArrayObject) else [contents]
|
|
222
|
+
streams = []
|
|
223
|
+
for entry in entries:
|
|
224
|
+
stream = entry.get_object() if entry is not None else None
|
|
225
|
+
if stream is not None and not isinstance(stream, NullObject):
|
|
226
|
+
streams.append(stream)
|
|
227
|
+
if len(streams) == 1:
|
|
228
|
+
return streams[0].clone(writer, force_duplicate=True)
|
|
229
|
+
form = DecodedStreamObject()
|
|
230
|
+
if not streams:
|
|
231
|
+
form.set_data(b'')
|
|
232
|
+
return form
|
|
233
|
+
form.set_data(b'\n'.join(stream.get_data() for stream in streams))
|
|
234
|
+
return form.flate_encode()
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _pdf_form(page: "PageObject", writer: "PdfWriter"
|
|
238
|
+
) -> tuple["IndirectObject", tuple[float, float]]:
|
|
239
|
+
"""Copy a page into a clipped Form XObject without parsing its operators.
|
|
240
|
+
|
|
241
|
+
Keep resources and the page transparency group local to the form. Its
|
|
242
|
+
matrix normalizes crop offsets and clockwise page rotation. Return the
|
|
243
|
+
writer-owned form reference and its visible width/height in layout units.
|
|
244
|
+
Single content streams retain their encoding without decompression.
|
|
245
|
+
Multiple streams and resource cloning still use pypdf's normal limits.
|
|
246
|
+
"""
|
|
247
|
+
from pypdf.generic import (
|
|
248
|
+
ArrayObject, DictionaryObject, FloatObject,
|
|
249
|
+
NameObject, NumberObject, RectangleObject,
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
box = page.cropbox
|
|
253
|
+
left, bottom, right, top = map(float, box)
|
|
254
|
+
if not all(_is_finite_real_scalar(v) for v in box):
|
|
255
|
+
raise ValueError('PDF crop box must contain finite coordinates')
|
|
256
|
+
if right <= left or top <= bottom:
|
|
257
|
+
raise ValueError('PDF crop box must have positive width and height')
|
|
258
|
+
# Exact right-angle coefficients avoid numerical drift from trigonometry.
|
|
259
|
+
matrices = {0: (1, 0, 0, 1, -left, -bottom),
|
|
260
|
+
90: (0, -1, 1, 0, -bottom, right),
|
|
261
|
+
180: (-1, 0, 0, -1, right, top),
|
|
262
|
+
270: (0, 1, -1, 0, top, -left)}
|
|
263
|
+
rotation = page.rotation % 360
|
|
264
|
+
if rotation not in matrices:
|
|
265
|
+
raise ValueError('PDF page rotation must be a multiple of 90 degrees')
|
|
266
|
+
size = (right - left, top - bottom)
|
|
267
|
+
if rotation in (90, 270):
|
|
268
|
+
size = size[::-1]
|
|
269
|
+
|
|
270
|
+
form = _pdf_form_stream(page, writer)
|
|
271
|
+
form.update({NameObject('/Type'): NameObject('/XObject'),
|
|
272
|
+
NameObject('/Subtype'): NameObject('/Form'),
|
|
273
|
+
NameObject('/FormType'): NumberObject(1),
|
|
274
|
+
NameObject('/BBox'): RectangleObject(box),
|
|
275
|
+
NameObject('/Matrix'): ArrayObject(
|
|
276
|
+
[FloatObject(v) for v in matrices[rotation]]),
|
|
277
|
+
NameObject('/Resources'): page.get(
|
|
278
|
+
'/Resources', DictionaryObject()).clone(writer)})
|
|
279
|
+
if '/Group' in page:
|
|
280
|
+
form[NameObject('/Group')] = page['/Group'].clone(writer)
|
|
281
|
+
# pypdf has no public writer method to register a new arbitrary stream.
|
|
282
|
+
return writer._add_object(form), size
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _read_pdf_form(filename: Path, writer: "PdfWriter"
|
|
286
|
+
) -> tuple["IndirectObject", tuple[float, float]]:
|
|
287
|
+
"""Read and clone the first page, closing its input before returning.
|
|
288
|
+
|
|
289
|
+
Add the source path to failures while preserving their exception type.
|
|
290
|
+
"""
|
|
291
|
+
from pypdf import PdfReader
|
|
292
|
+
|
|
293
|
+
try:
|
|
294
|
+
with filename.open('rb') as stream:
|
|
295
|
+
reader = PdfReader(stream)
|
|
296
|
+
try:
|
|
297
|
+
if reader.is_encrypted:
|
|
298
|
+
raise ValueError('Encrypted PDF is unsupported')
|
|
299
|
+
if not reader.pages:
|
|
300
|
+
raise ValueError('PDF has no pages')
|
|
301
|
+
return _pdf_form(reader.pages[0], writer)
|
|
302
|
+
finally:
|
|
303
|
+
reader.close()
|
|
304
|
+
except Exception as exc:
|
|
305
|
+
exc.add_note(f'PDF input: {filename}')
|
|
306
|
+
raise
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _place_pdf_forms(writer: "PdfWriter", forms: Sequence["IndirectObject"],
|
|
310
|
+
sizes: Sequence[tuple[float, float]],
|
|
311
|
+
canvas_size: tuple[int, int],
|
|
312
|
+
cells: Sequence[tuple[int, int, int, int]]) -> None:
|
|
313
|
+
"""Place forms with short drawing commands, retaining their aspect ratios."""
|
|
314
|
+
from pypdf.generic import (
|
|
315
|
+
DecodedStreamObject, DictionaryObject, FloatObject, NameObject,
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
canvas = writer.add_blank_page(width=canvas_size[0], height=canvas_size[1])
|
|
319
|
+
xobjects = DictionaryObject()
|
|
320
|
+
commands = []
|
|
321
|
+
for i, (form, (width, height), (x, y, w, h)) in enumerate(
|
|
322
|
+
zip(forms, sizes, cells)):
|
|
323
|
+
scale = min(w / width, h / height)
|
|
324
|
+
dx = x + (w - width * scale) / 2
|
|
325
|
+
dy = canvas_size[1] - y - h + (h - height * scale) / 2
|
|
326
|
+
name = NameObject(f'/Figure{i}')
|
|
327
|
+
xobjects[name] = form
|
|
328
|
+
# Use pypdf's PDF number formatting, including small nonzero values.
|
|
329
|
+
numbers = [FloatObject(v).myrepr() for v in (scale, dx, dy)]
|
|
330
|
+
commands.append(f'q {numbers[0]} 0 0 {numbers[0]} '
|
|
331
|
+
f'{numbers[1]} {numbers[2]} cm {name} Do Q\n')
|
|
332
|
+
canvas[NameObject('/Resources')] = DictionaryObject(
|
|
333
|
+
{NameObject('/XObject'): xobjects})
|
|
334
|
+
contents = DecodedStreamObject()
|
|
335
|
+
contents.set_data(''.join(commands).encode('ascii'))
|
|
336
|
+
canvas[NameObject('/Contents')] = writer._add_object(contents)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def concat_pdfs(file_list: Sequence[PathInput], output_file: PathInput,
|
|
340
|
+
columns: int, padding: RealScalar = 0, *,
|
|
341
|
+
scale_factors: ScaleInput = None) -> None:
|
|
342
|
+
"""Concatenate the first page of each PDF into one grid PDF page.
|
|
343
|
+
|
|
344
|
+
Uses the same direct scaling, whole-unit rounding, row/column sizing,
|
|
345
|
+
and centering rules as concat_pngs, with PDF points replacing pixels.
|
|
346
|
+
Matching numeric source dimensions give matching grid geometry; PNG DPI
|
|
347
|
+
metadata is ignored. PDF content preserves its aspect ratio within the
|
|
348
|
+
rounded cells. Text and vectors remain PDF content. Page rotations and
|
|
349
|
+
crop-box offsets are handled by form matrices. Page content is embedded
|
|
350
|
+
without parsing individual drawing operators. Single content streams
|
|
351
|
+
retain their original encoding without decompression; multiple streams
|
|
352
|
+
are decoded and joined while preserving graphics state. The background is
|
|
353
|
+
unpainted, and interactive annotations are omitted.
|
|
354
|
+
All readers and streams are closed, including on failure. Input read
|
|
355
|
+
and embedding errors include the source path in an exception note.
|
|
356
|
+
|
|
357
|
+
Args:
|
|
358
|
+
file_list (Sequence[PathInput]): Input paths to unencrypted PDFs
|
|
359
|
+
with at least one page, in row-major order. Only the first page
|
|
360
|
+
of each file is used.
|
|
361
|
+
output_file (PathInput): Output path ending in .pdf. Must differ
|
|
362
|
+
from every input path.
|
|
363
|
+
columns (int): Positive number of grid columns.
|
|
364
|
+
padding (RealScalar, optional): Finite nonnegative whole-number
|
|
365
|
+
space between neighboring cells, in PDF points. Defaults to 0.
|
|
366
|
+
scale_factors (ScaleInput, optional): Positive finite multipliers,
|
|
367
|
+
given as a flat sequence with one value per PDF or a nested
|
|
368
|
+
grid. Missing grid entries default to 1.0. Unused final-row
|
|
369
|
+
entries are validated but have no effect. Defaults to None,
|
|
370
|
+
which uses 1.0 for every PDF.
|
|
371
|
+
|
|
372
|
+
Returns:
|
|
373
|
+
None: The composed page is saved to output_file.
|
|
374
|
+
"""
|
|
375
|
+
files, output, columns, padding, scales = _inputs(
|
|
376
|
+
file_list, output_file, columns, padding, scale_factors, '.pdf')
|
|
377
|
+
try:
|
|
378
|
+
from pypdf import PdfWriter
|
|
379
|
+
except ImportError as exc:
|
|
380
|
+
raise ImportError('concat_pdfs() requires pypdf.') from exc
|
|
381
|
+
with PdfWriter() as writer:
|
|
382
|
+
forms, sizes = [], []
|
|
383
|
+
for filename in files:
|
|
384
|
+
form, size = _read_pdf_form(filename, writer)
|
|
385
|
+
forms.append(form)
|
|
386
|
+
sizes.append(size)
|
|
387
|
+
canvas_size, cells = _layout(sizes, columns, padding, scales)
|
|
388
|
+
_place_pdf_forms(writer, forms, sizes, canvas_size, cells)
|
|
389
|
+
with output.open('wb') as stream:
|
|
390
|
+
writer.write(stream)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: plotastrodata
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.13.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
|
|
@@ -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
|
|
@@ -124,8 +125,33 @@ PB correction. The array-based function is `noise_utils.estimate_ranges`,
|
|
|
124
125
|
with the same `pbcor` option and optional `sigma`. Here, `rmax` is a symmetric
|
|
125
126
|
spatial half-width; 2D images return `None` for both velocity limits.
|
|
126
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
|
+
|
|
127
147
|
## Requirement
|
|
128
148
|
|
|
149
|
+
The fitting libraries below are installed by default, but imported only when
|
|
150
|
+
the corresponding feature is used: emcee for ordinary MCMC, ptemcee for
|
|
151
|
+
parallel tempering, corner for corner plots, dynesty for nested sampling,
|
|
152
|
+
and tqdm for fitting progress bars. When using the source directory directly,
|
|
153
|
+
these libraries are needed only for those features.
|
|
154
|
+
|
|
129
155
|
* Python >= 3.11
|
|
130
156
|
* astropy >= 7.2
|
|
131
157
|
* corner (only for fitting)
|
|
@@ -134,10 +160,11 @@ spatial half-width; 2D images return `None` for both velocity limits.
|
|
|
134
160
|
* ffmpeg (only for movie)
|
|
135
161
|
* matplotlib
|
|
136
162
|
* numpy >= 2.0
|
|
137
|
-
* pillow
|
|
163
|
+
* pillow
|
|
138
164
|
* plotly (only for html cube)
|
|
139
165
|
* ptemcee (only for fitting)
|
|
140
166
|
* pydantic >= 2
|
|
167
|
+
* pypdf >= 6.21.2 (only for PDF grids)
|
|
141
168
|
* scikit-image (only for html cube)
|
|
142
169
|
* scipy
|
|
143
170
|
* tqdm (only for fitting)
|
|
@@ -4,6 +4,7 @@ README.md
|
|
|
4
4
|
setup.cfg
|
|
5
5
|
setup.py
|
|
6
6
|
plotastrodata/__init__.py
|
|
7
|
+
plotastrodata/_ptemcee_compat.py
|
|
7
8
|
plotastrodata/_type_utils.py
|
|
8
9
|
plotastrodata/_validation_utils.py
|
|
9
10
|
plotastrodata/analysis_utils.py
|
|
@@ -18,6 +19,7 @@ plotastrodata/matrix_utils.py
|
|
|
18
19
|
plotastrodata/noise_utils.py
|
|
19
20
|
plotastrodata/other_utils.py
|
|
20
21
|
plotastrodata/plot_utils.py
|
|
22
|
+
plotastrodata/pngpdf_utils.py
|
|
21
23
|
plotastrodata/script_utils.py
|
|
22
24
|
plotastrodata.egg-info/PKG-INFO
|
|
23
25
|
plotastrodata.egg-info/SOURCES.txt
|
|
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
|