PyDecisionGraph 0.3.1.post2__cp313-cp313-win_amd64.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 (144) hide show
  1. decision_graph/__init__.py +26 -0
  2. decision_graph/decision_tree/__init__.py +85 -0
  3. decision_graph/decision_tree/bake/__infra__.pxd +502 -0
  4. decision_graph/decision_tree/bake/__init__.pxd +502 -0
  5. decision_graph/decision_tree/bake/__init__.py +29 -0
  6. decision_graph/decision_tree/bake/c_action.cp313-win_amd64.pyd +0 -0
  7. decision_graph/decision_tree/bake/c_action.h +324 -0
  8. decision_graph/decision_tree/bake/c_action.pxd +54 -0
  9. decision_graph/decision_tree/bake/c_action.pyi +126 -0
  10. decision_graph/decision_tree/bake/c_action.pyx +65 -0
  11. decision_graph/decision_tree/bake/c_allocator_protocol.cp313-win_amd64.pyd +0 -0
  12. decision_graph/decision_tree/bake/c_allocator_protocol.pxd +24 -0
  13. decision_graph/decision_tree/bake/c_allocator_protocol.pyi +61 -0
  14. decision_graph/decision_tree/bake/c_allocator_protocol.pyx +109 -0
  15. decision_graph/decision_tree/bake/c_bake.cp313-win_amd64.pyd +0 -0
  16. decision_graph/decision_tree/bake/c_bake.h +629 -0
  17. decision_graph/decision_tree/bake/c_bake.pxd +52 -0
  18. decision_graph/decision_tree/bake/c_bake.pyi +151 -0
  19. decision_graph/decision_tree/bake/c_bake.pyx +142 -0
  20. decision_graph/decision_tree/bake/c_collections.cp313-win_amd64.pyd +0 -0
  21. decision_graph/decision_tree/bake/c_collections.h +692 -0
  22. decision_graph/decision_tree/bake/c_collections.pxd +52 -0
  23. decision_graph/decision_tree/bake/c_collections.pyi +193 -0
  24. decision_graph/decision_tree/bake/c_collections.pyx +161 -0
  25. decision_graph/decision_tree/bake/c_const.cp313-win_amd64.pyd +0 -0
  26. decision_graph/decision_tree/bake/c_const.h +395 -0
  27. decision_graph/decision_tree/bake/c_const.pxd +56 -0
  28. decision_graph/decision_tree/bake/c_const.pyi +305 -0
  29. decision_graph/decision_tree/bake/c_const.pyx +278 -0
  30. decision_graph/decision_tree/bake/c_edge.cp313-win_amd64.pyd +0 -0
  31. decision_graph/decision_tree/bake/c_edge.h +511 -0
  32. decision_graph/decision_tree/bake/c_edge.pxd +117 -0
  33. decision_graph/decision_tree/bake/c_edge.pyi +192 -0
  34. decision_graph/decision_tree/bake/c_edge.pyx +270 -0
  35. decision_graph/decision_tree/bake/c_eval.h +848 -0
  36. decision_graph/decision_tree/bake/c_eval.pxd +40 -0
  37. decision_graph/decision_tree/bake/c_expr.cp313-win_amd64.pyd +0 -0
  38. decision_graph/decision_tree/bake/c_expr.h +1900 -0
  39. decision_graph/decision_tree/bake/c_expr.pxd +129 -0
  40. decision_graph/decision_tree/bake/c_expr.pyi +280 -0
  41. decision_graph/decision_tree/bake/c_expr.pyx +272 -0
  42. decision_graph/decision_tree/bake/c_hierarchy.cp313-win_amd64.pyd +0 -0
  43. decision_graph/decision_tree/bake/c_hierarchy.h +731 -0
  44. decision_graph/decision_tree/bake/c_hierarchy.pxd +71 -0
  45. decision_graph/decision_tree/bake/c_hierarchy.pyi +409 -0
  46. decision_graph/decision_tree/bake/c_hierarchy.pyx +277 -0
  47. decision_graph/decision_tree/bake/c_logic_group.cp313-win_amd64.pyd +0 -0
  48. decision_graph/decision_tree/bake/c_logic_group.h +1226 -0
  49. decision_graph/decision_tree/bake/c_logic_group.pxd +162 -0
  50. decision_graph/decision_tree/bake/c_logic_group.pyi +264 -0
  51. decision_graph/decision_tree/bake/c_logic_group.pyx +308 -0
  52. decision_graph/decision_tree/bake/c_node.cp313-win_amd64.pyd +0 -0
  53. decision_graph/decision_tree/bake/c_node.h +2660 -0
  54. decision_graph/decision_tree/bake/c_node.pxd +381 -0
  55. decision_graph/decision_tree/bake/c_node.pyi +438 -0
  56. decision_graph/decision_tree/bake/c_node.pyx +639 -0
  57. decision_graph/decision_tree/bake/c_reconstruct.cp313-win_amd64.pyd +0 -0
  58. decision_graph/decision_tree/bake/c_reconstruct.pxd +63 -0
  59. decision_graph/decision_tree/bake/c_reconstruct.pyi +60 -0
  60. decision_graph/decision_tree/bake/c_reconstruct.pyx +252 -0
  61. decision_graph/decision_tree/bake/c_var.cp313-win_amd64.pyd +0 -0
  62. decision_graph/decision_tree/bake/c_var.h +2054 -0
  63. decision_graph/decision_tree/bake/c_var.pxd +205 -0
  64. decision_graph/decision_tree/bake/c_var.pyi +271 -0
  65. decision_graph/decision_tree/bake/c_var.pyx +228 -0
  66. decision_graph/decision_tree/capi/__init__.pxd +33 -0
  67. decision_graph/decision_tree/capi/__init__.py +57 -0
  68. decision_graph/decision_tree/capi/c_abc.cp313-win_amd64.pyd +0 -0
  69. decision_graph/decision_tree/capi/c_abc.pxd +246 -0
  70. decision_graph/decision_tree/capi/c_abc.pyi +770 -0
  71. decision_graph/decision_tree/capi/c_abc.pyx +1529 -0
  72. decision_graph/decision_tree/capi/c_collection.cp313-win_amd64.pyd +0 -0
  73. decision_graph/decision_tree/capi/c_collection.pxd +22 -0
  74. decision_graph/decision_tree/capi/c_collection.pyi +245 -0
  75. decision_graph/decision_tree/capi/c_collection.pyx +138 -0
  76. decision_graph/decision_tree/capi/c_node.cp313-win_amd64.pyd +0 -0
  77. decision_graph/decision_tree/capi/c_node.pxd +95 -0
  78. decision_graph/decision_tree/capi/c_node.pyi +492 -0
  79. decision_graph/decision_tree/capi/c_node.pyx +551 -0
  80. decision_graph/decision_tree/exc.py +189 -0
  81. decision_graph/decision_tree/native/__init__.py +57 -0
  82. decision_graph/decision_tree/native/abc.py +1164 -0
  83. decision_graph/decision_tree/native/collection.py +134 -0
  84. decision_graph/decision_tree/native/node.py +521 -0
  85. decision_graph/includes/decision_graph/decision_tree/bake/c_action.c +16320 -0
  86. decision_graph/includes/decision_graph/decision_tree/bake/c_action.h +324 -0
  87. decision_graph/includes/decision_graph/decision_tree/bake/c_allocator_protocol.c +12473 -0
  88. decision_graph/includes/decision_graph/decision_tree/bake/c_bake.c +16485 -0
  89. decision_graph/includes/decision_graph/decision_tree/bake/c_bake.h +629 -0
  90. decision_graph/includes/decision_graph/decision_tree/bake/c_collections.c +17381 -0
  91. decision_graph/includes/decision_graph/decision_tree/bake/c_collections.h +692 -0
  92. decision_graph/includes/decision_graph/decision_tree/bake/c_const.c +20815 -0
  93. decision_graph/includes/decision_graph/decision_tree/bake/c_const.h +395 -0
  94. decision_graph/includes/decision_graph/decision_tree/bake/c_edge.c +20696 -0
  95. decision_graph/includes/decision_graph/decision_tree/bake/c_edge.h +511 -0
  96. decision_graph/includes/decision_graph/decision_tree/bake/c_eval.h +848 -0
  97. decision_graph/includes/decision_graph/decision_tree/bake/c_expr.c +22065 -0
  98. decision_graph/includes/decision_graph/decision_tree/bake/c_expr.h +1900 -0
  99. decision_graph/includes/decision_graph/decision_tree/bake/c_hierarchy.c +23267 -0
  100. decision_graph/includes/decision_graph/decision_tree/bake/c_hierarchy.h +731 -0
  101. decision_graph/includes/decision_graph/decision_tree/bake/c_logic_group.c +22434 -0
  102. decision_graph/includes/decision_graph/decision_tree/bake/c_logic_group.h +1226 -0
  103. decision_graph/includes/decision_graph/decision_tree/bake/c_node.c +28385 -0
  104. decision_graph/includes/decision_graph/decision_tree/bake/c_node.h +2660 -0
  105. decision_graph/includes/decision_graph/decision_tree/bake/c_reconstruct.c +15955 -0
  106. decision_graph/includes/decision_graph/decision_tree/bake/c_var.c +16881 -0
  107. decision_graph/includes/decision_graph/decision_tree/bake/c_var.h +2054 -0
  108. decision_graph/includes/decision_graph/decision_tree/capi/c_abc.c +59143 -0
  109. decision_graph/includes/decision_graph/decision_tree/capi/c_collection.c +19967 -0
  110. decision_graph/includes/decision_graph/decision_tree/capi/c_node.c +39220 -0
  111. decision_graph/logic_group/__init__.py +25 -0
  112. decision_graph/logic_group/base.py +100 -0
  113. decision_graph/logic_group/pending_request.py +384 -0
  114. decision_graph/webui/__init__.py +24 -0
  115. decision_graph/webui/bake/__init__.py +65 -0
  116. decision_graph/webui/bake/app.py +488 -0
  117. decision_graph/webui/bake/static/d3.v7.min.js +2 -0
  118. decision_graph/webui/bake/static/script.js +1440 -0
  119. decision_graph/webui/bake/static/style.css +920 -0
  120. decision_graph/webui/bake/templates/index.html +183 -0
  121. decision_graph/webui/bake/templates/offline.html +184 -0
  122. decision_graph/webui/capi/__init__.py +54 -0
  123. decision_graph/webui/capi/app.py +366 -0
  124. decision_graph/webui/capi/main.py +53 -0
  125. decision_graph/webui/capi/static/d3.v7.min.js +2 -0
  126. decision_graph/webui/capi/static/script.js +1026 -0
  127. decision_graph/webui/capi/static/style.css +656 -0
  128. decision_graph/webui/capi/templates/index.html +93 -0
  129. decision_graph/webui/capi/templates/offline.html +94 -0
  130. decision_graph/webui/native/__init__.py +54 -0
  131. decision_graph/webui/native/app.py +366 -0
  132. decision_graph/webui/native/main.py +53 -0
  133. decision_graph/webui/native/static/d3.v7.min.js +2 -0
  134. decision_graph/webui/native/static/script.js +1026 -0
  135. decision_graph/webui/native/static/style.css +656 -0
  136. decision_graph/webui/native/templates/index.html +93 -0
  137. decision_graph/webui/native/templates/offline.html +94 -0
  138. pydecisiongraph-0.3.1.post2.dist-info/METADATA +130 -0
  139. pydecisiongraph-0.3.1.post2.dist-info/RECORD +144 -0
  140. pydecisiongraph-0.3.1.post2.dist-info/WHEEL +5 -0
  141. pydecisiongraph-0.3.1.post2.dist-info/licenses/LICENSE +373 -0
  142. pydecisiongraph-0.3.1.post2.dist-info/top_level.txt +2 -0
  143. tests/bake_c_evaluator.cp313-win_amd64.pyd +0 -0
  144. tests/bake_eval_probe.cp313-win_amd64.pyd +0 -0
@@ -0,0 +1,1164 @@
1
+ from __future__ import annotations
2
+
3
+ import linecache
4
+ import operator
5
+ import sys
6
+ import uuid
7
+ from collections.abc import Callable
8
+ from typing import Any, Self, final
9
+
10
+ from . import LOGGER
11
+ from ..exc import *
12
+
13
+ LOGGER = LOGGER.getChild('abc')
14
+
15
+ __all__ = ['Singleton',
16
+ 'NodeEdgeCondition', 'ConditionElse', 'ConditionAny', 'ConditionAuto', 'BinaryCondition', 'ConditionTrue', 'ConditionFalse',
17
+ 'NO_CONDITION', 'ELSE_CONDITION', 'AUTO_CONDITION', 'TRUE_CONDITION', 'FALSE_CONDITION',
18
+ 'SkipContextsBlock', 'LogicExpression', 'LogicNode',
19
+ 'LogicGroupManager', 'LGM', 'LogicGroup',
20
+ 'ActionNode', 'BreakpointNode', 'PlaceholderNode',
21
+ 'NoAction', 'LongAction', 'ShortAction', 'CancelAction']
22
+
23
+
24
+ class Singleton(type):
25
+ _instances = {}
26
+
27
+ def __call__(cls, *args, **kwargs):
28
+ if cls not in cls._instances:
29
+ cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
30
+ return cls._instances[cls]
31
+
32
+
33
+ class NodeEdgeCondition(metaclass=Singleton):
34
+ def __init__(self, value=None):
35
+ self._value = value
36
+
37
+ def __hash__(self):
38
+ return hash(self._value)
39
+
40
+ def __repr__(self):
41
+ return f'<{self.__class__.__name__} {id(self):#0x}>'
42
+
43
+ @property
44
+ def value(self):
45
+ if self._value is None:
46
+ raise ValueError("Condition has no value assigned.")
47
+ return self._value
48
+
49
+ @value.setter
50
+ def value(self, value):
51
+ self._value = value
52
+
53
+
54
+ class ConditionElse(NodeEdgeCondition):
55
+ def __init__(self, *args, **kwargs):
56
+ super().__init__()
57
+ self._value = None
58
+
59
+ def __hash__(self):
60
+ return id(self)
61
+
62
+ def __repr__(self):
63
+ return f'<CONDITION Internal {id(self):#0x}>(Else)'
64
+
65
+ def __str__(self):
66
+ return 'Else'
67
+
68
+ @NodeEdgeCondition.value.setter
69
+ def value(self, value):
70
+ raise NotImplementedError()
71
+
72
+
73
+ class ConditionAny(NodeEdgeCondition):
74
+ def __init__(self, *args, **kwargs):
75
+ super().__init__()
76
+ self._value = None
77
+
78
+ def __hash__(self):
79
+ return id(self)
80
+
81
+ def __repr__(self):
82
+ return f'<CONDITION {id(self):#0x}>(Unconditional)'
83
+
84
+ def __str__(self):
85
+ return 'Unconditional'
86
+
87
+ @NodeEdgeCondition.value.setter
88
+ def value(self, value):
89
+ raise NotImplementedError()
90
+
91
+
92
+ class ConditionAuto(NodeEdgeCondition):
93
+ def __init__(self, *args, **kwargs):
94
+ super().__init__()
95
+ self._value = None
96
+
97
+ def __hash__(self):
98
+ raise NotImplementedError()
99
+
100
+ def __repr__(self):
101
+ return f'<CONDITION Internal {id(self):#0x}>(AutoInfer)'
102
+
103
+ def __str__(self):
104
+ return 'AutoInfer'
105
+
106
+
107
+ class BinaryCondition(NodeEdgeCondition):
108
+ def __init__(self, *args, **kwargs):
109
+ super().__init__()
110
+ self._value = None
111
+
112
+ def __hash__(self):
113
+ return id(self)
114
+
115
+ def __invert__(self):
116
+ raise NotImplementedError()
117
+
118
+ @NodeEdgeCondition.value.setter
119
+ def value(self, value):
120
+ raise NotImplementedError()
121
+
122
+
123
+ class ConditionTrue(BinaryCondition):
124
+ def __repr__(self):
125
+ return f'<CONDITION {id(self):#0x}>(True)'
126
+
127
+ def __str__(self):
128
+ return 'True'
129
+
130
+ def __bool__(self):
131
+ return True
132
+
133
+ def __int__(self):
134
+ return 1
135
+
136
+ def __neg__(self):
137
+ return FALSE_CONDITION
138
+
139
+ def __invert__(self):
140
+ return FALSE_CONDITION
141
+
142
+ @property
143
+ def value(self):
144
+ return True
145
+
146
+
147
+ class ConditionFalse(BinaryCondition):
148
+ def __repr__(self):
149
+ return f'<CONDITION {id(self):#0x}>(False)'
150
+
151
+ def __str__(self):
152
+ return 'False'
153
+
154
+ def __bool__(self):
155
+ return False
156
+
157
+ def __int__(self):
158
+ return 0
159
+
160
+ def __neg__(self):
161
+ return TRUE_CONDITION
162
+
163
+ def __invert__(self):
164
+ return TRUE_CONDITION
165
+
166
+ @property
167
+ def value(self):
168
+ return False
169
+
170
+
171
+ NO_CONDITION = ConditionAny()
172
+ ELSE_CONDITION = ConditionElse()
173
+ AUTO_CONDITION = ConditionAuto()
174
+ TRUE_CONDITION = ConditionTrue()
175
+ FALSE_CONDITION = ConditionFalse()
176
+
177
+
178
+ class SkipContextsBlock(object):
179
+ def __init__(self):
180
+ self.skip_exception = type(f"{self.__class__.__name__}SkipException", (EmptyBlock,), {"owner": self})
181
+ self.tracer_override = False
182
+ self.default_entry_check = True
183
+ self.__cframe = None
184
+ self.__original_trace = None
185
+ self.__enter_line = None
186
+
187
+ def _entry_check(self) -> Any:
188
+ return self.default_entry_check
189
+
190
+ @final
191
+ def __enter__(self):
192
+ if self._entry_check(): # Check if the expression evaluates to True
193
+ self._on_enter()
194
+ return self
195
+
196
+ self.__cframe = sys._getframe().f_back
197
+ self.__original_trace = self.get_trace()
198
+ self.__enter_line = (self.__cframe.f_code.co_filename, self.__cframe.f_lineno)
199
+ self.__cframe.f_trace = self.__tracer_skipper
200
+ sys.settrace(self.__tracer_skipper)
201
+ self.tracer_override = True
202
+
203
+ @final
204
+ def __exit__(self, exc_type, exc_value, exc_traceback):
205
+ sys.settrace(None)
206
+ self.__restore_trace()
207
+
208
+ if exc_type is None:
209
+ self._on_exit()
210
+ return
211
+
212
+ if issubclass(exc_type, self.skip_exception):
213
+ return True
214
+
215
+ self._on_exit()
216
+ # Propagate any other exception raised in the block
217
+ return False
218
+
219
+ def _on_enter(self):
220
+ pass
221
+
222
+ def _on_exit(self):
223
+ pass
224
+
225
+ @staticmethod
226
+ def get_trace():
227
+ try:
228
+ # Check if PyDev debugger is active
229
+ # noinspection PyUnresolvedReferences
230
+ import pydevd
231
+ debugger = pydevd.GetGlobalDebugger()
232
+ if debugger is not None:
233
+ return debugger.trace_dispatch # Use PyDev's trace function
234
+ except ImportError:
235
+ pass # PyDev debugger is not installed or active
236
+
237
+ # Fall back to the standard trace function
238
+ return sys.gettrace()
239
+
240
+ def __restore_trace(self):
241
+ if self.tracer_override:
242
+ # print('[restore_trace]', f'storing tracer to {self.__original_trace}.')
243
+ self.__cframe.f_trace = self.__original_trace
244
+ sys.settrace(self.__original_trace) # Restore the original trace
245
+
246
+ def __tracer_skipper(self, frame, event, arg):
247
+ line = linecache.getline(frame.f_code.co_filename, frame.f_lineno).strip()
248
+ # print(f'[SkipContextsBlock]', line, frame, event, arg, (frame.f_code.co_filename, frame.f_lineno), self.__enter_line)
249
+ if line.startswith(('pass', '...')):
250
+ return self.__tracer_skipper
251
+ elif self.__enter_line == (frame.f_code.co_filename, frame.f_lineno):
252
+ # print(f'[SkipContextsBlock]', 'Restoring trace...')
253
+ self.__restore_trace()
254
+ return self.__tracer_skipper
255
+ elif self.tracer_override:
256
+ raise self.skip_exception("Expression evaluated to be False, cannot enter the block.")
257
+
258
+
259
+ class LogicExpression(SkipContextsBlock):
260
+ def __init__(self, *, expression: float | int | bool | Exception | Callable[[], Any], dtype: type = None, repr: str = None, uid: uuid.UUID = None):
261
+ super().__init__()
262
+ self.expression = expression
263
+ self.dtype = dtype
264
+ self.repr = repr if repr is not None else str(expression)
265
+ self.uid = uuid.uuid4() if uid is None else uid
266
+
267
+ def _entry_check(self) -> Any:
268
+ return bool(self._eval(False))
269
+
270
+ def eval(self, enforce_dtype: bool = False) -> Any:
271
+ return self._eval(enforce_dtype)
272
+
273
+ def _eval(self, enforce_dtype: bool) -> Any:
274
+ if isinstance(self.expression, (float, int, bool, str)):
275
+ value = self.expression
276
+ elif callable(self.expression):
277
+ value = self.expression()
278
+ elif isinstance(self.expression, Exception):
279
+ raise self.expression
280
+ else:
281
+ raise TypeError(f"Unsupported expression type: {type(self.expression)}.")
282
+
283
+ if self.dtype is Any or self.dtype is None:
284
+ pass # No type enforcement
285
+ elif enforce_dtype:
286
+ value = self.dtype(value)
287
+ elif not isinstance(value, self.dtype):
288
+ LOGGER.warning(f"Evaluated value {value} does not match dtype {self.dtype.__name__}.")
289
+
290
+ return value
291
+
292
+ @classmethod
293
+ def cast(cls, value: int | float | bool | Exception | Self, dtype: type = None) -> Self:
294
+ if isinstance(value, LogicExpression):
295
+ return value
296
+ if isinstance(value, (int, float, bool)):
297
+ return LogicExpression(
298
+ expression=value,
299
+ dtype=dtype or type(value),
300
+ repr=str(value)
301
+ )
302
+ if callable(value):
303
+ return LogicExpression(
304
+ expression=value,
305
+ dtype=dtype or Any,
306
+ repr=f"Eval({value})"
307
+ )
308
+ if isinstance(value, Exception):
309
+ return LogicExpression(
310
+ expression=value,
311
+ dtype=dtype or Any,
312
+ repr=f"Raises({type(value).__name__}: {value})"
313
+ )
314
+ raise TypeError(f"Unsupported type for LogicExpression conversion: {type(value)}.")
315
+
316
+ def __bool__(self) -> bool:
317
+ return bool(self.eval())
318
+
319
+ def __and__(self, other: Self | bool) -> Self:
320
+ other_expr = self.cast(value=other, dtype=bool)
321
+ new_expr = LogicExpression(
322
+ expression=lambda: self.eval() and other_expr.eval(),
323
+ dtype=bool,
324
+ repr=f"({self.repr} and {other_expr.repr})"
325
+ )
326
+ return new_expr
327
+
328
+ def __eq__(self, other: int | float | bool | str | Self) -> bool:
329
+ """
330
+ This behavior must differ from the CAPI version.
331
+ Python interface of __eq__ must return a boolean value.
332
+ Otherwise it interferes with the __contains__ operation.
333
+ Comparing reference is the most safe way.
334
+ """
335
+ return id(self) == id(other)
336
+
337
+ def __or__(self, other: Self | bool) -> Self:
338
+ other_expr = self.cast(value=other, dtype=bool)
339
+ new_expr = LogicExpression(
340
+ expression=lambda: self.eval() or other_expr.eval(),
341
+ dtype=bool,
342
+ repr=f"({self.repr} or {other_expr.repr})"
343
+ )
344
+ return new_expr
345
+
346
+ # Math operators
347
+ @staticmethod
348
+ def _math_op(self: LogicExpression, other: int | float | LogicExpression, op: Callable, operator_str: str, dtype: type = None) -> LogicExpression:
349
+ other_expr = LogicExpression.cast(other)
350
+
351
+ if dtype is None:
352
+ dtype = self.dtype
353
+
354
+ new_expr = LogicExpression(
355
+ expression=lambda: op(self.eval(), other_expr.eval()),
356
+ dtype=dtype,
357
+ repr=f"({self.repr} {operator_str} {other_expr.repr})",
358
+ )
359
+ return new_expr
360
+
361
+ def __add__(self, other: int | float | bool | Self) -> Self:
362
+ return LogicExpression._math_op(self, other, operator.add, "+", None)
363
+
364
+ def __sub__(self, other: int | float | bool | Self) -> Self:
365
+ return LogicExpression._math_op(self, other, operator.sub, "-", None)
366
+
367
+ def __mul__(self, other: int | float | bool | Self) -> Self:
368
+ return LogicExpression._math_op(self, other, operator.mul, "*", None)
369
+
370
+ def __truediv__(self, other: int | float | bool | Self) -> Self:
371
+ return LogicExpression._math_op(self, other, operator.truediv, "/", None)
372
+
373
+ def __floordiv__(self, other: int | float | bool | Self) -> Self:
374
+ return LogicExpression._math_op(self, other, operator.floordiv, "//", None)
375
+
376
+ def __pow__(self, other: int | float | bool | Self) -> Self:
377
+ return LogicExpression._math_op(self, other, operator.pow, "**", None)
378
+
379
+ # Comparison operators, note that __eq__, __ne__ is special and should not implement as math operator
380
+ def __lt__(self, other: int | float | bool | Self) -> Self:
381
+ return LogicExpression._math_op(self, other, operator.lt, "<", bool)
382
+
383
+ def __le__(self, other: int | float | bool | Self) -> Self:
384
+ return LogicExpression._math_op(self, other, operator.le, "<=", bool)
385
+
386
+ def __gt__(self, other: int | float | bool | Self) -> Self:
387
+ return LogicExpression._math_op(self, other, operator.gt, ">", bool)
388
+
389
+ def __ge__(self, other: int | float | bool | Self) -> Self:
390
+ return LogicExpression._math_op(self, other, operator.ge, ">=", bool)
391
+
392
+ def __repr__(self) -> str:
393
+ return f"<{self.__class__.__name__}>(dtype={'Any' if self.dtype is None else self.dtype.__name__}, repr={self.repr})"
394
+
395
+
396
+ class LogicGroupManager(metaclass=Singleton):
397
+ def __init__(self):
398
+ # Dictionary to store cached LogicGroup instances
399
+ self._cache = {}
400
+
401
+ # Stack cursors: top of stack is at index 0
402
+ self._active_groups: list[LogicGroup] = []
403
+ self._active_nodes: list[LogicNode] = []
404
+ self._breakpoint_nodes: list[BreakpointNode] = []
405
+ self._shelved_state: list[dict] = []
406
+
407
+ self.inspection_mode = False
408
+ self.vigilant_mode = False
409
+
410
+ def __call__(self, name: str, cls: type[LogicGroup], **kwargs) -> LogicGroup:
411
+ reg_key = (cls.__module__, cls.__qualname__)
412
+ registry = self._cache.get(reg_key)
413
+ if registry is None:
414
+ registry = self._cache[reg_key] = {}
415
+
416
+ if name in registry:
417
+ return registry[name]
418
+
419
+ logic_group = cls(name=name, **kwargs)
420
+ registry[name] = logic_group
421
+ return logic_group
422
+
423
+ def __contains__(self, instance: LogicGroup) -> bool:
424
+ cls = instance.__class__
425
+ name = instance.name
426
+ reg_key = (cls.__module__, cls.__qualname__)
427
+ registry = self._cache.get(reg_key)
428
+ if registry is None:
429
+ return False
430
+ return name in registry
431
+
432
+ def _lg_enter(self, logic_group: LogicGroup):
433
+ # Set parent if there's an active group
434
+ if self._active_groups:
435
+ logic_group.parent = self._active_groups[0]
436
+ self._active_groups.insert(0, logic_group)
437
+
438
+ def _lg_exit(self, logic_group: LogicGroup = None):
439
+ if not self._active_groups:
440
+ raise RuntimeError("No active LogicGroup to exit.")
441
+
442
+ current = self._active_groups[0]
443
+ if logic_group is not None and current is not logic_group:
444
+ raise AssertionError("The LogicGroup is not currently active.")
445
+ # If logic_group is None, we exit the top one (current)
446
+
447
+ # Activate pending breakpoints tied to this group
448
+ for node in self._breakpoint_nodes:
449
+ if node.break_from is current:
450
+ node.await_connection = True
451
+
452
+ self._active_groups.pop(0)
453
+
454
+ def _ln_enter(self, logic_node: LogicNode):
455
+ if isinstance(logic_node, ActionNode):
456
+ LOGGER.error('Enter the with code block of an ActionNode rejected. Check if this is intentional?')
457
+ return
458
+
459
+ # Connect and remove all awaiting breakpoint nodes
460
+ for breakpoint_node in self._breakpoint_nodes[:]:
461
+ if breakpoint_node.await_connection:
462
+ breakpoint_node._connect(logic_node)
463
+ self._breakpoint_nodes.remove(breakpoint_node)
464
+
465
+ # If no active node, push directly
466
+ if not self._active_nodes:
467
+ self._active_nodes.insert(0, logic_node)
468
+ return
469
+
470
+ # Otherwise, get current active node (top = index 0)
471
+ active_node = self._active_nodes[0]
472
+ placeholder = active_node._get_placeholder()
473
+ active_node._replace(placeholder, logic_node)
474
+ self._active_nodes.insert(0, logic_node)
475
+
476
+ def _ln_exit(self, logic_node: LogicNode):
477
+ if not self._active_nodes or self._active_nodes[0] is not logic_node:
478
+ raise AssertionError("The LogicNode is not currently active.")
479
+ self._active_nodes.pop(0)
480
+
481
+ def shelve(self):
482
+ shelved = {
483
+ 'active_groups': self._active_groups.copy(),
484
+ 'active_nodes': self._active_nodes.copy(),
485
+ 'breakpoint_nodes': self._breakpoint_nodes.copy(),
486
+ 'inspection_mode': self.inspection_mode,
487
+ 'vigilant_mode': self.vigilant_mode,
488
+ }
489
+ self._shelved_state.insert(0, shelved)
490
+
491
+ # Reset to clean state
492
+ self._active_groups = []
493
+ self._active_nodes = []
494
+ self._breakpoint_nodes = []
495
+
496
+ return shelved
497
+
498
+ def unshelve(self):
499
+ if not self._shelved_state:
500
+ raise RuntimeError("No shelved state to unshelve.")
501
+
502
+ state = self._shelved_state.pop(0)
503
+
504
+ self._active_groups = state['active_groups']
505
+ self._active_nodes = state['active_nodes']
506
+ self._breakpoint_nodes = state['breakpoint_nodes']
507
+ self.inspection_mode = state['inspection_mode']
508
+ self.vigilant_mode = state['vigilant_mode']
509
+
510
+ def clear(self):
511
+ self._cache.clear()
512
+ self._active_groups.clear()
513
+ self._active_nodes.clear()
514
+ self._breakpoint_nodes.clear()
515
+
516
+ @property
517
+ def active_group(self) -> LogicGroup | None:
518
+ return self._active_groups[0] if self._active_groups else None
519
+
520
+ @property
521
+ def active_node(self) -> LogicNode | None:
522
+ return self._active_nodes[0] if self._active_nodes else None
523
+
524
+
525
+ LGM = LogicGroupManager()
526
+
527
+
528
+ class LogicGroup(object):
529
+ def __init__(self, *, name: str = None, parent: LogicGroup = None, contexts: dict | None = None, **kwargs):
530
+ self.name = f"{self.__class__.__name__}.{uuid.uuid4()}" if name is None else name
531
+
532
+ if self in LGM:
533
+ raise RuntimeError(f"LogicGroup {name} of type {self.__class__.__name__} already exists!")
534
+
535
+ self.parent = parent
536
+ self.Break = type(f"{self.__class__.__name__}Break", (BreakBlock,), {})
537
+ self.contexts = {} if contexts is None else contexts
538
+
539
+ def _break_inspection(self) -> None:
540
+ # Case 1: No active node, breaks affect nothing
541
+ if not LGM._active_nodes:
542
+ return
543
+
544
+ active_node = LGM._active_nodes[0] # top of stack
545
+
546
+ # Step 2.1: Locate placeholder and replace with breakpoint
547
+ placeholder = active_node._get_placeholder()
548
+ breakpoint_node = BreakpointNode()
549
+ breakpoint_node.break_from = self
550
+ active_node._replace(placeholder, breakpoint_node)
551
+
552
+ # Step 2.2: Push to global breakpoint stack
553
+ LGM._breakpoint_nodes.insert(0, breakpoint_node)
554
+
555
+ def _break_active(self) -> None:
556
+ if not LGM._active_groups:
557
+ raise RuntimeError("No active LogicGroup to break from.")
558
+ active_group = LGM._active_groups[0]
559
+ if active_group is not self:
560
+ raise IndexError('Not breaking from the top active LogicGroup.')
561
+ raise self.Break()
562
+
563
+ def _break_runtime(self) -> None:
564
+ if not LGM._active_nodes:
565
+ raise RuntimeError("No active node context to break from.")
566
+
567
+ # Step 1: Validate that this group is in the active group stack
568
+ if self not in LGM._active_groups:
569
+ raise ValueError(f"Break scope {self} not in active LogicGroup stack.")
570
+
571
+ # Step 2: Unwind the group stack from top until we hit `self`
572
+ # We iterate from the top (end of list) downward
573
+ for group in LGM._active_groups[:]:
574
+ group._break_active()
575
+ if group is self:
576
+ break
577
+
578
+ # === Python Interfaces ===
579
+
580
+ def __repr__(self) -> str:
581
+ return f'<{self.__class__.__name__}>({self.name!r})'
582
+
583
+ def __enter__(self):
584
+ LGM._lg_enter(self)
585
+ return self
586
+
587
+ def __exit__(self, exc_type: type | None, exc_value: BaseException | None, exc_traceback: Any) -> bool | None:
588
+ LGM._lg_exit(self)
589
+
590
+ if exc_type is None:
591
+ return None
592
+
593
+ # Suppress only the dynamically created Break exception for this group
594
+ if issubclass(exc_type, self.Break):
595
+ return True
596
+ return False
597
+
598
+ @classmethod
599
+ def break_(cls, scope: LogicGroup = None) -> None:
600
+ if scope is None:
601
+ scope = LGM.active_group
602
+
603
+ if scope is None:
604
+ raise RuntimeError("No active LogicGroup to break from.")
605
+
606
+ if LGM.inspection_mode:
607
+ scope._break_inspection()
608
+ else:
609
+ scope._break_runtime()
610
+
611
+ def break_active(self) -> None:
612
+ self._break_active()
613
+
614
+ def break_inspection(self) -> None:
615
+ self._break_inspection()
616
+
617
+ def break_runtime(self) -> None:
618
+ self._break_runtime()
619
+
620
+
621
+ class LogicNode(LogicExpression):
622
+ def __init__(self, *, expression: float | int | bool | Exception | Callable[[], Any], dtype: type = None, repr: str = None, uid: uuid.UUID = None):
623
+ super().__init__(expression=expression, dtype=dtype, repr=repr, uid=uid)
624
+
625
+ self.subordinates = []
626
+ self.condition_to_parent = NO_CONDITION
627
+ self.parent = None
628
+ self.children = {}
629
+ self.labels = [_.name for _ in LGM._active_groups]
630
+ self.autogen = False
631
+
632
+ def _infer_condition(self, child: LogicNode) -> NodeEdgeCondition:
633
+ size = len(self.subordinates)
634
+
635
+ # Case 1: No child node registered, the first child is always TRUE unless specified
636
+ if size == 0:
637
+ return TRUE_CONDITION
638
+
639
+ last_node = self.subordinates[0]
640
+ last_condition = last_node.condition_to_parent
641
+
642
+ # Case 1: Only 1 child node registered, the second child is always opposite of the first
643
+ if size == 1 and isinstance(last_condition, BinaryCondition):
644
+ if last_condition is TRUE_CONDITION:
645
+ return FALSE_CONDITION
646
+ else:
647
+ return TRUE_CONDITION
648
+
649
+ # Case 2: Only 1 child node registered, and the first condition is not specified.
650
+ if size == 1 and isinstance(last_condition, ConditionElse):
651
+ # Case 2.1: If the child is auto generated, we can assume this child should be TRUE
652
+ if last_node.autogen:
653
+ return TRUE_CONDITION
654
+ # Case 2.2: Otherwise, we cannot infer the condition
655
+
656
+ if size == 1:
657
+ raise EdgeValueError('Cannot auto-infer condition from single existing non-binary condition.')
658
+
659
+ second_node = self.subordinates[1]
660
+ second_condition = second_node.condition_to_parent
661
+ # Case 3: check if any 2 node is from autogeneration
662
+ # Returning the condition of the auto-generated node, so that it can be replaced later.
663
+ if last_node.autogen:
664
+ return last_condition
665
+ elif second_node.autogen:
666
+ return second_condition
667
+
668
+ if size > 2:
669
+ raise TooManyChildren(size)
670
+ # Case 4: both conditions are non-binary, cannot infer
671
+ raise EdgeValueError('Cannot auto-infer condition for non-binary existing condition.')
672
+
673
+ def _get_placeholder(self) -> PlaceholderNode:
674
+ if not self.subordinates:
675
+ placeholder = PlaceholderNode(auto_connect=False)
676
+ self._append(placeholder, TRUE_CONDITION)
677
+ return placeholder
678
+
679
+ # Case 2: Traverse the stack to find existing placeholder
680
+ for node in self.subordinates:
681
+ if isinstance(node, PlaceholderNode):
682
+ return node
683
+
684
+ # Case 3: No existing placeholder, create a new one with AUTO_CONDITION.
685
+ placeholder = PlaceholderNode(auto_connect=False)
686
+ # c_append will validate and infer the condition, and raise error as we intended.
687
+ self._append(placeholder, AUTO_CONDITION)
688
+ return placeholder
689
+
690
+ def _append(self, child: LogicNode, condition: NodeEdgeCondition) -> None:
691
+ if condition is None:
692
+ raise ValueError("LogicNode must have an valid edge condition.")
693
+
694
+ if condition is AUTO_CONDITION:
695
+ condition = self._infer_condition(child)
696
+
697
+ if condition in self.children:
698
+ raise KeyError(f"Edge {condition} already registered.")
699
+
700
+ self.children[condition] = child
701
+ self.subordinates.insert(0, child)
702
+ child.parent = self
703
+ child.condition_to_parent = condition
704
+
705
+ def _overwrite(self, new_node: LogicNode, condition: NodeEdgeCondition) -> None:
706
+ if condition is None:
707
+ raise ValueError("LogicNode must have an valid edge condition.")
708
+
709
+ if condition is AUTO_CONDITION:
710
+ condition = self._infer_condition(new_node)
711
+
712
+ if condition not in self.children:
713
+ raise KeyError(f"Edge {condition} not registered, cannot overwrite.")
714
+
715
+ original_node = self.children[condition]
716
+ self.children[condition] = new_node
717
+ new_node.parent = self
718
+ new_node.condition_to_parent = condition
719
+
720
+ self.subordinates[self.subordinates.index(original_node)] = new_node
721
+ original_node.parent = None
722
+ original_node.condition_to_parent = NO_CONDITION
723
+
724
+ def _replace(self, original_node: LogicNode, new_node: LogicNode) -> None:
725
+ # The __eq__ of LogicExpression is overloaded, so we must check identity here.
726
+ for node in LGM._active_nodes:
727
+ if node is original_node:
728
+ raise RuntimeError('Must not replace active node. Existing first required.')
729
+
730
+ self.subordinates[self.subordinates.index(original_node)] = new_node
731
+
732
+ self.children[original_node.condition_to_parent] = new_node
733
+ new_node.parent = self
734
+ new_node.condition_to_parent = original_node.condition_to_parent
735
+
736
+ original_node.parent = None
737
+ original_node.condition_to_parent = NO_CONDITION
738
+
739
+ def _validate(self):
740
+ if len(self.subordinates) != len(self.children):
741
+ raise NodeValueError('Subordinate stack size does not match registered children.')
742
+
743
+ for condition, child in self.children.items():
744
+ if child.condition_to_parent is not condition:
745
+ raise EdgeValueError('Child node condition does not match registered condition.')
746
+ if child not in self.subordinates:
747
+ raise ValueError(f"LogicNode {child} not found in stack")
748
+
749
+ def _eval_recursively(self, path: list | None = None, default: Any = NO_DEFAULT) -> tuple[Any, list]:
750
+ if path is None:
751
+ path = [self]
752
+ else:
753
+ path.append(self)
754
+
755
+ value = self._eval(False)
756
+ if self.is_leaf:
757
+ return value, path
758
+
759
+ else_branch = None
760
+ for child in self.subordinates:
761
+ condition = child.condition_to_parent
762
+ if condition is ELSE_CONDITION:
763
+ else_branch = child
764
+ elif condition is NO_CONDITION or value == condition.value:
765
+ return child._eval_recursively(path, default)
766
+
767
+ if else_branch is not None:
768
+ return else_branch._eval_recursively(path, default)
769
+
770
+ if default is NO_DEFAULT:
771
+ raise ValueError(f"No matching condition found for value {value} at '{self.repr}'.")
772
+
773
+ LOGGER.warning(f"No matching condition found for value {value} at '{self.repr}', using default {default}.")
774
+ return default, path
775
+
776
+ def _auto_fill(self) -> None:
777
+ size = len(self.children)
778
+ no_action = NoAction(auto_connect=False, autogen=True)
779
+
780
+ # Case 1: No child node registered
781
+ if size == 0:
782
+ LOGGER.warning(f"{self} having no [True] branch. Check the <with> statement code block to see if this is intended.")
783
+ self._append(no_action, NO_CONDITION)
784
+ return
785
+
786
+ node = self.subordinates[0]
787
+ condition = node.condition_to_parent
788
+
789
+ # Case 2: Single child node
790
+ if size == 1:
791
+ # Case 2.1: single child with no condition
792
+ if condition is NO_CONDITION:
793
+ return
794
+ # Case 2.2: single child deliberately set to ELSE
795
+ if condition is ELSE_CONDITION:
796
+ LOGGER.warning(f"{self} having no [True] branch. Check the <with> statement code block to see if this is intended.")
797
+ self._overwrite(no_action, TRUE_CONDITION)
798
+ return
799
+ # Case 2.4: single child with binary condition
800
+ if isinstance(condition, BinaryCondition):
801
+ self._append(no_action, ~condition)
802
+ return
803
+
804
+ # Case 3: Double Node
805
+ second_node = self.subordinates[1]
806
+ second_condition = second_node.condition_to_parent
807
+
808
+ if size == 2:
809
+ # Case 3.1: unconditioned branch not allowed with two branches
810
+ if condition is NO_CONDITION or second_condition is NO_CONDITION:
811
+ raise TooManyChildren('Cannot have unconditioned branch when there are two branches.')
812
+ # Case 3.2: one branch is ELSE — valid
813
+ if condition is ELSE_CONDITION or second_condition is ELSE_CONDITION:
814
+ return
815
+ # Case 3.3: both binary — valid
816
+ if isinstance(condition, BinaryCondition) and isinstance(second_condition, BinaryCondition):
817
+ return
818
+ # Case 3.4: both non-binary — add protective else
819
+ if not isinstance(condition, BinaryCondition) and not isinstance(second_condition, BinaryCondition):
820
+ self._append(no_action, ELSE_CONDITION)
821
+ return
822
+ raise EdgeValueError(f'Conflicting conditions detected, {condition} and {second_condition}.')
823
+
824
+ # Case 4: Multiple nodes (>2)
825
+ else_detected = False
826
+ for cond in self.children:
827
+ if cond is NO_CONDITION:
828
+ raise TooManyChildren('Cannot have unconditioned branch when there are multiple branches.')
829
+ if cond is ELSE_CONDITION:
830
+ else_detected = True
831
+ if isinstance(cond, BinaryCondition):
832
+ raise TooManyChildren('Cannot have binary branch when there are more than 2 branches.')
833
+ if not else_detected:
834
+ self._append(no_action, ELSE_CONDITION)
835
+
836
+ def _consolidate_placeholder(self) -> int:
837
+ placeholder_count = 0
838
+ i = 0
839
+ while i < len(self.subordinates):
840
+ node = self.subordinates[i]
841
+ if isinstance(node, PlaceholderNode):
842
+ self._replace(node, NoAction(auto_connect=False, autogen=True))
843
+ placeholder_count += 1
844
+ # no increment: replacement maintains list length; continue checking same index
845
+ else:
846
+ i += 1
847
+ return placeholder_count
848
+
849
+ def _entry_check(self) -> bool:
850
+ if LGM.inspection_mode:
851
+ return True
852
+ return bool(self._eval(False))
853
+
854
+ def _on_enter(self) -> None:
855
+ # Placeholders must be in reversed order, so that locating placeholder works correctly.
856
+ self._append(PlaceholderNode(auto_connect=False), FALSE_CONDITION)
857
+ self._append(PlaceholderNode(auto_connect=False), TRUE_CONDITION)
858
+ LGM._ln_enter(self)
859
+
860
+ def _on_exit(self) -> None:
861
+ self._validate()
862
+ self._auto_fill()
863
+ self._consolidate_placeholder()
864
+ LGM._ln_exit(self)
865
+
866
+ # === Python Interfaces ===
867
+
868
+ def __rshift__(self, other: LogicNode) -> LogicNode:
869
+ self._append(other, AUTO_CONDITION)
870
+ return other # Allow chaining
871
+
872
+ def __call__(self, default: Any = None) -> Any:
873
+ if default is None:
874
+ default = NoAction(auto_connect=False, autogen=True)
875
+ inspection_mode = LGM.inspection_mode
876
+ if inspection_mode:
877
+ LOGGER.info('LGM inspection mode temporarily disabled to evaluate correctly.')
878
+ LGM.inspection_mode = False
879
+ try:
880
+ path = []
881
+ value, _ = self._eval_recursively(path, default)
882
+ return value
883
+ finally:
884
+ LGM.inspection_mode = inspection_mode
885
+
886
+ def __repr__(self) -> str:
887
+ return f'<{self.__class__.__name__}>({self.repr!r})'
888
+
889
+ def __hash__(self) -> int:
890
+ return id(self)
891
+
892
+ def append(self, child: LogicNode, condition: NodeEdgeCondition = AUTO_CONDITION) -> None:
893
+ self._append(child, condition)
894
+
895
+ def overwrite(self, new_node: LogicNode, condition: NodeEdgeCondition) -> None:
896
+ self._overwrite(new_node, condition)
897
+
898
+ def replace(self, original_node: LogicNode, new_node: LogicNode) -> None:
899
+ self._replace(original_node, new_node)
900
+
901
+ def eval_recursively(self, path: list | None = None, default: Any = NO_DEFAULT) -> tuple[Any, list]:
902
+ return self._eval_recursively(path, default)
903
+
904
+ def list_labels(self) -> dict[str, list[LogicNode]]:
905
+ labels = {}
906
+
907
+ def traverse(node: LogicNode):
908
+ for group in node.labels:
909
+ labels.setdefault(group, []).append(node)
910
+ for child in node.children.values():
911
+ traverse(child)
912
+
913
+ traverse(self)
914
+ return labels
915
+
916
+ @property
917
+ def leaves(self):
918
+ if not self.subordinates:
919
+ yield self
920
+ else:
921
+ for child in self.subordinates:
922
+ yield from child.leaves
923
+
924
+ @property
925
+ def is_leaf(self) -> bool:
926
+ return not self.children
927
+
928
+ @property
929
+ def child_stack(self):
930
+ yield from self.subordinates
931
+
932
+ @property
933
+ def descendants(self):
934
+ for child in self.subordinates:
935
+ yield child
936
+ yield from child.descendants
937
+ frame = frame.prev
938
+
939
+
940
+ class BreakpointNode(LogicNode):
941
+ def __init__(self, *, break_from: LogicGroup = None, expression: float | int | bool | Exception | Callable[[], Any] = None, dtype: type = None, repr: str = None, uid: uuid.UUID = None):
942
+ super().__init__(
943
+ expression=NoAction(auto_connect=False, autogen=True) if expression is None else expression,
944
+ dtype=dtype,
945
+ repr=repr,
946
+ uid=uid
947
+ )
948
+
949
+ self.break_from = break_from
950
+ self.autogen = True
951
+ self.await_connection = False
952
+
953
+ def _connect(self, child: LogicNode) -> None:
954
+ if self.subordinates:
955
+ raise TooManyChildren(f'{self.__class__.__name__} must not have more than one child node.')
956
+ self._append(child, NO_CONDITION)
957
+ self.await_connection = False
958
+
959
+ def _on_enter(self) -> None:
960
+ if self.subordinates:
961
+ raise TooManyChildren(f'{self.__class__.__name__} must not have more than one child node.')
962
+ self.await_connection = False
963
+ try:
964
+ LGM._breakpoint_nodes.remove(self)
965
+ except NodeNotFountError as _:
966
+ pass
967
+ self._append(PlaceholderNode(auto_connect=False), NO_CONDITION)
968
+ LGM._active_nodes.insert(0, self)
969
+
970
+ def _on_exit(self) -> None:
971
+ LGM._ln_exit(self)
972
+
973
+ def _eval(self, enforce_dtype: bool) -> Any:
974
+ if not self.subordinates:
975
+ if LGM.vigilant_mode:
976
+ raise NodeValueError(f'{self} not connected.')
977
+ return self.expression
978
+
979
+ linked_to = self.subordinates[0]
980
+ return linked_to._eval(enforce_dtype)
981
+
982
+ def _eval_recursively(self, path: list | None = None, default: Any = NO_DEFAULT) -> tuple[Any, list]:
983
+ if path is None:
984
+ path = []
985
+ path.append(self)
986
+
987
+ if not self.subordinates:
988
+ if LGM.vigilant_mode:
989
+ raise NodeValueError(f'{self} not connected.')
990
+ return self.expression, path
991
+
992
+ linked_to = self.subordinates[0]
993
+ return linked_to._eval_recursively(path, default)
994
+
995
+ def __repr__(self) -> str:
996
+ if self.subordinates:
997
+ return f'<{self.__class__.__name__} connected>(break_from={self.break_from})'
998
+ elif self.await_connection:
999
+ return f'<{self.__class__.__name__} active>(break_from={self.break_from})'
1000
+ elif self.parent:
1001
+ return f'<{self.__class__.__name__} idle>(break_from={self.break_from})'
1002
+ else:
1003
+ return f'<{self.__class__.__name__} dangling>(break_from={self.break_from})'
1004
+
1005
+ @classmethod
1006
+ def break_(cls, break_from: LogicGroup, **kwargs):
1007
+ breakpoint_node = BreakpointNode(break_from=break_from, **kwargs)
1008
+ active_node = LGM.active_node
1009
+ placeholder = active_node._get_placeholder()
1010
+ active_node._replace(placeholder, breakpoint_node)
1011
+ return breakpoint_node
1012
+
1013
+ def connect(self, child: LogicNode) -> None:
1014
+ self._connect(child)
1015
+
1016
+ @property
1017
+ def linked_to(self) -> LogicNode | None:
1018
+ return self.subordinates[0] if self.subordinates else None
1019
+
1020
+
1021
+ class ActionNode(LogicNode):
1022
+ def __init__(
1023
+ self,
1024
+ *,
1025
+ action: Callable[[], Any] | None = None,
1026
+ expression: Any = None,
1027
+ dtype: type = None,
1028
+ repr: str | None = None,
1029
+ uid: uuid.UUID = None,
1030
+ auto_connect: bool = True,
1031
+ **kwargs
1032
+ ):
1033
+ # Do not capture logic group labels — action nodes are leaves
1034
+ super().__init__(expression=expression, dtype=dtype, repr=repr, uid=uid)
1035
+
1036
+ self.action = action
1037
+
1038
+ if auto_connect:
1039
+ self._auto_connect()
1040
+
1041
+ def _auto_connect(self) -> None:
1042
+ if not LGM._active_nodes:
1043
+ if LGM.vigilant_mode:
1044
+ raise NodeValueError(f'Cannot set ActionNode {self} as root node.')
1045
+ return
1046
+
1047
+ active_node = LGM._active_nodes[0] # top of stack
1048
+ placeholder = active_node._get_placeholder()
1049
+ active_node._replace(placeholder, self)
1050
+
1051
+ def _post_eval(self) -> None:
1052
+ if self.action is not None:
1053
+ self.action()
1054
+
1055
+ def _append(self, child: LogicNode, condition: NodeEdgeCondition) -> None:
1056
+ raise TooManyChildren('Action node must not have any child node.')
1057
+
1058
+ def _on_enter(self) -> None:
1059
+ raise NodeContextError('ActionNode does not support context management with <with> statement.')
1060
+
1061
+ def _on_exit(self) -> None:
1062
+ pass
1063
+
1064
+ def _eval_recursively(self, path: list | None = None, default: Any = NO_DEFAULT) -> tuple[Any, list]:
1065
+ if path is None:
1066
+ path = []
1067
+ path.append(self)
1068
+
1069
+ value = self._eval(False)
1070
+ self._post_eval()
1071
+
1072
+ if not self.is_leaf:
1073
+ raise TooManyChildren('Action node must not have any child node.')
1074
+
1075
+ return value, path
1076
+
1077
+
1078
+ class PlaceholderNode(ActionNode):
1079
+ def __init__(self, **kwargs):
1080
+ super().__init__(**kwargs)
1081
+
1082
+ self.autogen = True
1083
+ self.action = NoAction(auto_connect=False, autogen=True)
1084
+
1085
+ def _eval(self, enforce_dtype: bool) -> Any:
1086
+ if LGM.vigilant_mode:
1087
+ return self
1088
+ return self.action
1089
+
1090
+
1091
+ class NoAction(ActionNode):
1092
+ def __init__(self, sig: int = 0, repr='NoAction', autogen: bool = False, **kwargs):
1093
+ super().__init__(repr=repr, **kwargs)
1094
+ self.sig = sig
1095
+ self.autogen = autogen
1096
+
1097
+ def _eval(self, enforce_dtype: bool) -> Any:
1098
+ return self
1099
+
1100
+ def __repr__(self) -> str:
1101
+ return f'<{self.__class__.__name__}>(sig={self.sig})'
1102
+
1103
+ def __int__(self):
1104
+ return self.sig
1105
+
1106
+
1107
+ class LongAction(ActionNode):
1108
+ def __init__(self, *, sig: int = 1, repr='LongAction', **kwargs):
1109
+ super().__init__(repr=repr, **kwargs)
1110
+ self.sig = sig
1111
+
1112
+ def _eval(self, enforce_dtype: bool) -> Any:
1113
+ return self
1114
+
1115
+ def __repr__(self) -> str:
1116
+ return f'<{self.__class__.__name__}>(sig={self.sig})'
1117
+
1118
+ def __int__(self):
1119
+ return self.sig
1120
+
1121
+
1122
+ class ShortAction(ActionNode):
1123
+ def __init__(self, *, sig: int = -1, repr='ShortAction', **kwargs):
1124
+ super().__init__(repr=repr, **kwargs)
1125
+ self.sig = sig
1126
+
1127
+ def _eval(self, enforce_dtype: bool) -> Any:
1128
+ return self
1129
+
1130
+ def __repr__(self) -> str:
1131
+ return f'<{self.__class__.__name__}>(sig={self.sig})'
1132
+
1133
+ def __int__(self):
1134
+ return self.sig
1135
+
1136
+
1137
+ class CancelAction(ActionNode):
1138
+ def __init__(self, sig: int = 0, repr='CancelAction', **kwargs):
1139
+ super().__init__(repr=repr, **kwargs)
1140
+ self.sig = sig
1141
+
1142
+ def _eval(self, enforce_dtype: bool) -> Any:
1143
+ return self
1144
+
1145
+ def __repr__(self) -> str:
1146
+ return f'<{self.__class__.__name__}>(sig={self.sig})'
1147
+
1148
+ def __int__(self):
1149
+ return self.sig
1150
+
1151
+
1152
+ class ClearAction(ActionNode):
1153
+ def __init__(self, sig: int = 0, repr='ClearAction', **kwargs):
1154
+ super().__init__(repr=repr, **kwargs)
1155
+ self.sig = sig
1156
+
1157
+ def _eval(self, enforce_dtype: bool) -> Any:
1158
+ return self
1159
+
1160
+ def __repr__(self) -> str:
1161
+ return f'<{self.__class__.__name__}>(sig={self.sig})'
1162
+
1163
+ def __int__(self):
1164
+ return self.sig