plotastrodata 1.13.0__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.13.0/plotastrodata.egg-info → plotastrodata-1.13.1}/PKG-INFO +8 -2
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/README.md +7 -1
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata/__init__.py +1 -1
- plotastrodata-1.13.1/plotastrodata/_ptemcee_compat.py +37 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata/fitting_utils.py +40 -48
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata/pngpdf_utils.py +166 -43
- {plotastrodata-1.13.0 → plotastrodata-1.13.1/plotastrodata.egg-info}/PKG-INFO +8 -2
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata.egg-info/SOURCES.txt +1 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/LICENSE +0 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/MANIFEST.in +0 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata/_type_utils.py +0 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata/_validation_utils.py +0 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata/analysis_utils.py +0 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata/const_utils.py +0 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata/coord_utils.py +0 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata/ext_utils.py +0 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata/fft_utils.py +0 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata/fits_utils.py +0 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata/los_utils.py +0 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata/matrix_utils.py +0 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata/noise_utils.py +0 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata/other_utils.py +0 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata/plot_utils.py +0 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata/script_utils.py +0 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata.egg-info/dependency_links.txt +0 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata.egg-info/not-zip-safe +0 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata.egg-info/requires.txt +0 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/plotastrodata.egg-info/top_level.txt +0 -0
- {plotastrodata-1.13.0 → plotastrodata-1.13.1}/setup.cfg +0 -0
- {plotastrodata-1.13.0 → 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.13.
|
|
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
|
|
@@ -146,6 +146,12 @@ Pillow and pypdf are installed with plotastrodata.
|
|
|
146
146
|
|
|
147
147
|
## Requirement
|
|
148
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
|
+
|
|
149
155
|
* Python >= 3.11
|
|
150
156
|
* astropy >= 7.2
|
|
151
157
|
* corner (only for fitting)
|
|
@@ -154,7 +160,7 @@ Pillow and pypdf are installed with plotastrodata.
|
|
|
154
160
|
* ffmpeg (only for movie)
|
|
155
161
|
* matplotlib
|
|
156
162
|
* numpy >= 2.0
|
|
157
|
-
* pillow
|
|
163
|
+
* pillow
|
|
158
164
|
* plotly (only for html cube)
|
|
159
165
|
* ptemcee (only for fitting)
|
|
160
166
|
* pydantic >= 2
|
|
@@ -116,6 +116,12 @@ Pillow and pypdf are installed with plotastrodata.
|
|
|
116
116
|
|
|
117
117
|
## Requirement
|
|
118
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
|
+
|
|
119
125
|
* Python >= 3.11
|
|
120
126
|
* astropy >= 7.2
|
|
121
127
|
* corner (only for fitting)
|
|
@@ -124,7 +130,7 @@ Pillow and pypdf are installed with plotastrodata.
|
|
|
124
130
|
* ffmpeg (only for movie)
|
|
125
131
|
* matplotlib
|
|
126
132
|
* numpy >= 2.0
|
|
127
|
-
* pillow
|
|
133
|
+
* pillow
|
|
128
134
|
* plotly (only for html cube)
|
|
129
135
|
* ptemcee (only for fitting)
|
|
130
136
|
* pydantic >= 2
|
|
@@ -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)
|
|
@@ -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]
|
|
@@ -6,7 +6,7 @@ PDF composition uses the required pypdf dependency, imported only when used.
|
|
|
6
6
|
from contextlib import ExitStack
|
|
7
7
|
from os import PathLike
|
|
8
8
|
from pathlib import Path
|
|
9
|
-
from typing import Sequence
|
|
9
|
+
from typing import TYPE_CHECKING, Sequence
|
|
10
10
|
|
|
11
11
|
from PIL import Image
|
|
12
12
|
|
|
@@ -19,6 +19,11 @@ from plotastrodata._validation_utils import (
|
|
|
19
19
|
)
|
|
20
20
|
|
|
21
21
|
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
from pypdf import PageObject, PdfWriter
|
|
24
|
+
from pypdf.generic import IndirectObject, StreamObject
|
|
25
|
+
|
|
26
|
+
|
|
22
27
|
PathInput = str | PathLike[str]
|
|
23
28
|
ScaleInput = Sequence[RealScalar] | Sequence[Sequence[RealScalar]] | None
|
|
24
29
|
|
|
@@ -43,15 +48,18 @@ def _inputs(file_list: Sequence[PathInput], output_file: PathInput,
|
|
|
43
48
|
_require_integer(columns, 'columns')
|
|
44
49
|
if not _is_finite_real_scalar(padding) or padding < 0:
|
|
45
50
|
raise ValueError('padding must be a finite nonnegative real scalar')
|
|
46
|
-
|
|
51
|
+
integer_padding = int(padding)
|
|
52
|
+
if padding != integer_padding:
|
|
47
53
|
raise ValueError('padding must be a whole number of layout units')
|
|
48
54
|
output = Path(output_file)
|
|
49
55
|
if output.suffix.lower() != suffix:
|
|
50
56
|
raise ValueError(f'output_file must end in {suffix}')
|
|
51
|
-
|
|
57
|
+
resolved_output = output.resolve()
|
|
58
|
+
if any(resolved_output == f.resolve() for f in files):
|
|
52
59
|
raise ValueError('output_file must differ from every input file')
|
|
53
|
-
|
|
54
|
-
|
|
60
|
+
columns = int(columns)
|
|
61
|
+
scales = _scale_factors(scale_factors, len(files), columns)
|
|
62
|
+
return files, output, columns, integer_padding, scales
|
|
55
63
|
|
|
56
64
|
|
|
57
65
|
def _grid_scales(values: Sequence[Sequence[RealScalar]], item_count: int,
|
|
@@ -115,11 +123,11 @@ def _layout(sizes: Sequence[tuple[RealScalar, RealScalar]], columns: int,
|
|
|
115
123
|
widths, heights = [0] * columns, [0] * rows
|
|
116
124
|
drawn = []
|
|
117
125
|
for i, ((w, h), scale) in enumerate(zip(sizes, scales)):
|
|
126
|
+
dw, dh = w * scale, h * scale
|
|
118
127
|
if not all(_is_positive_real_scalar(v)
|
|
119
|
-
for v in (w, h,
|
|
128
|
+
for v in (w, h, dw, dh)):
|
|
120
129
|
raise ValueError('input and scaled dimensions must be'
|
|
121
130
|
+ ' positive and finite')
|
|
122
|
-
dw, dh = w * scale, h * scale
|
|
123
131
|
cw, ch = max(1, round(dw)), max(1, round(dh))
|
|
124
132
|
drawn.append((cw, ch))
|
|
125
133
|
widths[i % columns] = max(widths[i % columns], cw)
|
|
@@ -184,16 +192,150 @@ def concat_pngs(file_list: Sequence[PathInput], output_file: PathInput,
|
|
|
184
192
|
source = stack.enter_context(Image.open(filename))
|
|
185
193
|
if source.format != 'PNG':
|
|
186
194
|
raise ValueError(f'Input is not PNG: {filename}')
|
|
187
|
-
|
|
195
|
+
image = (source if source.mode == 'RGBA' else
|
|
196
|
+
stack.enter_context(source.convert('RGBA')))
|
|
197
|
+
images.append(image)
|
|
188
198
|
sizes = [im.size for im in images]
|
|
189
199
|
size, cells = _layout(sizes, columns, padding, scales)
|
|
190
200
|
canvas = stack.enter_context(Image.new('RGBA', size, background))
|
|
191
201
|
for image, (x, y, w, h) in zip(images, cells):
|
|
192
|
-
|
|
193
|
-
canvas.alpha_composite(
|
|
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))
|
|
194
207
|
canvas.save(output, format='PNG')
|
|
195
208
|
|
|
196
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
|
+
|
|
197
339
|
def concat_pdfs(file_list: Sequence[PathInput], output_file: PathInput,
|
|
198
340
|
columns: int, padding: RealScalar = 0, *,
|
|
199
341
|
scale_factors: ScaleInput = None) -> None:
|
|
@@ -204,9 +346,13 @@ def concat_pdfs(file_list: Sequence[PathInput], output_file: PathInput,
|
|
|
204
346
|
Matching numeric source dimensions give matching grid geometry; PNG DPI
|
|
205
347
|
metadata is ignored. PDF content preserves its aspect ratio within the
|
|
206
348
|
rounded cells. Text and vectors remain PDF content. Page rotations and
|
|
207
|
-
crop-box offsets are
|
|
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
|
|
208
353
|
unpainted, and interactive annotations are omitted.
|
|
209
|
-
All readers and streams are closed, including on failure.
|
|
354
|
+
All readers and streams are closed, including on failure. Input read
|
|
355
|
+
and embedding errors include the source path in an exception note.
|
|
210
356
|
|
|
211
357
|
Args:
|
|
212
358
|
file_list (Sequence[PathInput]): Input paths to unencrypted PDFs
|
|
@@ -229,39 +375,16 @@ def concat_pdfs(file_list: Sequence[PathInput], output_file: PathInput,
|
|
|
229
375
|
files, output, columns, padding, scales = _inputs(
|
|
230
376
|
file_list, output_file, columns, padding, scale_factors, '.pdf')
|
|
231
377
|
try:
|
|
232
|
-
from pypdf import
|
|
378
|
+
from pypdf import PdfWriter
|
|
233
379
|
except ImportError as exc:
|
|
234
380
|
raise ImportError('concat_pdfs() requires pypdf.') from exc
|
|
235
|
-
with
|
|
236
|
-
|
|
237
|
-
source_writer = PdfWriter()
|
|
238
|
-
stack.callback(source_writer.close)
|
|
381
|
+
with PdfWriter() as writer:
|
|
382
|
+
forms, sizes = [], []
|
|
239
383
|
for filename in files:
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
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)
|
|
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)
|
|
266
389
|
with output.open('wb') as stream:
|
|
267
390
|
writer.write(stream)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: plotastrodata
|
|
3
|
-
Version: 1.13.
|
|
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
|
|
@@ -146,6 +146,12 @@ Pillow and pypdf are installed with plotastrodata.
|
|
|
146
146
|
|
|
147
147
|
## Requirement
|
|
148
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
|
+
|
|
149
155
|
* Python >= 3.11
|
|
150
156
|
* astropy >= 7.2
|
|
151
157
|
* corner (only for fitting)
|
|
@@ -154,7 +160,7 @@ Pillow and pypdf are installed with plotastrodata.
|
|
|
154
160
|
* ffmpeg (only for movie)
|
|
155
161
|
* matplotlib
|
|
156
162
|
* numpy >= 2.0
|
|
157
|
-
* pillow
|
|
163
|
+
* pillow
|
|
158
164
|
* plotly (only for html cube)
|
|
159
165
|
* ptemcee (only for fitting)
|
|
160
166
|
* pydantic >= 2
|
|
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
|