compiled-knowledge 4.0.0a5__cp313-cp313-macosx_10_13_universal2.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.

Potentially problematic release.


This version of compiled-knowledge might be problematic. Click here for more details.

Files changed (167) hide show
  1. ck/__init__.py +0 -0
  2. ck/circuit/__init__.py +13 -0
  3. ck/circuit/circuit.c +38749 -0
  4. ck/circuit/circuit.cpython-313-darwin.so +0 -0
  5. ck/circuit/circuit_py.py +807 -0
  6. ck/circuit/tmp_const.py +74 -0
  7. ck/circuit_compiler/__init__.py +2 -0
  8. ck/circuit_compiler/circuit_compiler.py +26 -0
  9. ck/circuit_compiler/cython_vm_compiler/__init__.py +1 -0
  10. ck/circuit_compiler/cython_vm_compiler/_compiler.c +17373 -0
  11. ck/circuit_compiler/cython_vm_compiler/_compiler.cpython-313-darwin.so +0 -0
  12. ck/circuit_compiler/cython_vm_compiler/cython_vm_compiler.py +96 -0
  13. ck/circuit_compiler/interpret_compiler.py +223 -0
  14. ck/circuit_compiler/llvm_compiler.py +388 -0
  15. ck/circuit_compiler/llvm_vm_compiler.py +546 -0
  16. ck/circuit_compiler/named_circuit_compilers.py +57 -0
  17. ck/circuit_compiler/support/__init__.py +0 -0
  18. ck/circuit_compiler/support/circuit_analyser.py +81 -0
  19. ck/circuit_compiler/support/input_vars.py +148 -0
  20. ck/circuit_compiler/support/llvm_ir_function.py +234 -0
  21. ck/example/__init__.py +53 -0
  22. ck/example/alarm.py +366 -0
  23. ck/example/asia.py +28 -0
  24. ck/example/binary_clique.py +32 -0
  25. ck/example/bow_tie.py +33 -0
  26. ck/example/cancer.py +37 -0
  27. ck/example/chain.py +38 -0
  28. ck/example/child.py +199 -0
  29. ck/example/clique.py +33 -0
  30. ck/example/cnf_pgm.py +39 -0
  31. ck/example/diamond_square.py +68 -0
  32. ck/example/earthquake.py +36 -0
  33. ck/example/empty.py +10 -0
  34. ck/example/hailfinder.py +539 -0
  35. ck/example/hepar2.py +628 -0
  36. ck/example/insurance.py +504 -0
  37. ck/example/loop.py +40 -0
  38. ck/example/mildew.py +38161 -0
  39. ck/example/munin.py +22982 -0
  40. ck/example/pathfinder.py +53674 -0
  41. ck/example/rain.py +39 -0
  42. ck/example/rectangle.py +161 -0
  43. ck/example/run.py +30 -0
  44. ck/example/sachs.py +129 -0
  45. ck/example/sprinkler.py +30 -0
  46. ck/example/star.py +44 -0
  47. ck/example/stress.py +64 -0
  48. ck/example/student.py +43 -0
  49. ck/example/survey.py +46 -0
  50. ck/example/triangle_square.py +54 -0
  51. ck/example/truss.py +49 -0
  52. ck/in_out/__init__.py +3 -0
  53. ck/in_out/parse_ace_lmap.py +216 -0
  54. ck/in_out/parse_ace_nnf.py +288 -0
  55. ck/in_out/parse_net.py +480 -0
  56. ck/in_out/parser_utils.py +185 -0
  57. ck/in_out/pgm_pickle.py +42 -0
  58. ck/in_out/pgm_python.py +268 -0
  59. ck/in_out/render_bugs.py +111 -0
  60. ck/in_out/render_net.py +177 -0
  61. ck/in_out/render_pomegranate.py +184 -0
  62. ck/pgm.py +3494 -0
  63. ck/pgm_circuit/__init__.py +1 -0
  64. ck/pgm_circuit/marginals_program.py +352 -0
  65. ck/pgm_circuit/mpe_program.py +237 -0
  66. ck/pgm_circuit/pgm_circuit.py +75 -0
  67. ck/pgm_circuit/program_with_slotmap.py +234 -0
  68. ck/pgm_circuit/slot_map.py +35 -0
  69. ck/pgm_circuit/support/__init__.py +0 -0
  70. ck/pgm_circuit/support/compile_circuit.py +83 -0
  71. ck/pgm_circuit/target_marginals_program.py +103 -0
  72. ck/pgm_circuit/wmc_program.py +323 -0
  73. ck/pgm_compiler/__init__.py +2 -0
  74. ck/pgm_compiler/ace/__init__.py +1 -0
  75. ck/pgm_compiler/ace/ace.py +252 -0
  76. ck/pgm_compiler/factor_elimination.py +383 -0
  77. ck/pgm_compiler/named_pgm_compilers.py +63 -0
  78. ck/pgm_compiler/pgm_compiler.py +19 -0
  79. ck/pgm_compiler/recursive_conditioning.py +226 -0
  80. ck/pgm_compiler/support/__init__.py +0 -0
  81. ck/pgm_compiler/support/circuit_table/__init__.py +9 -0
  82. ck/pgm_compiler/support/circuit_table/circuit_table.c +16042 -0
  83. ck/pgm_compiler/support/circuit_table/circuit_table.cpython-313-darwin.so +0 -0
  84. ck/pgm_compiler/support/circuit_table/circuit_table_py.py +269 -0
  85. ck/pgm_compiler/support/clusters.py +556 -0
  86. ck/pgm_compiler/support/factor_tables.py +398 -0
  87. ck/pgm_compiler/support/join_tree.py +275 -0
  88. ck/pgm_compiler/support/named_compiler_maker.py +33 -0
  89. ck/pgm_compiler/variable_elimination.py +89 -0
  90. ck/probability/__init__.py +0 -0
  91. ck/probability/empirical_probability_space.py +47 -0
  92. ck/probability/probability_space.py +568 -0
  93. ck/program/__init__.py +3 -0
  94. ck/program/program.py +129 -0
  95. ck/program/program_buffer.py +180 -0
  96. ck/program/raw_program.py +61 -0
  97. ck/sampling/__init__.py +0 -0
  98. ck/sampling/forward_sampler.py +211 -0
  99. ck/sampling/marginals_direct_sampler.py +113 -0
  100. ck/sampling/sampler.py +62 -0
  101. ck/sampling/sampler_support.py +232 -0
  102. ck/sampling/uniform_sampler.py +66 -0
  103. ck/sampling/wmc_direct_sampler.py +169 -0
  104. ck/sampling/wmc_gibbs_sampler.py +147 -0
  105. ck/sampling/wmc_metropolis_sampler.py +159 -0
  106. ck/sampling/wmc_rejection_sampler.py +113 -0
  107. ck/utils/__init__.py +0 -0
  108. ck/utils/iter_extras.py +153 -0
  109. ck/utils/map_list.py +128 -0
  110. ck/utils/map_set.py +128 -0
  111. ck/utils/np_extras.py +51 -0
  112. ck/utils/random_extras.py +64 -0
  113. ck/utils/tmp_dir.py +94 -0
  114. ck_demos/__init__.py +0 -0
  115. ck_demos/ace/__init__.py +0 -0
  116. ck_demos/ace/copy_ace_to_ck.py +15 -0
  117. ck_demos/ace/demo_ace.py +44 -0
  118. ck_demos/all_demos.py +88 -0
  119. ck_demos/circuit/__init__.py +0 -0
  120. ck_demos/circuit/demo_circuit_dump.py +22 -0
  121. ck_demos/circuit/demo_derivatives.py +43 -0
  122. ck_demos/circuit_compiler/__init__.py +0 -0
  123. ck_demos/circuit_compiler/compare_circuit_compilers.py +32 -0
  124. ck_demos/circuit_compiler/show_llvm_program.py +26 -0
  125. ck_demos/pgm/__init__.py +0 -0
  126. ck_demos/pgm/demo_pgm_dump.py +18 -0
  127. ck_demos/pgm/demo_pgm_dump_stress.py +18 -0
  128. ck_demos/pgm/demo_pgm_string_rendering.py +15 -0
  129. ck_demos/pgm/show_examples.py +25 -0
  130. ck_demos/pgm_compiler/__init__.py +0 -0
  131. ck_demos/pgm_compiler/compare_pgm_compilers.py +50 -0
  132. ck_demos/pgm_compiler/demo_compiler_dump.py +50 -0
  133. ck_demos/pgm_compiler/demo_factor_elimination.py +47 -0
  134. ck_demos/pgm_compiler/demo_join_tree.py +25 -0
  135. ck_demos/pgm_compiler/demo_marginals_program.py +53 -0
  136. ck_demos/pgm_compiler/demo_mpe_program.py +55 -0
  137. ck_demos/pgm_compiler/demo_pgm_compiler.py +38 -0
  138. ck_demos/pgm_compiler/demo_recursive_conditioning.py +33 -0
  139. ck_demos/pgm_compiler/demo_variable_elimination.py +33 -0
  140. ck_demos/pgm_compiler/demo_wmc_program.py +29 -0
  141. ck_demos/pgm_inference/__init__.py +0 -0
  142. ck_demos/pgm_inference/demo_inferencing_basic.py +188 -0
  143. ck_demos/pgm_inference/demo_inferencing_mpe_cancer.py +45 -0
  144. ck_demos/pgm_inference/demo_inferencing_wmc_and_mpe_sprinkler.py +154 -0
  145. ck_demos/pgm_inference/demo_inferencing_wmc_student.py +110 -0
  146. ck_demos/programs/__init__.py +0 -0
  147. ck_demos/programs/demo_program_buffer.py +24 -0
  148. ck_demos/programs/demo_program_multi.py +24 -0
  149. ck_demos/programs/demo_program_none.py +19 -0
  150. ck_demos/programs/demo_program_single.py +23 -0
  151. ck_demos/programs/demo_raw_program_interpreted.py +21 -0
  152. ck_demos/programs/demo_raw_program_llvm.py +21 -0
  153. ck_demos/sampling/__init__.py +0 -0
  154. ck_demos/sampling/check_sampler.py +71 -0
  155. ck_demos/sampling/demo_marginal_direct_sampler.py +40 -0
  156. ck_demos/sampling/demo_uniform_sampler.py +38 -0
  157. ck_demos/sampling/demo_wmc_direct_sampler.py +40 -0
  158. ck_demos/utils/__init__.py +0 -0
  159. ck_demos/utils/compare.py +88 -0
  160. ck_demos/utils/convert_network.py +45 -0
  161. ck_demos/utils/sample_model.py +216 -0
  162. ck_demos/utils/stop_watch.py +384 -0
  163. compiled_knowledge-4.0.0a5.dist-info/METADATA +50 -0
  164. compiled_knowledge-4.0.0a5.dist-info/RECORD +167 -0
  165. compiled_knowledge-4.0.0a5.dist-info/WHEEL +5 -0
  166. compiled_knowledge-4.0.0a5.dist-info/licenses/LICENSE.txt +21 -0
  167. compiled_knowledge-4.0.0a5.dist-info/top_level.txt +2 -0
@@ -0,0 +1,807 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from itertools import chain
5
+ from typing import Dict, Tuple, Optional, Iterable, Sequence, List, overload, Iterator, Set
6
+
7
+ # Type for values of ConstNode objects
8
+ ConstValue = float | int | bool
9
+
10
+ # Symbols for op nodes
11
+ ADD: int = 0
12
+ MUL: int = 1
13
+
14
+
15
+ class Circuit:
16
+ """
17
+ An arithmetic circuit defining computation based on input variables (VarNode objects)
18
+ and constant values (ConstNode objects). Computation is defined over a mathematical
19
+ ring, with two operations: addition (AddNode objects) and multiplication (MulNode objects).
20
+
21
+ An arithmetic circuit cam be directly interpreted, using `ck.circuit_compiler.circuit_interpreter`,
22
+ or may be compiled to an LLVM JIT, using `ck.circuit_compiler.llvm_compiler`.
23
+ """
24
+
25
+ def __init__(self, zero: ConstValue = 0, one: ConstValue = 1):
26
+ """
27
+ Construct a new, empty circuit.
28
+
29
+ Args:
30
+ zero: The constant value for zero. mul(x, zero) = zero, add(x, zero) = x.
31
+ one: The constant value for one. mul(x, one) = x.
32
+ """
33
+ self._vars: List[VarNode] = []
34
+ self._ops: List[OpNode] = []
35
+ self._const_map: Dict[ConstValue, ConstNode] = {}
36
+ self.__derivatives: Optional[_DerivativeHelper] = None # cache for partial derivatives calculations.
37
+ self._zero: ConstNode = self.const(zero)
38
+ self._one: ConstNode = self.const(one)
39
+
40
+ @property
41
+ def number_of_vars(self) -> int:
42
+ """
43
+ Returns:
44
+ the number of "var" nodes.
45
+ """
46
+ return len(self._vars)
47
+
48
+ @property
49
+ def number_of_consts(self) -> int:
50
+ """
51
+ Returns:
52
+ the number of "const" nodes.
53
+ """
54
+ return len(self._const_map)
55
+
56
+ @property
57
+ def number_of_op_nodes(self) -> int:
58
+ """
59
+ Returns:
60
+ the number of "op" nodes.
61
+ """
62
+ return len(self._ops)
63
+
64
+ @property
65
+ def number_of_arcs(self) -> int:
66
+ """
67
+ Returns:
68
+ the number of arcs in the circuit, i.e., the sum of the
69
+ number of arguments for all op nodes.
70
+ """
71
+ return sum(len(op.args) for op in self._ops)
72
+
73
+ @property
74
+ def number_of_operations(self):
75
+ """
76
+ How many op nodes are in the circuit.
77
+ This is number_of_arcs - number_of_op_nodes.
78
+ """
79
+ return self.number_of_arcs - self.number_of_op_nodes
80
+
81
+ @property
82
+ def vars(self) -> Sequence[VarNode]:
83
+ """
84
+ Returns:
85
+ the var nodes, in index order.
86
+
87
+ Ensures:
88
+ `self.vars[i].idx == i`.
89
+ """
90
+ return self._vars
91
+
92
+ @property
93
+ def ops(self) -> Sequence[OpNode]:
94
+ """
95
+ Returns:
96
+ the op nodes, in the order they were added to this circuit.
97
+ """
98
+ return self._ops
99
+
100
+ @property
101
+ def zero(self) -> ConstNode:
102
+ """
103
+ Get the constant representing zero.
104
+ """
105
+ return self._zero
106
+
107
+ @property
108
+ def one(self) -> ConstNode:
109
+ """
110
+ Get the constant representing one.
111
+ """
112
+ return self._one
113
+
114
+ def new_var(self) -> VarNode:
115
+ """
116
+ Create and return a new variable node.
117
+ """
118
+ node = VarNode(self, len(self._vars))
119
+ self._vars.append(node)
120
+ return node
121
+
122
+ def new_vars(self, num_of_vars: int) -> Sequence[VarNode]:
123
+ """
124
+ Create and return multiple variable nodes.
125
+ """
126
+ offset = self.number_of_vars
127
+ new_vars = tuple(VarNode(self, i) for i in range(offset, offset + num_of_vars))
128
+ self._vars.extend(new_vars)
129
+ return new_vars
130
+
131
+ def const(self, value: ConstValue | ConstNode) -> ConstNode:
132
+ """
133
+ Return a const node for the given value.
134
+ If a const node for that value already exists, then it will be returned,
135
+ otherwise a new const node will be created.
136
+ """
137
+ if isinstance(value, ConstNode):
138
+ value = value.value
139
+
140
+ node = self._const_map.get(value)
141
+ if node is None:
142
+ node = ConstNode(self, value)
143
+ self._const_map[value] = node
144
+ return node
145
+
146
+ def _op(self, symbol: int, args: Tuple[CircuitNode, ...]) -> OpNode:
147
+ """
148
+ Create and return a new op node, applied to the given arguments.
149
+ """
150
+ node = OpNode(self, symbol, args)
151
+ self._ops.append(node)
152
+ return node
153
+
154
+ def add(self, *args: Args) -> OpNode:
155
+ """
156
+ Create and return a new 'addition' node, applied to the given arguments.
157
+ """
158
+ return self._op(ADD, self._check_nodes(args))
159
+
160
+ def mul(self, *args: Args) -> OpNode:
161
+ """
162
+ Create and return a new 'multiplication' node, applied to the given arguments.
163
+ """
164
+ return self._op(MUL, self._check_nodes(args))
165
+
166
+ def optimised_add(self, *args: Args) -> CircuitNode:
167
+ """
168
+ Optimised circuit node addition.
169
+
170
+ Performs the following optimisations:
171
+ * addition to zero is avoided: add(x, 0) = x,
172
+ * singleton addition is avoided: add(x) = x,
173
+ * empty addition is avoided: add() = 0,
174
+ """
175
+ to_add = tuple(n for n in self._check_nodes(args) if not n.is_zero())
176
+ match len(to_add):
177
+ case 0:
178
+ return self.zero
179
+ case 1:
180
+ return to_add[0]
181
+ case _:
182
+ return self._op(ADD, to_add)
183
+
184
+ def optimised_mul(self, *args: Args) -> CircuitNode:
185
+ """
186
+ Optimised circuit node multiplication.
187
+
188
+ Performs the following optimisations:
189
+ * multiplication by zero is avoided: mul(x, 0) = 0,
190
+ * multiplication by one is avoided: mul(x, 1) = x,
191
+ * singleton multiplication is avoided: mul(x) = x,
192
+ * empty multiplication is avoided: mul() = 1,
193
+ """
194
+ to_mul = tuple(n for n in self._check_nodes(args) if not n.is_one())
195
+ if any(n.is_zero() for n in to_mul):
196
+ return self.zero
197
+ match len(to_mul):
198
+ case 0:
199
+ return self.one
200
+ case 1:
201
+ return to_mul[0]
202
+ case _:
203
+ return self._op(MUL, to_mul)
204
+
205
+ def cartesian_product(self, xs: Sequence[CircuitNode], ys: Sequence[CircuitNode]) -> List[CircuitNode]:
206
+ """
207
+ Add multiply operations, one for each possible combination of x from xs and y from ys.
208
+
209
+ Args:
210
+ xs: first list of circuit nodes, may be either a Node object or a list of Nodes.
211
+ ys: second list of circuit nodes, may be either a Node object or a list of Nodes.
212
+
213
+ Returns:
214
+ a list of 'mul' nodes, one for each combination of xs and ys. The results are in the order
215
+ given by `[mul(x, y) for x in xs for y in ys]`.
216
+ """
217
+ xs: Sequence[CircuitNode] = self._check_nodes(xs)
218
+ ys: Sequence[CircuitNode] = self._check_nodes(ys)
219
+ return [
220
+ self.optimised_mul(x, y)
221
+ for x in xs
222
+ for y in ys
223
+ ]
224
+
225
+ @overload
226
+ def partial_derivatives(
227
+ self,
228
+ f: CircuitNode,
229
+ args: Sequence[CircuitNode],
230
+ *,
231
+ self_multiply: bool = False,
232
+ ) -> List[CircuitNode]:
233
+ ...
234
+
235
+ @overload
236
+ def partial_derivatives(
237
+ self,
238
+ f: CircuitNode,
239
+ args: CircuitNode,
240
+ *,
241
+ self_multiply: bool = False,
242
+ ) -> CircuitNode:
243
+ ...
244
+
245
+ def partial_derivatives(
246
+ self,
247
+ f: CircuitNode,
248
+ args,
249
+ *,
250
+ self_multiply: bool = False,
251
+ ):
252
+ """
253
+ Add to the circuit the operations required to calculate the partial derivative of f
254
+ with respect to each of the given nodes. If self_multiple is True, then this is
255
+ equivalent to calculating the marginal probability at each var that represents
256
+ an indicator.
257
+
258
+ This method will cache partial derivative calculations for `f` so that subsequent calls
259
+ to this method with the same `f` will not cause duplicated calculations to be added to
260
+ the circuit. To release this cache, call `self.release_derivatives_cache()`.
261
+
262
+ Args:
263
+ f: is the circuit node that defines the function to differentiate.
264
+ args: nodes that are the arguments to f (typically VarNode objects).
265
+ The value may be either a CircuitNode object or a list of CircuitNode objects.
266
+ self_multiply: if true then each partial derivative df/dx will be multiplied by x.
267
+
268
+ Returns:
269
+ the results nodes for the partial derivatives, co-indexed with the given arg nodes.
270
+ If `args` is a single CircuitNode, then a single CircuitNode will be returned, otherwise
271
+ a list of CircuitNode is returned.
272
+ """
273
+ single_result: bool = isinstance(args, CircuitNode)
274
+
275
+ args: Sequence[CircuitNode] = self._check_nodes([args])
276
+ if len(args) == 0:
277
+ # Trivial case
278
+ return []
279
+
280
+ derivatives: _DerivativeHelper = self._derivatives(f)
281
+ result: List[CircuitNode]
282
+ if self_multiply:
283
+ result = [
284
+ derivatives.derivative_self_mul(arg)
285
+ for arg in args
286
+ ]
287
+ else:
288
+ result = [
289
+ derivatives.derivative(arg)
290
+ for arg in args
291
+ ]
292
+
293
+ if single_result:
294
+ return result[0]
295
+ else:
296
+ return result
297
+
298
+ def remove_derivatives_cache(self) -> None:
299
+ """
300
+ Release the memory held for partial derivative calculations, as per `partial_derivatives`.
301
+ """
302
+ self.__derivatives = None
303
+
304
+ def remove_unreachable_op_nodes(self, *nodes: Args) -> None:
305
+ """
306
+ Find all op nodes reachable from the given nodes, via op arguments.
307
+ (using `self.reachable_op_nodes`). Remove all other op nodes from this circuit.
308
+
309
+ If any external object holds a reference to a removed node, that node will be unusable.
310
+
311
+ Args:
312
+ *nodes: may be either a node or a list of nodes.
313
+ """
314
+ seen: Set[int] = set() # set of object ids for all reachable op nodes.
315
+ for node in self._check_nodes(nodes):
316
+ _reachable_op_nodes_seen_r(node, seen)
317
+
318
+ if len(seen) < len(self._ops):
319
+ # Invalidate unreadable op nodes
320
+ for op_node in self._ops:
321
+ if id(op_node) not in seen:
322
+ op_node.circuit = None
323
+ op_node.args = ()
324
+
325
+ # Keep only reachable op nodes
326
+ self._ops = tuple(op_node for op_node in self._ops if id(op_node) in seen)
327
+
328
+ def reachable_op_nodes(self, *nodes: Args) -> List[OpNode]:
329
+ """
330
+ Iterate over all op nodes reachable from the given nodes, via op arguments.
331
+
332
+ Args:
333
+ *nodes: may be either a node or a list of nodes.
334
+
335
+ Returns:
336
+ An list of all op nodes reachable from the given nodes.
337
+
338
+ Ensures:
339
+ Returned nodes are not repeated.
340
+ The result is ordered such that if result[i] is referenced by result[j] then i < j.
341
+ """
342
+ seen: Set[int] = set() # set of object ids for all reachable op nodes.
343
+ return [
344
+ reachable
345
+ for node in self._check_nodes(nodes)
346
+ for reachable in _reachable_op_nodes_r(node, seen)
347
+ ]
348
+
349
+ def dump(
350
+ self,
351
+ *,
352
+ prefix: str = '',
353
+ indent: str = ' ',
354
+ var_names: Optional[List[str]] = None,
355
+ ) -> None:
356
+ """
357
+ Print a dump of the Circuit.
358
+ This is intended for debugging and demonstration purposes.
359
+
360
+ Args:
361
+ prefix: optional prefix for indenting all lines.
362
+ indent: additional prefix to use for extra indentation.
363
+ var_names: optional variable names to show.
364
+ """
365
+
366
+ next_prefix: str = prefix + indent
367
+
368
+ node_name: Dict[int, str] = {}
369
+
370
+ print(f'{prefix}number of vars: {self.number_of_vars:,}')
371
+ print(f'{prefix}number of const nodes: {self.number_of_consts:,}')
372
+ print(f'{prefix}number of op nodes: {self.number_of_op_nodes:,}')
373
+ print(f'{prefix}number of operations: {self.number_of_operations:,}')
374
+ print(f'{prefix}number of arcs: {self.number_of_arcs:,}')
375
+
376
+ print(f'{prefix}var nodes: {self.number_of_vars}')
377
+ for var in self._vars:
378
+ node_name[id(var)] = f'var[{var.idx}]'
379
+ var_name: str = '' if var_names is None or var.idx >= len(var_names) else var_names[var.idx]
380
+ if var_name != '':
381
+ if var.is_const():
382
+ print(f'{next_prefix}var[{var.idx}]: {var_name}, const({var.const.value})')
383
+ else:
384
+ print(f'{next_prefix}var[{var.idx}]: {var_name}')
385
+ elif var.is_const():
386
+ print(f'{next_prefix}var[{var.idx}]: const({var.const.value})')
387
+
388
+ print(f'{prefix}const nodes: {self.number_of_consts}')
389
+ for const in self._const_map.values():
390
+ node_name[id(const)] = str(const.value)
391
+ print(f'{next_prefix}const({const.value})')
392
+
393
+ # Add op nodes to the node_name dict
394
+ for i, op in enumerate(self._ops):
395
+ node_name[id(op)] = f'{op.symbol}<{i}>'
396
+
397
+ print(
398
+ f'{prefix}op nodes: {self.number_of_op_nodes} '
399
+ f'(arcs: {self.number_of_arcs}, ops: {self.number_of_operations})'
400
+ )
401
+ for op in reversed(self._ops):
402
+ op_name = node_name[id(op)]
403
+ args_str = ' '.join(node_name[id(arg)] for arg in op.args)
404
+ print(f'{next_prefix}{op_name}\\{len(op.args)}: {args_str}')
405
+
406
+ def _check_nodes(self, nodes: Iterable[Args]) -> Tuple[CircuitNode, ...]:
407
+ """
408
+ Convert the given circuit nodes to a tuple, flattening nested iterables as needed.
409
+
410
+ Args:
411
+ nodes: some circuit nodes of constant values.
412
+
413
+ Raises:
414
+ RuntimeError: if any node does not belong to this circuit.
415
+ """
416
+ return tuple(self.__check_nodes(nodes))
417
+
418
+ def __check_nodes(self, nodes: Iterable[Args]) -> Iterable[CircuitNode]:
419
+ """
420
+ Convert the given circuit nodes to a tuple, flattening nested iterables as needed.
421
+
422
+ Args:
423
+ nodes: some circuit nodes of constant values.
424
+
425
+ Raises:
426
+ RuntimeError: if any node does not belong to this circuit.
427
+ """
428
+
429
+ for node in nodes:
430
+ if isinstance(node, CircuitNode):
431
+ if node.circuit is not self:
432
+ raise RuntimeError('node does not belong to this circuit')
433
+ else:
434
+ yield node
435
+ elif isinstance(node, ConstValue):
436
+ yield self.const(node)
437
+ else:
438
+ # Assume it's iterable
439
+ for n in self._check_nodes(node):
440
+ yield n
441
+
442
+ def _derivatives(self, f: CircuitNode) -> _DerivativeHelper:
443
+ """
444
+ Get a _DerivativeHelper for `f`.
445
+ Checking the derivative cache.
446
+ """
447
+ derivatives: Optional[_DerivativeHelper] = self.__derivatives
448
+ if derivatives is None or derivatives.f is not f:
449
+ derivatives = _DerivativeHelper(f)
450
+ self.__derivatives = derivatives
451
+ return derivatives
452
+
453
+
454
+ class CircuitNode:
455
+ """
456
+ A node in an arithmetic circuit.
457
+ Each node is either an op, var, or const node.
458
+
459
+ Each op node is either a mul, add or sub node. Each op
460
+ node has zero or more arguments. Each argument is another node.
461
+
462
+ Every var node has an index, `idx`, which is an integer counting from zero, and denotes
463
+ its creation order.
464
+
465
+ A var node may be temporarily set to be a constant node, which may
466
+ be useful for optimising a compiled circuit.
467
+ """
468
+ __slots__ = ('circuit',)
469
+
470
+ def __init__(self, circuit: Circuit):
471
+ self.circuit = circuit
472
+
473
+ def is_zero(self) -> bool:
474
+ """
475
+ Does this node represent the constant zero.
476
+ """
477
+ return False
478
+
479
+ def is_one(self) -> bool:
480
+ """
481
+ Does this node represent the constant one.
482
+ """
483
+ return False
484
+
485
+ def __add__(self, other: CircuitNode | ConstValue):
486
+ return self.circuit.add(self, other)
487
+
488
+ def __mul__(self, other: CircuitNode | ConstValue):
489
+ return self.circuit.mul(self, other)
490
+
491
+
492
+ # A type representing a flexible representation of multiple CircuitNode objects.
493
+ Args = CircuitNode | ConstValue | Iterable[CircuitNode | ConstValue]
494
+
495
+
496
+ class ConstNode(CircuitNode):
497
+ """
498
+ A node in a circuit representing a constant value.
499
+ """
500
+ __slots__ = ('_value',)
501
+
502
+ def __init__(self, circuit: Circuit, value: ConstValue):
503
+ super().__init__(circuit)
504
+ self._value: ConstValue = value
505
+
506
+ @property
507
+ def value(self) -> ConstValue:
508
+ return self._value
509
+
510
+ def is_zero(self) -> bool:
511
+ # noinspection PyProtectedMember
512
+ return self is self.circuit.zero
513
+
514
+ def is_one(self) -> bool:
515
+ # noinspection PyProtectedMember
516
+ return self is self.circuit.one
517
+
518
+ def __str__(self) -> str:
519
+ return f'const({self.value})'
520
+
521
+ def __lt__(self, other) -> bool:
522
+ if isinstance(other, ConstNode):
523
+ return self._value < other._value
524
+ else:
525
+ return False
526
+
527
+
528
+ class VarNode(CircuitNode):
529
+ """
530
+ A node in a circuit representing an input variable.
531
+ """
532
+ __slots__ = ('_idx', '_const')
533
+
534
+ def __init__(self, circuit: Circuit, idx: int):
535
+ super().__init__(circuit)
536
+ self._idx: int = idx
537
+ self._const: Optional[ConstNode] = None
538
+
539
+ @property
540
+ def idx(self) -> int:
541
+ return self._idx
542
+
543
+ def is_const(self) -> bool:
544
+ return self._const is not None
545
+
546
+ @property
547
+ def const(self) -> Optional[ConstNode]:
548
+ return self._const
549
+
550
+ @const.setter
551
+ def const(self, value: ConstValue | ConstNode | None) -> None:
552
+ if value is None:
553
+ self._const = None
554
+ else:
555
+ self._const = self.circuit.const(value)
556
+
557
+ def is_zero(self) -> bool:
558
+ return self._const is not None and self._const.is_zero()
559
+
560
+ def is_one(self) -> bool:
561
+ return self._const is not None and self._const.is_one()
562
+
563
+ def __lt__(self, other) -> bool:
564
+ if isinstance(other, VarNode):
565
+ return self._idx < other.idx
566
+ else:
567
+ return False
568
+
569
+ def __str__(self) -> str:
570
+ if self._const is None:
571
+ return f'var[{self.idx}]'
572
+ else:
573
+ return f'var[{self.idx}] = {self._const.value}'
574
+
575
+
576
+ class OpNode(CircuitNode):
577
+ """
578
+ A node in a circuit representing an arithmetic operation.
579
+ """
580
+ __slots__ = ('args', 'symbol')
581
+
582
+ def __init__(self, circuit: Circuit, symbol: int, args: Tuple[CircuitNode, ...]):
583
+ super().__init__(circuit)
584
+ self.args: Tuple[CircuitNode, ...] = args
585
+ self.symbol: int = symbol
586
+
587
+ def __str__(self) -> str:
588
+ if self.symbol == MUL:
589
+ return f'mul\\{len(self.args)}'
590
+ elif self.symbol == ADD:
591
+ return f'add\\{len(self.args)}'
592
+ else:
593
+ return f'?{self.symbol}\\{len(self.args)}'
594
+
595
+
596
+ @dataclass
597
+ class _DNode:
598
+ """
599
+ A data structure supporting derivative calculations.
600
+ A DNode holds all information needed to calculate the partial derivative at `node`.
601
+ """
602
+ node: CircuitNode
603
+ derivative: Optional[CircuitNode]
604
+ derivative_self_mul: Optional[CircuitNode] = None
605
+ sum_prod: List[_DNodeProduct] = field(default_factory=list)
606
+ processed: bool = False
607
+
608
+ def __str__(self) -> str:
609
+ """
610
+ for debugging
611
+ """
612
+ dots: str = '...'
613
+ return (
614
+ f'DNode({self.node}, '
615
+ f'{None if self.derivative is None else dots}, '
616
+ f'{None if self.derivative_self_mul is None else dots}, '
617
+ f'{len(self.sum_prod)}, '
618
+ f'{self.processed})'
619
+ )
620
+
621
+
622
+ @dataclass
623
+ class _DNodeProduct:
624
+ """
625
+ A data structure supporting derivative calculations.
626
+
627
+ The represents a product of `parent` and `prod`.
628
+ """
629
+ parent: _DNode
630
+ prod: List[CircuitNode]
631
+
632
+ def __str__(self) -> str:
633
+ """
634
+ for debugging
635
+ """
636
+ return f'DNodeProduct({self.parent}, {self.prod})'
637
+
638
+
639
+ class _DerivativeHelper:
640
+ """
641
+ A data structure to support efficient calculation of partial derivatives
642
+ with respect to some function node `f`.
643
+ """
644
+
645
+ def __init__(self, f: CircuitNode):
646
+ """
647
+ Prepare to calculate partial derivatives with respect to `f`.
648
+ """
649
+ self.f: CircuitNode = f
650
+ self.circuit: Circuit = f.circuit
651
+ self.d_nodes: Dict[int, _DNode] = {} # map id(CircuitNode) to its DNode
652
+ self.zero = self.circuit.zero
653
+ self.one = self.circuit.one
654
+ top_d_node: _DNode = _DNode(f, self.one)
655
+ self.d_nodes[id(f)] = top_d_node
656
+ self._mk_derivative_r(top_d_node)
657
+
658
+ def derivative(self, node: CircuitNode) -> CircuitNode:
659
+ d_node: Optional[_DNode] = self.d_nodes.get(id(node))
660
+ if d_node is None:
661
+ return self.zero
662
+ else:
663
+ return self._derivative(d_node)
664
+
665
+ def derivative_self_mul(self, node: CircuitNode) -> CircuitNode:
666
+ d_node: Optional[_DNode] = self.d_nodes.get(id(node))
667
+ if d_node is None:
668
+ return self.zero
669
+
670
+ if d_node.derivative_self_mul is None:
671
+ d: CircuitNode = self._derivative(d_node)
672
+ if d is self.zero:
673
+ d_node.derivative_self_mul = self.zero
674
+ elif d is self.one:
675
+ d_node.derivative_self_mul = node
676
+ else:
677
+ d_node.derivative_self_mul = self.circuit.optimised_mul(d, node)
678
+
679
+ return d_node.derivative_self_mul
680
+
681
+ def _derivative(self, d_node: _DNode) -> CircuitNode:
682
+ if d_node.derivative is not None:
683
+ return d_node.derivative
684
+
685
+ # Get the list of circuit nodes that must be added together.
686
+ to_add: Sequence[CircuitNode] = tuple(
687
+ value
688
+ for value in (self._derivative_prod(prods) for prods in d_node.sum_prod)
689
+ if not value.is_zero()
690
+ )
691
+ # we can release the temporary memory at this DNode now
692
+ d_node.sum_prod = None
693
+
694
+ # Construct the addition operation
695
+ d_node.derivative = self.circuit.optimised_add(to_add)
696
+
697
+ return d_node.derivative
698
+
699
+ def _derivative_prod(self, prods: _DNodeProduct) -> CircuitNode:
700
+ """
701
+ Support `_derivative` by constructing the derivative product for the given _DNodeProduct.
702
+ """
703
+ # Get the derivative of the parent node.
704
+ parent: CircuitNode = self._derivative(prods.parent)
705
+
706
+ # Multiply the parent derivative with all other nodes recorded at prod.
707
+ to_mul: List[CircuitNode] = []
708
+ for arg in chain((parent,), prods.prod):
709
+ if arg is self.zero:
710
+ # Multiplication by zero is zero
711
+ return self.zero
712
+ if arg is not self.one:
713
+ to_mul.append(arg)
714
+
715
+ # Construct the multiplication operation
716
+ return self.circuit.optimised_mul(to_mul)
717
+
718
+ def _mk_derivative_r(self, d_node: _DNode) -> None:
719
+ """
720
+ Construct a DNode for each argument of the given DNode.
721
+ """
722
+ if d_node.processed:
723
+ return
724
+ d_node.processed = True
725
+ node: CircuitNode = d_node.node
726
+
727
+ if isinstance(node, OpNode):
728
+ if node.symbol == ADD:
729
+ for arg in node.args:
730
+ child_d_node = self._add(arg, d_node, [])
731
+ self._mk_derivative_r(child_d_node)
732
+ elif node.symbol == MUL:
733
+ for arg in node.args:
734
+ prod = [arg2 for arg2 in node.args if arg is not arg2]
735
+ child_d_node = self._add(arg, d_node, prod)
736
+ self._mk_derivative_r(child_d_node)
737
+ else:
738
+ raise RuntimeError(f'unknown op node symbol: {node.symbol!r}')
739
+
740
+ def _add(self, node: CircuitNode, parent: _DNode, prod: List[CircuitNode]) -> _DNode:
741
+ """
742
+ Support for `_mk_derivative_r`.
743
+
744
+ Add a _DNodeProduct(parent, negate, prod) to the DNode for the given circuit node.
745
+
746
+ If the DNode for `node` does not yet exist, one will be created.
747
+
748
+ The given circuit node may have multiple parents (i.e., a shared sub-expression). Therefore,
749
+ this method may be called multiple times for a given node. Each time a new _DNodeProduct will be added.
750
+
751
+ Args:
752
+ node: the CircuitNode that the returned DNode is for.
753
+ parent: the DNode of the parent node, i.e., `node` is an argument to the parent node.
754
+ prod: other circuit nodes that need to be multiplied with the parent derivative when
755
+ constructing a derivative for `node`.
756
+
757
+ Returns:
758
+ the DNode for `node`.
759
+ """
760
+ child_d_node: _DNode = self._get(node)
761
+ child_d_node.sum_prod.append(_DNodeProduct(parent, prod))
762
+ return child_d_node
763
+
764
+ def _get(self, node: CircuitNode) -> _DNode:
765
+ """
766
+ Get the DNode for the given circuit node.
767
+ If no DNode exist for it yet, then one will be constructed.
768
+ """
769
+ node_id: int = id(node)
770
+ d_node: Optional[_DNode] = self.d_nodes.get(node_id)
771
+ if d_node is None:
772
+ d_node = _DNode(node, None)
773
+ self.d_nodes[node_id] = d_node
774
+ return d_node
775
+
776
+
777
+ def _reachable_op_nodes_r(node: CircuitNode, seen: Set[int]) -> Iterator[OpNode]:
778
+ """
779
+ Recursive helper for `reachable_op_nodes`. Performs a depth-first search.
780
+
781
+ Args:
782
+ node: the current node being checked.
783
+ seen: keep track of seen op node ids (to avoid returning multiple of the same node).
784
+
785
+ Returns:
786
+ An iterator over all op nodes reachable from the given node.
787
+ """
788
+ if isinstance(node, OpNode) and id(node) not in seen:
789
+ seen.add(id(node))
790
+ for arg in node.args:
791
+ for reachable in _reachable_op_nodes_r(arg, seen):
792
+ yield reachable
793
+ yield node
794
+
795
+
796
+ def _reachable_op_nodes_seen_r(node: CircuitNode, seen: Set[int]) -> None:
797
+ """
798
+ Recursive helper for `remove_unreachable_op_nodes`. Performs a depth-first search.
799
+
800
+ Args:
801
+ node: the current node being checked.
802
+ seen: set of seen op node ids.
803
+ """
804
+ if isinstance(node, OpNode) and id(node) not in seen:
805
+ seen.add(id(node))
806
+ for arg in node.args:
807
+ _reachable_op_nodes_seen_r(arg, seen)