frlab 0.1.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- FRLab/BooleanLogic/BooleanANF.py +522 -0
- FRLab/BooleanLogic/BooleanFunction.py +1759 -0
- FRLab/BooleanLogic/BooleanGF.py +171 -0
- FRLab/BooleanLogic/ChainingGeneration/TemplateBuilding.py +370 -0
- FRLab/BooleanLogic/ChainingGeneration/Templates/__init__.py +5 -0
- FRLab/BooleanLogic/ChainingGeneration/Templates/arman_template.py +80 -0
- FRLab/BooleanLogic/ChainingGeneration/Templates/fast_template.py +46 -0
- FRLab/BooleanLogic/ChainingGeneration/Templates/old_ANF_template.py +104 -0
- FRLab/BooleanLogic/ChainingGeneration/Templates/prob_ANF_template.py +38 -0
- FRLab/BooleanLogic/ChainingGeneration/Templates/three_majority_template.py +152 -0
- FRLab/BooleanLogic/ChainingGeneration/__init__.py +2 -0
- FRLab/BooleanLogic/FunctionInputs.py +317 -0
- FRLab/BooleanLogic/Gates.py +805 -0
- FRLab/BooleanLogic/Latex.py +266 -0
- FRLab/BooleanLogic/Optimization.py +630 -0
- FRLab/BooleanLogic/SAT.py +739 -0
- FRLab/BooleanLogic/__init__.py +6 -0
- FRLab/Cryptanalysis/Attacks/cube_attacks.py +647 -0
- FRLab/Cryptanalysis/Attacks/fast_algebraic_attack.py +353 -0
- FRLab/Cryptanalysis/Attacks/naive_algebraic_attack.py +203 -0
- FRLab/Cryptanalysis/Attacks/reduced_algebraic_attack.py +256 -0
- FRLab/Cryptanalysis/Components/Adapters/__init__.py +13 -0
- FRLab/Cryptanalysis/Components/Adapters/equation_repr.py +116 -0
- FRLab/Cryptanalysis/Components/Adapters/online_insertion.py +246 -0
- FRLab/Cryptanalysis/Components/Adapters/store_repr.py +159 -0
- FRLab/Cryptanalysis/Components/Annihilators/GaussianAnnihilator.py +484 -0
- FRLab/Cryptanalysis/Components/Annihilators/SparseAnnihilator.py +301 -0
- FRLab/Cryptanalysis/Components/Annihilators/__init__.py +0 -0
- FRLab/Cryptanalysis/Components/EquationGenerators/CompositionGenerator.py +3 -0
- FRLab/Cryptanalysis/Components/EquationGenerators/CubeEqGenerator.py +386 -0
- FRLab/Cryptanalysis/Components/EquationGenerators/Performance.md +1 -0
- FRLab/Cryptanalysis/Components/EquationGenerators/SubstitutionEqGenerator.py +120 -0
- FRLab/Cryptanalysis/Components/EquationGenerators/SymbolicEqGenerator.py +130 -0
- FRLab/Cryptanalysis/Components/EquationGenerators/__init__.py +0 -0
- FRLab/Cryptanalysis/Components/EquationGenerators/_utils.py +26 -0
- FRLab/Cryptanalysis/Components/EquationSolving/GaussElim.py +319 -0
- FRLab/Cryptanalysis/Components/EquationSolving/Grob_Solver.py +138 -0
- FRLab/Cryptanalysis/Components/EquationSolving/Grob_Solver_2.py +157 -0
- FRLab/Cryptanalysis/Components/EquationSolving/GuessSolver.py +185 -0
- FRLab/Cryptanalysis/Components/EquationSolving/LU_Solver.py +205 -0
- FRLab/Cryptanalysis/Components/EquationSolving/SplitGrob_Solver.py +287 -0
- FRLab/Cryptanalysis/Components/EquationSolving/__init__.py +23 -0
- FRLab/Cryptanalysis/Components/EquationStores/BaseEqStore.py +112 -0
- FRLab/Cryptanalysis/Components/EquationStores/EqStore.py +93 -0
- FRLab/Cryptanalysis/Components/EquationStores/FilteringEqStore.py +64 -0
- FRLab/Cryptanalysis/Components/EquationStores/GrobnerEqStore.py +545 -0
- FRLab/Cryptanalysis/Components/EquationStores/GrobnerEqStore2.py +662 -0
- FRLab/Cryptanalysis/Components/EquationStores/IndexedEqStore.py +127 -0
- FRLab/Cryptanalysis/Components/EquationStores/LUEqStore.py +437 -0
- FRLab/Cryptanalysis/Components/EquationStores/SymbolicEqStore.py +88 -0
- FRLab/Cryptanalysis/Components/EquationStores/__init__.py +0 -0
- FRLab/Cryptanalysis/Components/__init__.py +7 -0
- FRLab/Cryptanalysis/__init__.py +0 -0
- FRLab/FeedbackFunctions/CMPR.py +1073 -0
- FRLab/FeedbackFunctions/CrossJoin.py +355 -0
- FRLab/FeedbackFunctions/FCSR.py +270 -0
- FRLab/FeedbackFunctions/FeedbackFunction.py +597 -0
- FRLab/FeedbackFunctions/Fibonacci.py +399 -0
- FRLab/FeedbackFunctions/Galois.py +273 -0
- FRLab/FeedbackFunctions/MPR.py +156 -0
- FRLab/FeedbackFunctions/TFunction.py +79 -0
- FRLab/FeedbackFunctions/__init__.py +8 -0
- FRLab/FeedbackRegister.py +802 -0
- FRLab/JSON_Serialization.py +276 -0
- FRLab/Reporting.py +694 -0
- FRLab/Tools/AlgClosure/DLP.py +35 -0
- FRLab/Tools/AlgClosure/NumberTheory.py +283 -0
- FRLab/Tools/ClockControlled.py +68 -0
- FRLab/Tools/CostEstimation.py +182 -0
- FRLab/Tools/MersenneTools.py +296 -0
- FRLab/Tools/RegisterSynthesis/__init__.py +0 -0
- FRLab/Tools/RegisterSynthesis/fcsrSynthesis.py +197 -0
- FRLab/Tools/RegisterSynthesis/lfsrSynthesis.py +274 -0
- FRLab/Tools/RegisterSynthesis/nlfsrSynthesis.py +390 -0
- FRLab/Tools/ResolventSolving.py +187 -0
- FRLab/Tools/RootCounting/Combinatorics.py +19 -0
- FRLab/Tools/RootCounting/EvaluationFunctions.py +33 -0
- FRLab/Tools/RootCounting/JordanPartition.py +53 -0
- FRLab/Tools/RootCounting/JordanSet.py +49 -0
- FRLab/Tools/RootCounting/MeshOptimization.py +142 -0
- FRLab/Tools/RootCounting/MonomialProfile.py +487 -0
- FRLab/Tools/RootCounting/OverlappingRectangle.py +62 -0
- FRLab/Tools/RootCounting/PartialOrders.py +138 -0
- FRLab/Tools/RootCounting/RootExpression.py +415 -0
- FRLab/Tools/RootCounting/__init__.py +0 -0
- FRLab/Tools/__init__.py +0 -0
- FRLab/__init__.py +19 -0
- frlab-0.1.2.dist-info/METADATA +91 -0
- frlab-0.1.2.dist-info/RECORD +92 -0
- frlab-0.1.2.dist-info/WHEEL +5 -0
- frlab-0.1.2.dist-info/licenses/LICENSE.md +7 -0
- frlab-0.1.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,522 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from collections.abc import Iterable, Iterator
|
|
3
|
+
from itertools import product
|
|
4
|
+
from typing import Any, Self
|
|
5
|
+
|
|
6
|
+
from FRLab.JSON_Serialization import Serializable
|
|
7
|
+
|
|
8
|
+
from FRLab.BooleanLogic.BooleanFunction import BooleanFunction
|
|
9
|
+
from FRLab.BooleanLogic.FunctionInputs import CONST, VAR
|
|
10
|
+
from FRLab.BooleanLogic.Gates import AND, XOR
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _encode_variable(variable: Any) -> Any:
|
|
14
|
+
"""Write an ANF variable in JSON-compatible form.
|
|
15
|
+
|
|
16
|
+
Variables are hashable, so a JSON list can never be a variable itself; that
|
|
17
|
+
leaves lists free to stand for tuples, which is how tuple variables (such as
|
|
18
|
+
monomials used as variables) are written.
|
|
19
|
+
|
|
20
|
+
:param variable: The variable.
|
|
21
|
+
:type variable: Any
|
|
22
|
+
:raises TypeError: If the variable is not a JSON scalar or a tuple of them.
|
|
23
|
+
:return: The variable as a JSON value.
|
|
24
|
+
:rtype: Any
|
|
25
|
+
"""
|
|
26
|
+
if isinstance(variable, tuple):
|
|
27
|
+
return [_encode_variable(v) for v in variable]
|
|
28
|
+
if variable is None or isinstance(variable, (bool, int, float, str)):
|
|
29
|
+
return variable
|
|
30
|
+
raise TypeError(
|
|
31
|
+
f"cannot write a BooleanANF variable of type {type(variable).__name__} to JSON: "
|
|
32
|
+
f"variables must be ints, strings, floats, bools, None, or tuples of those"
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
def _decode_variable(value: Any) -> Any:
|
|
36
|
+
"""Inverse of `_encode_variable`: lists are read back as tuples."""
|
|
37
|
+
if isinstance(value, list):
|
|
38
|
+
return tuple(_decode_variable(v) for v in value)
|
|
39
|
+
return value
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# A container class which can hold an BooleanANF of any hashable type
|
|
43
|
+
# Note that this class is unordered, because it uses sets.
|
|
44
|
+
class BooleanANF(Serializable):
|
|
45
|
+
terms: frozenset[frozenset[Any]]
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def _convert_iterable_term(cls,
|
|
49
|
+
term: Iterable[Any] | bool | int
|
|
50
|
+
) -> frozenset[Any] | None:
|
|
51
|
+
"""Helper function converts a variety of iterables into a common from (frozensets)
|
|
52
|
+
|
|
53
|
+
Any iterable of hashable objects will be converted using a `frozenset()` call. There are
|
|
54
|
+
some checks for specific values which will be interpreted as either logical 1 (represented
|
|
55
|
+
in the BooleanANF class as an empty frozenset) or a logical 0 (represented by returning
|
|
56
|
+
None). These checks enable constructing a BooleanANF in a more flexible and readible way.
|
|
57
|
+
The behaviour of the function is as follows:
|
|
58
|
+
|
|
59
|
+
Will return `frozenset()` (logical True) if and only if `term` is:
|
|
60
|
+
- An empty iterable, which converts naturally to an empty frozenset()
|
|
61
|
+
- The bool `True`
|
|
62
|
+
- The int 1
|
|
63
|
+
|
|
64
|
+
Will return `None` if and only if `term` is:
|
|
65
|
+
- The bool False
|
|
66
|
+
- The int 0
|
|
67
|
+
|
|
68
|
+
Anything else will be cast to frozenset, and an error will be raised if that conversion fails
|
|
69
|
+
|
|
70
|
+
:param term: The term to be converted. Any iterable of hashable objects, as well as
|
|
71
|
+
specific int and bool representations for the constant term.
|
|
72
|
+
:type term: Iterable[Any] | bool | int
|
|
73
|
+
:raises TypeError: if term is passed which does not match the special exceptions, and
|
|
74
|
+
which is not able to be converted to frozenset,
|
|
75
|
+
:return: a frozenset representing the term
|
|
76
|
+
:rtype: frozenset[Any] | None
|
|
77
|
+
"""
|
|
78
|
+
# exceptions for ease of use:
|
|
79
|
+
if (term == False or term == 0):
|
|
80
|
+
return None
|
|
81
|
+
if (term == True or term == 1):
|
|
82
|
+
return frozenset()
|
|
83
|
+
|
|
84
|
+
try:
|
|
85
|
+
# we can ignore type warning because we plan to catch error.
|
|
86
|
+
return frozenset(term) # type: ignore
|
|
87
|
+
except TypeError:
|
|
88
|
+
raise TypeError( # thow better error.
|
|
89
|
+
f"Unable to convert term {term!s} (of type {type(term)}) to frozenset."
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
def __init__(self,
|
|
93
|
+
nested_iterable: Any = None,
|
|
94
|
+
fast_init: bool = False
|
|
95
|
+
):
|
|
96
|
+
# fast init allows you to skip extra input handling
|
|
97
|
+
if fast_init:
|
|
98
|
+
self.terms = nested_iterable
|
|
99
|
+
return
|
|
100
|
+
|
|
101
|
+
#if they want an empty BooleanANF object.
|
|
102
|
+
if nested_iterable == None:
|
|
103
|
+
self.terms = frozenset()
|
|
104
|
+
return
|
|
105
|
+
|
|
106
|
+
#convert any nested iterable to proper set/frozenset format:
|
|
107
|
+
terms = set()
|
|
108
|
+
for term in nested_iterable:
|
|
109
|
+
new_term = BooleanANF._convert_iterable_term(term)
|
|
110
|
+
if not(new_term == None):
|
|
111
|
+
terms ^= {new_term}
|
|
112
|
+
|
|
113
|
+
self.terms = frozenset(terms)
|
|
114
|
+
|
|
115
|
+
def degree(self) -> int:
|
|
116
|
+
"""Compute the algebraic degree of the ANF expression.
|
|
117
|
+
|
|
118
|
+
In the ANF representation, algebraic degree can be found by simply taking the
|
|
119
|
+
maximum over the lengths of all terms.
|
|
120
|
+
|
|
121
|
+
:return: The algebraic degree of the function
|
|
122
|
+
:rtype: int
|
|
123
|
+
"""
|
|
124
|
+
return max([len(term) for term in self.terms], default=0)
|
|
125
|
+
|
|
126
|
+
# BooleanANF Operations:
|
|
127
|
+
# ADD and XOR
|
|
128
|
+
def __xor__(self, other: "BooleanANF") -> "BooleanANF":
|
|
129
|
+
"""Compute the BooleanANF corresponding to the XOR of two BooleanANFs
|
|
130
|
+
|
|
131
|
+
This is also equivalent to `__add__(self, other)`, and is computed using
|
|
132
|
+
the exclusive union of the two term frozensets.
|
|
133
|
+
|
|
134
|
+
:param other: the other BooleanANF involved in the operation
|
|
135
|
+
:type other: "BooleanANF"
|
|
136
|
+
:return: the XOR of the two BooleanANFs
|
|
137
|
+
:rtype: BooleanANF
|
|
138
|
+
"""
|
|
139
|
+
return BooleanANF(self.terms ^ other.terms,fast_init=True)
|
|
140
|
+
def __add__(self, other: "BooleanANF") -> "BooleanANF":
|
|
141
|
+
"""An Alias for `__xor__`, which computes the BooleanANF corresponding to
|
|
142
|
+
the XOR of two BooleanANFs
|
|
143
|
+
|
|
144
|
+
Internally, this is computed using the exclusive union of the two term frozensets.
|
|
145
|
+
|
|
146
|
+
:param other: the other BooleanANF involved in the operation
|
|
147
|
+
:type other: "BooleanANF"
|
|
148
|
+
:return: the XOR of the two BooleanANFs
|
|
149
|
+
:rtype: BooleanANF
|
|
150
|
+
"""
|
|
151
|
+
return BooleanANF(self.terms ^ other.terms,fast_init=True)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
# MUL and AND (can make an BooleanANF very large, use w/ caution)
|
|
155
|
+
def __and__(self,other: "BooleanANF") -> "BooleanANF":
|
|
156
|
+
"""Compute the BooleanANF corresponding to the AND of two BooleanANFs
|
|
157
|
+
|
|
158
|
+
This is also equivalent to `__mul__(self, other)`. It is computed using the
|
|
159
|
+
frozenset union to merge terms, and fast addition/removal of terms in a regular
|
|
160
|
+
set, which is converted to a frozenset at the end of the multiplication.
|
|
161
|
+
|
|
162
|
+
:param other: the other BooleanANF involved in the operation
|
|
163
|
+
:type other: "BooleanANF"
|
|
164
|
+
:return: the AND of the two BooleanANFs
|
|
165
|
+
:rtype: BooleanANF
|
|
166
|
+
"""
|
|
167
|
+
termset = set()
|
|
168
|
+
for a,b in product(self.terms,other.terms):
|
|
169
|
+
new_term = a|b
|
|
170
|
+
if new_term in termset:
|
|
171
|
+
termset.remove(new_term)
|
|
172
|
+
else:
|
|
173
|
+
termset.add(new_term)
|
|
174
|
+
return BooleanANF(frozenset(termset),fast_init=True)
|
|
175
|
+
def __mul__(self,other: "BooleanANF") -> "BooleanANF":
|
|
176
|
+
"""An Alias for `__and__`, which computes the BooleanANF corresponding to the
|
|
177
|
+
AND of two BooleanANFs
|
|
178
|
+
|
|
179
|
+
It is computed using the frozenset union to merge terms, and fast addition/removal
|
|
180
|
+
of terms in a regular set, which is converted to a frozenset at the end of the
|
|
181
|
+
multiplication.
|
|
182
|
+
|
|
183
|
+
:param other: the other BooleanANF involved in the operation
|
|
184
|
+
:type other: "BooleanANF"
|
|
185
|
+
:return: the AND of the two BooleanANFs
|
|
186
|
+
:rtype: BooleanANF
|
|
187
|
+
"""
|
|
188
|
+
termset = set()
|
|
189
|
+
for a,b in product(self.terms,other.terms):
|
|
190
|
+
new_term = a|b
|
|
191
|
+
if new_term in termset:
|
|
192
|
+
termset.remove(new_term)
|
|
193
|
+
else:
|
|
194
|
+
termset.add(new_term)
|
|
195
|
+
return BooleanANF(frozenset(termset),fast_init=True)
|
|
196
|
+
|
|
197
|
+
# add an inverter operation
|
|
198
|
+
def __invert__(self) -> "BooleanANF":
|
|
199
|
+
"""Invert a BooleanANF by XORing with logical one (empty frozenset)
|
|
200
|
+
|
|
201
|
+
:return: The inverted ANF
|
|
202
|
+
:rtype: BooleanANF
|
|
203
|
+
"""
|
|
204
|
+
return self ^ BooleanANF({frozenset()},fast_init=True)
|
|
205
|
+
|
|
206
|
+
# use a pretty print for __str__, generic object for repr:
|
|
207
|
+
def __str__(self) -> str:
|
|
208
|
+
"""Convert a booleanANF into a simplified string representation
|
|
209
|
+
|
|
210
|
+
Each term is grouped by parentheses, and comma-separated. Terms with
|
|
211
|
+
only one variable omit the parentheses to save space.
|
|
212
|
+
|
|
213
|
+
:return: A string representation of the function
|
|
214
|
+
:rtype: str
|
|
215
|
+
"""
|
|
216
|
+
string_beginning = ""
|
|
217
|
+
term_strings = []
|
|
218
|
+
for term in self.terms:
|
|
219
|
+
if term == frozenset():
|
|
220
|
+
string_beginning = "True,"
|
|
221
|
+
elif len(term) == 1:
|
|
222
|
+
term_strings.append(repr(tuple(term)[0]) + ",")
|
|
223
|
+
else:
|
|
224
|
+
#if the internal objects have an order, sort terms.
|
|
225
|
+
try:
|
|
226
|
+
term_strings.append("(" + ",".join(repr(t) for t in sorted(term)) + "),")
|
|
227
|
+
except TypeError:
|
|
228
|
+
term_strings.append("(" + ",".join(repr(t) for t in term) + "),")
|
|
229
|
+
|
|
230
|
+
#sort string terms, and print vaguely by size
|
|
231
|
+
return string_beginning + "".join(sorted(term_strings, key = lambda x: len(x)))[:-1]
|
|
232
|
+
|
|
233
|
+
# Generic container methods
|
|
234
|
+
def __len__(self) -> int:
|
|
235
|
+
"""Return the number of terms in the BooleanANF
|
|
236
|
+
|
|
237
|
+
:return: the number of terms in the BooleanANF
|
|
238
|
+
:rtype: int
|
|
239
|
+
"""
|
|
240
|
+
return len(self.terms)
|
|
241
|
+
def __eq__(self,other: object) -> bool:
|
|
242
|
+
"""Determine if two BooleanANFs are equal.
|
|
243
|
+
|
|
244
|
+
because frozenset equality depends on the the equality of the stored items (and is
|
|
245
|
+
order independent), we can use the built-in equality check on the terms sets to check
|
|
246
|
+
equality between BooleanANF objects. Because ANF is a normal form, this also implies
|
|
247
|
+
that the two BooleanANFs are equivalent as functions.
|
|
248
|
+
|
|
249
|
+
The parameter is typed `object` because that is the signature the data
|
|
250
|
+
model requires of `__eq__`: Python calls it for any right-hand operand,
|
|
251
|
+
so a BooleanANF compared against an unrelated type must return
|
|
252
|
+
NotImplemented rather than fail on a missing attribute.
|
|
253
|
+
|
|
254
|
+
:param other: the other object involved in the operation
|
|
255
|
+
:type other: object
|
|
256
|
+
:return: whether or not the two functions are equal, or NotImplemented
|
|
257
|
+
if `other` is not a BooleanANF.
|
|
258
|
+
:rtype: bool
|
|
259
|
+
"""
|
|
260
|
+
if not isinstance(other, BooleanANF):
|
|
261
|
+
return NotImplemented
|
|
262
|
+
return self.terms == other.terms
|
|
263
|
+
def __hash__(self) -> int:
|
|
264
|
+
"""Return the hash of the underlying term set
|
|
265
|
+
|
|
266
|
+
Because we are using the builtin term set equality, we also use the builtin
|
|
267
|
+
term set hash, which will always agree with equality. This also makes it
|
|
268
|
+
possible to store and hash BooleanANFs nicely.
|
|
269
|
+
|
|
270
|
+
:return: The hash of the BooleanANF
|
|
271
|
+
:rtype: int
|
|
272
|
+
"""
|
|
273
|
+
return self.terms.__hash__()
|
|
274
|
+
def __iter__(self) -> Iterator[frozenset[Any]]:
|
|
275
|
+
"""Expose an iterator to the underlying term set.
|
|
276
|
+
|
|
277
|
+
Because frozensets are unordered, there is no guarantee for order in the returned
|
|
278
|
+
iterator. Still, this is convenient because it allows you to loop through terms or
|
|
279
|
+
pass BooleanANFs to `sorted` (or other functions expecting an iterable)
|
|
280
|
+
|
|
281
|
+
:return: An iterator for the underlying term set.
|
|
282
|
+
:rtype: Iterator[frozenset[Any]]
|
|
283
|
+
"""
|
|
284
|
+
return iter(self.terms)
|
|
285
|
+
def __contains__(self, term: Iterable[Any] | int | bool) -> bool:
|
|
286
|
+
"""Determines if a term is present in the ANF
|
|
287
|
+
|
|
288
|
+
uses `_convert_iterable_term`, which allows the user to pass iterables
|
|
289
|
+
other than frozensets, and also use more conveniet shortcuts for the
|
|
290
|
+
logical one (i.e. the bool True or the int 1). If a term corresponding
|
|
291
|
+
to an empty ANF (i.e.) is passed, True is returned by default.
|
|
292
|
+
|
|
293
|
+
:param term: The term to check
|
|
294
|
+
:type term: Iterable[Any] | int | bool
|
|
295
|
+
:return: whether or not the term is contained in the BooleanANF
|
|
296
|
+
:rtype: bool
|
|
297
|
+
"""
|
|
298
|
+
converted_term = self._convert_iterable_term(term)
|
|
299
|
+
if converted_term == None:
|
|
300
|
+
return True
|
|
301
|
+
else:
|
|
302
|
+
return (self._convert_iterable_term(term) in self.terms)
|
|
303
|
+
|
|
304
|
+
# Serialization (the id hook is the Serializable default: an ANF refers to
|
|
305
|
+
# no other serializable object, and since it is immutable and hashes by
|
|
306
|
+
# value, equal ANFs sharing one entry loses nothing)
|
|
307
|
+
def _generate_JSON_entry(self,
|
|
308
|
+
ids: dict[Any, int]
|
|
309
|
+
) -> dict[str, Any]:
|
|
310
|
+
"""Write the terms as lists of variables.
|
|
311
|
+
|
|
312
|
+
The constant term is the empty list. Variables within a term, and the
|
|
313
|
+
terms themselves, are written in a fixed order so that equal ANFs are
|
|
314
|
+
always written identically -- the set order in memory is arbitrary.
|
|
315
|
+
|
|
316
|
+
:param ids: The map from objects to ids; unused, as an ANF refers to no
|
|
317
|
+
other serializable object.
|
|
318
|
+
:type ids: dict[Any, int]
|
|
319
|
+
:raises TypeError: If a variable cannot be written to JSON (see
|
|
320
|
+
`_encode_variable`).
|
|
321
|
+
:return: The ANF's data.
|
|
322
|
+
:rtype: dict[str, Any]
|
|
323
|
+
"""
|
|
324
|
+
terms = []
|
|
325
|
+
for term in self.terms:
|
|
326
|
+
variables = [_encode_variable(v) for v in term]
|
|
327
|
+
try:
|
|
328
|
+
variables.sort()
|
|
329
|
+
except TypeError:
|
|
330
|
+
# variables of mixed types have no natural order
|
|
331
|
+
variables.sort(key=json.dumps)
|
|
332
|
+
terms.append(variables)
|
|
333
|
+
terms.sort(key=lambda t: (len(t), json.dumps(t)))
|
|
334
|
+
return {"terms": terms}
|
|
335
|
+
|
|
336
|
+
@classmethod
|
|
337
|
+
def _parse_JSON_entry(cls,
|
|
338
|
+
object_data: dict[str, Any],
|
|
339
|
+
parsed_objects: list[Any]
|
|
340
|
+
) -> Self:
|
|
341
|
+
"""Rebuild an ANF from the terms `_generate_JSON_entry` wrote.
|
|
342
|
+
|
|
343
|
+
:param object_data: The data written for this ANF.
|
|
344
|
+
:type object_data: dict[str, Any]
|
|
345
|
+
:param parsed_objects: The objects rebuilt so far; unused.
|
|
346
|
+
:type parsed_objects: list[Any]
|
|
347
|
+
:return: The rebuilt ANF.
|
|
348
|
+
:rtype: Self
|
|
349
|
+
"""
|
|
350
|
+
terms = frozenset(
|
|
351
|
+
frozenset(_decode_variable(v) for v in term)
|
|
352
|
+
for term in object_data["terms"]
|
|
353
|
+
)
|
|
354
|
+
return cls(terms, fast_init=True)
|
|
355
|
+
|
|
356
|
+
# Conversion methods
|
|
357
|
+
@classmethod
|
|
358
|
+
def from_BooleanFunction(cls,
|
|
359
|
+
fn: BooleanFunction
|
|
360
|
+
) -> "BooleanANF":
|
|
361
|
+
"""Convert a `BooleanFunction` to an equivalent `BooleanANF`
|
|
362
|
+
|
|
363
|
+
:param fn: the BooleanFunction to convert.
|
|
364
|
+
:type fn: BooleanFunction
|
|
365
|
+
:return: A BooleanANF which matches the ANF of the input function
|
|
366
|
+
:rtype: BooleanANF
|
|
367
|
+
"""
|
|
368
|
+
|
|
369
|
+
var_list = {i: BooleanANF([[i]]) for i in fn.idxs_used()}
|
|
370
|
+
new_fn = fn.remap_constants([
|
|
371
|
+
(0, BooleanANF([0])),
|
|
372
|
+
(1, BooleanANF([1]))
|
|
373
|
+
])
|
|
374
|
+
return new_fn.eval_ANF(var_list)
|
|
375
|
+
|
|
376
|
+
def to_BooleanFunction(self: "BooleanANF") -> "BooleanFunction":
|
|
377
|
+
"""Convert to an equivalent `BooleanFunction`
|
|
378
|
+
|
|
379
|
+
Every nonconstant term in the ANF will be converted to an AND (even
|
|
380
|
+
terms with only one variable). Constant terms will be converted to
|
|
381
|
+
CONST inputs. If the BooleanANF is empty, it will be filled with a CONST(0)
|
|
382
|
+
to prevent a gate with no arguments.
|
|
383
|
+
|
|
384
|
+
:return: A BooleanFunction which matches the given BooleanANF
|
|
385
|
+
:rtype: BooleanFunction
|
|
386
|
+
"""
|
|
387
|
+
top_node = XOR()
|
|
388
|
+
for term in self.terms:
|
|
389
|
+
if type(term) == bool or ((not term) and type(term) != bool):
|
|
390
|
+
new_arg = CONST(1)
|
|
391
|
+
else:
|
|
392
|
+
new_arg = AND(*(VAR(i) for i in term))
|
|
393
|
+
top_node.add_arguments(new_arg)
|
|
394
|
+
|
|
395
|
+
# don't return empty XORs:
|
|
396
|
+
if not top_node.args:
|
|
397
|
+
top_node.add_arguments(CONST(0))
|
|
398
|
+
|
|
399
|
+
return top_node
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
# after loading, add BooleanANF based methods to all boolean functions
|
|
403
|
+
def translate_ANF(self: "BooleanFunction") -> "BooleanFunction":
|
|
404
|
+
"""Convert a BooleanFunction to its ANF representation
|
|
405
|
+
|
|
406
|
+
This function translates a BooleanFunction to another BooleanFunction, but in
|
|
407
|
+
ANF form. This means that it is top level XOR gate, the arguments of which are
|
|
408
|
+
either CONST gates or an AND of VAR nodes. Note that this is the same as
|
|
409
|
+
`BooleanANF.from_BooleanFunction(fn).to_BooleanFunction`, but that the output
|
|
410
|
+
not be confused with BooleanFunction - This is a "round-trip" back to BooleanFunctions
|
|
411
|
+
|
|
412
|
+
:return: A BooleanFunction which models an ANF equation.
|
|
413
|
+
:rtype: BooleanFunction
|
|
414
|
+
"""
|
|
415
|
+
return BooleanANF.from_BooleanFunction(self).to_BooleanFunction()
|
|
416
|
+
BooleanFunction.translate_ANF = translate_ANF
|
|
417
|
+
|
|
418
|
+
def from_ANF(cls, nested_iterable: Any) -> "BooleanFunction":
|
|
419
|
+
"""Generates a BooleanFunction from either a BooleanANF or a nested iterable.
|
|
420
|
+
|
|
421
|
+
If the passed anf is a BooleanANF, convert it to a BooleanFunction (equivalent
|
|
422
|
+
to `anf.to_BooleanFunction()`). Otherwise, anf is assumed to be a nested iterable,
|
|
423
|
+
which can be converted to BooleanANF via the BooleanANF constructor. Then the
|
|
424
|
+
returned function is equivalent to `BooleanANF(anf).to_BooleanFunction`. This
|
|
425
|
+
enables forming a BooleanFunction from a nested list, or data structure which
|
|
426
|
+
can represent ANF via literals in a convenient way.
|
|
427
|
+
|
|
428
|
+
:param anf: The ANF object to be used to create the function. Because there are
|
|
429
|
+
a variety of types available to be parsed by the BooleanANF constructor, the
|
|
430
|
+
type is annotated as `Any` to avoid downstream type errors.
|
|
431
|
+
:type anf: Any
|
|
432
|
+
:return: The boolean function corresponding to the input ANF.
|
|
433
|
+
:rtype: BooleanFunction
|
|
434
|
+
"""
|
|
435
|
+
if type(nested_iterable) == BooleanANF:
|
|
436
|
+
return nested_iterable.to_BooleanFunction()
|
|
437
|
+
return BooleanANF(nested_iterable).to_BooleanFunction()
|
|
438
|
+
BooleanFunction.from_ANF = classmethod(from_ANF) # type: ignore
|
|
439
|
+
|
|
440
|
+
def anf_str(self):
|
|
441
|
+
"""Print a BooleanFunction using the ANF string format
|
|
442
|
+
|
|
443
|
+
This is identical to `str(BooleanANF.from_BooleanFunction(fn))`, and is mostly
|
|
444
|
+
included to make the code less verbose. A minor benefit is that it makes it slightly
|
|
445
|
+
easier to reproduce some of the really old experiments
|
|
446
|
+
|
|
447
|
+
:return: The string for the BooleanANF of the function
|
|
448
|
+
:rtype: str
|
|
449
|
+
"""
|
|
450
|
+
return str(BooleanANF.from_BooleanFunction(self))
|
|
451
|
+
BooleanFunction.anf_str = anf_str
|
|
452
|
+
|
|
453
|
+
def degree(self):
|
|
454
|
+
"""Calculate the algebraic degree of the function
|
|
455
|
+
|
|
456
|
+
This is implemented by computing the ANF, and then taking the max of the
|
|
457
|
+
degree of each monomial in the ANF. This is equivalent to
|
|
458
|
+
`BooleanANF.from_BooleanFunction(fn).degree()`. As with all methods which
|
|
459
|
+
depend on the ANF, this has the potential to become computationally infeasible
|
|
460
|
+
(but is usually fine).
|
|
461
|
+
|
|
462
|
+
:return: The algebraic degree of the function
|
|
463
|
+
:rtype: int
|
|
464
|
+
"""
|
|
465
|
+
return BooleanANF.from_BooleanFunction(self).degree()
|
|
466
|
+
BooleanFunction.degree = degree
|
|
467
|
+
|
|
468
|
+
def monomial_count(self, convert = True):
|
|
469
|
+
"""Calculate the number of monomials in the ANF of the function
|
|
470
|
+
|
|
471
|
+
This is implemented by computing the ANF, and then counting the number of the
|
|
472
|
+
monomials in the ANF. This is equivalent to
|
|
473
|
+
`len(BooleanANF.from_BooleanFunction(fn).degree().terms)`, but is more readible
|
|
474
|
+
and far less verbose. As with all methods which depend on the ANF, this has the
|
|
475
|
+
potential to become computationally infeasible (but is usually fine).
|
|
476
|
+
|
|
477
|
+
:return: The number of monomials in the ANF of the function
|
|
478
|
+
:rtype: int
|
|
479
|
+
"""
|
|
480
|
+
if convert:
|
|
481
|
+
return len(
|
|
482
|
+
BooleanANF.from_BooleanFunction(self)
|
|
483
|
+
)
|
|
484
|
+
|
|
485
|
+
return len(self.args)
|
|
486
|
+
BooleanFunction.monomial_count = monomial_count
|
|
487
|
+
|
|
488
|
+
# def anf_optimize(self):
|
|
489
|
+
# # graded list of terms, in frozenset form
|
|
490
|
+
# termlist = sorted(
|
|
491
|
+
# BooleanANF.from_BooleanFunction(self).terms,
|
|
492
|
+
# key = lambda x: len(x)
|
|
493
|
+
# )
|
|
494
|
+
|
|
495
|
+
# # map term -> its function
|
|
496
|
+
# # pick divisors to reuse
|
|
497
|
+
# # then sequentially add vars
|
|
498
|
+
# fn_dict = {}
|
|
499
|
+
# for term in termlist:
|
|
500
|
+
# if term == frozenset():
|
|
501
|
+
# fn_dict[term] = CONST(1)
|
|
502
|
+
# continue
|
|
503
|
+
|
|
504
|
+
# divisor = max(
|
|
505
|
+
# [t for t in fn_dict.keys() if t <= term],
|
|
506
|
+
# key = lambda x: len(x),
|
|
507
|
+
# default=None
|
|
508
|
+
# )
|
|
509
|
+
|
|
510
|
+
# if divisor == None:
|
|
511
|
+
# fn_dict[term] = AND(*(VAR(x) for x in term))
|
|
512
|
+
# else:
|
|
513
|
+
# fn_dict[term] = AND(
|
|
514
|
+
# fn_dict[divisor],
|
|
515
|
+
# *(VAR(x) for x in term - divisor)
|
|
516
|
+
# )
|
|
517
|
+
|
|
518
|
+
# top_node = XOR(*fn_dict.values())
|
|
519
|
+
# if not top_node.args:
|
|
520
|
+
# top_node.add_arguments(CONST(0))
|
|
521
|
+
# return top_node
|
|
522
|
+
# BooleanFunction.anf_optimize = anf_optimize
|