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,396 @@
1
+ # Adapted from sircuitenum/quantize.py choose_Z (GPL-3.0), sircuitenum commit b2c57e8.
2
+ # The ranking body follows choose_Z; the circuit preparation is replaced by
3
+ # circuit_quantization's decoupled Coordinates (Z0 = I on the retained modes), the
4
+ # compact alignments become the default seeds, the decoupling steps become stages,
5
+ # and the z3 instance step becomes choose_instance.
6
+ """Choose the residual transformation S_1 by seeds, stages, score, then instances."""
7
+
8
+ import inspect
9
+ from dataclasses import dataclass
10
+ from functools import cached_property, partial
11
+
12
+ import numpy as np
13
+ import sympy as sym
14
+
15
+ from ..modes import _check_residual, _cluster_cost, _clusters, junction_inversions, mode_types
16
+ from ..units import Phi0, e, h, h_GHz, hbar
17
+ from .equationset import extract_denom
18
+ from .patterns import Seed
19
+ from .stages import SIRCUITENUM, SIRCUITENUM_BLOCKS, Target, resolve, trans_blocks, zero_keys
20
+ from .transforms import (
21
+ H_hash, _find_Z_instance, _find_Z_instance_deterministic, _find_Z_min_cost,
22
+ _incidence_square_nonzero_str, _nonzero_entries_str,
23
+ _remove_permutation_equivalent_transformations, _sub_equal_LC, _var_col_perms,
24
+ compact_alignment_transformation, incidence_to_square, secondary_decouple,
25
+ )
26
+
27
+ ORDER = ("c", "e", "h") # sircuitenum's column order: compact, extended, harmonic
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Candidate:
32
+ """A candidate S_1 as a score sees it, with matrices in (compact, extended, harmonic) order.
33
+
34
+ instance is False while ranking symbolic candidates, whose free entries are set
35
+ deterministically with all C and all L equal, and True for concrete instances.
36
+ EJ holds one placeholder per junction (the junction structure is topological,
37
+ as in sircuitenum).
38
+
39
+ :ivar S: Residual transformation of the retained modes.
40
+ :ivar C_inv: (S^T C~ S)^{-1}.
41
+ :ivar L: S^T L~* S.
42
+ :ivar wJ_T: omega~_J^T S, one row per junction.
43
+ :ivar EJ: One placeholder E_J per junction.
44
+ :ivar var_types: Column indices of each mode type, keyed by "compact", "extended", and "harmonic".
45
+ :ivar instance: Whether S is a concrete instance.
46
+ :ivar targets: Every stage's matrices.
47
+ """
48
+
49
+ S: sym.Matrix # residual transformation of the retained modes
50
+ C_inv: sym.Matrix # (S^T C~ S)^{-1}
51
+ L: sym.Matrix # S^T L~* S
52
+ wJ_T: sym.Matrix # omega_J~^T S, one row per junction
53
+ EJ: tuple
54
+ var_types: dict
55
+ instance: bool
56
+ targets: tuple = () # every stage's matrices (stages.Target)
57
+
58
+ @cached_property
59
+ def zeros(self):
60
+ """Keys (name, i, j) of every stage's terms that vanish for this S, as the solver keys them."""
61
+ return zero_keys(self.targets, self.S, self.var_types["compact"])
62
+
63
+
64
+ def h_hash(candidate):
65
+ """sircuitenum's H_hash, the default score, with extra_nl for instances, as choose_Z.
66
+
67
+ Needs integer junction coefficients on compact and extended modes for instances.
68
+ Rank candidates without them, such as normal-mode seeds, with a custom score.
69
+ """
70
+ c = candidate
71
+ n_nl = len(c.var_types["compact"]) + len(c.var_types["extended"])
72
+ if c.instance and not all(sym.sympify(x).is_integer for x in c.wJ_T[:, :n_nl]):
73
+ raise ValueError("h_hash needs integer junction coefficients on compact and extended modes; "
74
+ "rank this candidate with a custom score")
75
+ return H_hash(c.C_inv, c.L, c.wJ_T, c.EJ, var_types=c.var_types, extra_nl=c.instance)[0]
76
+
77
+
78
+ def _with_seed(order, seed):
79
+ """The stage order, given the seed when it takes one (a seed parameter, as by_clusters)."""
80
+ return partial(order, seed=seed) if "seed" in inspect.signature(order).parameters else order
81
+
82
+
83
+ def _ordering(types):
84
+ """P selecting columns in (compact, extended, harmonic) order, and sircuitenum's var_types."""
85
+ columns = [j for t in ORDER for j, kind in enumerate(types) if kind == t]
86
+ P = sym.eye(len(columns))[:, columns]
87
+ var_types = {name: [i for i, j in enumerate(columns) if types[j] == t]
88
+ for name, t in (("compact", "c"), ("extended", "e"), ("harmonic", "h"))}
89
+ var_types.update(free=[], frozen=[], sigma=[])
90
+ return P, var_types
91
+
92
+
93
+ def _junctions(lag, coords, P):
94
+ """Junction incidence in P's order and one placeholder E_J per junction (sircuitenum's gen_w)."""
95
+ # One distinct E_J per junction, as choose_Z's gen_w(add_elem_number(circuit)): the
96
+ # junction structure is topological, so equal junctions never cancel a coupling.
97
+ EJ = list(sym.symbols(f"E_J1:{len(lag.EJ) + 1}", positive=True)) or [0]
98
+ wJ = P.T * coords.omega_J_tilde if lag.EJ else sym.zeros(P.cols, 1)
99
+ return wJ, EJ
100
+
101
+
102
+ def _seeded(lag, coords, S):
103
+ """A seed or family S_1 (coords.types order), as rows (c, e, h) of coords and columns
104
+ (c, e, h) of its own re-inferred types, with those columns' P and var_types."""
105
+ P, _ = _ordering(coords.types)
106
+ P_new, var_types = _ordering(mode_types(lag, coords.Z * sym.Matrix(S)))
107
+ return P.T * sym.Matrix(S) * P_new, var_types, P_new
108
+
109
+
110
+ def candidate(lag, coords, S1, *, instance=True, targets=()):
111
+ """The Candidate a score sees for S_1 in coords.types order, e.g. to rank instances."""
112
+ Z, var_types, _ = _seeded(lag, coords, S1)
113
+ P, _ = _ordering(coords.types)
114
+ wJ, EJ = _junctions(lag, coords, P)
115
+ C = sym.simplify(Z.T * (P.T * coords.C_tilde * P) * Z)
116
+ return Candidate(sym.ImmutableMatrix(Z), C.inv() if C.shape[0] else C,
117
+ sym.simplify(Z.T * (P.T * coords.Lstar_tilde * P) * Z),
118
+ sym.simplify(wJ.T * Z), tuple(EJ), var_types, instance, targets)
119
+
120
+
121
+ def junction_seeds(types=("c", "e"), *, clean=True):
122
+ """Seeds for choose_S1: the identity and every junction inversion.
123
+
124
+ A junction inversion is an S_1 that makes each junction of a chosen set act on a single coordinate.
125
+
126
+ :param types: Blocks to invert, ("c",), ("e",), or ("c", "e").
127
+ :param bool clean: Remove the extended components of the compact-aligned junctions.
128
+ :returns: (lag, coords) -> list of S_1 in coords.types order.
129
+ """
130
+ def seeds(lag, coords):
131
+ return [sym.eye(len(coords.types)), *junction_inversions(coords, types, clean=clean)]
132
+ return seeds
133
+
134
+
135
+ def cluster_score(dims=None):
136
+ """Score for choose_S1: the candidate's junction cluster dimensions, largest first.
137
+
138
+ A junction cluster is a set of modes linked by junctions, and its dimension is the product of its modes' basis sizes.
139
+
140
+ :param dims: Basis size per mode type. Defaults to c: 40 charge states, e: 100 phase-grid points, h: 20 oscillator states.
141
+ :returns: Candidate -> tuple, lower is better.
142
+ """
143
+ def score(candidate):
144
+ types = [None] * candidate.wJ_T.cols
145
+ for kind, t in (("compact", "c"), ("extended", "e"), ("harmonic", "h")):
146
+ for j in candidate.var_types[kind]:
147
+ types[j] = t
148
+ return _cluster_cost(_clusters(candidate.wJ_T, len(types)), types, dims)
149
+ return score
150
+
151
+
152
+ def compact_alignments(lag, coords):
153
+ """sircuitenum's compact alignment candidates, the default seeds, as S_1 in coords.types order."""
154
+ P, var_types = _ordering(coords.types)
155
+ wJ, _ = _junctions(lag, coords, P)
156
+ return [P * Z * P.T for Z in compact_alignment_transformation(sym.simplify(wJ.T), len(var_types["compact"]))]
157
+
158
+
159
+ def choose_S1(lag, coords, *, seeds=compact_alignments, blocks=SIRCUITENUM_BLOCKS, stages=SIRCUITENUM,
160
+ score=h_hash, debug=False):
161
+ """Residual transformations S_1 tied for the lowest score, with their free entries, and that score.
162
+
163
+ Each seed is refined by the stages in sequence: the first opens the S_1 blocks
164
+ in blocks as free entries and solves for those that zero its couplings
165
+ (Singular). Each later stage solves among the entries the previous one left
166
+ free. The results are ranked by score. Free entries stay symbolic, for
167
+ choose_instance or instance. The defaults reproduce sircuitenum's choose_Z:
168
+ compact alignments, junction couplings then inductive and charging couplings,
169
+ ranked by H_hash. With stages=() the seeds themselves are ranked.
170
+ Each S_1 is in coords.types column order. Apply it with transform or Result.transform.
171
+
172
+ :param lag: Node Lagrangian matrices.
173
+ :param coords: Decoupled retained coordinates, e.g. from quantize or decouple.
174
+ :param seeds: (lag, coords) -> iterable of S_1 in coords.types order, each a valid
175
+ residual transformation. Defaults to compact_alignments.
176
+ :param blocks: (old type, new type) blocks of S_1 the first stage opens, from
177
+ ALLOWED_BLOCKS. Defaults to sircuitenum's SIRCUITENUM_BLOCKS.
178
+ :param stages: Decoupling stages run in sequence, each Stage naming built-in or custom
179
+ matrices and the search order over their couplings. Defaults to SIRCUITENUM.
180
+ :param score: Ranks candidates, lowest first: called with a Candidate, returns
181
+ anything sortable. Defaults to h_hash, sircuitenum's ranking.
182
+ :param bool debug: Print sircuitenum's intermediate candidates.
183
+ :returns: Pair (list of S_1 tied for the lowest score, that score).
184
+ """
185
+ P, _ = _ordering(coords.types)
186
+ cMat = P.T * coords.C_tilde * P
187
+ lMat = P.T * coords.Lstar_tilde * P
188
+ wJ, EJ = _junctions(lag, coords, P) # retained-mode analogue of the node incidence wJ
189
+ jMat = incidence_to_square(wJ, EJ) if lag.EJ else sym.zeros(P.cols, P.cols)
190
+ n_dyn = P.cols
191
+ builtins = {
192
+ "J": Target("J", jMat, "flux", jMat, False) if lag.EJ else None,
193
+ "L": Target("L", lMat, "flux", lMat, False),
194
+ "Cinv": Target("Cinv", P.T * coords.C_tilde_inv * P, "charge", cMat, True),
195
+ "wJ": Target("wJ", wJ.T, "rows", wJ.T, False) if lag.EJ else None,
196
+ }
197
+ resolved = [(stage, *resolve(stage, builtins, P)) for stage in stages]
198
+ active = [(stage, square, rows) for stage, square, rows in resolved if square or rows]
199
+ all_targets = tuple(t for _, square, rows in resolved for t in square + rows)
200
+ free_blocks = trans_blocks(blocks)
201
+
202
+ # Step 1: Seeds, each validated and re-expressed in its own column types
203
+ seeded = []
204
+ for S in seeds(lag, coords):
205
+ _check_residual(coords.types, sym.Matrix(S))
206
+ seeded.append(_seeded(lag, coords, S))
207
+ if debug:
208
+ print(f"Generated {len(seeded)} seeds.")
209
+ for i, (Z, _, _) in enumerate(seeded):
210
+ print(f"Seed {i+1}:")
211
+ sym.pprint(Z)
212
+
213
+ # Step 2: Minimize intermode coupling, one stage at a time; each branch of a
214
+ # stage seeds the next (choose_Z: junction stage, then the linear stage).
215
+ lowest_hash = ""
216
+ lowest_Z = [] # (Z in rows c,e,h of coords and columns c,e,h of its own types, var_types, P_new)
217
+ for Z, var_types, P_new in seeded:
218
+ seed = Seed(var_types, (wJ.T * Z).applyfunc(sym.cancel))
219
+ Zs_in, vals = [None], [""]
220
+ for k, (stage, square, rows) in enumerate(active):
221
+ last = k == len(active) - 1
222
+ next_Z, next_vals = [], []
223
+ for Z_in in Zs_in:
224
+ out = secondary_decouple(var_types, [Z.transpose()*t.solver*Z for t in square],
225
+ [t.invert for t in square], Z_in=Z_in, debug=debug,
226
+ trans_blocks=free_blocks, names=[t.name for t in square],
227
+ row_mats=[t.solver*Z for t in rows], row_names=[t.name for t in rows],
228
+ pattern_order=_with_seed(stage.order, seed), return_tiebreaker=last)
229
+ Zs, vs = out if last else (out, [""]*len(out))
230
+ next_Z += Zs
231
+ next_vals += vs
232
+ Zs_in, vals = next_Z, next_vals
233
+ if debug:
234
+ print(f"Stage {k + 1}: {len(Zs_in)} candidate transformations.")
235
+ for Z2, val in zip(Zs_in, vals):
236
+ entry = (Z if Z2 is None else Z*Z2, var_types, P_new)
237
+ if score is not h_hash: # sircuitenum's tiebreaker prefilter belongs to its H_hash ranking
238
+ lowest_Z.append(entry)
239
+ elif val < lowest_hash or lowest_hash == "":
240
+ lowest_Z = [entry]
241
+ lowest_hash = val
242
+ elif val == lowest_hash:
243
+ lowest_Z += [entry]
244
+
245
+ if debug:
246
+ print(f"Found {len(lowest_Z)} transformations with lowest hash {lowest_hash}.")
247
+ for i, (Z, _, _) in enumerate(lowest_Z):
248
+ print(f"Lowest hash transformation {i+1}:")
249
+ sym.pprint(Z)
250
+ if not lowest_Z:
251
+ return [], None
252
+ # Filter out any bonkers transformations and sort by string length
253
+ str_len = [len(str(Z)) for Z, _, _ in lowest_Z]
254
+ order = np.argsort(str_len)
255
+ min_len = str_len[order[0]]
256
+ lowest_Z = [lowest_Z[i] for i in order if str_len[i] <= 50*min_len]
257
+
258
+ # Collapse column-permutation/sign-equivalent symbolic transformations
259
+ # before determinant instantiation, matrix inversion, and H_hash. These
260
+ # operations dominate runtime when compact alignment emits a large orbit.
261
+ # Seeds that changed column types are compared only with seeds of the same types.
262
+ kept = []
263
+ for key in dict.fromkeys(tuple(map(tuple, vt.values())) for _, vt, _ in lowest_Z):
264
+ group = [entry for entry in lowest_Z if tuple(map(tuple, entry[1].values())) == key]
265
+ col_perms = list(_var_col_perms(group[0][1], dyn_only=True))
266
+ _, unique_indices = _remove_permutation_equivalent_transformations([Z for Z, _, _ in group], perms=col_perms)
267
+ kept += [group[index] for index in unique_indices]
268
+ lowest_Z = kept
269
+
270
+ # If there are multiple Z with the same lowest hash
271
+ # then see if they separate with equal L/C values
272
+ Z_final = []
273
+ hash_final = tuple()
274
+ structural_hash_cache = {}
275
+ for Z, var_types, P_new in lowest_Z:
276
+ Z_equal = sym.simplify(_sub_equal_LC(Z))
277
+ var_list = [x for x in Z.free_symbols if "Z" in str(x)]
278
+ Z_hash = _find_Z_instance_deterministic(Z_equal, var_list, nonzero=extract_denom(Z_equal))
279
+ cTrans = sym.simplify(Z_hash.transpose()*cMat*Z_hash)[:n_dyn, :n_dyn]
280
+ if cTrans.shape[0] > 1:
281
+ cTransInv = sym.inv_quick(cTrans)
282
+ else:
283
+ cTransInv = cTrans.inv()
284
+ lTrans = sym.simplify(Z_hash.transpose()*lMat*Z_hash)
285
+ wJtTrans = sym.simplify(wJ.transpose()*Z_hash)
286
+ # The non-instance H hash depends only on these three zero/nonzero
287
+ # support patterns. Many distinct symbolic alignments instantiate to
288
+ # the same pattern, so avoid repeating all mode permutations for an
289
+ # already evaluated structure.
290
+ support_key = (
291
+ _nonzero_entries_str(cTransInv),
292
+ _nonzero_entries_str(lTrans),
293
+ _incidence_square_nonzero_str(wJtTrans.transpose(), EJ),
294
+ tuple(map(tuple, var_types.values())),
295
+ )
296
+ candidate_ = Candidate(Z_hash, cTransInv, lTrans, wJtTrans, tuple(EJ), var_types, False, all_targets)
297
+ if score is not h_hash: # the support cache holds only for the pattern-based default
298
+ val = score(candidate_)
299
+ else:
300
+ if support_key not in structural_hash_cache:
301
+ structural_hash_cache[support_key] = h_hash(candidate_)
302
+ val = structural_hash_cache[support_key]
303
+ if hash_final == tuple() or val < hash_final:
304
+ hash_final = val
305
+ Z_final = [(Z, P_new)]
306
+ elif val == hash_final:
307
+ Z_final.append((Z, P_new))
308
+ if debug:
309
+ print(f"Chosen Z transformations have H_hash = {hash_final} with {len(Z_final)} equivalent transformations.")
310
+ for Zf, _ in Z_final:
311
+ sym.pprint(Zf)
312
+ sym.pprint(wJ.transpose()*Zf)
313
+
314
+ return [sym.ImmutableMatrix(P * Zf * P_new.T) for Zf, P_new in Z_final], hash_final
315
+
316
+
317
+ def _free_entries(lag, coords, S):
318
+ """Symbols of S that are not circuit parameters or physical constants."""
319
+ parameters = set().union(*(sym.sympify(m).free_symbols for m in
320
+ (coords.C_tilde, coords.Lstar_tilde, coords.omega_J_tilde, *lag.EJ)))
321
+ return sym.Matrix(S).free_symbols - parameters - {Phi0, e, h, h_GHz, hbar}
322
+
323
+
324
+ def choose_instance(lag, coords, S1, *, max_weight=None, debug=False):
325
+ """sircuitenum's integer instance of one S_1 family: z3's minimum junction weight.
326
+
327
+ The weight is the sum of absolute junction coefficients on compact and extended modes,
328
+ which must come out integer, as in sircuitenum's parameter-independent families.
329
+ Families with non-integer extended coefficients, such as normal-mode seeds, are
330
+ not meant for this (use instance). An S_1 with no free entries is returned as is.
331
+ Entries z3 leaves free, being in no junction coefficient, are set as by instance.
332
+ Pass the best weight so far as max_weight to skip families that cannot reach it.
333
+
334
+ :param lag: Node Lagrangian matrices.
335
+ :param coords: The coordinates S_1 was chosen for.
336
+ :param S1: One S_1 family in coords.types order, e.g. from choose_S1.
337
+ :param max_weight: Return None unless an instance of at most this weight exists.
338
+ :returns: Pair (S_1 instance in coords.types order, its weight), or None.
339
+ :raises ValueError: No integer instance exists.
340
+ """
341
+ P, _ = _ordering(coords.types)
342
+ Zf, var_types, P_new = _seeded(lag, coords, S1)
343
+ wJ, _ = _junctions(lag, coords, P)
344
+ n_nl = len(var_types["compact"]) + len(var_types["extended"])
345
+
346
+ def weight(Z):
347
+ return sum(abs(x) for x in sym.simplify(wJ.T * Z)[:, :n_nl])
348
+
349
+ var_list = sorted(_free_entries(lag, coords, S1), key=str)
350
+ if not var_list:
351
+ return sym.ImmutableMatrix(S1), weight(Zf)
352
+ # Don't bother trying if we already know the cost can't be beat
353
+ if max_weight is not None and _find_Z_min_cost(Zf, var_list, var_types, wJ, nonzero=extract_denom(Zf)) > max_weight:
354
+ return None
355
+ # Include apriori solution to speed up search
356
+ ans = _find_Z_instance(Zf, var_list, var_types=var_types, wJ=wJ, nonzero=extract_denom(Zf),
357
+ apriori_sol=max_weight, debug=debug)
358
+ # Can't beat best cost
359
+ if ans == []:
360
+ return None
361
+ if ans is None:
362
+ raise ValueError("Could not find instance of Z transformation")
363
+ S = sym.ImmutableMatrix(P * ans * P_new.T)
364
+ # sircuitenum fixes only entries in a junction coefficient or det S_1; set the rest,
365
+ # e.g. a harmonic-into-extended entry, which cannot change the junction weight
366
+ if _free_entries(lag, coords, S):
367
+ S = instance(lag, coords, S)
368
+ return S, weight(ans)
369
+
370
+
371
+ def instance(lag, coords, S1):
372
+ """One valid instance of an S_1 family: its free entries set deterministically, no optimization.
373
+
374
+ Free entries, in name order, each take the first of 0, 1, -1, 2, -2, ... that
375
+ keeps det S_1 from vanishing identically and every entry finite. Junction
376
+ coefficients need not come out integer.
377
+
378
+ :param lag: Node Lagrangian matrices.
379
+ :param coords: The coordinates S_1 was chosen for.
380
+ :param S1: One S_1 family in coords.types order.
381
+ :returns: S_1 with no free entries, in coords.types order.
382
+ :raises ValueError: No small values keep S_1 invertible.
383
+ """
384
+ S = sym.Matrix(S1)
385
+ for x in sorted(_free_entries(lag, coords, S), key=str):
386
+ for k in range(41):
387
+ value = (k + 1) // 2 * (1 if k % 2 else -1) # 0, 1, -1, 2, -2, ...
388
+ trial = S.subs(x, value)
389
+ if not trial.has(sym.zoo, sym.oo, sym.nan) and sym.cancel(trial.det()) != 0:
390
+ S = trial
391
+ break
392
+ else:
393
+ raise ValueError(f"No small value of {x} keeps S_1 invertible")
394
+ S = S.applyfunc(sym.cancel)
395
+ _check_residual(coords.types, S)
396
+ return sym.ImmutableMatrix(S)