circuit-quantization 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,358 @@
1
+ # Vendored from sircuitenum/equationset.py (GPL-3.0), sircuitenum commit b2c57e8.
2
+ """Equation set management and symbolic solving utilities.
3
+
4
+ This module provides the EquationSet class for managing collections of
5
+ symbolic equations with deduplication, caching, and compatibility checking.
6
+
7
+ Author: Eli Weissler
8
+ Version: 0.1.0
9
+ """
10
+
11
+ __all__ = ["maximally_compatible_sol", "eq_indep_of_vars", "sol_indep_of_vars", "extract_denom"]
12
+
13
+ from dataclasses import dataclass, field
14
+ from typing import Union, Sequence, Iterable, Mapping, Optional, Tuple
15
+ import sympy as sym
16
+ import functools, itertools
17
+ from sympy.core.mul import Mul
18
+ import networkx as nx
19
+
20
+ from .singular_interface import solve_with_singular, extract_mappings, is_compatible, _eq_as_numer_denom
21
+ from .z3_interface import _zero_subs_for_nonzero
22
+
23
+
24
+ # Cache of solved equations
25
+ CACHE_VARS = sym.symbols(",".join([f'x{i}' for i in range(100)]), real=True)
26
+ CACHE_CONST = sym.symbols(",".join([f'c{i}' for i in range(100)]), real=True)
27
+ SOLVE_CACHE = {}
28
+ UNSOLVABLE_CACHE = set() # sets of equations with no solutions
29
+
30
+
31
+ def largest_subsets_first(n_terms: int):
32
+ """
33
+ circuit_quantization: the default search order of maximally_compatible_sol, as
34
+ (cost, keys) pairs: every subset of the n_terms term groups, largest first.
35
+ """
36
+ for nz in range(n_terms, 0, -1):
37
+ for keys in itertools.combinations(range(n_terms), nz):
38
+ yield -nz, keys
39
+
40
+
41
+ def maximally_compatible_sol(terms: list[list[sym.Expr]], nonzero: list[sym.Expr] = [],
42
+ nonzero_constraints: list[sym.Expr] = [],
43
+ rational_only = False, stop_at_first=False, debug=False,
44
+ get_all_sols = True, patterns=None) -> Tuple[list, list]:
45
+ """
46
+ Given a list of list of systems of equations, identifies the largest set of compatible
47
+ systems of equations that can be solved simultaneously. Returns the indices of the selected
48
+ systems along with the corresponding solutions.
49
+
50
+ Assumes that any free symbols in the equations are to be solved for.
51
+
52
+ Assumes that no fractions are present in the equations!
53
+
54
+ Parameters
55
+ ----------
56
+ terms : list[list[sym.Expr]]
57
+ List of term groups, each representing a system of equations
58
+ nonzero : list[sym.Expr], optional
59
+ Expressions that must be nonzero in solutions. Are checked after solving.
60
+ nonzero_constraints : list[sym.Expr], optional
61
+ Expressions to be included as constraints to the solver to enforce nonzero conditions.
62
+ rational_only : bool, optional
63
+ If ``True``, only allows for solutions that contain rational numbers
64
+ patterns : iterable of (cost, tuple[int, ...]), optional
65
+ circuit_quantization: candidate sets of term indices in non-decreasing cost.
66
+ The search returns every solvable set at the first cost that has one (only
67
+ the first, with ``stop_at_first``). Defaults to largest_subsets_first, the
68
+ original top-down search by size.
69
+
70
+ Returns
71
+ -------
72
+ tuple[list, list]
73
+ - List of index tuples identifying best compatible term combinations
74
+ - List of corresponding solution dictionaries
75
+
76
+ """
77
+ # Check for fractions in equations
78
+ for term_group in terms:
79
+ for eq in term_group:
80
+ numer, denom = eq.as_numer_denom()
81
+ if denom != 1:
82
+ raise ValueError("Equations with fractions are not supported in maximally_compatible_sol.")
83
+
84
+ # Rabinowitsch Trick to enforce nonzero conditions
85
+ nz_term = []
86
+ nz_var = sym.symbols('nzVar')
87
+ if len(nonzero_constraints) > 0:
88
+ nz_eq = sym.sympify(1)
89
+ for d in nonzero_constraints:
90
+ nz_eq *= d
91
+ nz_term = [1 - nz_var * nz_eq]
92
+
93
+ # Unique-ify terms
94
+ new_terms = []
95
+ for ti in terms:
96
+ new_ti = []
97
+ for eq in ti:
98
+ if not any(eq-eq0 == 0 for eq0 in new_ti):
99
+ new_ti.append(eq)
100
+ new_terms.append(new_ti)
101
+ terms = new_terms
102
+
103
+ # Mark ones that are individually compatible
104
+ # Quick check to skip incompatible terms
105
+ n_terms = len(terms)
106
+ is_solvable = []
107
+ for i in range(len(terms)):
108
+ compat = True
109
+ try:
110
+ if is_compatible(terms[i], check_fraction=False, timeout=1, debug=debug):
111
+ compat = is_compatible(terms[i] + nz_term, check_fraction=False, timeout=1, debug=debug)
112
+ else:
113
+ compat = False
114
+ except TimeoutError:
115
+ compat = True
116
+ is_solvable.append(compat)
117
+ if sum(is_solvable) == 0:
118
+ return [], []
119
+
120
+ # Identify all incompatible pairs of terms
121
+ # to speed up compatibility checking later
122
+ incompatible_pairs = set()
123
+ for i1, i2 in itertools.combinations(range(n_terms), 2):
124
+ if not is_solvable[i1] or not is_solvable[i2]:
125
+ incompatible_pairs.add((i1, i2))
126
+ continue
127
+ combined_terms = terms[i1] + terms[i2]
128
+ compat = True
129
+ # Check compatibility -- Okay to time out here we want a quick check
130
+ # and sometimes pairwise checks can be slower than larger sets
131
+ try:
132
+ if is_compatible(combined_terms, check_fraction=False, timeout=1, debug=debug):
133
+ compat = is_compatible(combined_terms + nz_term, check_fraction=False, timeout=1, debug=debug)
134
+ else:
135
+ compat = False
136
+ except TimeoutError:
137
+ compat = True
138
+ if not compat:
139
+ incompatible_pairs.add((i1, i2))
140
+
141
+ G = nx.Graph()
142
+ G.add_nodes_from(range(n_terms))
143
+ G.add_edges_from(incompatible_pairs)
144
+
145
+ # Search candidate sets in non-decreasing cost; the default is top down by size
146
+ all_sols = []
147
+ sol_keys = []
148
+ if patterns is None:
149
+ patterns = largest_subsets_first(n_terms)
150
+ level, sol_found = None, False
151
+ for cost, keys in patterns:
152
+ if cost != level:
153
+ if sol_found:
154
+ return sol_keys, all_sols
155
+ level = cost
156
+ elif sol_found and stop_at_first:
157
+ continue
158
+ if debug:
159
+ print("Checking compatibility of combined eqs:", keys)
160
+ # Check if all individual terms are solvable
161
+ if not all(is_solvable[k] for k in keys):
162
+ if debug:
163
+ print("Skipping incompatible individual term", [k for k in keys if not is_solvable[k]])
164
+ continue
165
+
166
+ # Check if a subset of the keys are incompatible
167
+ # by checking the conflict graph
168
+ if G.subgraph(keys).number_of_edges() > 0:
169
+ if debug:
170
+ print("Skipping incompatible subset of terms")
171
+ continue
172
+
173
+ # Check compatibility of combined terms
174
+ combined_eqs = list(itertools.chain.from_iterable(terms[k] for k in keys))
175
+ if is_compatible(combined_eqs + nz_term, check_fraction=False, debug=debug):
176
+ # Solve combined equations
177
+ sols = []
178
+ branches = solve_with_singular(combined_eqs + nz_term, check_fraction=False,
179
+ rational_only=True, debug=debug, get_all_sols=get_all_sols)
180
+ if debug:
181
+ print("found", len(branches), "branches")
182
+ if branches:
183
+ for sol in extract_mappings(branches, real_only=True):
184
+ # Sub out nzvar if present
185
+ if nz_var in sol:
186
+ nz_var_val = sol.pop(nz_var)
187
+ sol = {k: v.subs(nz_var, nz_var_val) for k, v in sol.items()}
188
+ # Check nonzero conditions
189
+ if any(sym.simplify(d.subs(sol)) == 0 for d in nonzero):
190
+ continue
191
+ sols.append(sol)
192
+ if len(sols) > 0:
193
+ all_sols.append(sols)
194
+ sol_keys.append(keys)
195
+ sol_found = True
196
+ if sol_found:
197
+ return sol_keys, all_sols
198
+
199
+ # Should not reach here
200
+ return [], []
201
+
202
+
203
+ def eq_indep_of_vars(expr: Union[sym.Eq, sym.Expr], exclude_vars: Iterable[sym.Symbol]):
204
+ """
205
+ Extract a system of equations whose solutions solve the input expression independently
206
+ of the specified excluded variables.
207
+
208
+ Args:
209
+ expr (Union[sym.Eq, sym.Expr]): Equation or expression to analyze.
210
+ exclude_vars: Iterable[sym.Symbol] (_type_): Variables you want solutions to be independent of.
211
+
212
+ Returns:
213
+ tuple[list[sym.Expr], sym.Expr]: The system of equations (as a list of expressions) whose solutions
214
+ solve the input expression independently of the excluded variables, and the denominator
215
+ of the original expression (i.e., this must be nonzero in the solutions).
216
+ """
217
+
218
+ # Simplify to rational form
219
+ numer, denom = _eq_as_numer_denom(expr)
220
+
221
+ # No solutions if there are no solve variables
222
+ if not any(v in numer.free_symbols for v in exclude_vars):
223
+ return [], sym.sympify(1)
224
+
225
+ # Get unique symbolic products of non-excluded vars
226
+ var_combos = _unique_products(numer, exclude=exclude_vars)
227
+
228
+ # All coefficients must be able to be zero simultaneously
229
+ coeffs = []
230
+ # Constant term must be 0
231
+ if 1 in var_combos:
232
+ val = var_combos[1]
233
+ if val.is_number and val != 0:
234
+ return []
235
+ else:
236
+ coeffs.append(var_combos.pop(1))
237
+ for v in var_combos:
238
+ coeffs.append(var_combos[v])
239
+
240
+ return coeffs, denom
241
+
242
+
243
+ def sol_indep_of_vars(expr: Union[sym.Eq, sym.Expr], solve_vars, nonzero=[],
244
+ real_only=True):
245
+ """Find solutions independent of non-solve variables.
246
+
247
+ Determines whether solutions exist that depend only on specified solve
248
+ variables, not on other free symbols in the expression.
249
+
250
+ Parameters
251
+ ----------
252
+ expr : sym.Eq or sym.Expr
253
+ Equation or expression to solve (expression set to 0).
254
+ solve_vars : list[sym.Symbol]
255
+ Variables to solve for.
256
+ nonzero : list[sym.Expr], optional
257
+ Expressions that must be nonzero in solutions.
258
+
259
+ Returns
260
+ -------
261
+ list[dict]
262
+ List of minimal solution dictionaries mapping solve_vars to values.
263
+
264
+ Raises
265
+ ------
266
+ ValueError
267
+ If solution does not satisfy the original expression.
268
+ """
269
+
270
+ coeffs, denom = eq_indep_of_vars(expr, solve_vars)
271
+ sols = extract_mappings(solve_with_singular(coeffs, solve_vars), real_only=real_only)
272
+
273
+ # Make sure none of the nonzero conditions are violated
274
+ sols = [s for s in sols if all(sym.simplify(d.subs(s)) != 0 for d in nonzero)]
275
+ sols = [s for s in sols if sym.simplify(denom.subs(s)) != 0]
276
+
277
+ return sols
278
+
279
+
280
+ def _unique_products(expr: sym.Expr, exclude: list[sym.Symbol] = []):
281
+ """Extract unique symbolic products from expanded expression.
282
+
283
+ Parameters
284
+ ----------
285
+ expr : sym.Expr
286
+ SymPy expression to analyze.
287
+ exclude : list[sym.Symbol], optional
288
+ Symbols to exclude from products.
289
+
290
+ Returns
291
+ -------
292
+ dict
293
+ Mapping from product (sym.Expr) to coefficient (sym.Expr).
294
+
295
+ Notes
296
+ -----
297
+ Expands expression and groups terms by unique products of symbols,
298
+ excluding specified symbols from the products.
299
+ """
300
+ expr = sym.expand(expr)
301
+ products = {}
302
+ for term in expr.as_ordered_terms():
303
+ if term == 0 or term == 0.0:
304
+ continue
305
+ # Extract multiplicative factors
306
+ factors = []
307
+ if isinstance(term, Mul):
308
+ for f in term.args:
309
+ if isinstance(f, sym.Symbol) and f not in exclude:
310
+ factors.append(f)
311
+ elif isinstance(f, sym.Pow):
312
+ if f.base not in exclude:
313
+ factors.append(f)
314
+ elif isinstance(term, sym.Pow):
315
+ if term.base not in exclude:
316
+ factors.append(term)
317
+ elif isinstance(term, sym.Symbol) and term not in exclude:
318
+ factors.append(term)
319
+ elif term.is_number:
320
+ factors.append(term)
321
+ factors = tuple(sorted(factors, key=lambda a: str(a))) + (1,)
322
+ prod = functools.reduce(lambda a,b: a*b, factors, sym.sympify(1))
323
+ coeff = term/prod
324
+ if factors in products:
325
+ products[factors].append(coeff)
326
+ else:
327
+ products[factors] = [coeff]
328
+
329
+ to_return = {}
330
+ for factors, coeffs in products.items():
331
+ prod = functools.reduce(lambda a,b: a*b, factors, sym.sympify(1))
332
+ coeff = functools.reduce(lambda a,b: a+b, coeffs, sym.sympify(0))
333
+ # to_return[prod] = sym.simplify(coeff)
334
+ to_return[prod] = coeff
335
+
336
+ return to_return
337
+
338
+
339
+ def extract_denom(Z: sym.Matrix):
340
+ """Extract unique denominators from matrix elements.
341
+
342
+ Parameters
343
+ ----------
344
+ Z : sym.Matrix
345
+ SymPy matrix to analyze.
346
+
347
+ Returns
348
+ -------
349
+ list[sym.Expr]
350
+ List of unique denominators from non-constant matrix elements.
351
+ """
352
+
353
+ denom_list = []
354
+ for i in range(Z.shape[0]):
355
+ for j in range(Z.shape[1]):
356
+ if len(Z[i,j].free_symbols) > 0:
357
+ denom_list.append(sym.simplify(Z[i,j].together().as_numer_denom()[1]))
358
+ return list(set(denom_list))
@@ -0,0 +1,88 @@
1
+ """Search orders for choose_S1: which sets of couplings to try to zero, cheapest first.
2
+
3
+ A search order takes the coupling terms of one decoupling stage, as keys
4
+ (name, i, j) for the off-diagonal entry (i, j) of the matrix called name, and
5
+ yields (cost, term indices) in non-decreasing cost. The solver returns every
6
+ solvable set at the first cost that has one, so a good order reaches the best
7
+ patterns without solving the ones that cannot win. An order with a seed parameter
8
+ also gets the seed being refined, as seed=Seed(var_types, wJ_T), from choose_S1.
9
+ """
10
+
11
+ from itertools import product
12
+ from typing import NamedTuple
13
+
14
+ import sympy as sym
15
+ from sympy.utilities.iterables import multiset_partitions
16
+
17
+ from ..modes import _cluster_cost
18
+ from .equationset import largest_subsets_first
19
+
20
+
21
+ class Seed(NamedTuple):
22
+ """The seed a stage refines, in its (compact, extended, harmonic) column order."""
23
+
24
+ var_types: dict # sircuitenum's var_types: column indices of each mode type
25
+ wJ_T: sym.Matrix # omega_J~^T times the seed, one row per junction
26
+
27
+
28
+ def most_zeros_first(term_keys, seed=None):
29
+ """sircuitenum's order: every set of couplings, largest first (cost = -size)."""
30
+ return largest_subsets_first(len(term_keys))
31
+
32
+
33
+ def by_cost(cost):
34
+ """Order every set of couplings by cost(keys), keys a tuple of (name, i, j).
35
+
36
+ Visits all 2^n subsets, so it suits few couplings. Ties keep most_zeros_first's
37
+ order. For many couplings, write an order that yields its candidates directly.
38
+ """
39
+ def order(term_keys, seed=None):
40
+ subsets = [keys for _, keys in largest_subsets_first(len(term_keys))]
41
+ return sorted(((cost(tuple(term_keys[k] for k in keys)), keys) for keys in subsets),
42
+ key=lambda pair: pair[0])
43
+ return order
44
+
45
+
46
+ def by_clusters(dims=None, name="wJ"):
47
+ """Junction clusters, cheapest first, for a rows stage on the junction incidence (built-in "wJ").
48
+
49
+ A pattern is a partition of the modes into clusters together with a cluster for each
50
+ junction. Its terms are that junction's entries (name, k, j) in noncompact columns j
51
+ outside its cluster, which are linear in S_1, and its cost is the tuple of cluster
52
+ dimensions for the partition, largest first, as in cluster_score. A stage cannot change compact columns, so a junction acting on a compact
53
+ mode must sit in that mode's cluster, and partitions splitting a junction's compact
54
+ modes are skipped without solving. Equal term sets keep their cheapest partition.
55
+
56
+ :param dims: Basis size per mode type, as in cluster_score.
57
+ :param name: The rows target holding the junction incidence.
58
+ :returns: An order for Stage(rows=(name,), order=...). It needs choose_S1's seed.
59
+ """
60
+ def order(term_keys, seed=None):
61
+ if seed is None:
62
+ raise ValueError("by_clusters needs the seed's mode types and junction incidence; use it in choose_S1")
63
+ W = seed.wJ_T
64
+ n = W.cols
65
+ types = [None] * n
66
+ for kind, t in (("compact", "c"), ("extended", "e"), ("harmonic", "h")):
67
+ for j in seed.var_types[kind]:
68
+ types[j] = t
69
+ index = {key: i for i, key in enumerate(term_keys)}
70
+ compact = [{j for j in seed.var_types["compact"] if sym.cancel(W[k, j]) != 0} for k in range(W.rows)]
71
+ patterns = []
72
+ for partition in multiset_partitions(list(range(n))) if n else []:
73
+ cluster_of = {j: a for a, block in enumerate(partition) for j in block}
74
+ choices = [sorted({cluster_of[j] for j in compact[k]}) or range(len(partition)) for k in range(W.rows)]
75
+ if any(len(c) > 1 and compact[k] for k, c in enumerate(choices)):
76
+ continue
77
+ cost = _cluster_cost([tuple(block) for block in partition], types, dims)
78
+ for assignment in product(*choices):
79
+ keys = tuple(sorted(index[(name, k, j)] for k, a in enumerate(assignment)
80
+ for j in range(n) if cluster_of[j] != a and (name, k, j) in index))
81
+ patterns.append((cost, keys))
82
+ seen, ordered = set(), []
83
+ for cost, keys in sorted(patterns, key=lambda pattern: pattern[0]):
84
+ if keys not in seen:
85
+ seen.add(keys)
86
+ ordered.append((cost, keys))
87
+ return ordered
88
+ return order