compiled-knowledge 4.0.0a7__cp313-cp313-macosx_10_13_universal2.whl → 4.0.0a8__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.

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