oprunner 0.1.0.dev0__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.
oprunner/__init__.py ADDED
@@ -0,0 +1,49 @@
1
+ """oprunner: run ops in their own environments.
2
+
3
+ An op is an ordinary Python function carrying opspec's ``@op`` decorator,
4
+ which names the environment it needs. oprunner builds that environment with
5
+ Appose, starts a worker in it, and calls the op there; or tiles the call to
6
+ fit memory, or loops a 2-D op over a stack. The op itself never changes.
7
+
8
+ The top level of this package is deliberately austere -- standard library,
9
+ numpy and appose only -- because it is imported inside every op environment.
10
+ Anything heavier lives in a submodule that is imported lazily.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import sys
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ # oprunner's neighbours in a checkout are opspec and ophelper, kept beside it
20
+ # rather than in it: <checkout>/opspec/src, <checkout>/ophelper/src. A worker,
21
+ # the metadata service and Fiji all reach oprunner by putting its src/ on
22
+ # sys.path, so put their directories there too, and first, for the reason
23
+ # src/ goes first -- a checkout shadows the copy an environment installs. An
24
+ # installed oprunner has no such directories; there they are ordinary
25
+ # dependencies.
26
+ for _package in ("opspec", "ophelper"):
27
+ _checkout = Path(__file__).resolve().parents[3] / _package / "src"
28
+ if (_checkout / _package).is_dir() and str(_checkout) not in sys.path:
29
+ sys.path.insert(0, str(_checkout))
30
+
31
+ __all__ = ["Runner", "Tiler", "discover", "run"]
32
+
33
+ _LAZY = {
34
+ "Runner": "runner",
35
+ "run": "runner",
36
+ "discover": "discovery",
37
+ "Tiler": "_tiling",
38
+ }
39
+
40
+
41
+ def __getattr__(name: str) -> Any:
42
+ # Host-side machinery is imported on demand, so that merely importing
43
+ # oprunner inside a worker stays cheap.
44
+ module_name = _LAZY.get(name)
45
+ if module_name is None:
46
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
47
+ import importlib
48
+
49
+ return getattr(importlib.import_module(f".{module_name}", __name__), name)
oprunner/_adapt.py ADDED
@@ -0,0 +1,198 @@
1
+ """Fitting the array a caller has to the axes an op consumes.
2
+
3
+ An op says how many axes it consumes, and what it likes to call them, through
4
+ ``Axes`` in its annotations. A caller says what its array actually is, by
5
+ naming the array's axes. Neither of those is a decision; this module makes one,
6
+ as an ``AdaptationPlan`` -- an explicit, inspectable value a front end can show
7
+ a user, and hand back edited.
8
+
9
+ The plan is built best-effort and then *overridden*, rather than chosen from an
10
+ enumeration. Which of the caller's axes fills which slot, and what becomes of
11
+ the ones left over, is a per-axis decision belonging to whoever owns the data:
12
+ whether a stack should be processed plane by plane or as a volume is a property
13
+ of the experiment, not of the op. So oprunner picks a sensible default, says where
14
+ that default looks doubtful (``AdaptationPlan.warnings``), and forbids nothing.
15
+
16
+ Planning is pure arithmetic over axis names and shapes, so it happens on the
17
+ host. Execution happens in the worker, so that iterating forty planes is one
18
+ task rather than forty round trips.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from typing import Any
24
+
25
+ import numpy as np
26
+
27
+ from opspec.op import FUNCTION, OpSpec, Role
28
+
29
+ # Planning is opspec's: pure arithmetic over axis names and shapes, so it
30
+ # needs no numpy. What follows it here is execution, which touches pixels.
31
+ from opspec.plan import (
32
+ DISPOSITIONS,
33
+ ITERATE,
34
+ PASS,
35
+ SELECT,
36
+ AdaptationPlan,
37
+ _name,
38
+ build,
39
+ normalize_axes,
40
+ plan,
41
+ )
42
+ from opspec.runtime import cancel_requested, progress
43
+
44
+ __all__ = [
45
+ "DISPOSITIONS",
46
+ "ITERATE",
47
+ "PASS",
48
+ "SELECT",
49
+ "AdaptationPlan",
50
+ "apply",
51
+ "build",
52
+ "execute",
53
+ "normalize_axes",
54
+ "plan",
55
+ ]
56
+
57
+
58
+ # -- execution, in the worker -------------------------------------------
59
+
60
+
61
+ def apply(plan: AdaptationPlan, array: np.ndarray) -> np.ndarray:
62
+ """Index and transpose *array* into the layout the op declared."""
63
+ selected = dict(plan.select)
64
+ if selected:
65
+ array = array[
66
+ tuple(
67
+ selected[i] if i in selected else slice(None)
68
+ for i in range(len(plan.input_axes))
69
+ )
70
+ ]
71
+ return array.transpose(plan.transpose)
72
+
73
+
74
+ def execute(
75
+ spec: OpSpec,
76
+ fn: Any,
77
+ args: dict,
78
+ plans: dict[str, AdaptationPlan],
79
+ ) -> Any:
80
+ """Call *fn*, adapting its arguments and reassembling its results."""
81
+ if not plans:
82
+ return fn(**args)
83
+
84
+ iterated = [plan for plan in plans.values() if plan.iterate]
85
+
86
+ for name, param_plan in plans.items():
87
+ args[name] = apply(param_plan, np.asarray(args[name]))
88
+
89
+ if not iterated:
90
+ return fn(**args)
91
+
92
+ if spec.form != FUNCTION:
93
+ raise ValueError(
94
+ f"Op {spec.name} is {spec.form} form; iteration is implemented for "
95
+ "function-form ops only, since the caller's buffer has the shape "
96
+ "of the whole input rather than of one slice."
97
+ )
98
+
99
+ # Several inputs are looped over together, a slice of each per call -- a
100
+ # stack of nuclei and a stack of membranes, say -- so they must agree on
101
+ # how many slices there are.
102
+ stacks = {plan.param: args[plan.param] for plan in iterated}
103
+ spans = {
104
+ plan.param: tuple(stacks[plan.param].shape[: len(plan.iterate)])
105
+ for plan in iterated
106
+ }
107
+ if len(set(spans.values())) > 1:
108
+ shown = "; ".join(f"{name} {span}" for name, span in spans.items())
109
+ raise ValueError(
110
+ f"Op {spec.name}: inputs looped over together must have as many "
111
+ f"slices as each other, but they have {shown}"
112
+ )
113
+ plan = iterated[0]
114
+ span = spans[plan.param]
115
+ labels = [_name(plan.input_axes, i) for i in plan.iterate]
116
+ gathered: list[list] = [[] for _ in spec.outputs]
117
+
118
+ for step, index in enumerate(np.ndindex(*span)):
119
+ if cancel_requested():
120
+ raise RuntimeError(
121
+ f"Op {spec.name} was cancelled after {step} of {plan.calls} slices"
122
+ )
123
+ where = ", ".join(f"{label}={i}" for label, i in zip(labels, index))
124
+ progress(f"Slice {step + 1} of {plan.calls} ({where})", step, plan.calls)
125
+ for name, stack in stacks.items():
126
+ args[name] = stack[index]
127
+ for slot, value in enumerate(_split(spec, fn(**args))):
128
+ gathered[slot].append(value)
129
+
130
+ results = tuple(
131
+ _reassemble(spec.name, output.name, values, span, output.role)
132
+ for output, values in zip(spec.outputs, gathered)
133
+ )
134
+ if len(results) == 1:
135
+ return results[0]
136
+ factory = spec.return_type
137
+ if getattr(factory, "_fields", None) == tuple(o.name for o in spec.outputs):
138
+ return factory(*results)
139
+ return results
140
+
141
+
142
+ def _split(spec: OpSpec, result: Any) -> tuple:
143
+ """One call's return value, as one value per declared output."""
144
+ names = tuple(o.name for o in spec.outputs)
145
+ if len(names) == 1:
146
+ return (result,)
147
+ if result is None or len(result) != len(names):
148
+ got = "None" if result is None else str(len(result))
149
+ raise TypeError(
150
+ f"Op {spec.name} declares {len(names)} outputs {names} but one "
151
+ f"iteration returned {got} value(s)"
152
+ )
153
+ return tuple(result)
154
+
155
+
156
+ def _reassemble(
157
+ op_name: str,
158
+ output: str,
159
+ values: list,
160
+ span: tuple[int, ...],
161
+ role: Role | None,
162
+ ) -> Any:
163
+ """Stack one output slot's per-slice values back into a whole."""
164
+ if all(isinstance(value, np.ndarray) for value in values):
165
+ shapes = {value.shape for value in values}
166
+ if len(shapes) == 1:
167
+ if role is Role.labels:
168
+ values = _renumber(values)
169
+ return np.stack(values).reshape(span + shapes.pop())
170
+ raise TypeError(
171
+ f"Op {op_name}: output {output!r} cannot be stacked across slices, "
172
+ f"because its shape varies between them ({len(shapes)} distinct "
173
+ "shapes). Adapt this op with a single-slice plan instead."
174
+ )
175
+ if all(isinstance(value, (int, float, bool, np.number)) for value in values):
176
+ return np.array(values).reshape(span)
177
+ kinds = ", ".join(sorted({type(value).__name__ for value in values}))
178
+ raise TypeError(
179
+ f"Op {op_name}: output {output!r} cannot be stacked across slices; "
180
+ f"iteration reassembles arrays and numbers, not {kinds}."
181
+ )
182
+
183
+
184
+ def _renumber(values: list[np.ndarray]) -> list[np.ndarray]:
185
+ """Make label IDs unique across slices.
186
+
187
+ Every slice numbers its own objects from 1, so stacking as-is would claim
188
+ that object 1 in slice 0 and object 1 in slice 1 are the same cell. They
189
+ are not: iterating an axis is precisely the statement that the slices were
190
+ processed independently.
191
+ """
192
+ shifted = []
193
+ offset = 0
194
+ for value in values:
195
+ top = int(value.max()) if value.size else 0
196
+ shifted.append(np.where(value > 0, value + offset, 0) if offset else value)
197
+ offset += top
198
+ return shifted
oprunner/_codec.py ADDED
@@ -0,0 +1,126 @@
1
+ """Conversion between plain Python values and Appose wire values.
2
+
3
+ Runs on both sides of the process boundary, so it stays austere: standard
4
+ library, numpy, and appose only.
5
+
6
+ Conversion is done explicitly here rather than by registering a global
7
+ ``appose.util.message`` codec for ``numpy.ndarray``. A global registration
8
+ would reinterpret every bare array passed by any Appose user in the same
9
+ process, including code that has nothing to do with oprunner.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import contextlib
15
+ from enum import Enum
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ import numpy as np
20
+ from appose import NDArray, SharedMemory
21
+
22
+ # dtypes whose element size Appose can derive from the dtype name.
23
+ _UNSUPPORTED_HINT = (
24
+ "Supported dtypes are the sized numeric types (int8/16/32/64, "
25
+ "uint8/16/32/64, float16/32/64). Cast before returning; note that "
26
+ "'bool' has no size in its name and so cannot cross the boundary."
27
+ )
28
+
29
+
30
+ def encode(value: Any, refs: list) -> Any:
31
+ """Convert a Python value into something Appose can put on the wire.
32
+
33
+ Any shared memory allocated along the way is appended to ``refs``, which
34
+ the caller must keep alive until the message has been sent.
35
+ """
36
+ if isinstance(value, np.ndarray):
37
+ return _to_ndarray(value, refs)
38
+ if isinstance(value, NDArray):
39
+ return value
40
+ if isinstance(value, Enum):
41
+ return value.value
42
+ if isinstance(value, Path):
43
+ return str(value)
44
+ if isinstance(value, dict):
45
+ return {k: encode(v, refs) for k, v in value.items()}
46
+ if isinstance(value, (list, tuple)):
47
+ return [encode(v, refs) for v in value]
48
+ if isinstance(value, np.generic):
49
+ # numpy scalar -- json cannot encode it, but its Python peer is fine.
50
+ return value.item()
51
+ return value
52
+
53
+
54
+ def decode(value: Any, refs: list) -> Any:
55
+ """Convert a value received from Appose back into plain Python.
56
+
57
+ Arrays are returned as views onto shared memory, with no copy. The
58
+ backing ``NDArray`` objects are appended to ``refs``; the caller must
59
+ keep them alive for as long as the views are in use.
60
+ """
61
+ if isinstance(value, NDArray):
62
+ refs.append(value)
63
+ return value.ndarray()
64
+ if isinstance(value, dict):
65
+ return {k: decode(v, refs) for k, v in value.items()}
66
+ if isinstance(value, list):
67
+ return [decode(v, refs) for v in value]
68
+ return value
69
+
70
+
71
+ def _to_ndarray(array: np.ndarray, refs: list) -> NDArray:
72
+ dtype = str(array.dtype)
73
+ _check_dtype(dtype)
74
+ shape = list(array.shape)
75
+ if array.size == 0:
76
+ # A shared memory block must have a positive size, but an empty result
77
+ # is ordinary -- a segmentation that finds nothing returns one. Carry
78
+ # the shape and dtype over a token block; numpy is happy to view zero
79
+ # elements of it.
80
+ nda = NDArray(dtype, shape, SharedMemory(create=True, rsize=1))
81
+ else:
82
+ nda = NDArray(dtype, shape)
83
+ refs.append(nda)
84
+ # The one unavoidable copy: an arbitrary array is not already in shared
85
+ # memory. Callers who allocate via oprunner can skip it.
86
+ nda.ndarray()[...] = array
87
+ return nda
88
+
89
+
90
+ def _check_dtype(dtype: str) -> None:
91
+ if not any(ch.isdigit() for ch in dtype):
92
+ raise TypeError(
93
+ f"Cannot transfer arrays of dtype '{dtype}'. {_UNSUPPORTED_HINT}"
94
+ )
95
+
96
+
97
+ def copy_out(value: Any) -> Any:
98
+ """Deep-copy shared-memory views into ordinary process-local arrays.
99
+
100
+ Used on results before their shared memory is released.
101
+ """
102
+ if isinstance(value, np.ndarray):
103
+ return np.array(value, copy=True)
104
+ if isinstance(value, dict):
105
+ return {k: copy_out(v) for k, v in value.items()}
106
+ if isinstance(value, list):
107
+ return [copy_out(v) for v in value]
108
+ return value
109
+
110
+
111
+ def release(refs: list, unlink: bool) -> None:
112
+ """Dispose of shared memory blocks held by ``refs``.
113
+
114
+ Appose's rule is that the service process cleans up shared memory
115
+ regardless of which process allocated it, so the host passes
116
+ ``unlink=True`` and the worker never unlinks.
117
+ """
118
+ for ref in refs:
119
+ shm = getattr(ref, "shm", None)
120
+ if shm is None:
121
+ continue
122
+ # Cleanup is best effort: a block the peer already released must not
123
+ # take down an otherwise successful call.
124
+ with contextlib.suppress(Exception):
125
+ shm.unlink_on_dispose(unlink)
126
+ shm.dispose()