tnfr 4.5.2__py3-none-any.whl → 6.0.0__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.
Files changed (161) hide show
  1. tnfr/__init__.py +228 -49
  2. tnfr/__init__.pyi +40 -0
  3. tnfr/_compat.py +11 -0
  4. tnfr/_version.py +7 -0
  5. tnfr/_version.pyi +7 -0
  6. tnfr/alias.py +106 -21
  7. tnfr/alias.pyi +140 -0
  8. tnfr/cache.py +666 -512
  9. tnfr/cache.pyi +232 -0
  10. tnfr/callback_utils.py +2 -9
  11. tnfr/callback_utils.pyi +105 -0
  12. tnfr/cli/__init__.py +21 -7
  13. tnfr/cli/__init__.pyi +47 -0
  14. tnfr/cli/arguments.py +42 -20
  15. tnfr/cli/arguments.pyi +33 -0
  16. tnfr/cli/execution.py +54 -20
  17. tnfr/cli/execution.pyi +80 -0
  18. tnfr/cli/utils.py +0 -2
  19. tnfr/cli/utils.pyi +8 -0
  20. tnfr/config/__init__.py +12 -0
  21. tnfr/config/__init__.pyi +8 -0
  22. tnfr/config/constants.py +104 -0
  23. tnfr/config/constants.pyi +12 -0
  24. tnfr/{config.py → config/init.py} +11 -7
  25. tnfr/config/init.pyi +8 -0
  26. tnfr/config/operator_names.py +106 -0
  27. tnfr/config/operator_names.pyi +28 -0
  28. tnfr/config/presets.py +104 -0
  29. tnfr/config/presets.pyi +7 -0
  30. tnfr/constants/__init__.py +78 -24
  31. tnfr/constants/__init__.pyi +104 -0
  32. tnfr/constants/core.py +1 -2
  33. tnfr/constants/core.pyi +17 -0
  34. tnfr/constants/init.pyi +12 -0
  35. tnfr/constants/metric.py +4 -12
  36. tnfr/constants/metric.pyi +19 -0
  37. tnfr/constants_glyphs.py +9 -91
  38. tnfr/constants_glyphs.pyi +12 -0
  39. tnfr/dynamics/__init__.py +112 -634
  40. tnfr/dynamics/__init__.pyi +83 -0
  41. tnfr/dynamics/adaptation.py +201 -0
  42. tnfr/dynamics/aliases.py +22 -0
  43. tnfr/dynamics/coordination.py +343 -0
  44. tnfr/dynamics/dnfr.py +1936 -354
  45. tnfr/dynamics/dnfr.pyi +33 -0
  46. tnfr/dynamics/integrators.py +369 -75
  47. tnfr/dynamics/integrators.pyi +35 -0
  48. tnfr/dynamics/runtime.py +521 -0
  49. tnfr/dynamics/sampling.py +8 -5
  50. tnfr/dynamics/sampling.pyi +7 -0
  51. tnfr/dynamics/selectors.py +680 -0
  52. tnfr/execution.py +56 -41
  53. tnfr/execution.pyi +65 -0
  54. tnfr/flatten.py +7 -7
  55. tnfr/flatten.pyi +28 -0
  56. tnfr/gamma.py +54 -37
  57. tnfr/gamma.pyi +40 -0
  58. tnfr/glyph_history.py +85 -38
  59. tnfr/glyph_history.pyi +53 -0
  60. tnfr/grammar.py +19 -338
  61. tnfr/grammar.pyi +13 -0
  62. tnfr/helpers/__init__.py +110 -30
  63. tnfr/helpers/__init__.pyi +66 -0
  64. tnfr/helpers/numeric.py +1 -0
  65. tnfr/helpers/numeric.pyi +12 -0
  66. tnfr/immutable.py +55 -19
  67. tnfr/immutable.pyi +37 -0
  68. tnfr/initialization.py +12 -10
  69. tnfr/initialization.pyi +73 -0
  70. tnfr/io.py +99 -34
  71. tnfr/io.pyi +11 -0
  72. tnfr/locking.pyi +7 -0
  73. tnfr/metrics/__init__.pyi +20 -0
  74. tnfr/metrics/coherence.py +934 -294
  75. tnfr/metrics/common.py +1 -3
  76. tnfr/metrics/common.pyi +15 -0
  77. tnfr/metrics/core.py +192 -34
  78. tnfr/metrics/core.pyi +13 -0
  79. tnfr/metrics/diagnosis.py +707 -101
  80. tnfr/metrics/diagnosis.pyi +89 -0
  81. tnfr/metrics/export.py +27 -13
  82. tnfr/metrics/glyph_timing.py +218 -38
  83. tnfr/metrics/reporting.py +22 -18
  84. tnfr/metrics/reporting.pyi +12 -0
  85. tnfr/metrics/sense_index.py +199 -25
  86. tnfr/metrics/sense_index.pyi +9 -0
  87. tnfr/metrics/trig.py +53 -18
  88. tnfr/metrics/trig.pyi +12 -0
  89. tnfr/metrics/trig_cache.py +3 -7
  90. tnfr/metrics/trig_cache.pyi +10 -0
  91. tnfr/node.py +148 -125
  92. tnfr/node.pyi +161 -0
  93. tnfr/observers.py +44 -30
  94. tnfr/observers.pyi +46 -0
  95. tnfr/ontosim.py +14 -13
  96. tnfr/ontosim.pyi +33 -0
  97. tnfr/operators/__init__.py +84 -52
  98. tnfr/operators/__init__.pyi +31 -0
  99. tnfr/operators/definitions.py +181 -0
  100. tnfr/operators/definitions.pyi +92 -0
  101. tnfr/operators/jitter.py +86 -23
  102. tnfr/operators/jitter.pyi +11 -0
  103. tnfr/operators/registry.py +80 -0
  104. tnfr/operators/registry.pyi +15 -0
  105. tnfr/operators/remesh.py +141 -57
  106. tnfr/presets.py +9 -54
  107. tnfr/presets.pyi +7 -0
  108. tnfr/py.typed +0 -0
  109. tnfr/rng.py +259 -73
  110. tnfr/rng.pyi +14 -0
  111. tnfr/selector.py +24 -17
  112. tnfr/selector.pyi +19 -0
  113. tnfr/sense.py +55 -43
  114. tnfr/sense.pyi +30 -0
  115. tnfr/structural.py +44 -267
  116. tnfr/structural.pyi +46 -0
  117. tnfr/telemetry/__init__.py +13 -0
  118. tnfr/telemetry/verbosity.py +37 -0
  119. tnfr/tokens.py +3 -2
  120. tnfr/tokens.pyi +41 -0
  121. tnfr/trace.py +272 -82
  122. tnfr/trace.pyi +68 -0
  123. tnfr/types.py +345 -6
  124. tnfr/types.pyi +145 -0
  125. tnfr/utils/__init__.py +158 -0
  126. tnfr/utils/__init__.pyi +133 -0
  127. tnfr/utils/cache.py +755 -0
  128. tnfr/utils/cache.pyi +156 -0
  129. tnfr/{collections_utils.py → utils/data.py} +57 -90
  130. tnfr/utils/data.pyi +73 -0
  131. tnfr/utils/graph.py +87 -0
  132. tnfr/utils/graph.pyi +10 -0
  133. tnfr/utils/init.py +746 -0
  134. tnfr/utils/init.pyi +85 -0
  135. tnfr/{json_utils.py → utils/io.py} +13 -18
  136. tnfr/utils/io.pyi +10 -0
  137. tnfr/utils/validators.py +130 -0
  138. tnfr/utils/validators.pyi +19 -0
  139. tnfr/validation/__init__.py +25 -0
  140. tnfr/validation/__init__.pyi +17 -0
  141. tnfr/validation/compatibility.py +59 -0
  142. tnfr/validation/compatibility.pyi +8 -0
  143. tnfr/validation/grammar.py +149 -0
  144. tnfr/validation/grammar.pyi +11 -0
  145. tnfr/validation/rules.py +194 -0
  146. tnfr/validation/rules.pyi +18 -0
  147. tnfr/validation/syntax.py +151 -0
  148. tnfr/validation/syntax.pyi +7 -0
  149. tnfr-6.0.0.dist-info/METADATA +135 -0
  150. tnfr-6.0.0.dist-info/RECORD +157 -0
  151. tnfr/graph_utils.py +0 -84
  152. tnfr/import_utils.py +0 -228
  153. tnfr/logging_utils.py +0 -116
  154. tnfr/validators.py +0 -84
  155. tnfr/value_utils.py +0 -59
  156. tnfr-4.5.2.dist-info/METADATA +0 -379
  157. tnfr-4.5.2.dist-info/RECORD +0 -67
  158. {tnfr-4.5.2.dist-info → tnfr-6.0.0.dist-info}/WHEEL +0 -0
  159. {tnfr-4.5.2.dist-info → tnfr-6.0.0.dist-info}/entry_points.txt +0 -0
  160. {tnfr-4.5.2.dist-info → tnfr-6.0.0.dist-info}/licenses/LICENSE.md +0 -0
  161. {tnfr-4.5.2.dist-info → tnfr-6.0.0.dist-info}/top_level.txt +0 -0
tnfr/graph_utils.py DELETED
@@ -1,84 +0,0 @@
1
- """Utilities for graph-level bookkeeping.
2
-
3
- This module centralises helpers that operate on the metadata stored inside
4
- graph objects. Besides flagging ΔNFR preparation caches it also exposes
5
- lightweight adapters to obtain the canonical ``graph`` mapping and to read
6
- validated configuration dictionaries.
7
- """
8
-
9
- from __future__ import annotations
10
-
11
- import warnings
12
- from types import MappingProxyType
13
- from typing import Any, Mapping
14
-
15
- __all__ = (
16
- "get_graph",
17
- "get_graph_mapping",
18
- "mark_dnfr_prep_dirty",
19
- "supports_add_edge",
20
- )
21
-
22
-
23
- def get_graph(obj: Any) -> Any:
24
- """Return ``obj.graph`` when present or ``obj`` otherwise."""
25
- return getattr(obj, "graph", obj)
26
-
27
-
28
- def get_graph_mapping(
29
- G: Any, key: str, warn_msg: str
30
- ) -> Mapping[str, Any] | None:
31
- """Return an immutable view of ``G``'s stored mapping for ``key``.
32
-
33
- The helper normalises access to ``G.graph[key]`` by returning
34
- ``None`` when the key is missing or holds a non-mapping value. When a
35
- mapping is found it is wrapped in :class:`types.MappingProxyType` to guard
36
- against accidental mutation. ``warn_msg`` is emitted via
37
- :func:`warnings.warn` when the stored value is not a mapping.
38
- """
39
- graph = get_graph(G)
40
- getter = getattr(graph, "get", None)
41
- if getter is None:
42
- return None
43
-
44
- data = getter(key)
45
- if data is None:
46
- return None
47
- if not isinstance(data, Mapping):
48
- warnings.warn(warn_msg, UserWarning, stacklevel=2)
49
- return None
50
- return MappingProxyType(data)
51
-
52
-
53
- def mark_dnfr_prep_dirty(G: Any) -> None:
54
- """Flag ΔNFR preparation data as stale.
55
-
56
- Parameters
57
- ----------
58
- G : Any
59
- Graph-like object whose ``graph`` attribute will receive the
60
- ``"_dnfr_prep_dirty"`` flag.
61
-
62
- Returns
63
- -------
64
- None
65
- This function mutates ``G`` in place.
66
- """
67
- graph = get_graph(G)
68
- graph["_dnfr_prep_dirty"] = True
69
-
70
-
71
- def supports_add_edge(graph: Any) -> bool:
72
- """Return ``True`` if ``graph`` exposes an ``add_edge`` method.
73
-
74
- Parameters
75
- ----------
76
- graph : Any
77
- Object representing a graph.
78
-
79
- Returns
80
- -------
81
- bool
82
- ``True`` when ``graph`` implements ``add_edge``; ``False`` otherwise.
83
- """
84
- return hasattr(graph, "add_edge")
tnfr/import_utils.py DELETED
@@ -1,228 +0,0 @@
1
- """Helpers for optional imports and cached access to heavy modules.
2
-
3
- This module centralises caching for optional dependencies. It exposes
4
- :func:`cached_import`, backed by a small :func:`functools.lru_cache`, alongside a
5
- light-weight registry that tracks failed imports and warnings. Use
6
- :func:`prune_failed_imports` or ``cached_import.cache_clear`` to reset state when
7
- new packages become available at runtime.
8
- """
9
-
10
- from __future__ import annotations
11
-
12
- import importlib
13
- import warnings
14
- from collections import OrderedDict
15
- from dataclasses import dataclass, field
16
- from functools import lru_cache
17
- from typing import Any, Callable, Literal
18
- import threading
19
-
20
- from .logging_utils import get_logger
21
-
22
- __all__ = (
23
- "cached_import",
24
- "get_numpy",
25
- "get_nodonx",
26
- "prune_failed_imports",
27
- "IMPORT_LOG",
28
- )
29
-
30
-
31
- logger = get_logger(__name__)
32
-
33
-
34
- def _emit(message: str, mode: Literal["warn", "log", "both"]) -> None:
35
- """Emit ``message`` via :mod:`warnings`, logger or both."""
36
-
37
- if mode in ("warn", "both"):
38
- warnings.warn(message, RuntimeWarning, stacklevel=2)
39
- if mode in ("log", "both"):
40
- logger.warning(message)
41
-
42
-
43
- EMIT_MAP: dict[str, Callable[[str], None]] = {
44
- "warn": lambda msg: _emit(msg, "warn"),
45
- "log": lambda msg: _emit(msg, "log"),
46
- "both": lambda msg: _emit(msg, "both"),
47
- }
48
-
49
-
50
- def _format_failure_message(module: str, attr: str | None, err: Exception) -> str:
51
- """Return a standardised failure message."""
52
-
53
- return (
54
- f"Failed to import module '{module}': {err}"
55
- if isinstance(err, ImportError)
56
- else f"Module '{module}' has no attribute '{attr}': {err}"
57
- )
58
-
59
-
60
- _FAILED_IMPORT_LIMIT = 128
61
- _DEFAULT_CACHE_SIZE = 128
62
-
63
-
64
- @dataclass(slots=True)
65
- class ImportRegistry:
66
- """Process-wide registry tracking failed imports and emitted warnings."""
67
-
68
- limit: int = _FAILED_IMPORT_LIMIT
69
- failed: OrderedDict[str, None] = field(default_factory=OrderedDict)
70
- warned: set[str] = field(default_factory=set)
71
- lock: threading.Lock = field(default_factory=threading.Lock)
72
-
73
- def _insert(self, key: str) -> None:
74
- self.failed[key] = None
75
- self.failed.move_to_end(key)
76
- while len(self.failed) > self.limit:
77
- self.failed.popitem(last=False)
78
-
79
- def record_failure(self, key: str, *, module: str | None = None) -> None:
80
- """Record ``key`` and, optionally, ``module`` as failed imports."""
81
-
82
- with self.lock:
83
- self._insert(key)
84
- if module and module != key:
85
- self._insert(module)
86
-
87
- def discard(self, key: str) -> None:
88
- """Remove ``key`` from the registry and clear its warning state."""
89
-
90
- with self.lock:
91
- self.failed.pop(key, None)
92
- self.warned.discard(key)
93
-
94
- def mark_warning(self, module: str) -> bool:
95
- """Mark ``module`` as warned and return ``True`` if it was new."""
96
-
97
- with self.lock:
98
- if module in self.warned:
99
- return False
100
- self.warned.add(module)
101
- return True
102
-
103
- def clear(self) -> None:
104
- """Remove all failure records and warning markers."""
105
-
106
- with self.lock:
107
- self.failed.clear()
108
- self.warned.clear()
109
-
110
- def __contains__(self, key: str) -> bool: # pragma: no cover - trivial
111
- with self.lock:
112
- return key in self.failed
113
-
114
-
115
- _IMPORT_STATE = ImportRegistry()
116
- # Public alias to ease direct introspection in tests and diagnostics.
117
- IMPORT_LOG = _IMPORT_STATE
118
-
119
-
120
- @lru_cache(maxsize=_DEFAULT_CACHE_SIZE)
121
- def _import_cached(module_name: str, attr: str | None) -> tuple[bool, Any]:
122
- """Import ``module_name`` (and optional ``attr``) capturing failures."""
123
-
124
- try:
125
- module = importlib.import_module(module_name)
126
- obj = getattr(module, attr) if attr else module
127
- except (ImportError, AttributeError) as exc:
128
- return False, exc
129
- return True, obj
130
-
131
-
132
- def _warn_failure(
133
- module: str,
134
- attr: str | None,
135
- err: Exception,
136
- *,
137
- emit: Literal["warn", "log", "both"] = "warn",
138
- ) -> None:
139
- """Emit a warning about a failed import."""
140
-
141
- msg = _format_failure_message(module, attr, err)
142
- if _IMPORT_STATE.mark_warning(module):
143
- EMIT_MAP[emit](msg)
144
- else:
145
- logger.debug(msg)
146
-
147
-
148
- def cached_import(
149
- module_name: str,
150
- attr: str | None = None,
151
- *,
152
- fallback: Any | None = None,
153
- emit: Literal["warn", "log", "both"] = "warn",
154
- ) -> Any | None:
155
- """Import ``module_name`` (and optional ``attr``) with caching and fallback.
156
-
157
- Parameters
158
- ----------
159
- module_name:
160
- Module to import.
161
- attr:
162
- Optional attribute to fetch from the module.
163
- fallback:
164
- Value returned when the import fails.
165
- emit:
166
- Destination for warnings emitted on failure (``"warn"``/``"log"``/``"both"``).
167
- """
168
-
169
- key = module_name if attr is None else f"{module_name}.{attr}"
170
- success, result = _import_cached(module_name, attr)
171
- if success:
172
- _IMPORT_STATE.discard(key)
173
- if attr is not None:
174
- _IMPORT_STATE.discard(module_name)
175
- return result
176
- exc = result
177
- include_module = isinstance(exc, ImportError)
178
- _warn_failure(module_name, attr, exc, emit=emit)
179
- _IMPORT_STATE.record_failure(key, module=module_name if include_module else None)
180
- return fallback
181
-
182
-
183
- def _clear_default_cache() -> None:
184
- global _NP_MISSING_LOGGED
185
-
186
- _import_cached.cache_clear()
187
- _NP_MISSING_LOGGED = False
188
-
189
-
190
- cached_import.cache_clear = _clear_default_cache # type: ignore[attr-defined]
191
-
192
-
193
- _NP_MISSING_LOGGED = False
194
-
195
-
196
- def get_numpy() -> Any | None:
197
- """Return the cached :mod:`numpy` module when available.
198
-
199
- Import attempts are delegated to :func:`cached_import`, which already caches
200
- successes and failures. A lightweight flag suppresses duplicate debug logs
201
- when :mod:`numpy` is unavailable so callers can repeatedly probe without
202
- spamming the logger.
203
- """
204
-
205
- global _NP_MISSING_LOGGED
206
-
207
- np = cached_import("numpy")
208
- if np is None:
209
- if not _NP_MISSING_LOGGED:
210
- logger.debug("Failed to import numpy; continuing in non-vectorised mode")
211
- _NP_MISSING_LOGGED = True
212
- return None
213
-
214
- if _NP_MISSING_LOGGED:
215
- _NP_MISSING_LOGGED = False
216
- return np
217
-
218
-
219
- def get_nodonx() -> type | None:
220
- """Return :class:`tnfr.node.NodoNX` using import caching."""
221
-
222
- return cached_import("tnfr.node", "NodoNX")
223
-
224
-
225
- def prune_failed_imports() -> None:
226
- """Clear the registry of recorded import failures and warnings."""
227
-
228
- _IMPORT_STATE.clear()
tnfr/logging_utils.py DELETED
@@ -1,116 +0,0 @@
1
- """Logging utilities for TNFR.
2
-
3
- Centralises creation of module-specific loggers so that all TNFR
4
- modules share a consistent configuration.
5
- """
6
-
7
- from __future__ import annotations
8
-
9
- import logging
10
- import threading
11
- from typing import Any, Hashable, Mapping
12
-
13
- __all__ = ("_configure_root", "get_logger", "WarnOnce", "warn_once")
14
-
15
- _LOGGING_CONFIGURED = False
16
-
17
-
18
- def _configure_root() -> None:
19
- """Ensure the root logger has handlers and a default format."""
20
-
21
- global _LOGGING_CONFIGURED
22
- if _LOGGING_CONFIGURED:
23
- return
24
-
25
- root = logging.getLogger()
26
- if not root.handlers:
27
- kwargs = {"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"}
28
- if root.level == logging.NOTSET:
29
- kwargs["level"] = logging.INFO
30
- logging.basicConfig(**kwargs)
31
-
32
- _LOGGING_CONFIGURED = True
33
-
34
-
35
- def get_logger(name: str) -> logging.Logger:
36
- """Return a module-specific logger."""
37
- _configure_root()
38
- return logging.getLogger(name)
39
-
40
-
41
- class WarnOnce:
42
- """Log a warning only once for each unique key.
43
-
44
- ``WarnOnce`` tracks seen keys in a bounded :class:`set`. When ``maxsize`` is
45
- reached an arbitrary key is evicted to keep memory usage stable; ordered
46
- eviction is intentionally avoided to keep the implementation lightweight.
47
- Instances are callable and accept either a mapping of keys to values or a
48
- single key/value pair. Passing ``maxsize <= 0`` disables caching and logs on
49
- every invocation.
50
- """
51
-
52
- def __init__(self, logger: logging.Logger, msg: str, *, maxsize: int = 1024) -> None:
53
- self._logger = logger
54
- self._msg = msg
55
- self._maxsize = maxsize
56
- self._seen: set[Hashable] = set()
57
- self._lock = threading.Lock()
58
-
59
- def _mark_seen(self, key: Hashable) -> bool:
60
- """Return ``True`` when ``key`` has not been seen before."""
61
-
62
- if self._maxsize <= 0:
63
- # Caching disabled – always log.
64
- return True
65
- if key in self._seen:
66
- return False
67
- if len(self._seen) >= self._maxsize:
68
- # ``set.pop()`` removes an arbitrary element which is acceptable for
69
- # this lightweight cache.
70
- self._seen.pop()
71
- self._seen.add(key)
72
- return True
73
-
74
- def __call__(
75
- self,
76
- data: Mapping[Hashable, Any] | Hashable,
77
- value: Any | None = None,
78
- ) -> None:
79
- """Log new keys found in ``data``.
80
-
81
- ``data`` may be a mapping of keys to payloads or a single key. When
82
- called with a single key ``value`` customises the payload passed to the
83
- logging message; the key itself is used when ``value`` is omitted.
84
- """
85
-
86
- if isinstance(data, Mapping):
87
- new_items: dict[Hashable, Any] = {}
88
- with self._lock:
89
- for key, item_value in data.items():
90
- if self._mark_seen(key):
91
- new_items[key] = item_value
92
- if new_items:
93
- self._logger.warning(self._msg, new_items)
94
- return
95
-
96
- key = data
97
- payload = value if value is not None else data
98
- with self._lock:
99
- should_log = self._mark_seen(key)
100
- if should_log:
101
- self._logger.warning(self._msg, payload)
102
-
103
- def clear(self) -> None:
104
- """Reset tracked keys."""
105
- with self._lock:
106
- self._seen.clear()
107
-
108
-
109
- def warn_once(
110
- logger: logging.Logger,
111
- msg: str,
112
- *,
113
- maxsize: int = 1024,
114
- ) -> WarnOnce:
115
- """Return a :class:`WarnOnce` logger."""
116
- return WarnOnce(logger, msg, maxsize=maxsize)
tnfr/validators.py DELETED
@@ -1,84 +0,0 @@
1
- """Validation utilities."""
2
-
3
- from __future__ import annotations
4
-
5
- import numbers
6
- import sys
7
-
8
- from .constants import get_aliases, get_param
9
- from .alias import get_attr
10
- from .sense import sigma_vector_from_graph
11
- from .helpers.numeric import within_range
12
- from .constants_glyphs import GLYPHS_CANONICAL_SET
13
-
14
- ALIAS_EPI = get_aliases("EPI")
15
- ALIAS_VF = get_aliases("VF")
16
-
17
- __all__ = ("validate_window", "run_validators")
18
-
19
-
20
- def validate_window(window: int, *, positive: bool = False) -> int:
21
- """Validate ``window`` as an ``int`` and return it.
22
-
23
- Non-integer values raise :class:`TypeError`. When ``positive`` is ``True``
24
- the value must be strictly greater than zero; otherwise it may be zero.
25
- Negative values always raise :class:`ValueError`.
26
- """
27
-
28
- if isinstance(window, bool) or not isinstance(window, numbers.Integral):
29
- raise TypeError("'window' must be an integer")
30
- if window < 0 or (positive and window == 0):
31
- kind = "positive" if positive else "non-negative"
32
- raise ValueError(f"'window'={window} must be {kind}")
33
- return int(window)
34
-
35
-
36
- def _require_attr(data, alias, node, name):
37
- """Return attribute value or raise if missing."""
38
- val = get_attr(data, alias, None)
39
- if val is None:
40
- raise ValueError(f"Missing {name} attribute in node {node}")
41
- return val
42
-
43
-
44
- def _validate_sigma(G) -> None:
45
- sv = sigma_vector_from_graph(G)
46
- if sv.get("mag", 0.0) > 1.0 + sys.float_info.epsilon:
47
- raise ValueError("σ norm exceeds 1")
48
-
49
-
50
- def _check_epi_vf(epi, vf, epi_min, epi_max, vf_min, vf_max, n):
51
- _check_range(epi, epi_min, epi_max, "EPI", n)
52
- _check_range(vf, vf_min, vf_max, "VF", n)
53
-
54
-
55
- def _out_of_range_msg(name, node, val):
56
- return f"{name} out of range in node {node}: {val}"
57
-
58
-
59
- def _check_range(val, lower, upper, name, node, tol: float = 1e-9):
60
- if not within_range(val, lower, upper, tol):
61
- raise ValueError(_out_of_range_msg(name, node, val))
62
-
63
-
64
- def _check_glyph(g, n):
65
- if g and g not in GLYPHS_CANONICAL_SET:
66
- raise KeyError(f"Invalid glyph {g} in node {n}")
67
-
68
-
69
- def run_validators(G) -> None:
70
- """Run all invariant validators on ``G`` with a single node pass."""
71
- from .glyph_history import last_glyph
72
-
73
- epi_min = float(get_param(G, "EPI_MIN"))
74
- epi_max = float(get_param(G, "EPI_MAX"))
75
- vf_min = float(get_param(G, "VF_MIN"))
76
- vf_max = float(get_param(G, "VF_MAX"))
77
-
78
- for n, data in G.nodes(data=True):
79
- epi = _require_attr(data, ALIAS_EPI, n, "EPI")
80
- vf = _require_attr(data, ALIAS_VF, n, "VF")
81
- _check_epi_vf(epi, vf, epi_min, epi_max, vf_min, vf_max, n)
82
- _check_glyph(last_glyph(data), n)
83
-
84
- _validate_sigma(G)
tnfr/value_utils.py DELETED
@@ -1,59 +0,0 @@
1
- """Conversion helpers with logging for value normalisation.
2
-
3
- Wraps conversion callables to standardise error handling and logging.
4
- """
5
-
6
- from __future__ import annotations
7
-
8
- from typing import Any, Callable, TypeVar
9
- import logging
10
- from .logging_utils import get_logger
11
-
12
- T = TypeVar("T")
13
-
14
- logger = get_logger(__name__)
15
-
16
- __all__ = ("convert_value",)
17
-
18
-
19
- def convert_value(
20
- value: Any,
21
- conv: Callable[[Any], T],
22
- *,
23
- strict: bool = False,
24
- key: str | None = None,
25
- log_level: int | None = None,
26
- ) -> tuple[bool, T | None]:
27
- """Attempt to convert a value and report failures.
28
-
29
- Parameters
30
- ----------
31
- value : Any
32
- Input value to convert.
33
- conv : Callable[[Any], T]
34
- Callable performing the conversion.
35
- strict : bool, optional
36
- Raise exceptions directly instead of logging them. Defaults to ``False``.
37
- key : str, optional
38
- Name associated with the value for logging context.
39
- log_level : int, optional
40
- Logging level used when reporting failures. Defaults to
41
- ``logging.DEBUG``.
42
-
43
- Returns
44
- -------
45
- tuple[bool, T | None]
46
- ``(True, result)`` on success or ``(False, None)`` when conversion
47
- fails.
48
- """
49
- try:
50
- return True, conv(value)
51
- except (ValueError, TypeError) as exc:
52
- if strict:
53
- raise
54
- level = log_level if log_level is not None else logging.DEBUG
55
- if key is not None:
56
- logger.log(level, "Could not convert value for %r: %s", key, exc)
57
- else:
58
- logger.log(level, "Could not convert value: %s", exc)
59
- return False, None