bigraph-schema 1.8.2__tar.gz → 1.8.4__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.
- {bigraph_schema-1.8.2/bigraph_schema.egg-info → bigraph_schema-1.8.4}/PKG-INFO +1 -1
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/assembly.py +31 -3
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/contract_expr.py +3 -34
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/core.py +54 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/edge.py +1 -1
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/merge.py +4 -1
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4/bigraph_schema.egg-info}/PKG-INFO +1 -1
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema.egg-info/SOURCES.txt +2 -4
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/pyproject.toml +1 -1
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/tests/test_bugfixes.py +19 -0
- bigraph_schema-1.8.4/tests/test_config_fill_and_projection.py +113 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/tests/test_contract_expr.py +0 -18
- bigraph_schema-1.8.4/tests/test_local_face_lookup.py +84 -0
- bigraph_schema-1.8.2/bigraph_schema/matching.py +0 -68
- bigraph_schema-1.8.2/bigraph_schema/subsumption.py +0 -191
- bigraph_schema-1.8.2/tests/test_matching.py +0 -95
- bigraph_schema-1.8.2/tests/test_subsumption.py +0 -171
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/AUTHORS.md +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/LICENSE +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/README.md +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/__init__.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/calculi.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/contract.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/contract_audit.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/fastdispatch.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/json_codec.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/__init__.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/apply.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/bundle.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/check.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/coerce.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/default.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/derive.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/diff.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/divide.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/events.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/generalize.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/handle_parameters.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/infer.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/is_empty.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/jump.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/patch.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/realize.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/reconcile.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/resolve.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/select.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/serialize.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/transform.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/validate.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/methods/walk.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/package/__init__.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/package/discover.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/package/lazy_registry.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/parse.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/protocols.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/schema.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/translator.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema/units.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema.egg-info/dependency_links.txt +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema.egg-info/requires.txt +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/bigraph_schema.egg-info/top_level.txt +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/setup.cfg +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/setup.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/tests/test_address_portability.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/tests/test_audit_face.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/tests/test_contract_audit.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/tests/test_contract_predicates.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/tests/test_control_inference.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/tests/test_fast_dispatch.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/tests/test_json_codec.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/tests/test_lazy_discovery.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/tests/test_multi_package_dist_discovery.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/tests/test_process_contract.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/tests/test_streamline_dispatch.py +0 -0
- {bigraph_schema-1.8.2 → bigraph_schema-1.8.4}/tests/test_translator.py +0 -0
|
@@ -599,6 +599,35 @@ def is_address(value):
|
|
|
599
599
|
and 'protocol' in value and 'data' in value)
|
|
600
600
|
|
|
601
601
|
|
|
602
|
+
def _resolve_edge_class(core, canonical):
|
|
603
|
+
"""Resolve the class a canonical address names.
|
|
604
|
+
|
|
605
|
+
For the ``local`` protocol, resolve through
|
|
606
|
+
:func:`bigraph_schema.protocols.local_lookup`, which handles BOTH the
|
|
607
|
+
portable ``local:!module.path.Class`` import form (via
|
|
608
|
+
``local_lookup_module``) and the bare ``local:<name>`` registry form. For
|
|
609
|
+
any other protocol — or when ``local_lookup`` yields nothing — fall back to
|
|
610
|
+
the process registry ``.get(...)`` so existing behavior is preserved.
|
|
611
|
+
|
|
612
|
+
Returns the class, or ``None`` when the address names nothing this core
|
|
613
|
+
knows.
|
|
614
|
+
"""
|
|
615
|
+
data = canonical.get('data')
|
|
616
|
+
|
|
617
|
+
if canonical.get('protocol') == 'local' and isinstance(data, str):
|
|
618
|
+
# Local import inside the function avoids any protocols<->assembly
|
|
619
|
+
# import-cycle risk at module load.
|
|
620
|
+
from bigraph_schema.protocols import local_lookup
|
|
621
|
+
try:
|
|
622
|
+
resolved = local_lookup(core, data)
|
|
623
|
+
except Exception:
|
|
624
|
+
resolved = None
|
|
625
|
+
if resolved is not None:
|
|
626
|
+
return resolved
|
|
627
|
+
|
|
628
|
+
return getattr(core, 'link_registry', {}).get(data)
|
|
629
|
+
|
|
630
|
+
|
|
602
631
|
def _face_from_address(core, address, config):
|
|
603
632
|
"""Resolve an edge's ports from the class its address names.
|
|
604
633
|
|
|
@@ -620,7 +649,7 @@ def _face_from_address(core, address, config):
|
|
|
620
649
|
if not isinstance(canonical, dict):
|
|
621
650
|
return None
|
|
622
651
|
|
|
623
|
-
edge_class =
|
|
652
|
+
edge_class = _resolve_edge_class(core, canonical)
|
|
624
653
|
if edge_class is None:
|
|
625
654
|
return None
|
|
626
655
|
|
|
@@ -746,8 +775,7 @@ def contract_of(core, node):
|
|
|
746
775
|
address = address._default
|
|
747
776
|
canonical = normalize_address(address)
|
|
748
777
|
if isinstance(canonical, dict):
|
|
749
|
-
edge_class =
|
|
750
|
-
canonical.get('data'))
|
|
778
|
+
edge_class = _resolve_edge_class(core, canonical)
|
|
751
779
|
if edge_class is not None:
|
|
752
780
|
try:
|
|
753
781
|
documented = resolve_contract(
|
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
"""A tiny, safe expression language for contract predicates.
|
|
2
2
|
|
|
3
3
|
parse() -> an Expr tree (frozen); names_in() -> referenced port/config/state
|
|
4
|
-
paths
|
|
5
|
-
|
|
6
|
-
|
|
4
|
+
paths. NEVER uses eval/exec: the string is parsed with the stdlib ``ast`` module
|
|
5
|
+
and every node is checked against a whitelist before a hand-written parser builds
|
|
6
|
+
the frozen Expr tree.
|
|
7
7
|
"""
|
|
8
8
|
from __future__ import annotations
|
|
9
9
|
import ast as _ast
|
|
10
|
-
import operator
|
|
11
10
|
from dataclasses import dataclass
|
|
12
11
|
|
|
13
12
|
class ExprError(ValueError):
|
|
@@ -84,33 +83,3 @@ def names_in(ast: Expr) -> set:
|
|
|
84
83
|
walk(ast)
|
|
85
84
|
return found
|
|
86
85
|
|
|
87
|
-
_BIN_OP = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}
|
|
88
|
-
_REDUCE = {'sum': sum, 'min': min, 'max': max, 'abs': abs, 'all': all, 'any': any}
|
|
89
|
-
|
|
90
|
-
def evaluate(ast: Expr, env: dict, *, tol: float = 0.0):
|
|
91
|
-
def ev(node):
|
|
92
|
-
if node.kind == 'lit':
|
|
93
|
-
return node.value
|
|
94
|
-
if node.kind == 'name':
|
|
95
|
-
if node.value == ('tol',):
|
|
96
|
-
return tol
|
|
97
|
-
if node.value not in env:
|
|
98
|
-
raise ExprError(f'no binding for {".".join(node.value)}')
|
|
99
|
-
return env[node.value]
|
|
100
|
-
if node.kind == 'neg':
|
|
101
|
-
return -ev(node.args[0])
|
|
102
|
-
if node.kind == 'bin':
|
|
103
|
-
a, b = ev(node.args[0]), ev(node.args[1])
|
|
104
|
-
return _BIN_OP[node.op](a, b)
|
|
105
|
-
if node.kind == 'call':
|
|
106
|
-
values = [ev(a) for a in node.args]
|
|
107
|
-
return _REDUCE[node.op](*values) if node.op == 'abs' else _REDUCE[node.op](values[0])
|
|
108
|
-
if node.kind == 'cmp':
|
|
109
|
-
a, b = ev(node.args[0]), ev(node.args[1])
|
|
110
|
-
if node.op == '==':
|
|
111
|
-
return abs(a - b) <= tol if isinstance(a, (int, float)) and isinstance(b, (int, float)) else a == b
|
|
112
|
-
if node.op == '!=':
|
|
113
|
-
return not (abs(a - b) <= tol) if isinstance(a, (int, float)) and isinstance(b, (int, float)) else a != b
|
|
114
|
-
return {'<': a < b, '<=': a <= b, '>': a > b, '>=': a >= b}[node.op]
|
|
115
|
-
raise ExprError(f'cannot evaluate node kind {node.kind!r}')
|
|
116
|
-
return ev(ast)
|
|
@@ -993,6 +993,55 @@ class Core:
|
|
|
993
993
|
else:
|
|
994
994
|
return merge(merge_schema, base_state, state)
|
|
995
995
|
|
|
996
|
+
def fill_config(self, config_schema, config):
|
|
997
|
+
"""Fill an edge/process config from its ``config_schema``.
|
|
998
|
+
|
|
999
|
+
Config-filling is NOT state-merging. A value the caller SUPPLIES
|
|
1000
|
+
replaces the schema default outright: a supplied ``0``, ``0.0``,
|
|
1001
|
+
``''`` or ``[]`` stands as given, and a supplied list replaces the
|
|
1002
|
+
default rather than concatenating onto it. A declared key the caller
|
|
1003
|
+
omits (or sets to ``None``) takes its default, so every declared key
|
|
1004
|
+
with a default is present. Only genuine field GROUPS (a dict of
|
|
1005
|
+
sub-fields, no ``_type``) recurse, which keeps a partially-supplied
|
|
1006
|
+
group's untouched siblings at their defaults.
|
|
1007
|
+
|
|
1008
|
+
``fill`` (used for state) keeps its merge semantics — this method is
|
|
1009
|
+
used only for config, so state-filling is untouched.
|
|
1010
|
+
"""
|
|
1011
|
+
self.access(config_schema)
|
|
1012
|
+
return self._fill_config(config_schema, config)
|
|
1013
|
+
|
|
1014
|
+
def _fill_config(self, schema, config):
|
|
1015
|
+
is_group = (
|
|
1016
|
+
isinstance(schema, dict)
|
|
1017
|
+
and '_type' not in schema
|
|
1018
|
+
and any(not str(key).startswith('_') for key in schema))
|
|
1019
|
+
|
|
1020
|
+
if not is_group:
|
|
1021
|
+
# A leaf field (typed, or an opaque schema): a supplied non-None
|
|
1022
|
+
# value replaces the default wholesale.
|
|
1023
|
+
if config is None:
|
|
1024
|
+
_, default_state = self.default(schema)
|
|
1025
|
+
return default_state
|
|
1026
|
+
return config
|
|
1027
|
+
|
|
1028
|
+
if config is not None and not isinstance(config, dict):
|
|
1029
|
+
return config
|
|
1030
|
+
config = config or {}
|
|
1031
|
+
|
|
1032
|
+
result = {}
|
|
1033
|
+
for key in schema:
|
|
1034
|
+
if str(key).startswith('_'):
|
|
1035
|
+
continue
|
|
1036
|
+
subschema = schema[key]
|
|
1037
|
+
if key in config and config[key] is not None:
|
|
1038
|
+
result[key] = self._fill_config(subschema, config[key])
|
|
1039
|
+
else:
|
|
1040
|
+
_, default_state = self.default(subschema)
|
|
1041
|
+
if default_state is not None:
|
|
1042
|
+
result[key] = default_state
|
|
1043
|
+
return result
|
|
1044
|
+
|
|
996
1045
|
def view_ports(self, schema, state, path, declared_schema, wires):
|
|
997
1046
|
"""Return the state visible through a port.
|
|
998
1047
|
|
|
@@ -1090,6 +1139,11 @@ class Core:
|
|
|
1090
1139
|
if isinstance(wires, (list, tuple)):
|
|
1091
1140
|
destination = resolve_path(list(path) + list(wires))
|
|
1092
1141
|
|
|
1142
|
+
# Only the keys the port declares may travel through it — a
|
|
1143
|
+
# projected view (e.g. from initial_state()) that carries extra
|
|
1144
|
+
# keys must not write them into the wired store (#201).
|
|
1145
|
+
view = self._project_through_schema(view, ports_schema)
|
|
1146
|
+
|
|
1093
1147
|
project_schema = self.resolve(
|
|
1094
1148
|
project_schema,
|
|
1095
1149
|
ports_schema,
|
|
@@ -241,7 +241,10 @@ def merge(schema: Array, current, update, path=()):
|
|
|
241
241
|
|
|
242
242
|
@dispatch
|
|
243
243
|
def merge(schema: Frame, current, update, path=()):
|
|
244
|
-
|
|
244
|
+
# No update (an empty branch the engine pruned) keeps the table, as the Array merge does.
|
|
245
|
+
if update is None:
|
|
246
|
+
return default(schema) if current is None else current
|
|
247
|
+
elif isinstance(update, dict):
|
|
245
248
|
return current
|
|
246
249
|
elif update.empty:
|
|
247
250
|
return current
|
|
@@ -13,11 +13,9 @@ bigraph_schema/core.py
|
|
|
13
13
|
bigraph_schema/edge.py
|
|
14
14
|
bigraph_schema/fastdispatch.py
|
|
15
15
|
bigraph_schema/json_codec.py
|
|
16
|
-
bigraph_schema/matching.py
|
|
17
16
|
bigraph_schema/parse.py
|
|
18
17
|
bigraph_schema/protocols.py
|
|
19
18
|
bigraph_schema/schema.py
|
|
20
|
-
bigraph_schema/subsumption.py
|
|
21
19
|
bigraph_schema/translator.py
|
|
22
20
|
bigraph_schema/units.py
|
|
23
21
|
bigraph_schema.egg-info/PKG-INFO
|
|
@@ -56,6 +54,7 @@ bigraph_schema/package/lazy_registry.py
|
|
|
56
54
|
tests/test_address_portability.py
|
|
57
55
|
tests/test_audit_face.py
|
|
58
56
|
tests/test_bugfixes.py
|
|
57
|
+
tests/test_config_fill_and_projection.py
|
|
59
58
|
tests/test_contract_audit.py
|
|
60
59
|
tests/test_contract_expr.py
|
|
61
60
|
tests/test_contract_predicates.py
|
|
@@ -63,9 +62,8 @@ tests/test_control_inference.py
|
|
|
63
62
|
tests/test_fast_dispatch.py
|
|
64
63
|
tests/test_json_codec.py
|
|
65
64
|
tests/test_lazy_discovery.py
|
|
66
|
-
tests/
|
|
65
|
+
tests/test_local_face_lookup.py
|
|
67
66
|
tests/test_multi_package_dist_discovery.py
|
|
68
67
|
tests/test_process_contract.py
|
|
69
68
|
tests/test_streamline_dispatch.py
|
|
70
|
-
tests/test_subsumption.py
|
|
71
69
|
tests/test_translator.py
|
|
@@ -163,3 +163,22 @@ def test_jump_into_empty_schema_is_unambiguous(token):
|
|
|
163
163
|
# plum.AmbiguousLookupError.
|
|
164
164
|
assert isinstance(schema, Empty)
|
|
165
165
|
assert state is None
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def test_frame_merge_keeps_the_table_when_the_update_is_none(core):
|
|
169
|
+
"""An empty branch that the engine prunes reaches merge as None (process-bigraph 1.11's
|
|
170
|
+
without_document_leaves drops an edge's empty initial state). A Frame merge must keep the current table, or
|
|
171
|
+
the default table when there is none, as the Array merge does, instead of failing on ``None.empty``.
|
|
172
|
+
vivarium-tyssue's EulerSolver hit this: its 2-D sheet's ``cell_df`` starts empty."""
|
|
173
|
+
import pandas as pd
|
|
174
|
+
|
|
175
|
+
from bigraph_schema.methods.merge import merge
|
|
176
|
+
|
|
177
|
+
schema = core.access('dataframe[a:float|b:integer[64]]')
|
|
178
|
+
table = pd.DataFrame({'a': [1.0], 'b': [2]})
|
|
179
|
+
|
|
180
|
+
assert merge(schema, table, None) is table
|
|
181
|
+
|
|
182
|
+
filled = merge(schema, None, None)
|
|
183
|
+
assert isinstance(filled, pd.DataFrame)
|
|
184
|
+
assert filled.empty and list(filled.columns) == ['a', 'b']
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Config-fill and port-projection fixes (vivarium-collective/bigraph-schema).
|
|
2
|
+
|
|
3
|
+
Three bugs, all surfaced while building viva-pulse:
|
|
4
|
+
|
|
5
|
+
- #203 — an explicit zero-valued config (0, 0.0, '') was replaced by the
|
|
6
|
+
default because state-merge emptiness rules were applied to config.
|
|
7
|
+
- #202 — a list config was concatenated onto a non-empty ``_default`` instead
|
|
8
|
+
of replacing it, and an unsupplied empty-list default was dropped entirely
|
|
9
|
+
once another key was supplied.
|
|
10
|
+
- #201 — projecting ``initial_state()`` through a port wrote keys the port
|
|
11
|
+
does not declare into the wired store.
|
|
12
|
+
"""
|
|
13
|
+
from bigraph_schema import Edge, allocate_core
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# ---------------------------------------------------------------------------
|
|
17
|
+
# Config fill (#202, #203): a supplied value replaces the default; a declared
|
|
18
|
+
# key the caller omits (or sets to None) takes its default.
|
|
19
|
+
# ---------------------------------------------------------------------------
|
|
20
|
+
|
|
21
|
+
def _config(schema, value):
|
|
22
|
+
class C(Edge):
|
|
23
|
+
config_schema = {'k': schema}
|
|
24
|
+
return C({'k': value}, core=allocate_core()).config['k']
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_zero_valued_config_is_kept_not_replaced_by_default(): # #203
|
|
28
|
+
assert _config({'_type': 'float', '_default': 5.0}, 0.0) == 0.0
|
|
29
|
+
assert _config({'_type': 'float', '_default': 5.0}, -1.0) == -1.0
|
|
30
|
+
assert _config({'_type': 'integer', '_default': 5}, 0) == 0
|
|
31
|
+
assert _config({'_type': 'string', '_default': 'a'}, '') == ''
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_supplied_config_still_wins_over_default():
|
|
35
|
+
assert _config({'_type': 'float', '_default': 5.0}, 7.5) == 7.5
|
|
36
|
+
assert _config({'_type': 'string', '_default': 'a'}, 'b') == 'b'
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_list_config_replaces_default_rather_than_concatenating(): # #202
|
|
40
|
+
assert _config({'_type': 'list[string]', '_default': ['a', 'b', 'c']},
|
|
41
|
+
['x']) == ['x']
|
|
42
|
+
assert _config({'_type': 'list[string]', '_default': []}, ['x']) == ['x']
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def test_omitted_or_none_config_key_falls_back_to_default():
|
|
46
|
+
assert _config({'_type': 'float', '_default': 5.0}, None) == 5.0
|
|
47
|
+
|
|
48
|
+
class C(Edge):
|
|
49
|
+
config_schema = {'k': {'_type': 'float', '_default': 5.0}}
|
|
50
|
+
assert C({}, core=allocate_core()).config['k'] == 5.0
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_every_declared_key_is_present_when_another_is_supplied(): # #202 (comment)
|
|
54
|
+
class C(Edge):
|
|
55
|
+
config_schema = {
|
|
56
|
+
'given': {'_type': 'float', '_default': 1.0},
|
|
57
|
+
'empty_list': {'_type': 'list[string]', '_default': []},
|
|
58
|
+
'list_abc': {'_type': 'list[string]', '_default': ['a']},
|
|
59
|
+
'zero_float': {'_type': 'float', '_default': 0.0},
|
|
60
|
+
'empty_string': {'_type': 'string', '_default': ''},
|
|
61
|
+
'zero_int': {'_type': 'integer', '_default': 0},
|
|
62
|
+
'empty_map': {'_type': 'map[float]', '_default': {}},
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
cfg = C({'given': 2.0}, core=allocate_core()).config
|
|
66
|
+
assert cfg['given'] == 2.0
|
|
67
|
+
assert cfg['empty_list'] == [] # was dropped before the fix
|
|
68
|
+
assert cfg['list_abc'] == ['a']
|
|
69
|
+
assert cfg['zero_float'] == 0.0
|
|
70
|
+
assert cfg['empty_string'] == ''
|
|
71
|
+
assert cfg['zero_int'] == 0
|
|
72
|
+
assert cfg['empty_map'] == {}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_nested_config_group_keeps_sibling_defaults():
|
|
76
|
+
"""A partially-supplied group of config fields keeps the untouched
|
|
77
|
+
siblings' defaults while replacing the supplied leaf."""
|
|
78
|
+
class C(Edge):
|
|
79
|
+
config_schema = {
|
|
80
|
+
'group': {
|
|
81
|
+
'a': {'_type': 'float', '_default': 1.0},
|
|
82
|
+
'b': {'_type': 'float', '_default': 2.0},
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
cfg = C({'group': {'a': 9.0}}, core=allocate_core()).config
|
|
87
|
+
assert cfg['group'] == {'a': 9.0, 'b': 2.0}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
# ---------------------------------------------------------------------------
|
|
91
|
+
# Port projection (#201): projecting through a port keeps only declared keys.
|
|
92
|
+
# ---------------------------------------------------------------------------
|
|
93
|
+
|
|
94
|
+
def test_project_ports_drops_keys_the_port_does_not_declare(): # #201
|
|
95
|
+
core = allocate_core()
|
|
96
|
+
ports_schema = {'m': {'cmd': 'float'}} # port m declares only 'cmd'
|
|
97
|
+
wires = {'m': ['interventions']}
|
|
98
|
+
view = {'m': {'cmd': 3.0, 'extra': 9.0}}
|
|
99
|
+
|
|
100
|
+
_, state = core.project_ports(ports_schema, wires, (), view)
|
|
101
|
+
|
|
102
|
+
assert state['interventions'] == {'cmd': 3.0} # 'extra' must not leak
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def test_project_ports_keeps_declared_keys_intact():
|
|
106
|
+
core = allocate_core()
|
|
107
|
+
ports_schema = {'m': {'cmd': 'float', 'gain': 'float'}}
|
|
108
|
+
wires = {'m': ['store']}
|
|
109
|
+
view = {'m': {'cmd': 3.0, 'gain': 2.0}}
|
|
110
|
+
|
|
111
|
+
_, state = core.project_ports(ports_schema, wires, (), view)
|
|
112
|
+
|
|
113
|
+
assert state['store'] == {'cmd': 3.0, 'gain': 2.0}
|
|
@@ -28,24 +28,6 @@ def test_names_in_collects_paths_and_excludes_tol():
|
|
|
28
28
|
names = names_in(parse("abs(sum(outputs.mass) - sum(inputs.mass)) <= tol"))
|
|
29
29
|
assert names == {('outputs', 'mass'), ('inputs', 'mass')}
|
|
30
30
|
|
|
31
|
-
from bigraph_schema.contract_expr import evaluate
|
|
32
|
-
|
|
33
|
-
def test_evaluate_conservation_true_within_tol():
|
|
34
|
-
ast = parse("abs(sum(outputs.flux) - sum(inputs.flux)) <= tol")
|
|
35
|
-
env = {('outputs', 'flux'): [1.0, 2.0], ('inputs', 'flux'): [3.0]}
|
|
36
|
-
assert evaluate(ast, env, tol=1e-9) is True
|
|
37
|
-
|
|
38
|
-
def test_evaluate_precondition():
|
|
39
|
-
assert evaluate(parse("inputs.biomass > 0"), {('inputs', 'biomass'): 0.5}) is True
|
|
40
|
-
assert evaluate(parse("inputs.biomass > 0"), {('inputs', 'biomass'): 0.0}) is False
|
|
41
|
-
|
|
42
|
-
def test_evaluate_missing_name_raises():
|
|
43
|
-
with pytest.raises(ExprError):
|
|
44
|
-
evaluate(parse("inputs.x > 0"), {})
|
|
45
|
-
|
|
46
|
-
def test_bin_does_not_eagerly_divide():
|
|
47
|
-
assert evaluate(parse('inputs.x + 0'), {('inputs', 'x'): 1}) == 1
|
|
48
|
-
|
|
49
31
|
def test_rejects_dunder_path_segment():
|
|
50
32
|
with pytest.raises(ExprError):
|
|
51
33
|
parse('inputs.__class__')
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Regression for #188 — face-sorted sites reject ``local:!module.Class`` fillers.
|
|
2
|
+
|
|
3
|
+
A site sorted by a contract/face is filled by a bare edge *address*: its face is
|
|
4
|
+
the face of the class the address names (:func:`collect_face` ->
|
|
5
|
+
:func:`_face_from_address`). Resolving that class only through
|
|
6
|
+
``core.link_registry.get(canonical['data'])`` works for the registry form
|
|
7
|
+
(``local:<name>``) but NOT for the portable import form
|
|
8
|
+
(``local:!pkg.mod.Class``) — there ``canonical['data']`` is ``'!pkg.mod.Class'``,
|
|
9
|
+
never a registry key, so the lookup returned ``None``, ``collect_face`` reported
|
|
10
|
+
no ports, and ``admits`` rejected an otherwise-conforming filler.
|
|
11
|
+
|
|
12
|
+
The fix routes ``local`` addresses through
|
|
13
|
+
:func:`bigraph_schema.protocols.local_lookup`, which resolves BOTH forms. These
|
|
14
|
+
tests pin the import form (the bug) and keep the registry form (the control).
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from bigraph_schema.core import allocate_core
|
|
18
|
+
from bigraph_schema.contract import ProcessContract
|
|
19
|
+
from bigraph_schema.assembly import admits, admits_why, collect_face
|
|
20
|
+
from bigraph_schema.edge import Edge
|
|
21
|
+
from bigraph_schema.schema import Site
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class _FaceWidget(Edge):
|
|
25
|
+
"""A trivial local edge with a real face, importable by module path so the
|
|
26
|
+
``local:!module.path.Class`` form can resolve it by import."""
|
|
27
|
+
|
|
28
|
+
def inputs(self):
|
|
29
|
+
return {'mass': 'float'}
|
|
30
|
+
|
|
31
|
+
def outputs(self):
|
|
32
|
+
return {'mass': 'float'}
|
|
33
|
+
|
|
34
|
+
def update(self, state, interval=None):
|
|
35
|
+
return {}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# Self-describing module-path (`!`) address for the class above — the portable
|
|
39
|
+
# form Jim's repro uses. ``__name__`` is the importable path of this test module.
|
|
40
|
+
_IMPORT_ADDRESS = f'local:!{__name__}._FaceWidget'
|
|
41
|
+
_REGISTRY_NAME = 'face_widget'
|
|
42
|
+
_REGISTRY_ADDRESS = f'local:{_REGISTRY_NAME}'
|
|
43
|
+
|
|
44
|
+
_HOLE_SORT = 'mass_hole'
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _core_with_hole():
|
|
48
|
+
core = allocate_core()
|
|
49
|
+
core.contract_registry[_HOLE_SORT] = ProcessContract(
|
|
50
|
+
face={'inputs': {'mass': 'float'}, 'outputs': {'mass': 'float'}})
|
|
51
|
+
return core
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_import_form_filler_face_resolves():
|
|
55
|
+
"""``_FaceWidget``'s ports are found through the ``!`` import address — the
|
|
56
|
+
unit at the heart of the bug (previously an empty face)."""
|
|
57
|
+
core = _core_with_hole()
|
|
58
|
+
inputs, outputs = collect_face(core, _IMPORT_ADDRESS)
|
|
59
|
+
assert set(inputs) == {'mass'}
|
|
60
|
+
assert set(outputs) == {'mass'}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_face_sorted_site_admits_import_form_filler():
|
|
64
|
+
"""THE FIX: a face-sorted site admits the ``local:!module.Class`` filler
|
|
65
|
+
even though that class is NOT in the link registry."""
|
|
66
|
+
core = _core_with_hole()
|
|
67
|
+
# Guard: the class is genuinely absent from the registry, so admission can
|
|
68
|
+
# only come from the import-form resolution path, not a stray registration.
|
|
69
|
+
assert core.link_registry.get(f'{__name__}._FaceWidget') is None
|
|
70
|
+
|
|
71
|
+
ok, reason = admits_why(core, Site(_sort=_HOLE_SORT), _IMPORT_ADDRESS)
|
|
72
|
+
assert ok, f'import-form filler was rejected: {reason}'
|
|
73
|
+
assert admits(core, Site(_sort=_HOLE_SORT), _IMPORT_ADDRESS)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_face_sorted_site_still_admits_registry_form_filler():
|
|
77
|
+
"""CONTROL: the bare ``local:<name>`` registry form admits exactly as before
|
|
78
|
+
(the fix keeps the registry ``.get(...)`` path intact)."""
|
|
79
|
+
core = _core_with_hole()
|
|
80
|
+
core.register_link(_REGISTRY_NAME, _FaceWidget)
|
|
81
|
+
|
|
82
|
+
ok, reason = admits_why(core, Site(_sort=_HOLE_SORT), _REGISTRY_ADDRESS)
|
|
83
|
+
assert ok, f'registry-form filler was rejected: {reason}'
|
|
84
|
+
assert admits(core, Site(_sort=_HOLE_SORT), _REGISTRY_ADDRESS)
|
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
"""find_candidates — enumerate the process registry for a hole.
|
|
2
|
-
|
|
3
|
-
The reverse direction §4 of the design: given an open sorted site, return the
|
|
4
|
-
registered processes whose DECLARED contract subsumes the hole's, each with
|
|
5
|
-
why (full match or near-miss + failing condition). Enumerates core.link_registry
|
|
6
|
-
(the only process registry in this repo — there is no separate composite or
|
|
7
|
-
generator registry; a composite registered as a link is enumerated like any
|
|
8
|
-
other edge).
|
|
9
|
-
"""
|
|
10
|
-
from dataclasses import dataclass, field
|
|
11
|
-
|
|
12
|
-
from bigraph_schema.assembly import contract_of
|
|
13
|
-
from bigraph_schema.contract import resolve_contract
|
|
14
|
-
from bigraph_schema.subsumption import contract_subsumes
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
@dataclass
|
|
18
|
-
class CandidateMatch:
|
|
19
|
-
address: str
|
|
20
|
-
match: str # 'full' | 'partial'
|
|
21
|
-
over_provides: list = field(default_factory=list)
|
|
22
|
-
fails: list = field(default_factory=list)
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
def _candidate_contract(core, address):
|
|
26
|
-
"""Declared contract of a registered process, without a crash.
|
|
27
|
-
|
|
28
|
-
Returns a ProcessContract or None. The cheapest declared-face source is
|
|
29
|
-
resolve_contract(edge_class({}, core)) (the repo's own pattern); a
|
|
30
|
-
candidate whose construction needs real config raises and is reported as
|
|
31
|
-
None so the caller can skip it.
|
|
32
|
-
"""
|
|
33
|
-
edge_class = core.link_registry.get(address)
|
|
34
|
-
if edge_class is None:
|
|
35
|
-
return None
|
|
36
|
-
try:
|
|
37
|
-
instance = edge_class({}, core)
|
|
38
|
-
return resolve_contract(instance)
|
|
39
|
-
except Exception: # noqa: BLE001 - uninstantiable candidate: skip, don't crash
|
|
40
|
-
return None
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
def find_candidates(core, site):
|
|
44
|
-
"""Processes whose declared contract satisfies the hole at `site`.
|
|
45
|
-
|
|
46
|
-
Full matches first, then near-misses (face conforms but a bound/unit/
|
|
47
|
-
condition fails). A candidate whose face does not conform at all, or that
|
|
48
|
-
cannot be instantiated to read its contract, is omitted. Each result
|
|
49
|
-
carries why.
|
|
50
|
-
"""
|
|
51
|
-
hole = contract_of(core, site)
|
|
52
|
-
if hole is None:
|
|
53
|
-
return []
|
|
54
|
-
|
|
55
|
-
full, partial = [], []
|
|
56
|
-
for address in core.list_processes():
|
|
57
|
-
candidate = _candidate_contract(core, address)
|
|
58
|
-
if candidate is None:
|
|
59
|
-
continue
|
|
60
|
-
result = contract_subsumes(core, hole, candidate)
|
|
61
|
-
if result.ok:
|
|
62
|
-
full.append(CandidateMatch(address, 'full', result.over_provides, []))
|
|
63
|
-
elif any(f['condition'].startswith('face.') for f in result.fails):
|
|
64
|
-
continue
|
|
65
|
-
else:
|
|
66
|
-
partial.append(CandidateMatch(address, 'partial', result.over_provides, result.fails))
|
|
67
|
-
|
|
68
|
-
return full + partial
|
|
@@ -1,191 +0,0 @@
|
|
|
1
|
-
"""Declaration-level contract subsumption — the reverse of contract_admits.
|
|
2
|
-
|
|
3
|
-
contract_admits (assembly.py) asks "does this filler INSTANCE admit into the
|
|
4
|
-
hole?". Subsumption asks "does this process's DECLARED contract admit into the
|
|
5
|
-
hole's declared contract?" — the relation find_candidates needs. Purely
|
|
6
|
-
additive; the instance-level admit path is untouched.
|
|
7
|
-
"""
|
|
8
|
-
import re
|
|
9
|
-
from dataclasses import dataclass, field
|
|
10
|
-
|
|
11
|
-
try:
|
|
12
|
-
from bigraph_schema.units import units as _unit_registry
|
|
13
|
-
except Exception: # noqa: BLE001 - pint is optional, mirror contract_audit
|
|
14
|
-
_unit_registry = None
|
|
15
|
-
|
|
16
|
-
from bigraph_schema.contract_expr import parse as _parse_expr, names_in as _names_in
|
|
17
|
-
|
|
18
|
-
_BRACKET = re.compile(r'^[A-Za-z_][\w]*\[(?P<units>[^\]]+)\]$')
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
def port_bounds(port):
|
|
22
|
-
"""(_min, _max, _units) from a raw port declaration, dict or string.
|
|
23
|
-
|
|
24
|
-
Reads the RAW declaration, never a resolved schema (core.resolve drops
|
|
25
|
-
_min/_max for plain float). A 'float[fg]' string carries units only.
|
|
26
|
-
"""
|
|
27
|
-
if isinstance(port, dict):
|
|
28
|
-
return port.get('_min'), port.get('_max'), port.get('_units')
|
|
29
|
-
if isinstance(port, str):
|
|
30
|
-
match = _BRACKET.match(port.strip())
|
|
31
|
-
if match:
|
|
32
|
-
return None, None, match.group('units')
|
|
33
|
-
return None, None, None
|
|
34
|
-
return None, None, None
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
def range_subsumes(required_port, candidate_port):
|
|
38
|
-
"""Candidate's numeric range ⊆ required's. Returns (ok, reason).
|
|
39
|
-
|
|
40
|
-
An absent required bound means "unconstrained on that side" and accepts
|
|
41
|
-
any candidate bound. An absent candidate bound against a present required
|
|
42
|
-
bound is a failure (candidate admits values the hole forbids).
|
|
43
|
-
"""
|
|
44
|
-
req_lo, req_hi, req_units = port_bounds(required_port)
|
|
45
|
-
cand_lo, cand_hi, cand_units = port_bounds(candidate_port)
|
|
46
|
-
|
|
47
|
-
# Bounds/units is the exact region (spec §4): normalize candidate bounds
|
|
48
|
-
# into the required units before comparing, so a scale mismatch (3 g vs a
|
|
49
|
-
# 5 mg ceiling) is caught. Incompatible/unparseable units are left raw and
|
|
50
|
-
# surfaced by units_compatible instead.
|
|
51
|
-
if req_units and cand_units and _unit_registry is not None:
|
|
52
|
-
try:
|
|
53
|
-
factor = _unit_registry.Quantity(1, cand_units).to(req_units).magnitude
|
|
54
|
-
if cand_lo is not None:
|
|
55
|
-
cand_lo = cand_lo * factor
|
|
56
|
-
if cand_hi is not None:
|
|
57
|
-
cand_hi = cand_hi * factor
|
|
58
|
-
except Exception: # noqa: BLE001 - incompatible/unparseable units: leave raw
|
|
59
|
-
pass
|
|
60
|
-
|
|
61
|
-
if req_lo is not None:
|
|
62
|
-
if cand_lo is None or cand_lo < req_lo:
|
|
63
|
-
return False, f'candidate _min {cand_lo} is below required _min {req_lo}'
|
|
64
|
-
if req_hi is not None:
|
|
65
|
-
if cand_hi is None or cand_hi > req_hi:
|
|
66
|
-
return False, f'candidate _max {cand_hi} is above required _max {req_hi}'
|
|
67
|
-
return True, None
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
def units_compatible(required_port, candidate_port):
|
|
71
|
-
"""Candidate units convertible to required units. Returns (ok, reason).
|
|
72
|
-
|
|
73
|
-
Absent units on either side, or pint unavailable, is permissive (cannot
|
|
74
|
-
disprove compatibility → do not reject). Matches contract_audit's stance.
|
|
75
|
-
"""
|
|
76
|
-
_, _, req_units = port_bounds(required_port)
|
|
77
|
-
_, _, cand_units = port_bounds(candidate_port)
|
|
78
|
-
if not req_units or not cand_units:
|
|
79
|
-
return True, None
|
|
80
|
-
if _unit_registry is None:
|
|
81
|
-
return True, None
|
|
82
|
-
try:
|
|
83
|
-
req = _unit_registry.Unit(req_units)
|
|
84
|
-
cand = _unit_registry.Unit(cand_units)
|
|
85
|
-
except Exception as error: # noqa: BLE001 - unparseable unit: cannot check
|
|
86
|
-
return True, f'unit parse skipped: {error}'
|
|
87
|
-
if req.is_compatible_with(cand):
|
|
88
|
-
return True, None
|
|
89
|
-
return False, f'cannot convert candidate {cand_units!r} to required {req_units!r}'
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
def _normalized(expr):
|
|
93
|
-
"""A kind-stable signature of an expression: the referenced-name set plus
|
|
94
|
-
the stripped source. Structural, not semantic (per spec §11): two exprs
|
|
95
|
-
that parse to the same names + text are treated as the same guarantee.
|
|
96
|
-
"""
|
|
97
|
-
try:
|
|
98
|
-
ast = _parse_expr(expr)
|
|
99
|
-
return (frozenset(_names_in(ast)), (expr or '').replace(' ', ''))
|
|
100
|
-
except Exception: # noqa: BLE001 - unparseable: fall back to raw text
|
|
101
|
-
return (frozenset(), (expr or '').replace(' ', ''))
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
def conditions_cover(hole_contract, candidate_contract):
|
|
105
|
-
"""Does the candidate DECLARE every condition the hole requires? Structural.
|
|
106
|
-
|
|
107
|
-
For each hole condition, the candidate must declare one of the same kind
|
|
108
|
-
whose expression normalizes identically. A sound filter: it will not pass
|
|
109
|
-
a candidate that fails to even claim a required guarantee. Returns
|
|
110
|
-
(ok, missing).
|
|
111
|
-
"""
|
|
112
|
-
missing = []
|
|
113
|
-
hole_conditions = hole_contract.conditions() if hasattr(hole_contract, 'conditions') else []
|
|
114
|
-
cand_conditions = candidate_contract.conditions() if hasattr(candidate_contract, 'conditions') else []
|
|
115
|
-
cand_index = {(c['kind'], _normalized(c.get('expr'))) for c in cand_conditions}
|
|
116
|
-
for condition in hole_conditions:
|
|
117
|
-
key = (condition['kind'], _normalized(condition.get('expr')))
|
|
118
|
-
if key not in cand_index:
|
|
119
|
-
missing.append({'condition': f"{condition['kind']}:{condition.get('name')}",
|
|
120
|
-
'reason': f"candidate does not declare {condition['kind']} "
|
|
121
|
-
f"{condition.get('name')!r} ({condition.get('expr')!r})"})
|
|
122
|
-
return (not missing), missing
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
def face_subsumes(core, required_face, candidate_face):
|
|
126
|
-
"""Structural + bound/unit subsumption between two declared faces.
|
|
127
|
-
|
|
128
|
-
The candidate must provide every required port at a type core.resolve
|
|
129
|
-
accepts (mirrors face_conforms), and for each required port its numeric
|
|
130
|
-
range must be ⊆ and its units convertible. Over-provided ports are fine
|
|
131
|
-
and recorded. Returns (ok, fails, over_provides).
|
|
132
|
-
"""
|
|
133
|
-
fails = []
|
|
134
|
-
over_provides = []
|
|
135
|
-
required_face = required_face or {}
|
|
136
|
-
candidate_face = candidate_face or {}
|
|
137
|
-
|
|
138
|
-
# Note: the per-port type check below mirrors the existing face_conforms
|
|
139
|
-
# (core.resolve), which is intentionally loose on primitive type identity
|
|
140
|
-
# (e.g. it does not reject 'string' for a 'float' port). Phase 2a's new
|
|
141
|
-
# strictness is bounds/units (here) and conditions (conditions_cover) — NOT
|
|
142
|
-
# primitive-type identity, so that subsumption mirrors the admit path.
|
|
143
|
-
for direction in ('inputs', 'outputs'):
|
|
144
|
-
required = required_face.get(direction) or {}
|
|
145
|
-
provided = candidate_face.get(direction) or {}
|
|
146
|
-
if not isinstance(required, dict) or not isinstance(provided, dict):
|
|
147
|
-
continue
|
|
148
|
-
for port, req_schema in required.items():
|
|
149
|
-
if port not in provided:
|
|
150
|
-
fails.append({'condition': f'face.{direction}.{port}',
|
|
151
|
-
'reason': f'candidate does not provide {direction} port {port!r}'})
|
|
152
|
-
continue
|
|
153
|
-
cand_schema = provided[port]
|
|
154
|
-
try:
|
|
155
|
-
core.resolve(req_schema, cand_schema)
|
|
156
|
-
except Exception as error: # noqa: BLE001 - resolve failure = non-conforming type
|
|
157
|
-
fails.append({'condition': f'face.{direction}.{port}',
|
|
158
|
-
'reason': f'{direction} port {port!r} type does not resolve: {error}'})
|
|
159
|
-
continue
|
|
160
|
-
ok, reason = range_subsumes(req_schema, cand_schema)
|
|
161
|
-
if not ok:
|
|
162
|
-
fails.append({'condition': f'bounds.{direction}.{port}', 'reason': reason})
|
|
163
|
-
ok, reason = units_compatible(req_schema, cand_schema)
|
|
164
|
-
if not ok:
|
|
165
|
-
fails.append({'condition': f'units.{direction}.{port}', 'reason': reason})
|
|
166
|
-
for port in provided:
|
|
167
|
-
if port not in required:
|
|
168
|
-
over_provides.append(f'{direction}.{port}')
|
|
169
|
-
|
|
170
|
-
return (not fails), fails, over_provides
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
@dataclass
|
|
174
|
-
class SubsumptionResult:
|
|
175
|
-
ok: bool
|
|
176
|
-
over_provides: list = field(default_factory=list)
|
|
177
|
-
fails: list = field(default_factory=list) # [{'condition','reason'}]
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
def contract_subsumes(core, hole_contract, candidate_contract):
|
|
181
|
-
"""Does candidate's declared contract satisfy the hole's? The reverse,
|
|
182
|
-
declaration-level counterpart of contract_admits. Face + bounds + units
|
|
183
|
-
are exact; conditions are structural (spec §4/§11). Returns a
|
|
184
|
-
SubsumptionResult; ok iff nothing failed.
|
|
185
|
-
"""
|
|
186
|
-
hole_face = getattr(hole_contract, 'face', None) or {}
|
|
187
|
-
cand_face = getattr(candidate_contract, 'face', None) or {}
|
|
188
|
-
_, fails, over = face_subsumes(core, hole_face, cand_face)
|
|
189
|
-
_, missing = conditions_cover(hole_contract, candidate_contract)
|
|
190
|
-
all_fails = list(fails) + list(missing)
|
|
191
|
-
return SubsumptionResult(ok=(not all_fails), over_provides=over, fails=all_fails)
|
|
@@ -1,95 +0,0 @@
|
|
|
1
|
-
from bigraph_schema.core import allocate_core
|
|
2
|
-
from bigraph_schema.contract import ProcessContract, narrow_condition
|
|
3
|
-
from bigraph_schema.matching import find_candidates
|
|
4
|
-
from bigraph_schema.schema import Site
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
def _register_contract_hole(core, sort, hole_contract):
|
|
8
|
-
core.contract_registry[sort] = hole_contract
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
def test_full_and_near_miss_are_both_returned():
|
|
12
|
-
core = allocate_core()
|
|
13
|
-
hole = narrow_condition(
|
|
14
|
-
ProcessContract(face={'inputs': {'m': 'float'}, 'outputs': {'m': 'float'}}),
|
|
15
|
-
'post', 'outputs.m >= 0', name='nonneg')
|
|
16
|
-
_register_contract_hole(core, 'hole_sort', hole)
|
|
17
|
-
|
|
18
|
-
from bigraph_schema.edge import Edge as Process
|
|
19
|
-
|
|
20
|
-
class GoodProc(Process):
|
|
21
|
-
contract = narrow_condition(
|
|
22
|
-
ProcessContract(face={'inputs': {'m': 'float'}, 'outputs': {'m': 'float'}}),
|
|
23
|
-
'post', 'outputs.m >= 0', name='nonneg')
|
|
24
|
-
def inputs(self): return {'m': 'float'}
|
|
25
|
-
def outputs(self): return {'m': 'float'}
|
|
26
|
-
def update(self, state, interval): return {}
|
|
27
|
-
|
|
28
|
-
class NearProc(Process): # face fits, but does not declare the guarantee
|
|
29
|
-
def inputs(self): return {'m': 'float'}
|
|
30
|
-
def outputs(self): return {'m': 'float'}
|
|
31
|
-
def update(self, state, interval): return {}
|
|
32
|
-
|
|
33
|
-
core.register_link('good_proc', GoodProc)
|
|
34
|
-
core.register_link('near_proc', NearProc)
|
|
35
|
-
|
|
36
|
-
results = find_candidates(core, Site(_sort='hole_sort'))
|
|
37
|
-
by_addr = {r.address: r for r in results}
|
|
38
|
-
assert by_addr['good_proc'].match == 'full'
|
|
39
|
-
assert by_addr['near_proc'].match == 'partial'
|
|
40
|
-
assert any('nonneg' in f['reason'] for f in by_addr['near_proc'].fails)
|
|
41
|
-
assert [r.match for r in results].index('full') < [r.match for r in results].index('partial')
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
def test_uninstantiable_candidate_is_skipped_not_crash():
|
|
45
|
-
core = allocate_core()
|
|
46
|
-
hole = ProcessContract(face={'inputs': {'m': 'float'}, 'outputs': {}})
|
|
47
|
-
_register_contract_hole(core, 'hole2', hole)
|
|
48
|
-
from bigraph_schema.edge import Edge as Process
|
|
49
|
-
|
|
50
|
-
class Explodes(Process):
|
|
51
|
-
def __init__(self, config=None, core=None):
|
|
52
|
-
raise RuntimeError('needs real config')
|
|
53
|
-
def inputs(self): return {'m': 'float'}
|
|
54
|
-
def outputs(self): return {}
|
|
55
|
-
def update(self, state, interval): return {}
|
|
56
|
-
|
|
57
|
-
core.register_link('explodes', Explodes)
|
|
58
|
-
results = find_candidates(core, Site(_sort='hole2'))
|
|
59
|
-
assert all(r.address != 'explodes' for r in results)
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
def test_end_to_end_template_hole_surfaces_fitting_and_near_miss():
|
|
63
|
-
"""A hole requiring a mass-conservation guarantee: a conserving process is
|
|
64
|
-
a full match; a non-conserving one of the same shape is a near-miss naming
|
|
65
|
-
the exact failing guarantee (the §4 'copasi fits except…' example)."""
|
|
66
|
-
core = allocate_core()
|
|
67
|
-
hole = narrow_condition(
|
|
68
|
-
ProcessContract(face={'inputs': {'mass': {'_type': 'float', '_min': 0, '_units': 'mg'}},
|
|
69
|
-
'outputs': {'mass': {'_type': 'float', '_min': 0, '_units': 'mg'}}}),
|
|
70
|
-
'invariant', 'outputs.mass - inputs.mass <= tol', name='conservation', tol=1e-9)
|
|
71
|
-
_register_contract_hole(core, 'conserver', hole)
|
|
72
|
-
|
|
73
|
-
from bigraph_schema.edge import Edge as Process
|
|
74
|
-
|
|
75
|
-
class Conserving(Process):
|
|
76
|
-
contract = narrow_condition(
|
|
77
|
-
ProcessContract(face={'inputs': {'mass': {'_type': 'float', '_min': 0, '_units': 'g'}},
|
|
78
|
-
'outputs': {'mass': {'_type': 'float', '_min': 0, '_units': 'g'}}}),
|
|
79
|
-
'invariant', 'outputs.mass - inputs.mass <= tol', name='conservation', tol=1e-9)
|
|
80
|
-
def inputs(self): return {'mass': {'_type': 'float', '_min': 0, '_units': 'g'}}
|
|
81
|
-
def outputs(self): return {'mass': {'_type': 'float', '_min': 0, '_units': 'g'}}
|
|
82
|
-
def update(self, state, interval): return {}
|
|
83
|
-
|
|
84
|
-
class Leaking(Process): # same shape + units, no conservation guarantee
|
|
85
|
-
def inputs(self): return {'mass': {'_type': 'float', '_min': 0, '_units': 'g'}}
|
|
86
|
-
def outputs(self): return {'mass': {'_type': 'float', '_min': 0, '_units': 'g'}}
|
|
87
|
-
def update(self, state, interval): return {}
|
|
88
|
-
|
|
89
|
-
core.register_link('conserving', Conserving)
|
|
90
|
-
core.register_link('leaking', Leaking)
|
|
91
|
-
|
|
92
|
-
results = {r.address: r for r in find_candidates(core, Site(_sort='conserver'))}
|
|
93
|
-
assert results['conserving'].match == 'full'
|
|
94
|
-
assert results['leaking'].match == 'partial'
|
|
95
|
-
assert any('conservation' in f['reason'] for f in results['leaking'].fails)
|
|
@@ -1,171 +0,0 @@
|
|
|
1
|
-
from bigraph_schema.subsumption import port_bounds, range_subsumes, units_compatible
|
|
2
|
-
|
|
3
|
-
def test_port_bounds_parses_both_spellings():
|
|
4
|
-
assert port_bounds({'_type': 'float', '_min': 0, '_max': 5, '_units': 'fg'}) == (0, 5, 'fg')
|
|
5
|
-
assert port_bounds('float[fg]') == (None, None, 'fg')
|
|
6
|
-
assert port_bounds('float') == (None, None, None)
|
|
7
|
-
assert port_bounds({'_type': 'float'}) == (None, None, None)
|
|
8
|
-
|
|
9
|
-
def test_range_subsumes_candidate_within_required():
|
|
10
|
-
# candidate [0,3] ⊆ required [0,5] → ok
|
|
11
|
-
ok, _ = range_subsumes({'_min': 0, '_max': 5}, {'_min': 0, '_max': 3})
|
|
12
|
-
assert ok is True
|
|
13
|
-
|
|
14
|
-
def test_range_subsumes_candidate_exceeds_required():
|
|
15
|
-
# candidate [-1,5] not ⊆ required [0,5] → fail
|
|
16
|
-
ok, reason = range_subsumes({'_min': 0, '_max': 5}, {'_min': -1, '_max': 5})
|
|
17
|
-
assert ok is False and 'min' in reason
|
|
18
|
-
|
|
19
|
-
def test_range_subsumes_required_unbounded_accepts_anything():
|
|
20
|
-
ok, _ = range_subsumes({'_type': 'float'}, {'_min': -10, '_max': 10})
|
|
21
|
-
assert ok is True
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
def test_units_compatible_same_dimension():
|
|
25
|
-
ok, _ = units_compatible({'_units': 'mg'}, {'_units': 'g'})
|
|
26
|
-
assert ok is True # mass ↔ mass
|
|
27
|
-
|
|
28
|
-
def test_units_incompatible_dimensions():
|
|
29
|
-
ok, reason = units_compatible({'_units': 'mg'}, {'_units': 'second'})
|
|
30
|
-
assert ok is False and 'convert' in reason.lower()
|
|
31
|
-
|
|
32
|
-
def test_units_absent_is_permissive():
|
|
33
|
-
assert units_compatible({'_type': 'float'}, {'_type': 'float'})[0] is True
|
|
34
|
-
assert units_compatible({'_units': 'mg'}, {'_type': 'float'})[0] is True # candidate unitless
|
|
35
|
-
|
|
36
|
-
def test_units_compatible_without_pint_is_permissive(monkeypatch):
|
|
37
|
-
import bigraph_schema.subsumption as sub
|
|
38
|
-
monkeypatch.setattr(sub, '_unit_registry', None)
|
|
39
|
-
ok, _ = units_compatible({'_units': 'mg'}, {'_units': 'second'})
|
|
40
|
-
assert ok is True # pint absent → cannot check → permit (matches audit_contract)
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
# Face subsumption tests (Task 3)
|
|
44
|
-
from bigraph_schema.core import allocate_core
|
|
45
|
-
from bigraph_schema.subsumption import face_subsumes
|
|
46
|
-
|
|
47
|
-
def _core():
|
|
48
|
-
return allocate_core()
|
|
49
|
-
|
|
50
|
-
def test_face_subsumes_exact():
|
|
51
|
-
core = _core()
|
|
52
|
-
face = {'inputs': {'m': {'_type': 'float', '_min': 0, '_max': 5000, '_units': 'mg'}}, 'outputs': {}}
|
|
53
|
-
ok, fails, over = face_subsumes(core, face, {'inputs': {'m': {'_type': 'float', '_min': 0, '_max': 3, '_units': 'g'}}, 'outputs': {}})
|
|
54
|
-
assert ok is True and fails == []
|
|
55
|
-
|
|
56
|
-
def test_face_missing_required_port_fails():
|
|
57
|
-
core = _core()
|
|
58
|
-
face = {'inputs': {'m': 'float'}, 'outputs': {}}
|
|
59
|
-
ok, fails, _ = face_subsumes(core, face, {'inputs': {}, 'outputs': {}})
|
|
60
|
-
assert ok is False and any('m' in f['reason'] for f in fails)
|
|
61
|
-
|
|
62
|
-
def test_face_out_of_range_fails():
|
|
63
|
-
core = _core()
|
|
64
|
-
face = {'inputs': {'m': {'_type': 'float', '_min': 0, '_max': 5}}, 'outputs': {}}
|
|
65
|
-
ok, fails, _ = face_subsumes(core, face, {'inputs': {'m': {'_type': 'float', '_min': -1, '_max': 5}}, 'outputs': {}})
|
|
66
|
-
assert ok is False and any('min' in f['reason'] for f in fails)
|
|
67
|
-
|
|
68
|
-
def test_over_provision_is_allowed_and_recorded():
|
|
69
|
-
core = _core()
|
|
70
|
-
face = {'inputs': {'m': 'float'}, 'outputs': {}}
|
|
71
|
-
ok, fails, over = face_subsumes(core, face, {'inputs': {'m': 'float', 'extra': 'float'}, 'outputs': {}})
|
|
72
|
-
assert ok is True and fails == [] and 'inputs.extra' in over
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
# Condition coverage tests (Task 4)
|
|
76
|
-
from bigraph_schema.contract import ProcessContract, narrow_condition
|
|
77
|
-
from bigraph_schema.subsumption import conditions_cover
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
def _with(kind, expr, name):
|
|
81
|
-
return narrow_condition(ProcessContract(face={'inputs': {}, 'outputs': {}}), kind, expr, name=name)
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
def test_candidate_declares_required_guarantee():
|
|
85
|
-
hole = _with('post', 'outputs.mass >= 0', 'nonneg')
|
|
86
|
-
cand = _with('post', 'outputs.mass >= 0', 'nonneg')
|
|
87
|
-
ok, missing = conditions_cover(hole, cand)
|
|
88
|
-
assert ok is True and missing == []
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
def test_candidate_missing_required_guarantee():
|
|
92
|
-
hole = _with('post', 'outputs.mass >= 0', 'nonneg')
|
|
93
|
-
cand = ProcessContract(face={'inputs': {}, 'outputs': {}}) # declares nothing
|
|
94
|
-
ok, missing = conditions_cover(hole, cand)
|
|
95
|
-
assert ok is False and any('nonneg' in m['reason'] or 'post' in m['reason'] for m in missing)
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
def test_candidate_matches_by_normalized_expr_not_name():
|
|
99
|
-
hole = _with('invariant', 'outputs.x - inputs.x <= tol', 'conservation')
|
|
100
|
-
cand = _with('invariant', 'outputs.x - inputs.x <= tol', 'different_name')
|
|
101
|
-
ok, missing = conditions_cover(hole, cand)
|
|
102
|
-
assert ok is True # same kind + same parsed expr ⇒ covered
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
def test_bare_hole_is_covered_by_anything():
|
|
106
|
-
hole = ProcessContract(face={'inputs': {}, 'outputs': {}})
|
|
107
|
-
cand = ProcessContract(face={'inputs': {}, 'outputs': {}})
|
|
108
|
-
assert conditions_cover(hole, cand) == (True, [])
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
def test_face_mirrors_face_conforms_resolvability():
|
|
112
|
-
# Pins inherited behavior: a primitive TYPE mismatch is NOT caught at the
|
|
113
|
-
# face level (core.resolve does not reject it), matching the existing
|
|
114
|
-
# face_conforms / admit path. Phase 2a adds bounds/units/conditions strictness.
|
|
115
|
-
core = _core()
|
|
116
|
-
face = {'inputs': {'m': 'float'}, 'outputs': {}}
|
|
117
|
-
ok, fails, _ = face_subsumes(core, face, {'inputs': {'m': 'string'}, 'outputs': {}})
|
|
118
|
-
assert ok is True and fails == []
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
# Contract subsumption tests (Task 5)
|
|
122
|
-
from bigraph_schema.subsumption import contract_subsumes, SubsumptionResult
|
|
123
|
-
|
|
124
|
-
def test_bare_hole_matches_on_face_alone():
|
|
125
|
-
core = _core()
|
|
126
|
-
hole = ProcessContract(face={'inputs': {'m': 'float'}, 'outputs': {}})
|
|
127
|
-
cand = ProcessContract(face={'inputs': {'m': 'float', 'extra': 'float'}, 'outputs': {}})
|
|
128
|
-
result = contract_subsumes(core, hole, cand)
|
|
129
|
-
assert isinstance(result, SubsumptionResult)
|
|
130
|
-
assert result.ok is True and result.fails == [] and 'inputs.extra' in result.over_provides
|
|
131
|
-
|
|
132
|
-
def test_near_miss_face_ok_but_missing_guarantee():
|
|
133
|
-
core = _core()
|
|
134
|
-
hole = narrow_condition(ProcessContract(face={'inputs': {'m': 'float'}, 'outputs': {'m': 'float'}}),
|
|
135
|
-
'post', 'outputs.m >= 0', name='nonneg')
|
|
136
|
-
cand = ProcessContract(face={'inputs': {'m': 'float'}, 'outputs': {'m': 'float'}})
|
|
137
|
-
result = contract_subsumes(core, hole, cand)
|
|
138
|
-
assert result.ok is False
|
|
139
|
-
assert any('nonneg' in f['reason'] for f in result.fails)
|
|
140
|
-
|
|
141
|
-
def test_full_fail_on_missing_port():
|
|
142
|
-
core = _core()
|
|
143
|
-
hole = ProcessContract(face={'inputs': {'m': 'float'}, 'outputs': {}})
|
|
144
|
-
cand = ProcessContract(face={'inputs': {}, 'outputs': {}})
|
|
145
|
-
result = contract_subsumes(core, hole, cand)
|
|
146
|
-
assert result.ok is False and any('face' in f['condition'] for f in result.fails)
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
def test_range_subsumes_unit_scaled_exceeds():
|
|
150
|
-
# 3 g = 3000 mg, which exceeds the 5 mg ceiling → fail after unit normalization
|
|
151
|
-
ok, reason = range_subsumes({'_min': 0, '_max': 5, '_units': 'mg'},
|
|
152
|
-
{'_min': 0, '_max': 3, '_units': 'g'})
|
|
153
|
-
assert ok is False and 'max' in reason
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
def test_range_subsumes_unit_scaled_within():
|
|
157
|
-
# 3 g = 3000 mg ⊆ 5000 mg ceiling → ok
|
|
158
|
-
ok, _ = range_subsumes({'_min': 0, '_max': 5000, '_units': 'mg'},
|
|
159
|
-
{'_min': 0, '_max': 3, '_units': 'g'})
|
|
160
|
-
assert ok is True
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
def test_conditions_cover_validity_kind():
|
|
164
|
-
hole = narrow_condition(ProcessContract(face={'inputs': {}, 'outputs': {}}),
|
|
165
|
-
'validity', 'config.k > 0', name='k_positive')
|
|
166
|
-
cand = narrow_condition(ProcessContract(face={'inputs': {}, 'outputs': {}}),
|
|
167
|
-
'validity', 'config.k > 0', name='k_positive')
|
|
168
|
-
assert conditions_cover(hole, cand) == (True, [])
|
|
169
|
-
bare = ProcessContract(face={'inputs': {}, 'outputs': {}})
|
|
170
|
-
ok, missing = conditions_cover(hole, bare)
|
|
171
|
-
assert ok is False and any('k_positive' in m['reason'] for m in missing)
|
|
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
|
|
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
|
|
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
|