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,199 @@
1
+ """Floating-point Hamiltonians evaluated from a saved Hamiltonian.
2
+
3
+ ``numeric_hamiltonian`` evaluates a ``Result`` or ``HamiltonianSpec`` once at numerical parameter values.
4
+ The returned ``NumericHamiltonian`` changes frame with NumPy alone, so many coordinate choices can be compared
5
+ without symbolic work. It follows the convention of :doc:`/exporting`::
6
+
7
+ H/h [GHz] = 4 (n - n_g)^T E_C (n - n_g) + 1/2 phi^T E_L phi + phi^T b
8
+ - sum_k E_k cos(omega_k^T phi + delta_k) + c
9
+
10
+ Under ``phi = S phi'`` and ``n' = S^T n`` the coefficients transform as::
11
+
12
+ E_C' = S^-1 E_C S^-T, n_g' = S^T n_g, E_L' = S^T E_L S,
13
+ b' = S^T b, omega_k' = S^T omega_k.
14
+ """
15
+
16
+ from dataclasses import dataclass, replace
17
+
18
+ import numpy as np
19
+ import sympy as sym
20
+ from scipy.linalg import eigh
21
+
22
+ from .modes import _S1b
23
+
24
+ __all__ = ["NumericHamiltonian", "numeric_hamiltonian", "normal_mode_transformation"]
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class NumericHamiltonian:
29
+ """Floating-point Hamiltonian coefficients in the convention above."""
30
+
31
+ types: tuple
32
+ E_C: np.ndarray
33
+ E_L: np.ndarray
34
+ flux_linear: np.ndarray
35
+ n_g: np.ndarray
36
+ cosines: tuple # of (energy, omega, offset)
37
+ constant: float = 0.0
38
+ n_g_source: np.ndarray | None = None
39
+ n_g_sector: np.ndarray | None = None
40
+
41
+ def __post_init__(self):
42
+ N = len(self.types)
43
+ E_C, E_L = (np.asarray(M, dtype=float) for M in (self.E_C, self.E_L))
44
+ b, n_g = (np.asarray(v, dtype=float).reshape(-1) for v in (self.flux_linear, self.n_g))
45
+ if E_C.shape != (N, N) or E_L.shape != (N, N) or b.shape != (N,) or n_g.shape != (N,):
46
+ raise ValueError("coefficient shapes do not match the number of modes")
47
+ cosines = tuple((float(E), np.asarray(w, dtype=float).reshape(N), float(d))
48
+ for E, w, d in self.cosines)
49
+ for name, value in (("E_C", E_C), ("E_L", E_L), ("flux_linear", b), ("n_g", n_g)):
50
+ object.__setattr__(self, name, value)
51
+ object.__setattr__(self, "types", tuple(self.types))
52
+ object.__setattr__(self, "cosines", cosines)
53
+ object.__setattr__(self, "constant", float(self.constant))
54
+ compact = np.array([t == "c" for t in self.types])
55
+ sector = np.where(compact, n_g, 0.0) if self.n_g_sector is None else np.asarray(self.n_g_sector, dtype=float).reshape(N)
56
+ source = n_g - sector if self.n_g_source is None else np.asarray(self.n_g_source, dtype=float).reshape(N)
57
+ if np.any(sector[~compact]) or not np.allclose(source + sector, n_g, rtol=1e-12, atol=1e-14):
58
+ raise ValueError("source and compact sector offsets must sum to n_g")
59
+ object.__setattr__(self, "n_g_source", source)
60
+ object.__setattr__(self, "n_g_sector", sector)
61
+
62
+ @property
63
+ def size(self):
64
+ return len(self.types)
65
+
66
+ def transformed(self, S):
67
+ """Checked numeric frame change, ``phi = S phi'`` (no symbolic work).
68
+
69
+ Compact entries within 1e-12 of integers are snapped, and the compact
70
+ block must be unimodular. Source offsets transform on every mode.
71
+ Static sector offsets transform only within the compact block.
72
+ Junction participation reclassifies extended/harmonic columns.
73
+ """
74
+ S = np.array(S, dtype=float, copy=True)
75
+ if S.shape != (self.size, self.size) or not np.isfinite(S).all():
76
+ raise ValueError("S1 must be finite, square, and match the retained modes")
77
+ compact = [i for i, t in enumerate(self.types) if t == "c"]
78
+ for i in range(self.size):
79
+ for j in range(self.size):
80
+ if i in compact and j in compact:
81
+ nearest = round(S[i, j])
82
+ if abs(S[i, j] - nearest) > 1e-12:
83
+ raise ValueError(f"S_cc entry S1[{i}, {j}] = {S[i,j]} must be an integer")
84
+ S[i, j] = nearest
85
+ if S[i, j] != 0 and (self.types[i], self.types[j]) not in _S1b:
86
+ raise ValueError(f"S1[{i}, {j}] = {S[i,j]} mixes {self.types[i]!r} into {self.types[j]!r}")
87
+ if compact and abs(_integer_det([[int(S[i,j]) for j in compact] for i in compact])) != 1:
88
+ raise ValueError("S_cc must lie in GL(N_c, Z)")
89
+ try:
90
+ S_inv = np.linalg.inv(S)
91
+ except np.linalg.LinAlgError as error:
92
+ raise ValueError("S1 must be invertible") from error
93
+ cosines = tuple((E, S.T @ w, d) for E, w, d in self.cosines)
94
+ E_L = S.T @ self.E_L @ S
95
+ # Retained columns remain dynamical; compact directions are invariant.
96
+ types = tuple("c" if i in compact else
97
+ "e" if any(w[i] != 0 for _, w, _ in cosines) else "h"
98
+ for i in range(self.size))
99
+ source = S.T @ self.n_g_source
100
+ sector = np.zeros(self.size)
101
+ sector[compact] = S[np.ix_(compact, compact)].T @ self.n_g_sector[compact]
102
+ return replace(
103
+ self, types=types,
104
+ E_C=S_inv @ self.E_C @ S_inv.T,
105
+ E_L=E_L,
106
+ flux_linear=S.T @ self.flux_linear,
107
+ n_g=source + sector, n_g_source=source, n_g_sector=sector,
108
+ cosines=cosines,
109
+ )
110
+
111
+
112
+ def _integer_det(rows):
113
+ """Exact Bareiss determinant of the small compact integer block."""
114
+ rows = [row[:] for row in rows]
115
+ sign, previous = 1, 1
116
+ for k in range(len(rows) - 1):
117
+ pivot = next((i for i in range(k, len(rows)) if rows[i][k]), None)
118
+ if pivot is None:
119
+ return 0
120
+ if pivot != k:
121
+ rows[k], rows[pivot] = rows[pivot], rows[k]
122
+ sign = -sign
123
+ value = rows[k][k]
124
+ for i in range(k + 1, len(rows)):
125
+ for j in range(k + 1, len(rows)):
126
+ rows[i][j] = (rows[i][j] * value - rows[i][k] * rows[k][j]) // previous
127
+ previous = value
128
+ return sign * rows[-1][-1]
129
+
130
+
131
+ def numeric_hamiltonian(spec, values=None):
132
+ """Evaluate a Result or HamiltonianSpec at values keyed by symbols or names.
133
+
134
+ Evaluation is paid once. Subsequent ``transformed(S)`` calls use NumPy
135
+ only. Compact ``n_g{j}`` parameters are static sector labels. All remaining
136
+ offset charge is the source contribution. To compare to Result.transform,
137
+ assign its fresh compact labels the returned ``n_g_sector`` values.
138
+ """
139
+ from .quantize import Result
140
+ from .io import load_spec, to_spec
141
+ if isinstance(spec, Result):
142
+ spec = load_spec(to_spec(spec))
143
+ values = {} if values is None else values
144
+ by_name = {s.name: s for s in spec.parameters}
145
+ subs = {}
146
+ for key, value in values.items():
147
+ symbol = by_name[key] if isinstance(key, str) else by_name[key.name]
148
+ subs[symbol] = value
149
+
150
+ def scalar(expr):
151
+ value = sym.sympify(expr).subs(subs)
152
+ if value.free_symbols:
153
+ raise ValueError(f"unassigned parameters {value.free_symbols} in {expr}")
154
+ return float(value)
155
+
156
+ def array(M):
157
+ return np.array([[scalar(x) for x in row] for row in sym.Matrix(M).tolist()])
158
+
159
+ sector_symbols = {p for j, (_, kind) in enumerate(spec.modes)
160
+ if kind == "c" for p in spec.parameters if p.name == f"n_g{j + 1}"}
161
+ source_expr = spec.n_g.subs(dict.fromkeys(sector_symbols, 0))
162
+ source = array(source_expr).reshape(-1)
163
+ sector = array(spec.n_g - source_expr).reshape(-1)
164
+ return NumericHamiltonian(
165
+ n_g_source=source, n_g_sector=sector,
166
+ types=tuple(kind for _, kind in spec.modes),
167
+ E_C=array(spec.E_C),
168
+ E_L=array(spec.E_L),
169
+ flux_linear=array(spec.flux_linear).reshape(-1),
170
+ n_g=array(spec.n_g).reshape(-1),
171
+ cosines=tuple((scalar(E), [float(w) for w in omega], scalar(d))
172
+ for E, omega, d in spec.cosines),
173
+ constant=scalar(spec.constant),
174
+ )
175
+
176
+
177
+ def normal_mode_transformation(ham):
178
+ """Numeric S1 to the normal modes of ``ham``, with ``C = E_C^{-1}``.
179
+
180
+ Noncompact columns solve the generalized eigenproblem of ``E_L`` and the capacitance left after the compact
181
+ modes, with compact components that remove their charge coupling to the compact modes. Compact columns are
182
+ unchanged.
183
+ """
184
+ N = ham.size
185
+ c = [i for i, kind in enumerate(ham.types) if kind == "c"]
186
+ n = [i for i, kind in enumerate(ham.types) if kind != "c"]
187
+ C = np.linalg.inv(ham.E_C)
188
+ S = np.eye(N)
189
+ if not n:
190
+ return S
191
+ C_bar = C[np.ix_(n, n)]
192
+ if c:
193
+ C_cc_inv = np.linalg.inv(C[np.ix_(c, c)])
194
+ C_bar = C_bar - C[np.ix_(n, c)] @ C_cc_inv @ C[np.ix_(c, n)]
195
+ _, V = eigh(ham.E_L[np.ix_(n, n)], C_bar)
196
+ S[np.ix_(n, n)] = V
197
+ if c:
198
+ S[np.ix_(c, n)] = -C_cc_inv @ C[np.ix_(c, n)] @ V
199
+ return S
@@ -0,0 +1,391 @@
1
+ """Numerical search over the residual transformation ``S_1``.
2
+
3
+ The real invertible blocks of ``S_1`` are written in polar form as
4
+ ``exp(A) exp(B)``, with ``A`` antisymmetric and ``B`` symmetric.
5
+ The compact block ``S_cc`` stays a fixed integer matrix.
6
+ """
7
+
8
+ from dataclasses import dataclass, field
9
+
10
+ import numpy as np
11
+ import sympy as sym
12
+ from scipy.linalg import expm
13
+ from scipy.optimize import OptimizeResult, minimize
14
+
15
+ from .quantize import numerify
16
+
17
+ __all__ = ["numerical_S1", "NumericalInfo", "cost_normal_modes", "cost_targeted", "cost_localization"]
18
+
19
+
20
+ def _indices(types, kind):
21
+ return tuple(i for i, value in enumerate(types) if value == kind)
22
+
23
+
24
+ def _skew_symmetric(values, n):
25
+ matrix = np.zeros((n, n))
26
+ k = 0
27
+ for i in range(n):
28
+ for j in range(i + 1, n):
29
+ matrix[i, j] = values[k]
30
+ matrix[j, i] = -values[k]
31
+ k += 1
32
+ return matrix
33
+
34
+
35
+ def _symmetric(values, n):
36
+ matrix = np.zeros((n, n))
37
+ k = 0
38
+ for i in range(n):
39
+ for j in range(i, n):
40
+ matrix[i, j] = matrix[j, i] = values[k]
41
+ k += 1
42
+ return matrix
43
+
44
+
45
+ def _polar_block(values, n):
46
+ n_skew = n * (n - 1) // 2
47
+ A = _skew_symmetric(values[:n_skew], n)
48
+ B = _symmetric(values[n_skew:], n)
49
+ return expm(A) @ expm(B)
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class Parameterization:
54
+ """The parameterized residual transformation ``S(x)`` in ``coords.types`` order.
55
+
56
+ ``S_cc`` is fixed. With ``relaxed=False`` the extended and harmonic
57
+ diagonal blocks have independent polar parameterizations and ``S_ce`` and
58
+ ``S_he`` are free. With ``relaxed=True`` all noncompact columns form one
59
+ polar block and their compact-row block is free.
60
+ """
61
+
62
+ types: tuple
63
+ S_cc: np.ndarray
64
+ relaxed: bool
65
+ c: tuple = field(init=False, repr=False)
66
+ e: tuple = field(init=False, repr=False)
67
+ h: tuple = field(init=False, repr=False)
68
+ n: tuple = field(init=False, repr=False)
69
+
70
+ def __post_init__(self):
71
+ types = tuple(self.types)
72
+ if set(types) - {"c", "e", "h"}:
73
+ raise ValueError("types must contain only retained modes 'c', 'e', and 'h'")
74
+ c, e, h = (_indices(types, kind) for kind in ("c", "e", "h"))
75
+ S_cc = np.asarray(self.S_cc)
76
+ if S_cc.shape != (len(c), len(c)):
77
+ raise ValueError(f"S_cc must have shape {(len(c), len(c))}")
78
+ if not np.all(np.equal(S_cc, np.rint(S_cc))):
79
+ raise ValueError("S_cc must have integer entries")
80
+ if c and round(abs(np.linalg.det(np.asarray(S_cc, dtype=float)))) != 1:
81
+ raise ValueError("S_cc must be unimodular")
82
+ object.__setattr__(self, "types", types)
83
+ object.__setattr__(self, "S_cc", np.asarray(np.rint(S_cc), dtype=int))
84
+ object.__setattr__(self, "c", c)
85
+ object.__setattr__(self, "e", e)
86
+ object.__setattr__(self, "h", h)
87
+ object.__setattr__(self, "n", e + h)
88
+
89
+ @property
90
+ def size(self):
91
+ nc, ne, nh, nn = len(self.c), len(self.e), len(self.h), len(self.n)
92
+ if self.relaxed:
93
+ return nc * nn + nn * nn
94
+ return nc * ne + nh * ne + ne * ne + nh * nh
95
+
96
+ def x0(self):
97
+ """The origin, which gives ``blockdiag(S_cc, I)``."""
98
+ return np.zeros(self.size)
99
+
100
+ def S(self, x):
101
+ """Assemble the residual transformation represented by ``x``."""
102
+ x = np.asarray(x, dtype=float)
103
+ if x.shape != (self.size,):
104
+ raise ValueError(f"x must have shape {(self.size,)}")
105
+ S = np.eye(len(self.types))
106
+ if self.c:
107
+ S[np.ix_(self.c, self.c)] = self.S_cc
108
+ k = 0
109
+ if self.relaxed:
110
+ free = len(self.c) * len(self.n)
111
+ if free:
112
+ S[np.ix_(self.c, self.n)] = x[k:k + free].reshape(len(self.c), len(self.n))
113
+ k += free
114
+ if self.n:
115
+ S[np.ix_(self.n, self.n)] = _polar_block(x[k:], len(self.n))
116
+ return S
117
+
118
+ free = len(self.c) * len(self.e)
119
+ if free:
120
+ S[np.ix_(self.c, self.e)] = x[k:k + free].reshape(len(self.c), len(self.e))
121
+ k += free
122
+ free = len(self.h) * len(self.e)
123
+ if free:
124
+ S[np.ix_(self.h, self.e)] = x[k:k + free].reshape(len(self.h), len(self.e))
125
+ k += free
126
+ if self.e:
127
+ count = len(self.e) ** 2
128
+ S[np.ix_(self.e, self.e)] = _polar_block(x[k:k + count], len(self.e))
129
+ k += count
130
+ if self.h:
131
+ S[np.ix_(self.h, self.h)] = _polar_block(x[k:], len(self.h))
132
+ return S
133
+
134
+
135
+ def parameterization(types, *, S_cc=None, relaxed=False):
136
+ """Construct the parameterization ``S(x)`` for retained mode types."""
137
+ types = tuple(types)
138
+ nc = types.count("c")
139
+ if S_cc is None:
140
+ S_cc = np.eye(nc, dtype=int)
141
+ return Parameterization(types, S_cc, relaxed)
142
+
143
+
144
+ def _kappa(M, indices):
145
+ """Normalized sub-block, with a finite-value check for optimizer safety."""
146
+ indices = tuple(indices)
147
+ if not indices:
148
+ return np.zeros((0, 0))
149
+ block = np.asarray(M)[np.ix_(indices, indices)]
150
+ diagonal = np.diag(block)
151
+ if np.any(diagonal <= 0) or not np.all(np.isfinite(diagonal)):
152
+ return np.full(block.shape, np.nan)
153
+ return block / np.sqrt(np.outer(diagonal, diagonal))
154
+
155
+
156
+ def _quadratic_forms(S, C, L):
157
+ Cp = S.T @ C @ S
158
+ Lp = S.T @ L @ S
159
+ try:
160
+ Cp_inv = np.linalg.solve(Cp, np.eye(Cp.shape[0]))
161
+ except np.linalg.LinAlgError:
162
+ return Cp, None, Lp
163
+ return Cp, Cp_inv, Lp
164
+
165
+
166
+ def _masked_upper_square(K, mask=None):
167
+ if not np.all(np.isfinite(K)):
168
+ return np.inf
169
+ upper = np.triu(np.ones(K.shape, dtype=bool), 1)
170
+ if mask is not None:
171
+ upper &= np.asarray(mask, dtype=bool)
172
+ return float(np.sum(K[upper] ** 2))
173
+
174
+
175
+ def cost_normal_modes(C, L, types):
176
+ """Return the scale-free normal-mode objective ``f(S)``.
177
+
178
+ ``f`` sums the squared off-diagonal entries of ``(S^T C S)^{-1}`` over all modes
179
+ and of ``S^T L S`` over the noncompact modes, each matrix normalized as
180
+ ``M_ij / sqrt(M_ii M_jj)``. It vanishes when both forms are diagonal.
181
+
182
+ :param C: Numeric capacitance matrix C~ in coords.types order.
183
+ :param L: Numeric susceptance matrix L~* in the same order.
184
+ :param types: Mode types in coords.types order.
185
+ :returns: The objective, a function of a square array S.
186
+ """
187
+ C, L = np.asarray(C, dtype=float), np.asarray(L, dtype=float)
188
+ all_indices = tuple(range(len(types)))
189
+ noncompact = tuple(i for i, kind in enumerate(types) if kind != "c")
190
+
191
+ def objective(S):
192
+ _, Cp_inv, Lp = _quadratic_forms(np.asarray(S), C, L)
193
+ if Cp_inv is None:
194
+ return np.inf
195
+ return (_masked_upper_square(_kappa(Cp_inv, all_indices))
196
+ + _masked_upper_square(_kappa(Lp, noncompact)))
197
+
198
+ return objective
199
+
200
+
201
+ def cost_targeted(C, L, types, mask):
202
+ """Return a normal-mode objective restricted by coupling masks.
203
+
204
+ ``mask`` may be one square array, applied to both forms, or a pair
205
+ ``(mask_C_inv, mask_L)``. The latter may use either full-size masks or a
206
+ mask already restricted to the noncompact block.
207
+ True entries mark the couplings that count toward the cost.
208
+ numerical_S1 calls ``cost(C, L, types)``, so bind the mask first, as in
209
+ ``functools.partial(cost_targeted, mask=mask)``.
210
+ """
211
+ C, L = np.asarray(C, dtype=float), np.asarray(L, dtype=float)
212
+ all_indices = tuple(range(len(types)))
213
+ noncompact = tuple(i for i, kind in enumerate(types) if kind != "c")
214
+ if isinstance(mask, tuple) and len(mask) == 2:
215
+ mask_C, mask_L = map(np.asarray, mask)
216
+ else:
217
+ mask_C = mask_L = np.asarray(mask)
218
+ if mask_C.shape != C.shape:
219
+ raise ValueError("the C^-1 mask must have the same shape as C")
220
+ if mask_L.shape == L.shape:
221
+ mask_L = mask_L[np.ix_(noncompact, noncompact)]
222
+ if mask_L.shape != (len(noncompact), len(noncompact)):
223
+ raise ValueError("the L mask must be full-size or match the noncompact block")
224
+
225
+ def objective(S):
226
+ _, Cp_inv, Lp = _quadratic_forms(np.asarray(S), C, L)
227
+ if Cp_inv is None:
228
+ return np.inf
229
+ return (_masked_upper_square(_kappa(Cp_inv, all_indices), mask_C)
230
+ + _masked_upper_square(_kappa(Lp, noncompact), mask_L))
231
+
232
+ return objective
233
+
234
+
235
+ def cost_localization(C, L, wJ, types):
236
+ """Return the junction-localization objective, an l1 norm of ``omega~_J^T S``.
237
+
238
+ The objective sums the absolute entries of ``wJ @ S`` in compact and extended columns.
239
+ Each column of ``S`` is first rescaled so that ``(S^T C S)_jj = C_jj``, which fixes its scale.
240
+ numerical_S1 calls ``cost(C, L, types)``, so bind ``wJ`` first, as in
241
+ ``lambda C, L, types: cost_localization(C, L, wJ, types)``.
242
+
243
+ :param C: Numeric capacitance matrix C~ in coords.types order.
244
+ :param L: Not used.
245
+ :param wJ: Numeric junction matrix ``coords.omega_J_tilde.T``, one row per junction
246
+ and one column per mode.
247
+ :param types: Mode types in coords.types order.
248
+ :returns: The objective, a function of a square array S.
249
+ """
250
+ C, wJ = np.asarray(C, dtype=float), np.asarray(wJ, dtype=float)
251
+ del L # The lexicographic quadratic stage follows after localization.
252
+ active = tuple(i for i, kind in enumerate(types) if kind != "h")
253
+
254
+ def objective(S):
255
+ Cp = S.T @ C @ S
256
+ diagonal = np.diag(Cp)
257
+ if np.any(diagonal <= 0) or not np.all(np.isfinite(diagonal)):
258
+ return np.inf
259
+ # Gauge-fix to (S.T C S)_jj = C_jj without actually changing S.
260
+ normalized = (wJ @ S) * np.sqrt(np.diag(C) / diagonal)[None, :]
261
+ return float(np.sum(np.abs(normalized[:, active])))
262
+
263
+ return objective
264
+
265
+
266
+ @dataclass(frozen=True)
267
+ class NumericalInfo:
268
+ """Diagnostics returned by :func:`numerical_S1`.
269
+
270
+ :ivar result: SciPy OptimizeResult of the best start.
271
+ :ivar cost: Cost of the returned S_1.
272
+ :ivar C_tilde: S_1^T C~ S_1.
273
+ :ivar C_tilde_inv: Its inverse.
274
+ :ivar Lstar_tilde: S_1^T L~* S_1.
275
+ :ivar kappa_C_inv: C_tilde_inv normalized as M_ij / sqrt(M_ii M_jj).
276
+ :ivar kappa_L: Lstar_tilde normalized likewise, on the noncompact modes.
277
+ """
278
+
279
+ result: OptimizeResult
280
+ cost: float
281
+ C_tilde: np.ndarray
282
+ C_tilde_inv: np.ndarray
283
+ Lstar_tilde: np.ndarray
284
+ kappa_C_inv: np.ndarray
285
+ kappa_L: np.ndarray
286
+
287
+
288
+ def _normalized(S, C, noncompact, mode):
289
+ if mode is None:
290
+ return S
291
+ if mode not in {"C", "keep"}:
292
+ raise ValueError("normalize must be 'C', 'keep', or None")
293
+ S = S.copy()
294
+ Cp = S.T @ C @ S
295
+ for j in noncompact:
296
+ target = 1.0 if mode == "C" else C[j, j]
297
+ S[:, j] *= np.sqrt(target / Cp[j, j])
298
+ return S
299
+
300
+
301
+ def _sympy_matrix(S, parameterization):
302
+ result = sym.zeros(*S.shape)
303
+ compact_positions = {(i, j) for i in parameterization.c for j in parameterization.c}
304
+ for i in range(S.shape[0]):
305
+ for j in range(S.shape[1]):
306
+ if (i, j) in compact_positions:
307
+ result[i, j] = sym.Integer(int(parameterization.S_cc[
308
+ parameterization.c.index(i), parameterization.c.index(j)]))
309
+ elif S[i, j] != 0:
310
+ result[i, j] = sym.Float(float(S[i, j]), 17)
311
+ return sym.ImmutableMatrix(result)
312
+
313
+
314
+ def numerical_S1(lag, coords, values, cost, *, S_cc=None, relaxed=False,
315
+ x0=None, restarts=3, seed=0, tol=1e-12, normalize="C"):
316
+ """Minimize a cost over the residual transformation ``S(x)`` with BFGS.
317
+
318
+ The compact block of ``S_1`` is fixed at ``S_cc``.
319
+ With ``relaxed=False`` the extended and harmonic diagonal blocks are separate
320
+ polar blocks, and extended columns may also take compact and harmonic components.
321
+ With ``relaxed=True`` all noncompact columns form one polar block and may also
322
+ take compact components, so harmonic and extended modes mix.
323
+
324
+ :param lag: Not used. It matches the signature of normal_mode_decoupling.
325
+ :param coords: Retained Coordinates.
326
+ :param values: {symbol: number} that makes C~ and L~* numeric, or None if they already are.
327
+ :param cost: Constructor ``cost(C, L, types) -> f(S)``, such as cost_normal_modes.
328
+ Bind the extra arguments of cost_targeted and cost_localization first.
329
+ :param S_cc: Integer unimodular compact block. Defaults to the identity.
330
+ :param bool relaxed: Use one polar block for all noncompact columns.
331
+ :param x0: Initial parameter vector. Defaults to zero, which gives blockdiag(S_cc, I).
332
+ :param int restarts: Number of extra random starts, each 0.3 times a standard normal vector.
333
+ :param int seed: Seed of the random starts.
334
+ :param float tol: Gradient tolerance of BFGS.
335
+ :param normalize: Column scaling of the result. "C" sets each noncompact
336
+ ``(S^T C~ S)_jj`` to 1, "keep" keeps it at ``C~_jj``, and None leaves S as found.
337
+ :returns: ``(S1, info)``, with S1 a SymPy matrix in coords.types order whose compact
338
+ block is exact and other entries are Floats, and info a NumericalInfo.
339
+ :raises ValueError: Non-numeric matrices, a bad x0, S_cc, or normalize, or negative restarts.
340
+ :raises RuntimeError: Every start ends at a non-finite cost.
341
+ """
342
+ del lag
343
+ numeric = numerify(coords, values or {})
344
+ C = np.asarray(numeric.C_tilde, dtype=float)
345
+ L = np.asarray(numeric.Lstar_tilde, dtype=float)
346
+ if C.shape != L.shape or C.shape != (len(coords.types), len(coords.types)):
347
+ raise ValueError("coordinate matrices and types have incompatible shapes")
348
+ if not np.all(np.isfinite(C)) or not np.all(np.isfinite(L)):
349
+ raise ValueError("values must numerically specify every entry of C and L")
350
+ p = parameterization(coords.types, S_cc=S_cc, relaxed=relaxed)
351
+ objective_S = cost(C, L, coords.types)
352
+ objective_x = lambda x: objective_S(p.S(x))
353
+
354
+ if restarts < 0:
355
+ raise ValueError("restarts must be nonnegative")
356
+
357
+ starts = []
358
+ if x0 is not None:
359
+ x0 = np.asarray(x0, dtype=float)
360
+ if x0.shape != (p.size,):
361
+ raise ValueError(f"x0 must have shape {(p.size,)}")
362
+ starts.append(x0)
363
+ else:
364
+ starts.append(p.x0())
365
+ rng = np.random.default_rng(seed)
366
+ starts.extend(0.3 * rng.normal(size=p.size) for _ in range(restarts))
367
+ if p.size:
368
+ results = [minimize(objective_x, start, method="BFGS",
369
+ options={"gtol": tol, "maxiter": 5000}) for start in starts]
370
+ else:
371
+ value = objective_x(p.x0())
372
+ results = [OptimizeResult(x=p.x0(), fun=value, success=True,
373
+ message="the parameterization has no free variables")]
374
+ finite = [result for result in results if np.isfinite(result.fun)]
375
+ if not finite:
376
+ raise RuntimeError("every numerical-search restart returned a non-finite cost")
377
+ best = min(finite, key=lambda result: result.fun)
378
+
379
+ noncompact = tuple(i for i, kind in enumerate(coords.types) if kind != "c")
380
+ S = _normalized(p.S(best.x), C, noncompact, normalize)
381
+ Cp, Cp_inv, Lp = _quadratic_forms(S, C, L)
382
+ info = NumericalInfo(
383
+ result=best,
384
+ cost=float(objective_S(S)),
385
+ C_tilde=Cp,
386
+ C_tilde_inv=Cp_inv,
387
+ Lstar_tilde=Lp,
388
+ kappa_C_inv=_kappa(Cp_inv, range(len(coords.types))),
389
+ kappa_L=_kappa(Lp, noncompact),
390
+ )
391
+ return _sympy_matrix(S, p), info
@@ -0,0 +1,32 @@
1
+ """Optional exact search for the residual transformation S_1, ported from sircuitenum.
2
+
3
+ Needs the optional dependencies, the Singular binary (conda-forge ``singular``),
4
+ ``z3-solver``, and ``func-timeout``. ``environment.yml`` installs all three.
5
+ Nothing in the core package imports this subpackage.
6
+ A typical search::
7
+
8
+ from circuit_quantization.optimize import choose_instance, choose_S1
9
+ S1s, h_class = choose_S1(result.lag, result.coords) # families, free entries symbolic
10
+ S1, weight = choose_instance(result.lag, result.coords, S1s[0])
11
+ best = result.transform(S1)
12
+
13
+ Three constants set or bound the arguments of choose_S1.
14
+ ``SIRCUITENUM`` is the default sequence of stages, junction couplings first, then inductive and charging couplings.
15
+ ``SIRCUITENUM_BLOCKS`` is the default set of (old type, new type) blocks of S_1 that the first stage opens.
16
+ ``ALLOWED_BLOCKS`` is the set of every block a stage may open.
17
+ A Stage names its matrices by the built-in names "J" (junction matrix), "L" (L~*), "Cinv" (C~^{-1}),
18
+ and "wJ" (junction incidence omega~_J^T, a rows matrix), or by custom (name, matrix) entries.
19
+ """
20
+
21
+ from .choose import (
22
+ Candidate, candidate, choose_instance, choose_S1, cluster_score, compact_alignments, h_hash, instance,
23
+ junction_seeds,
24
+ )
25
+ from .patterns import Seed, by_clusters, by_cost, most_zeros_first
26
+ from .stages import ALLOWED_BLOCKS, SIRCUITENUM, SIRCUITENUM_BLOCKS, Stage
27
+
28
+ __all__ = [
29
+ "ALLOWED_BLOCKS", "Candidate", "SIRCUITENUM", "SIRCUITENUM_BLOCKS", "Seed", "Stage", "by_clusters", "by_cost",
30
+ "candidate", "choose_S1", "choose_instance", "cluster_score", "compact_alignments", "h_hash", "instance",
31
+ "junction_seeds", "most_zeros_first",
32
+ ]
@@ -0,0 +1,37 @@
1
+ # Vendored from sircuitenum/utils.py (GPL-3.0): run_with_timeout only.
2
+ """Timeout helper used by the vendored solver modules."""
3
+
4
+ from func_timeout import FunctionTimedOut, func_timeout
5
+
6
+
7
+ def run_with_timeout(func, args=(), kwargs=None, timeout=1):
8
+ """
9
+ Runs the specified function with a timeout
10
+
11
+ Args:
12
+ func (function): function to run
13
+ args (tuple, optional): arguments to the function. Defaults to ().
14
+ kwargs (_type_, optional): kwarguments to the function. Defaults to None.
15
+ timeout (int, optional): timeout in minutes. Defaults to 1.
16
+ Raises:
17
+ KI: KeyboardInterrupt if interrupted by user
18
+ Returns:
19
+ None if didn't return, else the function output
20
+ """
21
+ if kwargs is None:
22
+ kwargs = {}
23
+
24
+ # Pass a zero-argument closure to func_timeout. On timeout the library
25
+ # formats the supplied args/kwargs into its exception message; symbolic
26
+ # matrices can take minutes to stringify and can raise again inside the
27
+ # timeout thread. Keeping those objects in the closure makes timeout
28
+ # reporting bounded without changing the function call.
29
+ def call_with_arguments():
30
+ return func(*args, **kwargs)
31
+
32
+ try:
33
+ return func_timeout(60*timeout, call_with_arguments)
34
+ except FunctionTimedOut:
35
+ return None
36
+ except KeyboardInterrupt as KI:
37
+ raise KI