viva-basic-processes 0.4.1__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.
- pbg_basic_processes/__init__.py +87 -0
- viva_basic_processes/__init__.py +48 -0
- viva_basic_processes/clock.py +75 -0
- viva_basic_processes/intervention.py +163 -0
- viva_basic_processes/math_expression.py +201 -0
- viva_basic_processes/plotting.py +127 -0
- viva_basic_processes/tick.py +77 -0
- viva_basic_processes/time_series.py +61 -0
- viva_basic_processes-0.4.1.dist-info/METADATA +91 -0
- viva_basic_processes-0.4.1.dist-info/RECORD +13 -0
- viva_basic_processes-0.4.1.dist-info/WHEEL +5 -0
- viva_basic_processes-0.4.1.dist-info/licenses/LICENSE +21 -0
- viva_basic_processes-0.4.1.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Back-compat shim: ``pbg_basic_processes`` was renamed to ``viva_basic_processes``.
|
|
2
|
+
|
|
3
|
+
The import package was renamed as part of the pbg -> viva rebrand. This shim keeps
|
|
4
|
+
every existing consumer working during the deprecation window (Phase 1 of the
|
|
5
|
+
rename):
|
|
6
|
+
|
|
7
|
+
* ``import pbg_basic_processes`` / ``from pbg_basic_processes import X`` works
|
|
8
|
+
(re-exports the new package's top-level ``__all__``);
|
|
9
|
+
* ``import pbg_basic_processes.<sub>`` transparently resolves to
|
|
10
|
+
``viva_basic_processes.<sub>`` via a meta-path finder; and
|
|
11
|
+
* ``python -m pbg_basic_processes.<sub>`` still executes (``get_code`` forwards
|
|
12
|
+
the real module's code object to ``runpy``).
|
|
13
|
+
|
|
14
|
+
Importing anything under this package emits a one-time
|
|
15
|
+
:class:`DeprecationWarning`. Update imports to ``viva_basic_processes``; this shim
|
|
16
|
+
is removed in a future major release. (A ``pbg-basic-processes`` distribution shim
|
|
17
|
+
also ships under ``shim/`` so existing dependency strings keep resolving.)
|
|
18
|
+
"""
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import importlib
|
|
22
|
+
import importlib.abc
|
|
23
|
+
import importlib.util
|
|
24
|
+
import sys
|
|
25
|
+
import warnings
|
|
26
|
+
|
|
27
|
+
warnings.warn(
|
|
28
|
+
"pbg_basic_processes is renamed to viva_basic_processes; update your imports "
|
|
29
|
+
"(the pbg_basic_processes alias is removed in a future major release).",
|
|
30
|
+
DeprecationWarning,
|
|
31
|
+
stacklevel=2,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
_OLD = "pbg_basic_processes."
|
|
35
|
+
_NEW = "viva_basic_processes."
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class _Redirect(importlib.abc.MetaPathFinder, importlib.abc.Loader):
|
|
39
|
+
"""Forward ``pbg_basic_processes.<sub>`` imports to ``viva_basic_processes.<sub>``.
|
|
40
|
+
|
|
41
|
+
``create_module``/``exec_module`` handle ordinary ``import`` (the imported
|
|
42
|
+
submodule object is aliased into ``sys.modules`` under both names), while
|
|
43
|
+
``get_code`` lets ``python -m pbg_basic_processes.<sub>`` execute the real
|
|
44
|
+
module's code object as ``__main__``.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
def _target(self, name: str) -> str:
|
|
48
|
+
return _NEW + name[len(_OLD):]
|
|
49
|
+
|
|
50
|
+
def find_spec(self, name, path=None, target=None):
|
|
51
|
+
if not name.startswith(_OLD):
|
|
52
|
+
return None
|
|
53
|
+
real = importlib.util.find_spec(self._target(name))
|
|
54
|
+
if real is None:
|
|
55
|
+
return None
|
|
56
|
+
spec = importlib.util.spec_from_loader(
|
|
57
|
+
name,
|
|
58
|
+
self,
|
|
59
|
+
origin=real.origin,
|
|
60
|
+
is_package=real.submodule_search_locations is not None,
|
|
61
|
+
)
|
|
62
|
+
if real.submodule_search_locations is not None:
|
|
63
|
+
spec.submodule_search_locations = list(real.submodule_search_locations)
|
|
64
|
+
return spec
|
|
65
|
+
|
|
66
|
+
def create_module(self, spec):
|
|
67
|
+
# Alias the fully-initialized new-package module under BOTH names so
|
|
68
|
+
# `import a.b` and identity checks against either name agree.
|
|
69
|
+
mod = importlib.import_module(self._target(spec.name))
|
|
70
|
+
sys.modules[spec.name] = mod
|
|
71
|
+
return mod
|
|
72
|
+
|
|
73
|
+
def exec_module(self, module): # already executed by import_module
|
|
74
|
+
pass
|
|
75
|
+
|
|
76
|
+
def get_code(self, name):
|
|
77
|
+
# Support `python -m pbg_basic_processes.<sub>`: runpy needs a code object.
|
|
78
|
+
target = self._target(name)
|
|
79
|
+
return importlib.util.find_spec(target).loader.get_code(target)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
sys.meta_path.insert(0, _Redirect())
|
|
83
|
+
|
|
84
|
+
_viva = importlib.import_module("viva_basic_processes")
|
|
85
|
+
__version__ = getattr(_viva, "__version__", "0.1.0")
|
|
86
|
+
# Re-export the new package's public surface.
|
|
87
|
+
globals().update({k: getattr(_viva, k) for k in getattr(_viva, "__all__", [])})
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""viva-basic-processes: reusable, composite-agnostic process-bigraph processes.
|
|
2
|
+
|
|
3
|
+
These processes auto-register into any workspace ``core`` via bigraph-schema
|
|
4
|
+
package discovery (``allocate_core`` walks every installed ``bigraph-schema``
|
|
5
|
+
dependent and registers its ``Process`` / ``Step`` subclasses) — no entry
|
|
6
|
+
points or ``register_*`` boilerplate required. Add ``viva-basic-processes`` as a
|
|
7
|
+
dependency and ``Clock`` / ``Intervention`` / ``MathExpressionStep`` appear in
|
|
8
|
+
the registry, the same way ``viva-emitters`` surfaces its emitters.
|
|
9
|
+
|
|
10
|
+
(Was ``pbg-basic-processes`` before the pbg -> viva rename; a ``pbg_basic_processes``
|
|
11
|
+
import shim still ships for back-compat.)
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from viva_basic_processes.clock import Clock, register_clock, clock_node
|
|
15
|
+
from viva_basic_processes.tick import Tick, register_tick, tick_node
|
|
16
|
+
from viva_basic_processes.intervention import (
|
|
17
|
+
Intervention,
|
|
18
|
+
register_intervention,
|
|
19
|
+
intervention_node,
|
|
20
|
+
)
|
|
21
|
+
from viva_basic_processes.time_series import TimeSeriesStep
|
|
22
|
+
|
|
23
|
+
try:
|
|
24
|
+
from viva_basic_processes.math_expression import MathExpressionStep
|
|
25
|
+
except ImportError: # pragma: no cover - sympy is a base dep, but stay defensive
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
# Plotting helpers (plot_timeseries / plot_single_eval) live in
|
|
29
|
+
# viva_basic_processes.plotting and require the optional ``[plotting]`` extra
|
|
30
|
+
# (matplotlib). Import them here for convenience, but stay importable without
|
|
31
|
+
# matplotlib installed — the helpers raise a clear error only when called.
|
|
32
|
+
from viva_basic_processes.plotting import plot_timeseries, plot_single_eval
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
"Clock",
|
|
36
|
+
"register_clock",
|
|
37
|
+
"clock_node",
|
|
38
|
+
"Tick",
|
|
39
|
+
"register_tick",
|
|
40
|
+
"tick_node",
|
|
41
|
+
"Intervention",
|
|
42
|
+
"register_intervention",
|
|
43
|
+
"intervention_node",
|
|
44
|
+
"MathExpressionStep",
|
|
45
|
+
"TimeSeriesStep",
|
|
46
|
+
"plot_timeseries",
|
|
47
|
+
"plot_single_eval",
|
|
48
|
+
]
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""A minimal Clock process — an integer step counter.
|
|
2
|
+
|
|
3
|
+
process-bigraph's engine already maintains ``global_time`` (absolute simulation
|
|
4
|
+
time, a float) as a reserved store in *every* composite: wire any process input
|
|
5
|
+
to ``['global_time']`` to read it — no Clock required (see
|
|
6
|
+
:class:`viva_basic_processes.intervention.Intervention`'s ``use_global_time``).
|
|
7
|
+
|
|
8
|
+
What the engine does **not** track as a wireable store is a discrete *step
|
|
9
|
+
count*. That is ``Clock``'s job: it takes no inputs and emits ``tick`` (int),
|
|
10
|
+
incremented every update, so processes can schedule on "every N steps" or count
|
|
11
|
+
elapsed updates. Writing to the reserved ``global_time`` store is deliberately
|
|
12
|
+
avoided — doing so corrupts the engine's master clock.
|
|
13
|
+
|
|
14
|
+
Pure process-bigraph; no heavy dependencies. Auto-registers into any workspace
|
|
15
|
+
``core`` via bigraph-schema package discovery.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from typing import Any, Optional
|
|
20
|
+
|
|
21
|
+
from process_bigraph import Process
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Clock(Process):
|
|
25
|
+
"""Emit an integer ``tick`` step counter each update.
|
|
26
|
+
|
|
27
|
+
(For absolute simulation time, read the engine-maintained ``global_time``
|
|
28
|
+
store directly — see the module docstring.)
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
config_schema = {
|
|
32
|
+
'start_tick': {'_type': 'integer', '_default': 0},
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
def __init__(self, config: Optional[dict] = None, core: Any = None) -> None:
|
|
36
|
+
super().__init__(config, core)
|
|
37
|
+
self._tick = int(self.config.get('start_tick', 0))
|
|
38
|
+
|
|
39
|
+
def inputs(self):
|
|
40
|
+
return {}
|
|
41
|
+
|
|
42
|
+
def outputs(self):
|
|
43
|
+
return {'tick': 'overwrite[integer]'}
|
|
44
|
+
|
|
45
|
+
def update(self, state, interval):
|
|
46
|
+
self._tick += 1
|
|
47
|
+
return {'tick': self._tick}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def register_clock(core: Any, name: str = 'Clock') -> bool:
|
|
51
|
+
"""Register :class:`Clock` into ``core`` (via ``register_link``). No-op-safe;
|
|
52
|
+
returns True when newly registered, False if already present or on error."""
|
|
53
|
+
try:
|
|
54
|
+
link_reg = getattr(core, 'link_registry', {}) or {}
|
|
55
|
+
if name in link_reg:
|
|
56
|
+
return False
|
|
57
|
+
core.register_link(name, Clock)
|
|
58
|
+
return True
|
|
59
|
+
except Exception:
|
|
60
|
+
return False
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def clock_node(*, start_tick: int = 0, interval: float = 1.0,
|
|
64
|
+
tick_path=('tick',), address: str = 'local:Clock') -> dict:
|
|
65
|
+
"""Build a process-bigraph node dict for a :class:`Clock`, ready to drop into
|
|
66
|
+
a composite's ``state``. ``tick_path`` is the store the clock writes its
|
|
67
|
+
``tick`` output to."""
|
|
68
|
+
return {
|
|
69
|
+
'_type': 'process',
|
|
70
|
+
'address': address,
|
|
71
|
+
'config': {'start_tick': int(start_tick)},
|
|
72
|
+
'interval': interval,
|
|
73
|
+
'inputs': {},
|
|
74
|
+
'outputs': {'tick': list(tick_path)},
|
|
75
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""A reusable Intervention process.
|
|
2
|
+
|
|
3
|
+
Investigations repeatedly need to apply a *specific perturbation* to a model —
|
|
4
|
+
clamp a quantity, knock a store to zero, externally supply something, scale a
|
|
5
|
+
pool — to build negative controls and test counterfactuals (the kind of
|
|
6
|
+
controls a skeptical reviewer asks for). Rather than hand-write a bespoke
|
|
7
|
+
process per perturbation, ``pbg-basic-processes`` ships one generic
|
|
8
|
+
``Intervention`` process that any workspace can wire into a composite.
|
|
9
|
+
|
|
10
|
+
Wire it into a composite by pointing its single ``target`` port at the store to
|
|
11
|
+
perturb; it reads the current value and emits the additive delta needed to
|
|
12
|
+
realise the perturbation, optionally only within a time window.
|
|
13
|
+
|
|
14
|
+
Modes (config ``mode``):
|
|
15
|
+
|
|
16
|
+
- ``set`` — drive the target to ``value`` every step (a clamp).
|
|
17
|
+
- ``knockout`` — drive the target to 0 (``set`` with value 0).
|
|
18
|
+
- ``scale`` — multiply the target by ``value`` (factor) each step.
|
|
19
|
+
- ``add`` — add ``value`` each step; with ``per_step: true`` it adds
|
|
20
|
+
``value * interval`` (a rate) instead of a fixed bolus.
|
|
21
|
+
- ``decouple`` (alias ``remove``) — freeze the target at its value when the
|
|
22
|
+
intervention *first became active*, severing this process's net
|
|
23
|
+
contribution without nulling the pool (``delta = frozen - current``).
|
|
24
|
+
- ``invert`` — flip the coupling sign each step: ``delta = -2 * current`` drives
|
|
25
|
+
the store toward ``-current``.
|
|
26
|
+
|
|
27
|
+
``window: [t0, t1]`` (optional) restricts the intervention to ``t0 <= t < t1``.
|
|
28
|
+
By default ``t`` is the process's own elapsed time (accumulated across
|
|
29
|
+
``update`` calls). Set ``use_global_time: true`` and wire the ``global_time``
|
|
30
|
+
input to a :class:`viva_basic_processes.clock.Clock` to gate on *absolute*
|
|
31
|
+
simulation time instead. Omitted/empty window ⇒ always active.
|
|
32
|
+
|
|
33
|
+
Pure process-bigraph; no AI. Auto-registers into any workspace ``core`` via
|
|
34
|
+
bigraph-schema package discovery; or register explicitly with
|
|
35
|
+
:func:`register_intervention` and add a node with :func:`intervention_node`.
|
|
36
|
+
"""
|
|
37
|
+
from __future__ import annotations
|
|
38
|
+
|
|
39
|
+
from typing import Any, Optional
|
|
40
|
+
|
|
41
|
+
from process_bigraph import Process
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Intervention(Process):
|
|
45
|
+
"""Apply a specific perturbation to one target store (see module docstring)."""
|
|
46
|
+
|
|
47
|
+
config_schema = {
|
|
48
|
+
'mode': {'_type': 'string', '_default': 'set'}, # set|knockout|scale|add|decouple(remove)|invert
|
|
49
|
+
'value': {'_type': 'float', '_default': 0.0},
|
|
50
|
+
'window': {'_type': 'list', '_default': []}, # [t0, t1] or []
|
|
51
|
+
'per_step': {'_type': 'boolean', '_default': False}, # add-mode: value*interval
|
|
52
|
+
'use_global_time': {'_type': 'boolean', '_default': False}, # gate window on a wired Clock
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
def __init__(self, config: Optional[dict] = None, core: Any = None) -> None:
|
|
56
|
+
super().__init__(config, core)
|
|
57
|
+
# Elapsed process time, accumulated across update() calls so a `window`
|
|
58
|
+
# can gate the intervention without a global-time wire.
|
|
59
|
+
self._elapsed = 0.0
|
|
60
|
+
# decouple/remove: the target value captured the first step the
|
|
61
|
+
# intervention is active; None until then.
|
|
62
|
+
self._frozen = None
|
|
63
|
+
|
|
64
|
+
def inputs(self):
|
|
65
|
+
ports = {'target': 'float'}
|
|
66
|
+
if self.config.get('use_global_time'):
|
|
67
|
+
ports['global_time'] = 'float'
|
|
68
|
+
return ports
|
|
69
|
+
|
|
70
|
+
def outputs(self):
|
|
71
|
+
return {'target': 'float'}
|
|
72
|
+
|
|
73
|
+
def update(self, state, interval):
|
|
74
|
+
if self.config.get('use_global_time'):
|
|
75
|
+
# Gate on absolute simulation time from a wired Clock.
|
|
76
|
+
t = float(state.get('global_time', 0.0) or 0.0)
|
|
77
|
+
else:
|
|
78
|
+
t = self._elapsed
|
|
79
|
+
self._elapsed += interval
|
|
80
|
+
|
|
81
|
+
window = self.config.get('window') or []
|
|
82
|
+
if isinstance(window, (list, tuple)) and len(window) == 2:
|
|
83
|
+
t0, t1 = window
|
|
84
|
+
if not (t0 <= t < t1):
|
|
85
|
+
return {}
|
|
86
|
+
|
|
87
|
+
current = state.get('target', 0.0) or 0.0
|
|
88
|
+
mode = (self.config.get('mode') or 'set').lower()
|
|
89
|
+
value = self.config.get('value', 0.0)
|
|
90
|
+
|
|
91
|
+
if mode == 'set':
|
|
92
|
+
delta = value - current
|
|
93
|
+
elif mode == 'knockout':
|
|
94
|
+
delta = -current
|
|
95
|
+
elif mode == 'scale':
|
|
96
|
+
delta = current * (value - 1.0)
|
|
97
|
+
elif mode == 'add':
|
|
98
|
+
delta = value * interval if self.config.get('per_step') else value
|
|
99
|
+
elif mode in ('decouple', 'remove'):
|
|
100
|
+
# Freeze at the value the target held when first active.
|
|
101
|
+
if self._frozen is None:
|
|
102
|
+
self._frozen = current
|
|
103
|
+
delta = self._frozen - current
|
|
104
|
+
elif mode == 'invert':
|
|
105
|
+
delta = -2.0 * current
|
|
106
|
+
else:
|
|
107
|
+
delta = 0.0
|
|
108
|
+
|
|
109
|
+
return {'target': delta}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def register_intervention(core: Any, name: str = 'Intervention') -> bool:
|
|
113
|
+
"""Register :class:`Intervention` into ``core`` (via ``register_link``) so a
|
|
114
|
+
composite can reference ``local:Intervention``. No-op-safe; returns True when
|
|
115
|
+
newly registered, False if already present or on error."""
|
|
116
|
+
try:
|
|
117
|
+
link_reg = getattr(core, 'link_registry', {}) or {}
|
|
118
|
+
if name in link_reg:
|
|
119
|
+
return False
|
|
120
|
+
core.register_link(name, Intervention)
|
|
121
|
+
return True
|
|
122
|
+
except Exception:
|
|
123
|
+
return False
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def intervention_node(target_path, *, mode: str = 'set', value: float = 0.0,
|
|
127
|
+
window=None, per_step: bool = False, interval: float = 1.0,
|
|
128
|
+
use_global_time: bool = False, global_time_path=('global_time',),
|
|
129
|
+
address: str = 'local:Intervention') -> dict:
|
|
130
|
+
"""Build a process-bigraph node dict for an Intervention, ready to drop into
|
|
131
|
+
a composite's ``state``.
|
|
132
|
+
|
|
133
|
+
``target_path`` is the path (list of keys) to the store to perturb; it is
|
|
134
|
+
wired to both the input and output ``target`` port so the process reads the
|
|
135
|
+
current value and writes the corrective delta.
|
|
136
|
+
|
|
137
|
+
Set ``use_global_time=True`` to gate the ``window`` on absolute simulation
|
|
138
|
+
time; ``global_time_path`` is then wired to a :class:`Clock`'s
|
|
139
|
+
``global_time`` store.
|
|
140
|
+
|
|
141
|
+
Example::
|
|
142
|
+
|
|
143
|
+
state['clamp_nutrient'] = intervention_node(
|
|
144
|
+
['nutrient'], mode='set', value=0.0) # externally hold nutrient at 0
|
|
145
|
+
"""
|
|
146
|
+
if isinstance(target_path, str):
|
|
147
|
+
target_path = [target_path]
|
|
148
|
+
config = {'mode': mode, 'value': float(value), 'per_step': bool(per_step)}
|
|
149
|
+
if window:
|
|
150
|
+
config['window'] = list(window)
|
|
151
|
+
inputs = {'target': list(target_path)}
|
|
152
|
+
outputs = {'target': list(target_path)}
|
|
153
|
+
if use_global_time:
|
|
154
|
+
config['use_global_time'] = True
|
|
155
|
+
inputs['global_time'] = list(global_time_path)
|
|
156
|
+
return {
|
|
157
|
+
'_type': 'process',
|
|
158
|
+
'address': address,
|
|
159
|
+
'config': config,
|
|
160
|
+
'interval': interval,
|
|
161
|
+
'inputs': inputs,
|
|
162
|
+
'outputs': outputs,
|
|
163
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""A MathExpression Step: evaluate named symbolic expressions as one Step.
|
|
2
|
+
|
|
3
|
+
Configure a list of ``{"out": <name>, "expr": <string>}`` entries. The Step
|
|
4
|
+
parses each expression with SymPy, infers its input ports from the free symbols
|
|
5
|
+
(anything that isn't another output or a declared param), evaluates the
|
|
6
|
+
expressions in dependency-respecting topological order, and writes an overwrite
|
|
7
|
+
patch for every output. Expressions may reference other outputs; algebraic
|
|
8
|
+
cycles raise a ``ValueError`` with a dependency hint.
|
|
9
|
+
|
|
10
|
+
Pure process-bigraph + SymPy; no plotting or I/O. Auto-registers into any
|
|
11
|
+
workspace ``core`` via bigraph-schema package discovery.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import sympy as sp
|
|
16
|
+
|
|
17
|
+
from process_bigraph import Step
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class MathExpressionStep(Step):
|
|
21
|
+
"""Evaluate a set of user-configured mathematical expressions as a single Step.
|
|
22
|
+
|
|
23
|
+
Configuration
|
|
24
|
+
-------------
|
|
25
|
+
expressions : list[dict]
|
|
26
|
+
List of ``{"out": <str>, "expr": <str>}`` entries. Each ``out`` becomes
|
|
27
|
+
an output port and state field.
|
|
28
|
+
params : dict[str, float], optional
|
|
29
|
+
Named constants available to expressions without becoming input ports.
|
|
30
|
+
functions : str, optional
|
|
31
|
+
SymPy ``lambdify`` backend module name (default ``"numpy"``).
|
|
32
|
+
debug : bool, optional
|
|
33
|
+
If True, prints inferred ports, dependency order, and compilation details.
|
|
34
|
+
|
|
35
|
+
Notes
|
|
36
|
+
-----
|
|
37
|
+
Single-pass evaluation in dependency order; not a simultaneous-equation
|
|
38
|
+
solver. Cyclic dependencies require a different approach (fixed-point
|
|
39
|
+
iteration or root finding).
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
config_schema = {
|
|
43
|
+
"expressions": "node", # list[{"out": str, "expr": str}]
|
|
44
|
+
"params": {"_type": "node", "_default": {}},
|
|
45
|
+
"functions": {"_type": "string", "_default": "numpy"},
|
|
46
|
+
"debug": {"_type": "boolean", "_default": False},
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
def initialize(self, config=None):
|
|
50
|
+
cfg = self.config
|
|
51
|
+
debug = bool(cfg.get("debug", False))
|
|
52
|
+
|
|
53
|
+
expr_specs = cfg.get("expressions", None)
|
|
54
|
+
if not isinstance(expr_specs, (list, tuple)) or len(expr_specs) == 0:
|
|
55
|
+
raise ValueError("MathExpressionStep requires config['expressions'] as a non-empty list")
|
|
56
|
+
|
|
57
|
+
self._params = dict(cfg.get("params", {}))
|
|
58
|
+
backend = cfg.get("functions", "numpy")
|
|
59
|
+
|
|
60
|
+
# Validate + parse
|
|
61
|
+
out_names = []
|
|
62
|
+
expr_map = {} # out -> sympy expr
|
|
63
|
+
raw_map = {} # out -> expr string (for debugging)
|
|
64
|
+
for spec in expr_specs:
|
|
65
|
+
out = spec.get("out", None)
|
|
66
|
+
expr_str = spec.get("expr", None)
|
|
67
|
+
if not isinstance(out, str) or not out:
|
|
68
|
+
raise ValueError("Each expression spec must have a non-empty string 'out'")
|
|
69
|
+
if not isinstance(expr_str, str) or not expr_str:
|
|
70
|
+
raise ValueError(f"Expression for '{out}' must be a non-empty string")
|
|
71
|
+
if out in expr_map:
|
|
72
|
+
raise ValueError(f"Duplicate output name: '{out}'")
|
|
73
|
+
|
|
74
|
+
try:
|
|
75
|
+
expr = sp.sympify(expr_str)
|
|
76
|
+
except Exception as e:
|
|
77
|
+
raise ValueError(f"Failed to parse expression for '{out}': {expr_str}\n{e}") from e
|
|
78
|
+
|
|
79
|
+
out_names.append(out)
|
|
80
|
+
expr_map[out] = expr
|
|
81
|
+
raw_map[out] = expr_str
|
|
82
|
+
|
|
83
|
+
self._out_names = out_names
|
|
84
|
+
out_set = set(out_names)
|
|
85
|
+
param_set = set(self._params.keys())
|
|
86
|
+
|
|
87
|
+
# Build dependency graph among outputs
|
|
88
|
+
# deps[out] = set of output-names that out depends on
|
|
89
|
+
deps = {out: set() for out in out_names}
|
|
90
|
+
external_inputs = set()
|
|
91
|
+
|
|
92
|
+
for out, expr in expr_map.items():
|
|
93
|
+
free = {str(s) for s in expr.free_symbols}
|
|
94
|
+
|
|
95
|
+
# outputs referenced become dependencies
|
|
96
|
+
deps[out] = {name for name in free if name in out_set and name != out}
|
|
97
|
+
|
|
98
|
+
# anything else that isn't a param and isn't an output is an external input port
|
|
99
|
+
external_inputs |= {name for name in free if name not in out_set and name not in param_set}
|
|
100
|
+
|
|
101
|
+
# Topological sort (Kahn) to get execution order
|
|
102
|
+
indeg = {o: 0 for o in out_names}
|
|
103
|
+
for o in out_names:
|
|
104
|
+
for d in deps[o]:
|
|
105
|
+
indeg[o] += 1
|
|
106
|
+
|
|
107
|
+
# Start with nodes that have no dependencies.
|
|
108
|
+
# Use sorted() for deterministic order.
|
|
109
|
+
queue = [o for o in sorted(out_names) if indeg[o] == 0]
|
|
110
|
+
exec_order = []
|
|
111
|
+
|
|
112
|
+
# adjacency: who depends on me
|
|
113
|
+
rev = {o: set() for o in out_names}
|
|
114
|
+
for o in out_names:
|
|
115
|
+
for d in deps[o]:
|
|
116
|
+
rev[d].add(o)
|
|
117
|
+
|
|
118
|
+
while queue:
|
|
119
|
+
n = queue.pop(0)
|
|
120
|
+
exec_order.append(n)
|
|
121
|
+
for m in sorted(rev[n]):
|
|
122
|
+
indeg[m] -= 1
|
|
123
|
+
if indeg[m] == 0:
|
|
124
|
+
queue.append(m)
|
|
125
|
+
|
|
126
|
+
if len(exec_order) != len(out_names):
|
|
127
|
+
# cycle exists
|
|
128
|
+
remaining = [o for o in out_names if o not in exec_order]
|
|
129
|
+
# give a helpful hint about the cycle region
|
|
130
|
+
cycle_hint = {o: sorted(list(deps[o])) for o in remaining}
|
|
131
|
+
raise ValueError(
|
|
132
|
+
"Cyclic dependency between expressions. Cannot order outputs.\n"
|
|
133
|
+
f"Remaining outputs: {remaining}\n"
|
|
134
|
+
f"Dependencies among remaining: {cycle_hint}"
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
self._exec_order = exec_order
|
|
138
|
+
self._in_names = sorted(external_inputs)
|
|
139
|
+
|
|
140
|
+
# Compile each expression with *just the symbols it needs* (deterministic arg list)
|
|
141
|
+
self._compiled = {} # out -> callable
|
|
142
|
+
self._needed_symbols = {} # out -> list[str] (argument names)
|
|
143
|
+
for out in out_names:
|
|
144
|
+
expr = expr_map[out]
|
|
145
|
+
needed = sorted({str(s) for s in expr.free_symbols})
|
|
146
|
+
fn = sp.lambdify([sp.Symbol(n) for n in needed], expr, modules=backend)
|
|
147
|
+
self._compiled[out] = fn
|
|
148
|
+
self._needed_symbols[out] = needed
|
|
149
|
+
|
|
150
|
+
if debug:
|
|
151
|
+
print("\n[MathExpressionStep] initialize()")
|
|
152
|
+
print(" outputs declared:", self._out_names)
|
|
153
|
+
print(" params:", self._params)
|
|
154
|
+
print(" inferred input ports:", self._in_names)
|
|
155
|
+
print(" dependency order:", self._exec_order)
|
|
156
|
+
for out in self._exec_order:
|
|
157
|
+
print(f" - {out} = {raw_map[out]}")
|
|
158
|
+
print(f" depends on outputs: {sorted(list(deps[out]))}")
|
|
159
|
+
print(f" needs symbols : {self._needed_symbols[out]}")
|
|
160
|
+
print("[MathExpressionStep] initialize complete\n")
|
|
161
|
+
|
|
162
|
+
return cfg
|
|
163
|
+
|
|
164
|
+
def inputs(self):
|
|
165
|
+
return {name: "float" for name in self._in_names}
|
|
166
|
+
|
|
167
|
+
def outputs(self):
|
|
168
|
+
# all declared outputs are ports, regardless of execution order
|
|
169
|
+
return {name: "overwrite[float]" for name in self._out_names}
|
|
170
|
+
|
|
171
|
+
def update(self, state):
|
|
172
|
+
# Values available for expression evaluation
|
|
173
|
+
values = {}
|
|
174
|
+
|
|
175
|
+
# External input ports come from state
|
|
176
|
+
for name in self._in_names:
|
|
177
|
+
values[name] = float(state[name])
|
|
178
|
+
|
|
179
|
+
# Params are constants
|
|
180
|
+
for k, v in self._params.items():
|
|
181
|
+
values[k] = float(v)
|
|
182
|
+
|
|
183
|
+
# Evaluate in dependency order
|
|
184
|
+
out_patch = {}
|
|
185
|
+
for out in self._exec_order:
|
|
186
|
+
needed = self._needed_symbols[out]
|
|
187
|
+
args = []
|
|
188
|
+
for name in needed:
|
|
189
|
+
if name not in values:
|
|
190
|
+
raise ValueError(
|
|
191
|
+
f"While computing '{out}', missing symbol '{name}'. "
|
|
192
|
+
f"(Likely an internal dependency not yet computed or missing input/param.)"
|
|
193
|
+
)
|
|
194
|
+
args.append(values[name])
|
|
195
|
+
|
|
196
|
+
y = self._compiled[out](*args)
|
|
197
|
+
y = float(y)
|
|
198
|
+
values[out] = y
|
|
199
|
+
out_patch[out] = y
|
|
200
|
+
|
|
201
|
+
return out_patch
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Small matplotlib plotting helpers for process-bigraph records.
|
|
2
|
+
|
|
3
|
+
These are convenience utilities for notebooks and tutorials — ``plot_timeseries``
|
|
4
|
+
(line plots of emitted records over a time column) and ``plot_single_eval`` (a
|
|
5
|
+
bar chart of a single step's inputs/outputs, optionally vs. expected values).
|
|
6
|
+
|
|
7
|
+
matplotlib is an *optional* dependency: it is imported lazily inside each
|
|
8
|
+
function so that ``import viva_basic_processes`` (and the auto-registration of
|
|
9
|
+
the processes) never requires it. Install the extra to use these helpers::
|
|
10
|
+
|
|
11
|
+
pip install "viva-basic-processes[plotting]"
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _require_matplotlib():
|
|
19
|
+
try:
|
|
20
|
+
import matplotlib.pyplot as plt # noqa: WPS433 (lazy import by design)
|
|
21
|
+
except ImportError as exc: # pragma: no cover - exercised only without the extra
|
|
22
|
+
raise ImportError(
|
|
23
|
+
"matplotlib is required for viva_basic_processes.plotting. "
|
|
24
|
+
"Install it with: pip install 'viva-basic-processes[plotting]'"
|
|
25
|
+
) from exc
|
|
26
|
+
return plt
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def plot_single_eval(state, *, inputs=("a", "b", "c"), outputs=("z",), expected=None, title=None):
|
|
30
|
+
"""Plot a single evaluation (e.g. of a MathExpressionStep): inputs and
|
|
31
|
+
outputs as bars.
|
|
32
|
+
|
|
33
|
+
Parameters
|
|
34
|
+
----------
|
|
35
|
+
state : dict-like
|
|
36
|
+
Typically ``sim.state`` (or a nested dict) containing the variables.
|
|
37
|
+
inputs, outputs : tuple[str]
|
|
38
|
+
Names to plot from the state.
|
|
39
|
+
expected : dict[str, float] | None
|
|
40
|
+
Optional expected values to overlay for outputs, e.g. ``{"z": ...}``.
|
|
41
|
+
title : str | None
|
|
42
|
+
Plot title.
|
|
43
|
+
|
|
44
|
+
Returns
|
|
45
|
+
-------
|
|
46
|
+
matplotlib.figure.Figure
|
|
47
|
+
The figure for the inputs/outputs bar chart.
|
|
48
|
+
"""
|
|
49
|
+
plt = _require_matplotlib()
|
|
50
|
+
|
|
51
|
+
names = list(inputs) + list(outputs)
|
|
52
|
+
values = [float(state[n]) for n in names]
|
|
53
|
+
|
|
54
|
+
fig = plt.figure()
|
|
55
|
+
plt.bar(names, values)
|
|
56
|
+
plt.ylabel("value")
|
|
57
|
+
plt.title(title or "Single evaluation: inputs -> outputs")
|
|
58
|
+
plt.show()
|
|
59
|
+
|
|
60
|
+
if expected:
|
|
61
|
+
# Small companion plot: output vs expected
|
|
62
|
+
out_names = list(outputs)
|
|
63
|
+
out_vals = [float(state[n]) for n in out_names]
|
|
64
|
+
exp_vals = [float(expected[n]) for n in out_names]
|
|
65
|
+
|
|
66
|
+
x = np.arange(len(out_names))
|
|
67
|
+
width = 0.35
|
|
68
|
+
|
|
69
|
+
plt.figure()
|
|
70
|
+
plt.bar(x - width / 2, out_vals, width, label="computed")
|
|
71
|
+
plt.bar(x + width / 2, exp_vals, width, label="expected")
|
|
72
|
+
plt.xticks(x, out_names)
|
|
73
|
+
plt.ylabel("value")
|
|
74
|
+
plt.title("Outputs: computed vs expected")
|
|
75
|
+
plt.legend()
|
|
76
|
+
plt.show()
|
|
77
|
+
|
|
78
|
+
return fig
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def plot_timeseries(records, series, *, x="t", title=None, xlabel=None, ylabel=None,
|
|
82
|
+
marker=".", linewidth=None, legend=True):
|
|
83
|
+
"""Plot one or more series from a list of emitted ``records`` over a time column.
|
|
84
|
+
|
|
85
|
+
Parameters
|
|
86
|
+
----------
|
|
87
|
+
records : list[dict]
|
|
88
|
+
Emitted records (e.g. ``emitter.query()``), each a dict keyed by variable.
|
|
89
|
+
series : Iterable[str] | dict[str, str]
|
|
90
|
+
Keys to plot. A dict maps key -> legend label.
|
|
91
|
+
x : str
|
|
92
|
+
The record key to use for the x-axis (default ``"t"``).
|
|
93
|
+
|
|
94
|
+
Returns
|
|
95
|
+
-------
|
|
96
|
+
matplotlib.figure.Figure
|
|
97
|
+
The figure.
|
|
98
|
+
"""
|
|
99
|
+
plt = _require_matplotlib()
|
|
100
|
+
|
|
101
|
+
if not records:
|
|
102
|
+
raise ValueError("No records to plot")
|
|
103
|
+
|
|
104
|
+
ts = np.array([r[x] for r in records], dtype=float)
|
|
105
|
+
|
|
106
|
+
if isinstance(series, dict):
|
|
107
|
+
keys = list(series.keys())
|
|
108
|
+
labels = series
|
|
109
|
+
else:
|
|
110
|
+
keys = list(series)
|
|
111
|
+
labels = {k: k for k in keys}
|
|
112
|
+
|
|
113
|
+
fig = plt.figure()
|
|
114
|
+
for k in keys:
|
|
115
|
+
ys = np.array([r[k] for r in records], dtype=float)
|
|
116
|
+
plt.plot(ts, ys, marker=marker, linewidth=linewidth, label=labels[k])
|
|
117
|
+
|
|
118
|
+
plt.xlabel(xlabel or x)
|
|
119
|
+
if ylabel is not None:
|
|
120
|
+
plt.ylabel(ylabel)
|
|
121
|
+
if title is not None:
|
|
122
|
+
plt.title(title)
|
|
123
|
+
if legend and len(keys) > 1:
|
|
124
|
+
plt.legend()
|
|
125
|
+
plt.show()
|
|
126
|
+
|
|
127
|
+
return fig
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""A minimal Tick process — a continuous simulation-time accumulator.
|
|
2
|
+
|
|
3
|
+
``Tick`` reads a floating-point time store ``t`` and writes ``t + interval``
|
|
4
|
+
every update, turning the engine's per-update ``interval`` into an explicit,
|
|
5
|
+
wireable ``t(sim-time)`` signal that other processes/steps can consume (e.g. a
|
|
6
|
+
:class:`~viva_basic_processes.math_expression.MathExpressionStep` whose
|
|
7
|
+
expressions are functions of ``t``).
|
|
8
|
+
|
|
9
|
+
This differs from :class:`~viva_basic_processes.clock.Clock`:
|
|
10
|
+
|
|
11
|
+
* ``Clock`` emits a discrete integer *step count* (``tick``).
|
|
12
|
+
* ``Tick`` accumulates *continuous time* (a float ``t``) into a user store.
|
|
13
|
+
|
|
14
|
+
process-bigraph already maintains ``global_time`` as a reserved store in every
|
|
15
|
+
composite; wire an input to ``['global_time']`` to read absolute sim time
|
|
16
|
+
without any process. ``Tick`` is for the cases where you want that running total
|
|
17
|
+
in an ordinary (non-reserved) store you control and emit — writing to the
|
|
18
|
+
reserved ``global_time`` store directly would corrupt the engine's master clock.
|
|
19
|
+
|
|
20
|
+
Pure process-bigraph; no heavy dependencies. Auto-registers into any workspace
|
|
21
|
+
``core`` via bigraph-schema package discovery.
|
|
22
|
+
"""
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
from typing import Any, Optional
|
|
26
|
+
|
|
27
|
+
from process_bigraph import Process
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Tick(Process):
|
|
31
|
+
"""Accumulate continuous simulation time into a float ``t`` store.
|
|
32
|
+
|
|
33
|
+
Reads ``t`` and writes ``t + interval`` each update, where ``interval`` is
|
|
34
|
+
the process interval supplied by the engine. The starting value comes from
|
|
35
|
+
whatever the ``t`` store is initialized to in the composite state.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
config_schema: dict = {}
|
|
39
|
+
|
|
40
|
+
def __init__(self, config: Optional[dict] = None, core: Any = None) -> None:
|
|
41
|
+
super().__init__(config, core)
|
|
42
|
+
|
|
43
|
+
def inputs(self):
|
|
44
|
+
return {"t": "float"}
|
|
45
|
+
|
|
46
|
+
def outputs(self):
|
|
47
|
+
return {"t": "overwrite[float]"}
|
|
48
|
+
|
|
49
|
+
def update(self, state, interval):
|
|
50
|
+
return {"t": float(state["t"]) + float(interval)}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def register_tick(core: Any, name: str = "Tick") -> bool:
|
|
54
|
+
"""Register :class:`Tick` into ``core`` (via ``register_link``). No-op-safe;
|
|
55
|
+
returns True when newly registered, False if already present or on error."""
|
|
56
|
+
try:
|
|
57
|
+
link_reg = getattr(core, "link_registry", {}) or {}
|
|
58
|
+
if name in link_reg:
|
|
59
|
+
return False
|
|
60
|
+
core.register_link(name, Tick)
|
|
61
|
+
return True
|
|
62
|
+
except Exception:
|
|
63
|
+
return False
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def tick_node(*, interval: float = 1.0, t_path=("t",), address: str = "local:Tick") -> dict:
|
|
67
|
+
"""Build a process-bigraph node dict for a :class:`Tick`, ready to drop into
|
|
68
|
+
a composite's ``state``. ``t_path`` is the store the tick reads and writes
|
|
69
|
+
its accumulated time to (same store on both ports)."""
|
|
70
|
+
return {
|
|
71
|
+
"_type": "process",
|
|
72
|
+
"address": address,
|
|
73
|
+
"config": {},
|
|
74
|
+
"interval": interval,
|
|
75
|
+
"inputs": {"t": list(t_path)},
|
|
76
|
+
"outputs": {"t": list(t_path)},
|
|
77
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""A sampled time series, read back at a given time.
|
|
2
|
+
|
|
3
|
+
``TimeSeriesStep`` holds one or more named series sampled at the same increasing ``times``. Given an input ``time``,
|
|
4
|
+
it writes each series' value at the latest sample at or before that time: a zero-order hold, which is how a coupling
|
|
5
|
+
that samples a signal and holds it for an interval sees it. A time within ``tolerance`` of a sample counts as that
|
|
6
|
+
sample, so a clock that reads 29.999999 at the 30 s instant still gets the 30 s value (bigraph-schema before 1.8.3
|
|
7
|
+
replaces an explicit 0 in a config with the default, so use a tiny positive tolerance for an exact match there).
|
|
8
|
+
Before the first sample is an error; after the last, the last value holds.
|
|
9
|
+
|
|
10
|
+
It drives a model with a signal computed elsewhere, exactly at its sampled instants: for example the concentration at
|
|
11
|
+
a cell's surface, recorded from a field simulation that the cell does not change.
|
|
12
|
+
|
|
13
|
+
Pure process-bigraph. Auto-registers into any workspace ``core`` via bigraph-schema package discovery; reference it as
|
|
14
|
+
``local:TimeSeriesStep`` or ``local:viva_basic_processes.time_series.TimeSeriesStep``.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import bisect
|
|
20
|
+
|
|
21
|
+
from process_bigraph import Step
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class TimeSeriesStep(Step):
|
|
25
|
+
"""Write each named series' value at the input ``time`` (the latest sample at or before it)."""
|
|
26
|
+
|
|
27
|
+
config_schema = {
|
|
28
|
+
"times": "node", # strictly increasing sample times
|
|
29
|
+
"values": "node", # {name: [one value per sample time]}
|
|
30
|
+
"tolerance": {"_type": "float", "_default": 1e-9}, # in the units of `times`
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
def initialize(self, config=None):
|
|
34
|
+
times = [float(t) for t in self.config["times"]]
|
|
35
|
+
if not times:
|
|
36
|
+
raise ValueError("TimeSeriesStep needs at least one sample time")
|
|
37
|
+
if any(later <= earlier for earlier, later in zip(times, times[1:])):
|
|
38
|
+
raise ValueError("TimeSeriesStep's times must be strictly increasing")
|
|
39
|
+
values = {str(name): [float(v) for v in series] for name, series in dict(self.config["values"]).items()}
|
|
40
|
+
if not values:
|
|
41
|
+
raise ValueError("TimeSeriesStep needs at least one named series in `values`")
|
|
42
|
+
for name, series in values.items():
|
|
43
|
+
if len(series) != len(times):
|
|
44
|
+
raise ValueError(f"series {name!r} has {len(series)} values for {len(times)} times")
|
|
45
|
+
tolerance = float(self.config.get("tolerance", 1e-9))
|
|
46
|
+
if tolerance < 0:
|
|
47
|
+
raise ValueError("TimeSeriesStep's tolerance must not be negative")
|
|
48
|
+
self._times, self._values, self._tolerance = times, values, tolerance
|
|
49
|
+
|
|
50
|
+
def inputs(self):
|
|
51
|
+
return {"time": "float"}
|
|
52
|
+
|
|
53
|
+
def outputs(self):
|
|
54
|
+
return {name: "overwrite[float]" for name in self._values}
|
|
55
|
+
|
|
56
|
+
def update(self, state):
|
|
57
|
+
t = float(state["time"])
|
|
58
|
+
i = bisect.bisect_right(self._times, t + self._tolerance) - 1
|
|
59
|
+
if i < 0:
|
|
60
|
+
raise ValueError(f"time {t} is before the first sample, {self._times[0]}")
|
|
61
|
+
return {name: series[i] for name, series in self._values.items()}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: viva-basic-processes
|
|
3
|
+
Version: 0.4.1
|
|
4
|
+
Summary: Reusable, composite-agnostic process-bigraph processes — Clock, Tick, Intervention, MathExpression, and beyond (was pbg-basic-processes)
|
|
5
|
+
License: MIT
|
|
6
|
+
Requires-Python: >=3.11
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: process-bigraph>=1.4.12
|
|
10
|
+
Requires-Dist: bigraph-schema
|
|
11
|
+
Requires-Dist: sympy
|
|
12
|
+
Requires-Dist: numpy
|
|
13
|
+
Provides-Extra: plotting
|
|
14
|
+
Requires-Dist: matplotlib; extra == "plotting"
|
|
15
|
+
Provides-Extra: dev
|
|
16
|
+
Requires-Dist: pytest; extra == "dev"
|
|
17
|
+
Requires-Dist: matplotlib; extra == "dev"
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# pbg-basic-processes
|
|
21
|
+
|
|
22
|
+
Reusable, composite-agnostic [process-bigraph](https://github.com/vivarium-collective/process-bigraph) processes — the small, generic building blocks that show up in almost every workspace.
|
|
23
|
+
|
|
24
|
+
| Process | What it does |
|
|
25
|
+
|---|---|
|
|
26
|
+
| `Clock` | Emits an integer `tick` step counter each step — the one temporal quantity the engine does *not* expose as a store. (Absolute simulation time, `global_time`, is already maintained by the engine in every composite; wire any input to `['global_time']` to read it.) |
|
|
27
|
+
| `Tick` | Accumulates continuous simulation time into a float `t` store (`t -> t + interval` each update) — a wireable time signal for processes/steps that are functions of `t` (e.g. a time-driven `MathExpressionStep`). |
|
|
28
|
+
| `Intervention` | Applies a specific perturbation to one target store — `set` / `knockout` / `scale` / `add` / `decouple` / `invert`, optionally within a time window. The building block for negative controls and counterfactuals. |
|
|
29
|
+
| `MathExpressionStep` | Evaluates a list of named symbolic (SymPy) expressions as one Step, inferring input ports from free symbols and resolving inter-expression dependencies in topological order. |
|
|
30
|
+
| `TimeSeriesStep` | Holds one or more named series sampled at the same increasing `times` and, given an input `time`, writes each one's value at the latest sample at or before it (a zero-order hold, within a small `tolerance`). Drives a model with a signal computed elsewhere, exactly at its sampled instants. |
|
|
31
|
+
|
|
32
|
+
## Auto-registration
|
|
33
|
+
|
|
34
|
+
Like [`pbg-emitters`](https://github.com/vivarium-collective/pbg-emitters), these processes **auto-register** into any workspace `core`. `allocate_core()` walks every installed distribution that depends on `bigraph-schema` and registers its `Process`/`Step` subclasses — no entry points, no `register_*` boilerplate:
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from bigraph_schema import allocate_core
|
|
38
|
+
|
|
39
|
+
core = allocate_core()
|
|
40
|
+
assert 'Clock' in core.link_registry # just by being installed
|
|
41
|
+
assert 'Intervention' in core.link_registry
|
|
42
|
+
assert 'MathExpressionStep' in core.link_registry
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Add `pbg-basic-processes` as a dependency of your workspace (it is a base dependency of `pbg-superpowers`, so every pbg workspace gets it) and reference the processes by `local:Clock`, `local:Tick`, `local:Intervention`, `local:MathExpressionStep`.
|
|
46
|
+
|
|
47
|
+
## Plotting helpers (optional)
|
|
48
|
+
|
|
49
|
+
`viva_basic_processes.plotting` provides two notebook/tutorial convenience helpers — `plot_timeseries` (line plots of emitted records over a time column) and `plot_single_eval` (a bar chart of one step's inputs/outputs). They require matplotlib, which is an **optional** extra so the core processes stay lightweight:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pip install "viva-basic-processes[plotting]"
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
from viva_basic_processes import plot_timeseries, plot_single_eval
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Install
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
pip install pbg-basic-processes # from PyPI (when published)
|
|
63
|
+
pip install -e . # from a checkout
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Usage
|
|
67
|
+
|
|
68
|
+
Node-builder helpers make wiring into a composite easy:
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from pbg_basic_processes import clock_node, intervention_node
|
|
72
|
+
|
|
73
|
+
state = {
|
|
74
|
+
'tick': 0,
|
|
75
|
+
'nutrient': 5.0,
|
|
76
|
+
'clock': clock_node(interval=1.0), # writes a step counter to ['tick']
|
|
77
|
+
# hold nutrient at 0 only between t=10 and t=20 of absolute sim time.
|
|
78
|
+
# use_global_time wires the window to the engine's reserved global_time store.
|
|
79
|
+
'starve': intervention_node(['nutrient'], mode='set', value=0.0,
|
|
80
|
+
window=[10, 20], use_global_time=True),
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Develop
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
pip install -e '.[dev]'
|
|
88
|
+
pytest -q
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
MIT-licensed. Part of the [vivarium-collective](https://github.com/vivarium-collective) process-bigraph ecosystem.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
pbg_basic_processes/__init__.py,sha256=rkRmcZM1HhMxMnevjCOFfdYtPjcqi0zvAK6LFFP0A54,3358
|
|
2
|
+
viva_basic_processes/__init__.py,sha256=0Fe9DSfqgvFDLt6H1gzS9dVOlLrkYY2punAvdsx1KYA,1825
|
|
3
|
+
viva_basic_processes/clock.py,sha256=Vom1nq9NK0rFqvMEzLRd-5x2Qwpolt6kJRMHAzCtZNE,2663
|
|
4
|
+
viva_basic_processes/intervention.py,sha256=Bc5qzRaqazGKI4hB33C3y0obVIV2DJpdSK-bxc9kq10,6853
|
|
5
|
+
viva_basic_processes/math_expression.py,sha256=8-dgsaMroYfmqtlEgkxp3LBNiYccbXpGPWNTJJed3cM,7781
|
|
6
|
+
viva_basic_processes/plotting.py,sha256=b4ySiWNEnpiFCpF2Ky5NSnQuwqY4tDubeNWea23NQE4,3963
|
|
7
|
+
viva_basic_processes/tick.py,sha256=YddaAwgmY91_sbVWZ0KARAkKoiPYVtWbNO7G1t9taNk,2912
|
|
8
|
+
viva_basic_processes/time_series.py,sha256=UpmSgV_xSpUxaHUkFp6aX_mWBvXY-oaagUw4vUWg8Wg,3051
|
|
9
|
+
viva_basic_processes-0.4.1.dist-info/licenses/LICENSE,sha256=maQeFlc3T-NvPiE9gAcxsbChR6QKcvwelPrAQqe3FK0,1080
|
|
10
|
+
viva_basic_processes-0.4.1.dist-info/METADATA,sha256=-nekGSMdw1t7hXdJvsz10CMquV7SHLHgHelG9Uc1hkE,4360
|
|
11
|
+
viva_basic_processes-0.4.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
12
|
+
viva_basic_processes-0.4.1.dist-info/top_level.txt,sha256=3QN6vHyQYu9_z719WmqvRZSXUozio2TbUlEKdWruWaI,41
|
|
13
|
+
viva_basic_processes-0.4.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 The Vivarium Collective
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|