pystackreg 0.3.0__cp315-cp315-macosx_11_0_arm64.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.
- pystackreg/__init__.py +16 -0
- pystackreg/_internal.py +271 -0
- pystackreg/py.typed +0 -0
- pystackreg/pystackreg.py +814 -0
- pystackreg/turboreg.cpython-315-darwin.so +0 -0
- pystackreg/util/__init__.py +181 -0
- pystackreg/version.py +1 -0
- pystackreg-0.3.0.dist-info/METADATA +360 -0
- pystackreg-0.3.0.dist-info/RECORD +13 -0
- pystackreg-0.3.0.dist-info/WHEEL +6 -0
- pystackreg-0.3.0.dist-info/licenses/LICENSE +674 -0
- pystackreg-0.3.0.dist-info/licenses/NOTICE +109 -0
- pystackreg-0.3.0.dist-info/top_level.txt +1 -0
pystackreg/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
2
|
+
# Copyright (C) 2018-2026 Gregor Lichtner and PyStackReg contributors
|
|
3
|
+
"""pystackreg: image registration with a Python/C++ port of TurboReg/StackReg.
|
|
4
|
+
|
|
5
|
+
The registration algorithm is the one of the ImageJ plugin TurboReg by
|
|
6
|
+
Philippe Thévenaz (EPFL), described in
|
|
7
|
+
|
|
8
|
+
P. Thévenaz, U.E. Ruttimann, M. Unser, "A Pyramid Approach to Subpixel
|
|
9
|
+
Registration Based on Intensity", IEEE Transactions on Image Processing,
|
|
10
|
+
vol. 7, no. 1, pp. 27-41, January 1998.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from pystackreg.pystackreg import StackReg
|
|
14
|
+
from pystackreg.version import __version__
|
|
15
|
+
|
|
16
|
+
__all__ = ["StackReg", "__version__"]
|
pystackreg/_internal.py
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
2
|
+
# Copyright (C) 2018-2026 Gregor Lichtner and PyStackReg contributors
|
|
3
|
+
"""Internal helpers of pystackreg.
|
|
4
|
+
|
|
5
|
+
Nothing in this module is part of the public API; it may change without notice.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import math
|
|
11
|
+
import os
|
|
12
|
+
from collections.abc import Callable, Sequence
|
|
13
|
+
from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait
|
|
14
|
+
from types import TracebackType
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
|
|
19
|
+
from pystackreg.util import simple_slice, to_int_dtype
|
|
20
|
+
|
|
21
|
+
#: Approximate number of array elements processed per chunk by the streaming
|
|
22
|
+
#: helpers (16 MiB of float64).
|
|
23
|
+
_CHUNK_ELEMENTS = 2**21
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def available_cpus() -> int:
|
|
27
|
+
"""Number of CPUs usable by the current process (at least 1)."""
|
|
28
|
+
process_cpu_count = getattr(os, "process_cpu_count", None) # Python >= 3.13
|
|
29
|
+
if process_cpu_count is not None:
|
|
30
|
+
return process_cpu_count() or 1
|
|
31
|
+
if hasattr(os, "sched_getaffinity"):
|
|
32
|
+
return len(os.sched_getaffinity(0)) or 1
|
|
33
|
+
return os.cpu_count() or 1
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def resolve_n_jobs(n_jobs: int | None) -> int:
|
|
37
|
+
"""Translate an ``n_jobs`` argument into a number of worker threads.
|
|
38
|
+
|
|
39
|
+
Follows the joblib/scikit-learn convention: ``None`` and ``1`` mean
|
|
40
|
+
sequential execution, a positive number is used as is, and a negative
|
|
41
|
+
number ``-k`` means "all CPUs but ``k - 1``" (``-1``: all CPUs).
|
|
42
|
+
"""
|
|
43
|
+
if n_jobs is None:
|
|
44
|
+
return 1
|
|
45
|
+
if isinstance(n_jobs, bool) or not isinstance(n_jobs, (int, np.integer)):
|
|
46
|
+
raise TypeError(f"n_jobs must be an integer or None, got {n_jobs!r}")
|
|
47
|
+
n_jobs = int(n_jobs)
|
|
48
|
+
if n_jobs == 0:
|
|
49
|
+
raise ValueError("n_jobs must not be 0; use 1 for sequential execution")
|
|
50
|
+
if n_jobs < 0:
|
|
51
|
+
return max(1, available_cpus() + 1 + n_jobs)
|
|
52
|
+
return n_jobs
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def run_tasks(
|
|
56
|
+
func: Callable[[int], None],
|
|
57
|
+
indices: Sequence[int],
|
|
58
|
+
n_jobs: int,
|
|
59
|
+
on_done: Callable[[int], None],
|
|
60
|
+
) -> None:
|
|
61
|
+
"""Call ``func(i)`` for every index, sequentially or in a thread pool.
|
|
62
|
+
|
|
63
|
+
``func`` must store its own result and must be safe to call concurrently
|
|
64
|
+
for different indices. ``on_done(count)`` is called in the calling thread
|
|
65
|
+
after each completed task with the number of tasks finished so far, so
|
|
66
|
+
progress reporting never runs in a worker thread.
|
|
67
|
+
|
|
68
|
+
At most ``2 * n_jobs`` tasks are submitted ahead of time. If a task (or
|
|
69
|
+
``on_done``) raises, including ``KeyboardInterrupt``, tasks that have not
|
|
70
|
+
started are cancelled, running ones are allowed to finish, and the
|
|
71
|
+
exception is re-raised. Which task's exception is reported first is not
|
|
72
|
+
deterministic when several fail.
|
|
73
|
+
"""
|
|
74
|
+
n_workers = min(n_jobs, len(indices))
|
|
75
|
+
if n_workers <= 1:
|
|
76
|
+
for count, index in enumerate(indices, 1):
|
|
77
|
+
func(index)
|
|
78
|
+
on_done(count)
|
|
79
|
+
return
|
|
80
|
+
|
|
81
|
+
pending: set[Future[None]] = set()
|
|
82
|
+
remaining = iter(indices)
|
|
83
|
+
finished = 0
|
|
84
|
+
with ThreadPoolExecutor(
|
|
85
|
+
max_workers=n_workers, thread_name_prefix="pystackreg"
|
|
86
|
+
) as executor:
|
|
87
|
+
try:
|
|
88
|
+
while True:
|
|
89
|
+
for index in remaining:
|
|
90
|
+
pending.add(executor.submit(func, index))
|
|
91
|
+
if len(pending) >= 2 * n_workers:
|
|
92
|
+
break
|
|
93
|
+
if not pending:
|
|
94
|
+
break
|
|
95
|
+
done, pending = wait(pending, return_when=FIRST_COMPLETED)
|
|
96
|
+
for future in done:
|
|
97
|
+
future.result() # re-raises an exception from the worker
|
|
98
|
+
finished += 1
|
|
99
|
+
on_done(finished)
|
|
100
|
+
except BaseException:
|
|
101
|
+
for future in pending:
|
|
102
|
+
future.cancel()
|
|
103
|
+
raise
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class Progress:
|
|
107
|
+
"""Progress reporting through a tqdm bar and/or a user callback.
|
|
108
|
+
|
|
109
|
+
:param total: number of iterations
|
|
110
|
+
:param verbose: show a tqdm progress bar
|
|
111
|
+
:param callback: called after every iteration with the keyword arguments
|
|
112
|
+
``current_iteration`` (1-based count of finished iterations) and
|
|
113
|
+
``end_iteration`` (the total)
|
|
114
|
+
:param desc: label of the progress bar
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
def __init__(
|
|
118
|
+
self,
|
|
119
|
+
total: int,
|
|
120
|
+
verbose: bool,
|
|
121
|
+
callback: Callable[..., Any] | None,
|
|
122
|
+
desc: str,
|
|
123
|
+
) -> None:
|
|
124
|
+
if callback is not None and not callable(callback):
|
|
125
|
+
raise TypeError("progress_callback must be callable")
|
|
126
|
+
self._total = total
|
|
127
|
+
self._callback = callback
|
|
128
|
+
self._bar = None
|
|
129
|
+
if verbose and total > 0:
|
|
130
|
+
# imported lazily: tqdm.auto selects a notebook widget or a
|
|
131
|
+
# terminal bar and is only needed when a bar is requested
|
|
132
|
+
from tqdm.auto import tqdm
|
|
133
|
+
|
|
134
|
+
self._bar = tqdm(total=total, desc=desc)
|
|
135
|
+
|
|
136
|
+
def step(self, count: int) -> None:
|
|
137
|
+
"""Report that ``count`` iterations have finished."""
|
|
138
|
+
if self._bar is not None:
|
|
139
|
+
self._bar.update(1)
|
|
140
|
+
if self._callback is not None:
|
|
141
|
+
self._callback(current_iteration=count, end_iteration=self._total)
|
|
142
|
+
|
|
143
|
+
def __enter__(self) -> Progress:
|
|
144
|
+
return self
|
|
145
|
+
|
|
146
|
+
def __exit__(
|
|
147
|
+
self,
|
|
148
|
+
exc_type: type[BaseException] | None,
|
|
149
|
+
exc: BaseException | None,
|
|
150
|
+
tb: TracebackType | None,
|
|
151
|
+
) -> None:
|
|
152
|
+
if self._bar is not None:
|
|
153
|
+
self._bar.close()
|
|
154
|
+
self._bar = None
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class FrameSource:
|
|
158
|
+
"""Frame-wise access to a stack, optionally through a moving average.
|
|
159
|
+
|
|
160
|
+
The moving average reproduces :func:`pystackreg.util.running_mean`
|
|
161
|
+
(window ``[i + 1 - ceil(N / 2), i + N - ceil(N / 2)]`` with edge
|
|
162
|
+
replication) but computes one frame at a time, so the averaged stack is
|
|
163
|
+
never held in memory.
|
|
164
|
+
|
|
165
|
+
:param img: 3-D stack
|
|
166
|
+
:param axis: frame axis (non-negative)
|
|
167
|
+
:param window: moving-average window; 1 disables averaging
|
|
168
|
+
"""
|
|
169
|
+
|
|
170
|
+
def __init__(self, img: np.ndarray, axis: int, window: int) -> None:
|
|
171
|
+
self._img = img
|
|
172
|
+
self._axis = axis
|
|
173
|
+
self._window = window
|
|
174
|
+
self.n_frames = img.shape[axis]
|
|
175
|
+
if img.dtype.kind == "u":
|
|
176
|
+
self._sum_dtype: Any = np.uint64
|
|
177
|
+
elif img.dtype.kind in "ib":
|
|
178
|
+
self._sum_dtype = np.int64
|
|
179
|
+
else:
|
|
180
|
+
self._sum_dtype = np.float64
|
|
181
|
+
|
|
182
|
+
def frame(self, index: int) -> np.ndarray:
|
|
183
|
+
"""Return frame ``index`` (a view if no averaging is requested)."""
|
|
184
|
+
if self._window == 1:
|
|
185
|
+
return simple_slice(self._img, index, self._axis)
|
|
186
|
+
first = index + 1 - math.ceil(self._window / 2)
|
|
187
|
+
idx = np.clip(np.arange(first, first + self._window), 0, self.n_frames - 1)
|
|
188
|
+
frames = np.take(self._img, idx, axis=self._axis)
|
|
189
|
+
return frames.sum(axis=self._axis, dtype=self._sum_dtype) / float(self._window)
|
|
190
|
+
|
|
191
|
+
def mean_of_first(self, n: int) -> np.ndarray:
|
|
192
|
+
"""Mean of the first ``n`` (averaged) frames."""
|
|
193
|
+
if self._window == 1:
|
|
194
|
+
return np.mean(self._img.take(range(n), axis=self._axis), axis=self._axis)
|
|
195
|
+
return np.mean(np.stack([self.frame(i) for i in range(n)]), axis=0)
|
|
196
|
+
|
|
197
|
+
def mean_of_all(self) -> np.ndarray:
|
|
198
|
+
"""Mean of all (averaged) frames."""
|
|
199
|
+
if self._window == 1:
|
|
200
|
+
return self._img.mean(axis=self._axis)
|
|
201
|
+
total = np.zeros(self.frame(0).shape, dtype=np.float64)
|
|
202
|
+
for i in range(self.n_frames):
|
|
203
|
+
total += self.frame(i)
|
|
204
|
+
return total / self.n_frames
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def detect_time_axis(img: np.ndarray) -> int:
|
|
208
|
+
"""Return the axis of a 3-D stack with the lowest average variance.
|
|
209
|
+
|
|
210
|
+
Equivalent to ``argmin([np.var(img, axis=i).mean() for i in range(3)])``,
|
|
211
|
+
but evaluated in chunks along the first axis: ``np.var`` on the whole
|
|
212
|
+
stack allocates a float64 copy of it, which for integer stacks is several
|
|
213
|
+
times the size of the data.
|
|
214
|
+
"""
|
|
215
|
+
n0 = img.shape[0]
|
|
216
|
+
if img.size == 0:
|
|
217
|
+
return 0
|
|
218
|
+
plane = img.shape[1] * img.shape[2]
|
|
219
|
+
step = max(1, _CHUNK_ELEMENTS // max(plane, 1))
|
|
220
|
+
|
|
221
|
+
# Variance along axis 0 from running sums of values shifted by the first
|
|
222
|
+
# plane (the shift keeps the sums well conditioned for data with a large
|
|
223
|
+
# offset). Variances along axes 1 and 2 are local to a chunk.
|
|
224
|
+
# Non-finite pixels make the statistics meaningless but must not emit
|
|
225
|
+
# floating-point warnings here; the registration reports them clearly.
|
|
226
|
+
with np.errstate(invalid="ignore", over="ignore"):
|
|
227
|
+
first = img[0].astype(np.float64)
|
|
228
|
+
sum0 = np.zeros_like(first)
|
|
229
|
+
sumsq0 = np.zeros_like(first)
|
|
230
|
+
var1_total = 0.0
|
|
231
|
+
var2_total = 0.0
|
|
232
|
+
for start in range(0, n0, step):
|
|
233
|
+
chunk = img[start : start + step].astype(np.float64)
|
|
234
|
+
var1_total += float(np.var(chunk, axis=1).sum())
|
|
235
|
+
var2_total += float(np.var(chunk, axis=2).sum())
|
|
236
|
+
chunk -= first
|
|
237
|
+
sum0 += chunk.sum(axis=0)
|
|
238
|
+
sumsq0 += np.square(chunk, out=chunk).sum(axis=0)
|
|
239
|
+
var0 = float((sumsq0 / n0 - np.square(sum0 / n0)).mean())
|
|
240
|
+
var1 = var1_total / (n0 * img.shape[2])
|
|
241
|
+
var2 = var2_total / (n0 * img.shape[1])
|
|
242
|
+
return int(np.argmin([var0, var1, var2]))
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def check_output_array(out: Any, shape: tuple[int, ...]) -> np.ndarray:
|
|
246
|
+
"""Validate a user-supplied output array for :func:`store_frame`."""
|
|
247
|
+
if not isinstance(out, np.ndarray):
|
|
248
|
+
raise TypeError("out must be a numpy array (np.memmap is accepted)")
|
|
249
|
+
if out.shape != shape:
|
|
250
|
+
raise ValueError(f"out has shape {out.shape}, but the stack has shape {shape}")
|
|
251
|
+
if out.dtype.kind not in "fiu":
|
|
252
|
+
raise TypeError(
|
|
253
|
+
f"out must have a floating-point or integer dtype, got {out.dtype}"
|
|
254
|
+
)
|
|
255
|
+
if not out.flags.writeable:
|
|
256
|
+
raise ValueError("out is read-only")
|
|
257
|
+
return out
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def store_frame(out: np.ndarray, index: int, axis: int, frame: np.ndarray) -> None:
|
|
261
|
+
"""Write a transformed (float64) frame into ``out`` along ``axis``.
|
|
262
|
+
|
|
263
|
+
Integer outputs receive values rounded and clipped to the range of the
|
|
264
|
+
dtype (see :func:`pystackreg.util.to_int_dtype`); a plain cast would
|
|
265
|
+
truncate and wrap around.
|
|
266
|
+
"""
|
|
267
|
+
target: Any = [slice(None)] * out.ndim
|
|
268
|
+
target[axis] = index
|
|
269
|
+
if out.dtype.kind in "iu":
|
|
270
|
+
frame = to_int_dtype(frame, out.dtype.type)
|
|
271
|
+
out[tuple(target)] = frame
|
pystackreg/py.typed
ADDED
|
File without changes
|