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,672 @@
1
+ """Mode classification, decoupling, and residual freedom.
2
+
3
+ The mode types are
4
+ "c" compact, "e" extended, "h" harmonic (dynamical) and
5
+ "fr" free, "fz" frozen, "cy" cyclic (non-dynamical).
6
+ """
7
+
8
+ from dataclasses import dataclass
9
+ from functools import reduce
10
+ from itertools import combinations
11
+ from math import gcd
12
+
13
+ import networkx as nx
14
+ import sympy as sym
15
+ import numpy as np
16
+ from scipy.linalg import eigh
17
+
18
+ __all__ = [
19
+ "Coordinates", "mode_basis", "mode_types", "mode_dimensions", "decouple", "transform", "residual_freedom",
20
+ "compact_charge_decoupling", "normal_mode_decoupling",
21
+ ]
22
+
23
+ DYNAMICAL = ("c", "e", "h")
24
+ NONDYNAMICAL = ("fr", "fz", "cy")
25
+ TYPES = DYNAMICAL + NONDYNAMICAL
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Coordinates:
30
+ """Retained coordinates and the circuit matrices transformed into them.
31
+
32
+ Internal node fluxes are Phi_int = Z Phi_tilde + Z_2 Phi_disc, with Phi_disc the discarded coordinates.
33
+
34
+ :ivar Z_full: Full square decoupled basis, including non-dynamical columns.
35
+ :ivar types_full: Mode type of each column of Z_full.
36
+ :ivar Z: Retained dynamical columns of Z_full.
37
+ :ivar R: Retained rows of Z_full^{-1}, so Phi_tilde = R Phi_int.
38
+ :ivar types: Mode type of each retained column, c, e, or h.
39
+ :ivar C_tilde: Capacitance matrix Z^T C_int Z.
40
+ :ivar C_tilde_inv: Inverse of C_tilde.
41
+ :ivar Lstar_tilde: Susceptance matrix Z^T L*_int Z.
42
+ :ivar omega_J_tilde: Z^T omega_J_int, one column per junction.
43
+ :ivar omega_L_tilde: Z^T omega_L_int, one column per inductor.
44
+ """
45
+
46
+ Z_full: sym.ImmutableMatrix # full decoupled basis, including non-dynamical columns
47
+ types_full: tuple
48
+ Z: sym.ImmutableMatrix # retained embedding: Phi_int = Z Phi_tilde + Z_2 Phi_disc
49
+ R: sym.ImmutableMatrix # retained extraction: Phi_tilde = R Phi_int
50
+ types: tuple
51
+ C_tilde: sym.ImmutableMatrix
52
+ C_tilde_inv: sym.ImmutableMatrix
53
+ Lstar_tilde: sym.ImmutableMatrix
54
+ omega_J_tilde: sym.ImmutableMatrix # Z^T omega_J_int
55
+ omega_L_tilde: sym.ImmutableMatrix # Z^T omega_L_int
56
+
57
+
58
+ def _cancel(M):
59
+ """Cancel each entry; the result is immutable."""
60
+ return sym.ImmutableMatrix(M).applyfunc(sym.cancel)
61
+
62
+
63
+ def _quick_inv(M):
64
+ """Inverse by cofactors for 2x2 to 4x4, where it beats elimination; M.inv() otherwise.
65
+
66
+ 3x3 and 4x4 use sym.inv_quick, whose determinants expand over permutations, so
67
+ larger matrices fall back. 2x2 is written out: in sympy 1.14 inv_quick returns
68
+ zeros for a 2x2 with any numeric entry, such as a 0 off the diagonal.
69
+ """
70
+ if M.rows == 2:
71
+ (a, b), (c, d) = M.tolist()
72
+ return sym.Matrix([[d, -b], [-c, a]]) / (a * d - b * c)
73
+ return sym.inv_quick(M) if 3 <= M.rows <= 4 else M.inv()
74
+
75
+
76
+ # --- subspaces, each a matrix of basis columns ------------------------------
77
+
78
+
79
+ def _columns(vectors, n):
80
+ return sym.Matrix.hstack(*vectors) if vectors else sym.zeros(n, 0)
81
+
82
+
83
+ def _null(A, n):
84
+ return _columns(A.nullspace(), n)
85
+
86
+
87
+ def _perp(S):
88
+ return _null(S.T, S.rows)
89
+
90
+
91
+ def _sum(A, B):
92
+ return _columns(sym.Matrix.hstack(A, B).columnspace(), A.rows)
93
+
94
+
95
+ def _cap(A, B):
96
+ return _perp(_sum(_perp(A), _perp(B)))
97
+
98
+
99
+ def _contains(S, v):
100
+ return sym.Matrix.hstack(S, v).rank() == S.rank()
101
+
102
+
103
+ def subspaces(lag):
104
+ """Column bases of the six mode subspaces of tab:var_basis.
105
+
106
+ x^T C_int x = sum_k C_k (Omega_k^T x)^2 with C_k > 0, so N(C_int) is the
107
+ nullspace of the capacitive columns of Omega_int, and likewise for L*_int.
108
+ All three nullspaces therefore come from integer incidence matrices.
109
+ """
110
+ n = lag.Omega_int.rows
111
+ capacitive = [k for k in range(lag.C_b.rows) if lag.C_b[k, k] != 0]
112
+ J = _null(lag.omega_J_int.T, n)
113
+ L = _null(lag.omega_L_int.T, n)
114
+ C = _null(lag.Omega_int[:, capacitive].T, n)
115
+ JL, CL = _cap(J, L), _cap(C, L)
116
+ return {
117
+ "c": _cap(L, _perp(JL)),
118
+ "e": _perp(_sum(J, L)),
119
+ "h": _cap(J, _perp(_sum(C, JL))),
120
+ "fr": _cap(JL, _perp(CL)),
121
+ "fz": _cap(C, _perp(CL)),
122
+ "cy": CL,
123
+ "J": J, "L": L, "C": C, "JL": JL,
124
+ }
125
+
126
+
127
+ def _normalize_compact(Z_c, omega_J_int):
128
+ """Give each compact coordinate period Phi0: S_cc = (omega_{J,K}^T)^{-1}, eq:Scc_selection."""
129
+ if Z_c.cols == 0:
130
+ return Z_c
131
+ W = omega_J_int.T * Z_c
132
+ K = list(W.T.rref()[1]) # independent rows of omega_{J,c}^T
133
+ return Z_c * W.extract(K, list(range(W.cols))).inv()
134
+
135
+
136
+ def mode_basis(lag):
137
+ """Square Z = (Z^c Z^e Z^h Z^fr Z^fz Z^cy), one block per mode type, and its column types.
138
+
139
+ :param lag: Node Lagrangian matrices.
140
+ :returns: Pair (Z_full, types), ordered c, e, h, fr, fz, cy.
141
+ """
142
+ sub = subspaces(lag)
143
+ sub["c"] = _normalize_compact(sub["c"], lag.omega_J_int)
144
+ Z = sym.Matrix.hstack(*(sub[t] for t in TYPES))
145
+ types = tuple(t for t in TYPES for _ in range(sub[t].cols))
146
+ return sym.ImmutableMatrix(Z), types
147
+
148
+
149
+ # --- validation ------------------------------------------------------------
150
+
151
+
152
+ def _is_integer(x):
153
+ return sym.simplify(x).is_integer # exact: nsimplify would round 1 + 10**-20 to 1
154
+
155
+
156
+ def mode_dimensions(lag):
157
+ """Dimensions of the six mode subspaces, which are circuit invariants.
158
+
159
+ These differ from the column types of a particular Z: the compact and
160
+ non-dynamical counts are fixed, but the harmonic count is only a maximum,
161
+ since a harmonic direction may sit inside extended columns.
162
+
163
+ :param lag: Node Lagrangian matrices.
164
+ :returns: Dict of intrinsic dimensions keyed by c, e, h, fr, fz, cy.
165
+ """
166
+ sub = subspaces(lag)
167
+ return {t: sub[t].cols for t in TYPES}
168
+
169
+
170
+ def check_coordinates(lag, Z_full, types):
171
+ """Check a decoupled full basis against the mode subspaces and the compact period lattice.
172
+
173
+ Decoupling changes neither the junction content of a column nor the
174
+ non-dynamical columns, so passing here also validates the basis given to decouple.
175
+ Every declared type must match mode_types, and the compact and non-dynamical
176
+ counts must match mode_dimensions; together with invertibility this leaves
177
+ at most dim h harmonic columns and a positive-definite C_tilde.
178
+ """
179
+ n = lag.Omega_int.rows
180
+ if Z_full.shape != (n, n) or len(types) != n:
181
+ raise ValueError(f"Z_full must be {n}x{n} with {n} types, including non-dynamical columns")
182
+ if sym.simplify(Z_full.det()) == 0:
183
+ raise ValueError("Z_full is singular")
184
+ for j, (declared, inferred) in enumerate(zip(types, mode_types(lag, Z_full))):
185
+ if declared != inferred:
186
+ raise ValueError(f"Column {j} is not a valid {declared!r} direction")
187
+ dims = mode_dimensions(lag)
188
+ for t in ("c", *NONDYNAMICAL):
189
+ if types.count(t) != dims[t]:
190
+ raise ValueError(f"Circuit has {dims[t]} {t!r} modes, Z_full declares {types.count(t)}")
191
+ compact = [j for j, t in enumerate(types) if t == "c"]
192
+ if compact:
193
+ W = _cancel(lag.omega_J_int.T * Z_full[:, compact]) # omega_{J,c}^T
194
+ if not all(_is_integer(x) for x in W):
195
+ raise ValueError("omega_J,c^T must be integer")
196
+ minors = [sym.simplify(W.extract(list(rows), list(range(W.cols))).det()) for rows in combinations(range(W.rows), W.cols)]
197
+ if reduce(gcd, (int(m) for m in minors), 0) != 1:
198
+ raise ValueError("Compact periods are not primitive")
199
+
200
+
201
+ def _check_residual(types, S):
202
+ """S_1 is invertible, mixes only as eq:S1_structure allows, and S_cc lies in GL(N_c, Z)."""
203
+ S = sym.MutableDenseMatrix(S).applyfunc(lambda x: sym.S.Zero if x.is_zero else x)
204
+ compact = [j for j, t in enumerate(types) if t == "c"]
205
+ if S.shape == (len(types), len(types)):
206
+ for i in compact:
207
+ for j in compact:
208
+ value = S[i, j]
209
+ if isinstance(value, sym.Float) and value.is_finite:
210
+ nearest = round(value)
211
+ if abs(value - nearest) <= 1e-12:
212
+ S[i, j] = sym.Integer(nearest)
213
+ if not _is_integer(S[i, j]):
214
+ raise ValueError(f"S_cc entry S1[{i}, {j}] = {value} must be an integer for GL(N_c, Z)")
215
+ if S.shape != (len(types), len(types)) or sym.simplify(S.det()) == 0:
216
+ raise ValueError("S1 must be square, invertible, and match the retained modes")
217
+ for i in range(S.rows):
218
+ for j in range(S.cols):
219
+ if S[i, j] != 0 and (types[i], types[j]) not in _S1b:
220
+ raise ValueError(f"S1[{i}, {j}] mixes {types[i]!r} into {types[j]!r}")
221
+ compact = [j for j, t in enumerate(types) if t == "c"]
222
+ S_cc = _cancel(S.extract(compact, compact))
223
+ if compact and (not all(_is_integer(x) for x in S_cc) or abs(S_cc.det()) != 1):
224
+ raise ValueError("S_cc must lie in GL(N_c, Z)")
225
+ return sym.ImmutableMatrix(S)
226
+
227
+
228
+ # --- decoupling and truncation ----------------------------------------------
229
+
230
+
231
+ def mode_types(lag, Z):
232
+ """Classify each column by capacitive, junction, and inductor participation.
233
+
234
+ :param lag: Node Lagrangian matrices.
235
+ :param Z: Node-space columns, full or retained, in internal-node row order.
236
+ :returns: Tuple of c, e, h, fr, fz, or cy labels in column order.
237
+ """
238
+ J, L, C = [_cancel(Z.T * mat).tolist() for mat in (lag.omega_J_int, lag.omega_L_int, lag.C_int)]
239
+ return tuple(
240
+ ("e" if any(l) else "c") if any(j) else
241
+ ("h" if any(c) else "fz") if any(l) else
242
+ ("fr" if any(c) else "cy")
243
+ for j, l, c in zip(J, L, C)
244
+ )
245
+
246
+
247
+ def coordinates(lag, Z_full, types=None, *, C_tilde=None, Lstar_tilde=None, R=None):
248
+ """Build retained objects from a full decoupled basis.
249
+
250
+ No validation; decouple runs check_coordinates first.
251
+
252
+ :param lag: Node Lagrangian matrices.
253
+ :param Z_full: Square decoupled node-to-coordinate matrix, including all
254
+ non-dynamical columns. Use decouple first if the sectors are coupled.
255
+ :param types: Optional labels for all columns; otherwise infer with mode_types.
256
+ :param C_tilde: Optional Z^T C_int Z, when already known (e.g. diagonal by construction).
257
+ :param Lstar_tilde: Optional Z^T L*_int Z, likewise.
258
+ :param R: Optional retained rows of Z_full^{-1}, likewise.
259
+ :returns: Coordinates retaining Z_full and types_full, with dynamical columns
260
+ Z and corresponding rows R of the full inverse. Column order is preserved.
261
+ :raises ValueError: No dynamical modes.
262
+ """
263
+ Z_full = sym.ImmutableMatrix(Z_full)
264
+ types = mode_types(lag, Z_full) if types is None else tuple(types)
265
+ retained = [i for i, t in enumerate(types) if t in DYNAMICAL]
266
+ if not retained:
267
+ raise ValueError("Circuit has no dynamical modes")
268
+ Z = Z_full[:, retained]
269
+ C_tilde = _cancel(Z.T * lag.C_int * Z if C_tilde is None else C_tilde)
270
+ Lstar_tilde = _cancel(Z.T * lag.Lstar_int * Z if Lstar_tilde is None else Lstar_tilde)
271
+ return Coordinates(
272
+ Z_full=Z_full, types_full=types,
273
+ Z=Z, types=tuple(types[i] for i in retained),
274
+ R=_cancel(_quick_inv(Z_full)[retained, :] if R is None else R), # eq:Z_truncated
275
+ C_tilde=C_tilde,
276
+ C_tilde_inv=_cancel(_quick_inv(C_tilde)),
277
+ Lstar_tilde=Lstar_tilde,
278
+ omega_J_tilde=Z.T * lag.omega_J_int, omega_L_tilde=Z.T * lag.omega_L_int,
279
+ )
280
+
281
+
282
+ def _decouple_block(V, n_to_decouple, form):
283
+ """Make every column of V form-orthogonal to the final n columns.
284
+
285
+ Eliminate one n_to_decouple column at a time, in reverse order, updating all
286
+ earlier columns, including the earlier n_to_decouple ones. A degenerate
287
+ sector therefore needs no inverse.
288
+ """
289
+ k = V.cols
290
+ Z = sym.Matrix.hstack(V, n_to_decouple)
291
+ for i in range(Z.cols - 1, k - 1, -1):
292
+ w = Z[:, i]
293
+ pivot = sym.cancel((w.T * form * w)[0])
294
+ if pivot != 0: # A null direction of this positive-semidefinite form needs no correction.
295
+ Z[:, :i] = (Z[:, :i] - w * (w.T * form * Z[:, :i]) / pivot).applyfunc(sym.cancel)
296
+ return Z[:, :k]
297
+
298
+
299
+ def decouple(lag, Z_full, types, *, check=True):
300
+ """Decouple the dynamical block, check, then truncate.
301
+
302
+ Eliminate free directions in C and frozen directions in L* serially,
303
+ updating the remaining columns.
304
+ Cyclic directions are discarded. No discarded-sector matrix is inverted.
305
+
306
+ :param lag: Node Lagrangian matrices.
307
+ :param Z_full: Full square node-to-coordinate basis.
308
+ :param types: Mode label for each basis column.
309
+ :param bool check: Validate the decoupled basis. Skip only
310
+ for a basis that is valid by construction, such as mode_basis.
311
+ :returns: Coordinates containing the retained columns of Z_dc, corresponding
312
+ rows of its full inverse R = P Z_dc^{-1}, and transformed matrices.
313
+ :raises ValueError: An invalid basis or types, if check is True.
314
+ """
315
+ Z = sym.Matrix(Z_full)
316
+ types = tuple(types)
317
+ dynamical = [j for j, t in enumerate(types) if t in DYNAMICAL]
318
+ Z_d = Z[:, dynamical]
319
+ for kind, form in (("fr", lag.C_int), ("fz", lag.Lstar_int)):
320
+ Z_d = _decouple_block(Z_d, Z[:, [j for j, t in enumerate(types) if t == kind]], form)
321
+ for col, j in enumerate(dynamical):
322
+ Z[:, j] = Z_d[:, col]
323
+ Z = _cancel(Z)
324
+ if check:
325
+ check_coordinates(lag, Z, types)
326
+ return coordinates(lag, Z, types)
327
+
328
+
329
+ # --- residual freedom -------------------------------------------------------
330
+
331
+ # (old type, new type) pairs a column may be mixed along, eq:S1_structure.
332
+ _S1a = {("c", "c"), ("c", "e"), ("e", "e"), ("h", "e"), ("h", "h")}
333
+ # Without preserving harmonic columns, any noncompact column may take extended or
334
+ # compact components; a harmonic column that takes a compact one becomes extended.
335
+ # Compact columns still take only compact components, so the lattice is kept.
336
+ _S1b = _S1a | {("e", "h"), ("c", "h")}
337
+
338
+
339
+ def residual_freedom(coords, keep_harmonic=True):
340
+ """Symbolic S_1 with free entries wherever mode mixing is allowed.
341
+
342
+ With keep_harmonic=True, a compact column takes only compact components,
343
+ an extended column takes components of any type, and a harmonic column takes
344
+ only harmonic ones. keep_harmonic=False also lets harmonic columns take
345
+ extended or compact components, which makes them extended.
346
+ The compact block S_cc must also be an integer matrix with determinant +-1.
347
+ transform checks that once values are chosen.
348
+
349
+ :param coords: Retained Coordinates defining the current mode order.
350
+ :param bool keep_harmonic: Preserve harmonic columns when True. Allow
351
+ extended/harmonic mixing when False.
352
+ :returns: Symbolic matrix of allowed residual mixing parameters.
353
+ """
354
+ allowed = _S1a if keep_harmonic else _S1b
355
+ types = coords.types
356
+ return sym.Matrix(
357
+ len(types), len(types),
358
+ lambda i, j: sym.Symbol(f"s_{i + 1}_{j + 1}") if (types[i], types[j]) in allowed else 0,
359
+ )
360
+
361
+
362
+ def junction_inversions(coords, types=("c", "e"), *, clean=True):
363
+ """S_1 that make chosen junctions single-mode coordinates, one per choice of junctions.
364
+
365
+ Compact ("c"): every set K of N_c junctions whose compact rows of omega~_J^T are
366
+ independent gives S_cc = (omega~_{J,K}^T)^{-1}, kept when S_cc and
367
+ omega~_{J,c}^T S_cc are integer. With clean, S_ce = -S_cc B, B the
368
+ extended columns of those rows, also removes their extended components, so each
369
+ junction in K acts on one compact mode.
370
+ Extended ("e"): after the compact step, let r be the rank of the junctions' extended
371
+ rows. Every set E of r junctions with independent extended rows A gives
372
+ S_ee = (A^T (A A^T)^{-1}, N), N a basis of the extended directions no junction acts on,
373
+ so each junction in E acts on one extended mode (keeping its compact components,
374
+ which no allowed S_1 removes) and the N_e - r columns of N become harmonic.
375
+ When r = N_e this is S_ee = A^{-1}.
376
+ Requesting both yields every compact choice combined with every extended choice.
377
+
378
+ :param coords: Retained Coordinates, in any column order.
379
+ :param types: The blocks to invert: ("c",), ("e",), or ("c", "e").
380
+ :param bool clean: Remove the extended components of the compact-aligned junctions.
381
+ :returns: Generator of distinct S_1 in coords.types order, valid for transform.
382
+ """
383
+ if not types or set(types) - {"c", "e"}:
384
+ raise ValueError(f"types must be a nonempty subset of ('c', 'e'), not {types!r}")
385
+ n = len(coords.types)
386
+ c = [j for j, t in enumerate(coords.types) if t == "c"]
387
+ e = [j for j, t in enumerate(coords.types) if t == "e"]
388
+ W = _cancel(coords.omega_J_tilde.T) # one row per junction
389
+ rows = range(W.rows)
390
+
391
+ def compact_steps():
392
+ if "c" not in types or not c:
393
+ yield sym.eye(n)
394
+ return
395
+ W_c = W.extract(list(rows), c)
396
+ for K in combinations(rows, len(c)):
397
+ A = W_c.extract(list(K), list(range(len(c))))
398
+ if A.det() == 0:
399
+ continue
400
+ S_cc = _quick_inv(A)
401
+ if not all(_is_integer(x) for x in list(S_cc) + list(W_c * S_cc)):
402
+ continue
403
+ S = sym.eye(n)
404
+ for a, i in enumerate(c):
405
+ for b, j in enumerate(c):
406
+ S[i, j] = S_cc[a, b]
407
+ if clean and e:
408
+ S_ce = -S_cc * W.extract(list(K), e)
409
+ for a, i in enumerate(c):
410
+ for b, j in enumerate(e):
411
+ S[i, j] = S_ce[a, b]
412
+ yield S
413
+
414
+ def extended_steps(S_c):
415
+ if "e" not in types or not e:
416
+ yield sym.eye(n)
417
+ return
418
+ W_e = _cancel(W * S_c).extract(list(rows), e)
419
+ r = W_e.rank(simplify=True)
420
+ N = _null(W_e, len(e))
421
+ for E in combinations(rows, r):
422
+ A = W_e.extract(list(E), list(range(len(e))))
423
+ gram = _cancel(A * A.T)
424
+ if sym.cancel(gram.det()) == 0:
425
+ continue
426
+ yield _embed(_cancel(sym.Matrix.hstack(A.T * _quick_inv(gram), N)), e, n)
427
+
428
+ seen = set()
429
+ for S_c in compact_steps():
430
+ for S_e in extended_steps(S_c):
431
+ S = _cancel(S_c * S_e)
432
+ if S not in seen:
433
+ seen.add(S)
434
+ yield S
435
+
436
+
437
+ def _clusters(W, n):
438
+ """Connected components of n modes, linked whenever one row of W acts on both."""
439
+ graph = nx.Graph()
440
+ graph.add_nodes_from(range(n))
441
+ for k in range(W.rows):
442
+ acted = [j for j in range(n) if sym.cancel(W[k, j]) != 0]
443
+ graph.add_edges_from(zip(acted, acted[1:]))
444
+ return sorted(tuple(sorted(cluster)) for cluster in nx.connected_components(graph))
445
+
446
+
447
+ def junction_clusters(coords):
448
+ """Modes grouped by junction coupling: connected components of the graph linking any
449
+ two modes that share a junction, i.e. the nonzero pattern of the junction matrix.
450
+
451
+ :param coords: Retained Coordinates.
452
+ :returns: Sorted list of tuples of mode indices, in coords.types order.
453
+ """
454
+ return _clusters(coords.omega_J_tilde.T, len(coords.types))
455
+
456
+
457
+ CLUSTER_DIMS = {"c": 40, "e": 100, "h": 20}
458
+
459
+
460
+ def cluster_cost(coords, dims=None):
461
+ """Hilbert-space dimension of each junction cluster, largest first, for lexicographic comparison.
462
+
463
+ A cluster's dimension is the product of its modes' basis sizes, a proxy for the cost of
464
+ diagonalizing it on its own, as in hierarchical diagonalization.
465
+
466
+ :param coords: Retained Coordinates.
467
+ :param dims: Basis size per mode type. Defaults to CLUSTER_DIMS (c: 40 charge states,
468
+ e: 100 phase-grid points, h: 20 oscillator states).
469
+ :returns: Tuple of cluster dimensions in decreasing order.
470
+ """
471
+ return _cluster_cost(junction_clusters(coords), coords.types, dims)
472
+
473
+
474
+ def _cluster_cost(clusters, types, dims=None):
475
+ dims = CLUSTER_DIMS | (dims or {})
476
+ return tuple(sorted((reduce(lambda a, j: a * dims[types[j]], cluster, 1) for cluster in clusters), reverse=True))
477
+
478
+
479
+ def hierarchical_decoupling(coords, types=("c", "e"), dims=None, *, clean=True):
480
+ """The junction inversion with the smallest junction clusters, for hierarchical diagonalization.
481
+
482
+ Ranks the identity and every S_1 of junction_inversions by cluster_cost. The first
483
+ of the cheapest wins. The cost is read from omega~_J^T S_1 without rebuilding the
484
+ coordinates: a noncompact column no junction acts on is harmonic, as in mode_types,
485
+ so an extended inversion can turn an extended column of a mixed basis harmonic.
486
+
487
+ :param coords: Retained Coordinates, in any column order.
488
+ :param types: Blocks to invert, as in junction_inversions.
489
+ :param dims: Basis size per mode type, as in cluster_cost.
490
+ :param bool clean: As in junction_inversions.
491
+ :returns: (S_1, cost). Apply S_1 with transform or Result.transform.
492
+ """
493
+ W = coords.omega_J_tilde.T
494
+ n = len(coords.types)
495
+ best = None
496
+ for S in [sym.eye(n), *junction_inversions(coords, types, clean=clean)]:
497
+ W_S = _cancel(W * S)
498
+ new_types = tuple(t if t == "c" or any(W_S.col(j)) else "h" for j, t in enumerate(coords.types))
499
+ cost = _cluster_cost(_clusters(W_S, n), new_types, dims)
500
+ if best is None or cost < best[1]:
501
+ best = (S, cost)
502
+ return best
503
+
504
+
505
+ def compact_charge_decoupling(coords):
506
+ """S_1 that removes the charge coupling between compact and noncompact modes exactly.
507
+
508
+ Makes each noncompact column C~-orthogonal to the compact columns, the same
509
+ elimination decouple applies to free modes. In (c, n) blocks this is
510
+ S = [[I, -X], [0, I]] with C_cc X = C_cn, so S^T C~ S = diag(C_cc, M), with
511
+ M = C_nn - C_nc X = ((C~^{-1})_nn)^{-1}, and S^T L~* S = L~*, since compact
512
+ columns carry no inductance. Compact columns are unchanged, keeping their periods.
513
+ Noncompact columns gain compact components, so junction participation can spread
514
+ and a harmonic column becomes extended. Rational in the circuit parameters.
515
+
516
+ :param coords: Retained Coordinates, in any column order.
517
+ :returns: S_1 in coords.types order. Apply it with transform or Result.transform.
518
+ """
519
+ columns = sym.eye(len(coords.types))
520
+ compact = [j for j, t in enumerate(coords.types) if t == "c"]
521
+ other = [j for j, t in enumerate(coords.types) if t != "c"]
522
+ S = sym.Matrix(columns)
523
+ if compact and other:
524
+ sheared = _decouple_block(columns[:, other], columns[:, compact], coords.C_tilde)
525
+ for k, j in enumerate(other):
526
+ S[:, j] = sheared[:, k]
527
+ return _cancel(S)
528
+
529
+
530
+ def _gram_schmidt(vectors, form):
531
+ """Make the columns form-orthogonal, keeping their order (no normalization)."""
532
+ orthogonal = []
533
+ for v in vectors:
534
+ for u in orthogonal:
535
+ v = v - ((u.T * form * v)[0] / (u.T * form * u)[0]) * u
536
+ orthogonal.append(v.applyfunc(sym.cancel))
537
+ return orthogonal
538
+
539
+
540
+ def normal_mode_decoupling(lag, coords, values=None):
541
+ """S_1 that removes every quadratic coupling: compact charge shear, then normal modes.
542
+
543
+ After compact_charge_decoupling, the noncompact block of C~ is
544
+ C = ((C~^{-1})_nn)^{-1} and that of L~* is unchanged, so the noncompact columns
545
+ become the solutions of L* x = lambda C x, i.e. eigenvectors of (C~^{-1})_nn L*.
546
+ Distinct eigenvalues are already C-orthogonal. Degenerate eigenspaces are
547
+ C-orthogonalized by Gram-Schmidt. Extended and harmonic columns mix, so harmonic
548
+ modes generally become extended.
549
+
550
+ Symbolically (values=None) the eigenvalues are roots of a degree-N_n polynomial,
551
+ so this is only practical for two or three noncompact modes. With values, the
552
+ circuit parameters are substituted first and scipy.linalg.eigh(L*, C, type=1)
553
+ gives C-orthonormal columns, so the noncompact block of S_1 is floating point.
554
+
555
+ The new C~ and L~* are known by construction: the compact block of the shear and
556
+ diag(x_i^T C x_i), diag(x_i^T L* x_i) on the noncompact block. They are returned so
557
+ Result.transform can skip recomputing them, which is slow when S_1 carries square roots.
558
+
559
+ :param lag: Node Lagrangian for the same circuit as coords.
560
+ :param coords: Retained Coordinates, in any column order.
561
+ :param values: Optional {symbol: number} substituted before diagonalizing.
562
+ :returns: (S_1, C_tilde, Lstar_tilde), S_1 in coords.types order. Apply it with
563
+ result.transform(S_1, C_tilde=C_tilde, Lstar_tilde=Lstar_tilde).
564
+ C_tilde and Lstar_tilde are None when there is nothing to diagonalize.
565
+ """
566
+ # Count the noncompact modes, which are the last N_n columns of S_1.
567
+ eh = [j for j, t in enumerate(coords.types) if t != "c"]
568
+ n_non_compact = len(eh)
569
+ if n_non_compact == 0:
570
+ return sym.eye(len(coords.types)), None, None
571
+
572
+ # Compact-charge decoupling
573
+ S_a = compact_charge_decoupling(coords)
574
+ if values is not None:
575
+ S_a = S_a.subs(values)
576
+ if n_non_compact == 1:
577
+ return S_a, None, None
578
+ coords_a = transform(lag, coords, S_a)
579
+ C_tilde, Lstar_tilde = coords_a.C_tilde.as_mutable(), coords_a.Lstar_tilde.as_mutable()
580
+ if values is not None:
581
+ C_tilde, Lstar_tilde = C_tilde.subs(values), Lstar_tilde.subs(values)
582
+ C_a = C_tilde.extract(eh, eh)
583
+ L_a = Lstar_tilde.extract(eh, eh)
584
+
585
+ # Normal-mode decoupling of the noncompact block
586
+ S_b = _normal_mode_block(C_a, L_a, values)
587
+
588
+ # Concatenate S_b with identity on the compact block
589
+ S_n = _embed(S_b, eh, len(coords.types))
590
+
591
+ # The noncompact blocks of C~ and L~* become diagonal
592
+ for a, i in enumerate(eh):
593
+ v = S_b[:, a]
594
+ for j in eh:
595
+ C_tilde[i, j] = Lstar_tilde[i, j] = 0
596
+ C_tilde[i, i] = _radical_cancel((v.T * C_a * v)[0])
597
+ Lstar_tilde[i, i] = _radical_cancel((v.T * L_a * v)[0])
598
+
599
+ # Return the product of the two transformations
600
+ return S_a * S_n, C_tilde, Lstar_tilde
601
+
602
+
603
+ def _normal_mode_block(C_a, L_a, values=None):
604
+ """Columns x_i solving L_a x = lambda C_a x, C_a-orthogonal; C_a-orthonormal when numerical."""
605
+ # Numerical path
606
+ if values is not None:
607
+ _, X = eigh(np.array(L_a, dtype=float), np.array(C_a, dtype=float), type=1)
608
+ return sym.Matrix(X.tolist())
609
+ # Symbolic path
610
+ columns = []
611
+ C_a_inv = _quick_inv(C_a)
612
+ for eval, multiplicity, vectors in _cancel(C_a_inv*L_a).eigenvects(simplify=False):
613
+ columns += _gram_schmidt(vectors, C_a)
614
+ return sym.Matrix.hstack(*columns)
615
+
616
+
617
+ def _embed(B, indices, n):
618
+ """n x n identity with B in the rows and columns indices."""
619
+ M = sym.eye(n)
620
+ for a, i in enumerate(indices):
621
+ for b, j in enumerate(indices):
622
+ M[i, j] = B[a, b]
623
+ return M
624
+
625
+
626
+ def _radical_cancel(x):
627
+ """cancel, with each square root sqrt(D) a symbol r reduced mod r^2 - D and rationalized away below.
628
+
629
+ Normal modes of two noncompact modes carry one sqrt of the discriminant, which
630
+ plain cancel expands as an independent generator; reducing mod r^2 - D lets
631
+ the entries that vanish by construction cancel to 0.
632
+ """
633
+ x = sym.sympify(x)
634
+ roots = {p.base: sym.Dummy("r") for p in x.atoms(sym.Pow) if p.exp.is_Rational and p.exp.q == 2}
635
+ if not roots:
636
+ return sym.cancel(x)
637
+ x = x.replace(lambda e: e.is_Pow and e.base in roots and e.exp.is_Rational and e.exp.q == 2,
638
+ lambda e: roots[e.base] ** e.exp.p)
639
+ num, den = sym.fraction(sym.cancel(x))
640
+ for D, r in roots.items():
641
+ num, den = sym.rem(num, r**2 - D, r), sym.rem(den, r**2 - D, r)
642
+ if den.has(r): # den = a + b r; multiply through by a - b r
643
+ conjugate = den.subs(r, -r)
644
+ num, den = sym.rem(sym.expand(num * conjugate), r**2 - D, r), sym.rem(sym.expand(den * conjugate), r**2 - D, r)
645
+ return sym.cancel(num / den).xreplace({r: sym.sqrt(D) for D, r in roots.items()})
646
+
647
+
648
+ def transform(lag, coords, S1, *, C_tilde=None, Lstar_tilde=None):
649
+ """Apply Z -> Z S_1, rebuild from lag, and classify the final columns.
650
+
651
+ The allowed mixing is that of residual_freedom.
652
+ Cancellations can restore harmonic axes inside the extended block.
653
+ The new compact columns are Z_c S_cc, so their periods stay primitive.
654
+ Z_full gains blockdiag(S_1, I) on the right, so the new R is S_1^{-1} R and the
655
+ full node matrix is not inverted again.
656
+
657
+ :param lag: Node Lagrangian for the same circuit as coords.
658
+ :param coords: Current retained coordinates.
659
+ :param S1: Invertible matrix satisfying residual mixing and compact-period constraints.
660
+ :param C_tilde: Optional S1^T C~ S1, when already known. It is used as given, without a check.
661
+ :param Lstar_tilde: Optional S1^T L~* S1, likewise.
662
+ :returns: New Coordinates with node matrix coords.Z * S1.
663
+ :raises ValueError: Invalid dimensions, disallowed mixing, or nonprimitive compact periods.
664
+ """
665
+ S = sym.ImmutableMatrix(S1)
666
+ S = _check_residual(coords.types, S)
667
+ retained = [i for i, t in enumerate(coords.types_full) if t in DYNAMICAL]
668
+ Z_full = coords.Z_full.as_mutable()
669
+ Z = coords.Z * S
670
+ for j, index in enumerate(retained):
671
+ Z_full[:, index] = Z[:, j]
672
+ return coordinates(lag, Z_full, C_tilde=C_tilde, Lstar_tilde=Lstar_tilde, R=_quick_inv(S) * coords.R)