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.
- circuit_quantization/__init__.py +64 -0
- circuit_quantization/circuit.py +258 -0
- circuit_quantization/draw.py +199 -0
- circuit_quantization/flux.py +54 -0
- circuit_quantization/hamiltonian.py +101 -0
- circuit_quantization/io.py +704 -0
- circuit_quantization/lagrangian.py +85 -0
- circuit_quantization/loops.py +248 -0
- circuit_quantization/modes.py +672 -0
- circuit_quantization/numeric_spec.py +199 -0
- circuit_quantization/numerical.py +391 -0
- circuit_quantization/optimize/__init__.py +32 -0
- circuit_quantization/optimize/_utils.py +37 -0
- circuit_quantization/optimize/choose.py +396 -0
- circuit_quantization/optimize/equationset.py +358 -0
- circuit_quantization/optimize/patterns.py +88 -0
- circuit_quantization/optimize/poly_solver.sing +381 -0
- circuit_quantization/optimize/rational_check.py +675 -0
- circuit_quantization/optimize/singular_interface.py +1071 -0
- circuit_quantization/optimize/stages.py +115 -0
- circuit_quantization/optimize/transforms.py +1337 -0
- circuit_quantization/optimize/z3_interface.py +794 -0
- circuit_quantization/qpackage_interface.py +126 -0
- circuit_quantization/quantize.py +186 -0
- circuit_quantization/shear.py +252 -0
- circuit_quantization/units.py +91 -0
- circuit_quantization-0.1.0.dist-info/METADATA +99 -0
- circuit_quantization-0.1.0.dist-info/RECORD +31 -0
- circuit_quantization-0.1.0.dist-info/WHEEL +5 -0
- circuit_quantization-0.1.0.dist-info/licenses/LICENSE +674 -0
- circuit_quantization-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1337 @@
|
|
|
1
|
+
# Vendored from sircuitenum/quantize.py (GPL-3.0), sircuitenum commit b2c57e8.
|
|
2
|
+
# Only the transformation-level helpers are kept: compact alignment, secondary
|
|
3
|
+
# decoupling, H_hash, and parameter instances. Circuit construction and choose_Z
|
|
4
|
+
# are replaced by circuit_quantization (see optimize/__init__.py).
|
|
5
|
+
"""Residual-freedom search: secondary decoupling and H_hash ranking (from sircuitenum)."""
|
|
6
|
+
|
|
7
|
+
import itertools
|
|
8
|
+
import functools
|
|
9
|
+
import time
|
|
10
|
+
from copy import deepcopy
|
|
11
|
+
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import Union, Sequence, Iterable, Mapping, Optional, Tuple, Any
|
|
14
|
+
|
|
15
|
+
import sympy as sym
|
|
16
|
+
import numpy as np
|
|
17
|
+
import networkx as nx
|
|
18
|
+
|
|
19
|
+
from sympy import collect, expand_mul, Mul, Dummy
|
|
20
|
+
from sympy.core.add import Add
|
|
21
|
+
|
|
22
|
+
from . import _utils as utils
|
|
23
|
+
from .equationset import maximally_compatible_sol, extract_denom, eq_indep_of_vars, _unique_products, _eq_as_numer_denom
|
|
24
|
+
from .z3_interface import find_rational_vars_integer_results, _calc_min_cost, _heuristic_upper_bound
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
PERIODIC_CHARGE = "n"
|
|
28
|
+
PERIODIC_PHASE = "θ"
|
|
29
|
+
EXTENDED_CHARGE = "q"
|
|
30
|
+
EXTENDED_PHASE = "φ"
|
|
31
|
+
NODE_CHARGE = "q"
|
|
32
|
+
NODE_PHASE = "ϕ"
|
|
33
|
+
EXT_CHARGE = "n_g"
|
|
34
|
+
EXT_PHASE = "_{ext}"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _independent_from(A, B):
|
|
38
|
+
"""
|
|
39
|
+
Returns the maximum set of vectors in A such that
|
|
40
|
+
their span has no overlap with the span of B.
|
|
41
|
+
Assumes A and B are sets of linearly independent column vectors.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
A (list[sym.Matrix] or sym.Matrix): Set of linearly independent column vectors.
|
|
45
|
+
B (list[sym.Matrix] or sym.Matrix): Set of linearly independent column vectors.
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
list[sym.Matrix]: Basis vectors in span(A) not in span(B).
|
|
49
|
+
"""
|
|
50
|
+
# Convert to list of column vectors if needed
|
|
51
|
+
if isinstance(A, sym.Matrix):
|
|
52
|
+
A = [A[:, j] for j in range(A.shape[1])]
|
|
53
|
+
if isinstance(B, sym.Matrix):
|
|
54
|
+
B = [B[:, j] for j in range(B.shape[1])]
|
|
55
|
+
|
|
56
|
+
# If B is empty, all of A is independent
|
|
57
|
+
if not B:
|
|
58
|
+
return [v for v in A]
|
|
59
|
+
|
|
60
|
+
# Stack B and A, get linearly independent columns
|
|
61
|
+
mat = sym.Matrix.hstack(*B, *A)
|
|
62
|
+
li_cols = _linearly_indep_cols(mat)
|
|
63
|
+
# Only keep those columns that come from A
|
|
64
|
+
offset = len(B)
|
|
65
|
+
result = []
|
|
66
|
+
for idx in li_cols:
|
|
67
|
+
if idx >= offset:
|
|
68
|
+
result.append(mat[:, idx])
|
|
69
|
+
return result
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _vec_space_overlap(vecs1:Union[list[sym.Matrix], sym.Matrix],
|
|
73
|
+
vecs2:Union[list[sym.Matrix], sym.Matrix],
|
|
74
|
+
support:Union[list[sym.Matrix], sym.Matrix] = [],
|
|
75
|
+
return_decomp:bool = False
|
|
76
|
+
) -> list[sym.Matrix]:
|
|
77
|
+
"""
|
|
78
|
+
Calculates the overlap of two linearly independent sets of
|
|
79
|
+
vectors vecs1, vecs2 using NULL(vecs1, -vecs2)
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
vecs1 (Union[list[sym.Matrix], sym.Matrix]): set of column vectors
|
|
83
|
+
vecs2 (Union[list[sym.Matrix], sym.Matrix]): set of column vectors
|
|
84
|
+
support (Union[list[sym.Matrix], sym.Matrix]): set of vectors that can be
|
|
85
|
+
included to make the overlap work,
|
|
86
|
+
if used in addition to the vectors
|
|
87
|
+
from the individual sets
|
|
88
|
+
|
|
89
|
+
Returns:
|
|
90
|
+
list[sym.Matrix]: list of vectors that span the overlap space.
|
|
91
|
+
"""
|
|
92
|
+
# Convert matrices to list
|
|
93
|
+
if isinstance(vecs1, sym.Matrix):
|
|
94
|
+
vecs1 = [vecs1[:, j] for j in range(vecs1.shape[1])]
|
|
95
|
+
if isinstance(vecs2, sym.Matrix):
|
|
96
|
+
vecs2 = [vecs2[:, j] for j in range(vecs2.shape[1])]
|
|
97
|
+
if isinstance(support, sym.Matrix):
|
|
98
|
+
support = [support[:, j] for j in range(support.shape[1])]
|
|
99
|
+
|
|
100
|
+
# If either one is empty, return no overlap
|
|
101
|
+
if len(vecs1) == 0 or len(vecs2) == 0:
|
|
102
|
+
if return_decomp:
|
|
103
|
+
if len(support) > 0:
|
|
104
|
+
return [], [], [], []
|
|
105
|
+
else:
|
|
106
|
+
return [], [], []
|
|
107
|
+
else:
|
|
108
|
+
return []
|
|
109
|
+
|
|
110
|
+
# Assert vector sets are linearly independent and same length
|
|
111
|
+
assert len(_linearly_indep_cols(sym.Matrix.hstack(*vecs1))) == len(vecs1)
|
|
112
|
+
assert len(_linearly_indep_cols(sym.Matrix.hstack(*vecs2))) == len(vecs2)
|
|
113
|
+
assert len(_linearly_indep_cols(sym.Matrix.hstack(*support))) == len(support)
|
|
114
|
+
assert vecs1[0].shape[0] == vecs2[0].shape[0]
|
|
115
|
+
if len(support) > 0:
|
|
116
|
+
assert support[0].shape[0] == vecs1[0].shape[0]
|
|
117
|
+
|
|
118
|
+
# Calculate the overlap of the two vector spaces
|
|
119
|
+
divide = (len(vecs1), len(support) + len(vecs1))
|
|
120
|
+
ns = sym.Matrix.hstack(*[v for v in vecs1],
|
|
121
|
+
*[-v for v in support],
|
|
122
|
+
*[-v for v in vecs2]).nullspace()
|
|
123
|
+
|
|
124
|
+
# Gather the entries
|
|
125
|
+
in_v1 = []
|
|
126
|
+
in_v2 = []
|
|
127
|
+
in_sup = []
|
|
128
|
+
overlap_vecs = []
|
|
129
|
+
mat = sym.Matrix.hstack(*vecs1)
|
|
130
|
+
for vec in ns:
|
|
131
|
+
v1_entry = vec[:divide[0], :]
|
|
132
|
+
sup_entry = vec[divide[0]:divide[1], :]
|
|
133
|
+
v2_entry = vec[divide[1]:, :]
|
|
134
|
+
if not(v1_entry.is_zero_matrix or v2_entry.is_zero_matrix):
|
|
135
|
+
in_v1.append(v1_entry)
|
|
136
|
+
in_v2.append(v2_entry)
|
|
137
|
+
in_sup.append(sup_entry)
|
|
138
|
+
overlap_vecs.append(mat*v1_entry)
|
|
139
|
+
|
|
140
|
+
if return_decomp:
|
|
141
|
+
if len(support) == 0:
|
|
142
|
+
return overlap_vecs, in_v1, in_v2
|
|
143
|
+
else:
|
|
144
|
+
return overlap_vecs, in_v1, in_v2, in_sup
|
|
145
|
+
else:
|
|
146
|
+
return overlap_vecs
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _linearly_indep_cols(X):
|
|
150
|
+
rref, pivot_cols = X.rref()
|
|
151
|
+
return pivot_cols
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _linearly_indep_rows(X):
|
|
155
|
+
return _linearly_indep_cols(X.transpose())
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _linearly_indep_col_sets(X):
|
|
159
|
+
pivot_cols = _linearly_indep_cols(X)
|
|
160
|
+
rank = len(pivot_cols)
|
|
161
|
+
if rank == X.shape[1]:
|
|
162
|
+
return [pivot_cols]
|
|
163
|
+
|
|
164
|
+
# Every independent column set is a rank-sized basis. The previous
|
|
165
|
+
# implementation discovered these by trying all n! column permutations
|
|
166
|
+
# and rerunning RREF. Enumerating the n-choose-r candidate bases directly
|
|
167
|
+
# is equivalent and avoids factorial work for junction-rich circuits.
|
|
168
|
+
return [
|
|
169
|
+
cols
|
|
170
|
+
for cols in itertools.combinations(range(X.shape[1]), rank)
|
|
171
|
+
if len(_linearly_indep_cols(X[:, cols])) == rank
|
|
172
|
+
]
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _linearly_indep_row_sets(X):
|
|
176
|
+
return _linearly_indep_col_sets(X.transpose())
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _det_fast(M):
|
|
180
|
+
"""
|
|
181
|
+
Hardcoded determinant for small sympy matrices (up to 4x4)
|
|
182
|
+
|
|
183
|
+
Falls back to M.det() for larger
|
|
184
|
+
"""
|
|
185
|
+
n = M.shape[0]
|
|
186
|
+
if M.shape[0] != M.shape[1]:
|
|
187
|
+
raise ValueError("Matrix must be square")
|
|
188
|
+
|
|
189
|
+
if n == 1:
|
|
190
|
+
return M[0,0]
|
|
191
|
+
|
|
192
|
+
elif n == 2:
|
|
193
|
+
return M[0,0]*M[1,1] - M[0,1]*M[1,0]
|
|
194
|
+
|
|
195
|
+
elif n == 3:
|
|
196
|
+
return (M[0,0]*(M[1,1]*M[2,2] - M[1,2]*M[2,1])
|
|
197
|
+
- M[0,1]*(M[1,0]*M[2,2] - M[1,2]*M[2,0])
|
|
198
|
+
+ M[0,2]*(M[1,0]*M[2,1] - M[1,1]*M[2,0]))
|
|
199
|
+
elif n == 4:
|
|
200
|
+
return (
|
|
201
|
+
M[0,0]*(M[1,1]*(M[2,2]*M[3,3] - M[2,3]*M[3,2])
|
|
202
|
+
-M[1,2]*(M[2,1]*M[3,3] - M[2,3]*M[3,1])
|
|
203
|
+
+M[1,3]*(M[2,1]*M[3,2] - M[2,2]*M[3,1]))
|
|
204
|
+
- M[0,1]*(M[1,0]*(M[2,2]*M[3,3] - M[2,3]*M[3,2])
|
|
205
|
+
-M[1,2]*(M[2,0]*M[3,3] - M[2,3]*M[3,0])
|
|
206
|
+
+M[1,3]*(M[2,0]*M[3,2] - M[2,2]*M[3,0]))
|
|
207
|
+
+ M[0,2]*(M[1,0]*(M[2,1]*M[3,3] - M[2,3]*M[3,1])
|
|
208
|
+
-M[1,1]*(M[2,0]*M[3,3] - M[2,3]*M[3,0])
|
|
209
|
+
+M[1,3]*(M[2,0]*M[3,1] - M[2,1]*M[3,0]))
|
|
210
|
+
- M[0,3]*(M[1,0]*(M[2,1]*M[3,2] - M[2,2]*M[3,1])
|
|
211
|
+
-M[1,1]*(M[2,0]*M[3,2] - M[2,2]*M[3,0])
|
|
212
|
+
+M[1,2]*(M[2,0]*M[3,1] - M[2,1]*M[3,0]))
|
|
213
|
+
)
|
|
214
|
+
else:
|
|
215
|
+
# The default Bareiss path can spend minutes expanding rational
|
|
216
|
+
# expressions for the 5x5 symbolic transformations encountered during
|
|
217
|
+
# H-class enumeration. DomainMatrix Gaussian elimination preserves a
|
|
218
|
+
# compact exact rational form and is dramatically faster for these
|
|
219
|
+
# matrices.
|
|
220
|
+
return M.det(method="domain-ge")
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _equiv_cols(c1, c2, shifts=None):
|
|
224
|
+
"""
|
|
225
|
+
Are two transformation columns equivalent up to a change
|
|
226
|
+
in sign and and given shifts?
|
|
227
|
+
|
|
228
|
+
Args:
|
|
229
|
+
c1 (sym.Matrix): column 1
|
|
230
|
+
c2 (sym.Matrix): column 2
|
|
231
|
+
shifts (list[sym.Matrix], optional): Shifts. Defaults to global 1.
|
|
232
|
+
|
|
233
|
+
Returns:
|
|
234
|
+
bool: True if equivalent up to sign and shifts. False otherwise.
|
|
235
|
+
"""
|
|
236
|
+
if shifts is None:
|
|
237
|
+
# Just the global shift
|
|
238
|
+
shifts = [sym.ones(c1.shape[0], 1)]
|
|
239
|
+
for sign in [1, -1]:
|
|
240
|
+
# Can you make the difference using the specified shifts?
|
|
241
|
+
diff = sign*c1 - c2
|
|
242
|
+
if diff.is_zero_matrix:
|
|
243
|
+
return True
|
|
244
|
+
if not shifts is None:
|
|
245
|
+
if len(shifts) > 0:
|
|
246
|
+
li_cols = _linearly_indep_cols(sym.Matrix.hstack(diff, *shifts))
|
|
247
|
+
if len(li_cols) == len(shifts):
|
|
248
|
+
return True
|
|
249
|
+
return False
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _equal_up_to_column_shift_and_sign(A: sym.Matrix, B: sym.Matrix, shifts: Union[sym.Matrix,list[sym.Matrix]] = None):
|
|
253
|
+
"""
|
|
254
|
+
Assumes that the columns in A and B are linearly independent
|
|
255
|
+
|
|
256
|
+
Args:
|
|
257
|
+
A (sym.Matrix): Transformation matrix A
|
|
258
|
+
B (sym.Matrix): Transformation matrix B
|
|
259
|
+
shifts (list[sym.Matrix], optional): _description_. Defaults to None.
|
|
260
|
+
|
|
261
|
+
Returns:
|
|
262
|
+
_type_: _description_
|
|
263
|
+
"""
|
|
264
|
+
if A.shape != B.shape:
|
|
265
|
+
return False
|
|
266
|
+
if isinstance(shifts, sym.Matrix):
|
|
267
|
+
shifts = [shifts[:, i] for i in range(shifts.shape[1])]
|
|
268
|
+
if shifts is None:
|
|
269
|
+
# Just the global shift
|
|
270
|
+
shifts = [sym.ones(A.shape[0], 1)]
|
|
271
|
+
elif len(shifts) > 0:
|
|
272
|
+
# Get linearly independent set of shifts
|
|
273
|
+
li_shifts = _linearly_indep_cols(sym.Matrix.hstack(*shifts))
|
|
274
|
+
shifts = [shifts[i] for i in li_shifts]
|
|
275
|
+
|
|
276
|
+
rows, cols = A.shape
|
|
277
|
+
for j in range(cols):
|
|
278
|
+
if not _equiv_cols(A[:, j], B[:, j], shifts):
|
|
279
|
+
return False
|
|
280
|
+
return True
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _find_equiv_cols(c1, cList, shifts: Union[sym.Matrix, list[sym.Matrix]]=None):
|
|
284
|
+
if isinstance(shifts, sym.Matrix):
|
|
285
|
+
shifts = [shifts[:, i] for i in range(shifts.shape[1])]
|
|
286
|
+
return [i for i in range(len(cList)) if _equal_up_to_column_shift_and_sign(c1, cList[i], shifts)]
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _find_equiv_mats(m1, mList, shifts=None):
|
|
290
|
+
return [i for i in range(len(mList)) if _equal_up_to_column_swaps_and_shift_and_sign(m1, mList[i], shifts)]
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _equal_up_to_column_swaps_and_shift_and_sign(A: sym.Matrix, B: sym.Matrix, shifts: Union[sym.Matrix, list[sym.Matrix]] = None):
|
|
294
|
+
"""
|
|
295
|
+
|
|
296
|
+
Args:
|
|
297
|
+
A (sym.Matrix): _description_
|
|
298
|
+
B (sym.Matrix): _description_
|
|
299
|
+
|
|
300
|
+
Returns:
|
|
301
|
+
_type_: _description_
|
|
302
|
+
"""
|
|
303
|
+
|
|
304
|
+
if A.shape != B.shape:
|
|
305
|
+
return False
|
|
306
|
+
|
|
307
|
+
# Count unique columns and number of occurances
|
|
308
|
+
colsA = []
|
|
309
|
+
countsA = []
|
|
310
|
+
colsB = []
|
|
311
|
+
countsB = []
|
|
312
|
+
for j in range(A.shape[1]):
|
|
313
|
+
for mat, cols, counts in zip([A, B],
|
|
314
|
+
[colsA, colsB],
|
|
315
|
+
[countsA, countsB]):
|
|
316
|
+
c = mat[:, j]
|
|
317
|
+
equiv = _find_equiv_cols(c, cols, shifts)
|
|
318
|
+
if len(equiv) == 0:
|
|
319
|
+
cols.append(c)
|
|
320
|
+
counts.append(1)
|
|
321
|
+
else:
|
|
322
|
+
counts[equiv[0]] += 1
|
|
323
|
+
|
|
324
|
+
# Make sure there are equal sets of equal columns
|
|
325
|
+
# Function that returns equivalent columns in an iterable
|
|
326
|
+
for cA in colsA:
|
|
327
|
+
# Identify equivalent columns
|
|
328
|
+
eq_cols = _find_equiv_cols(cA, colsB, shifts)
|
|
329
|
+
if len(eq_cols) > 1:
|
|
330
|
+
raise ValueError("Columns are not unique")
|
|
331
|
+
elif len(eq_cols) != 1:
|
|
332
|
+
return False
|
|
333
|
+
return True
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _nonzero_entries_str(X: Union[sym.Matrix, np.ndarray],
|
|
337
|
+
prepend_sum: bool = True,
|
|
338
|
+
full_mat: bool = False) -> str:
|
|
339
|
+
"""
|
|
340
|
+
For a symmetric matrix X, returns the flattened indices
|
|
341
|
+
of nonzero off-diagonal entries
|
|
342
|
+
|
|
343
|
+
Args:
|
|
344
|
+
X (Union[sym.Matrix, np.ndarray]): symmetric matrix
|
|
345
|
+
prepend_sum (bool): prepends the sum of the binary string
|
|
346
|
+
|
|
347
|
+
Returns:
|
|
348
|
+
str: binary string 10101001 with 1 being the indices
|
|
349
|
+
of nonzero entries and 0 being the indices of
|
|
350
|
+
zero entries. optionally prepend the sum of the
|
|
351
|
+
binary string 4-10101001
|
|
352
|
+
"""
|
|
353
|
+
if isinstance(X, np.ndarray):
|
|
354
|
+
X = sym.Matrix(X)
|
|
355
|
+
all_vars = list(X.free_symbols)
|
|
356
|
+
nz_idx = []
|
|
357
|
+
n_nz = 0
|
|
358
|
+
for i in range(X.shape[0]):
|
|
359
|
+
for j in range(X.shape[1]):
|
|
360
|
+
if j > i or full_mat:
|
|
361
|
+
terms = _unique_products(X[i,j].as_numer_denom()[0])
|
|
362
|
+
if any(coeff != 0 for coeff in terms.values()):
|
|
363
|
+
nz_idx.append("1")
|
|
364
|
+
n_nz += 1
|
|
365
|
+
else:
|
|
366
|
+
nz_idx.append("0")
|
|
367
|
+
|
|
368
|
+
bin_str = "".join(nz_idx)
|
|
369
|
+
if prepend_sum:
|
|
370
|
+
bin_str = str(n_nz) + "-" + bin_str
|
|
371
|
+
return bin_str
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _incidence_square_nonzero_str(w: sym.Matrix, vals: list) -> str:
|
|
375
|
+
"""Return the off-diagonal support of ``w diag(vals) w.T`` cheaply.
|
|
376
|
+
|
|
377
|
+
With distinct symbolic coefficients, terms from different incidence
|
|
378
|
+
columns cannot cancel. The support can therefore be read directly from
|
|
379
|
+
pairs of nonzero incidence entries, avoiding construction and expansion of
|
|
380
|
+
a symbolic weighted Gram matrix. Repeated coefficients use the original
|
|
381
|
+
exact symbolic path because cancellation is then possible.
|
|
382
|
+
"""
|
|
383
|
+
if len(set(vals)) != len(vals):
|
|
384
|
+
return _nonzero_entries_str(incidence_to_square(w, vals))
|
|
385
|
+
|
|
386
|
+
bits = []
|
|
387
|
+
count = 0
|
|
388
|
+
for row in range(w.rows):
|
|
389
|
+
for column in range(row + 1, w.rows):
|
|
390
|
+
nonzero = any(
|
|
391
|
+
sym.simplify(w[row, edge] * w[column, edge]) != 0
|
|
392
|
+
for edge in range(w.cols)
|
|
393
|
+
)
|
|
394
|
+
bits.append("1" if nonzero else "0")
|
|
395
|
+
count += int(nonzero)
|
|
396
|
+
return f"{count}-" + "".join(bits)
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _remove_permutation_equivalent_transformations(Z_list, perms=[]):
|
|
400
|
+
"""Filter transformations that are column permutations or sign-flips of each other. Considers
|
|
401
|
+
subsets of columns based on variable types. Substitutes dummy variables to allow for equality
|
|
402
|
+
checks even when symbolic variables differ.
|
|
403
|
+
|
|
404
|
+
For each transformation matrix in ``Z_list``, generates column permutations
|
|
405
|
+
based on perms and checks if it's equivalent (up to column shifts
|
|
406
|
+
and sign flips) to any previously kept transformation.
|
|
407
|
+
|
|
408
|
+
Parameters
|
|
409
|
+
----------
|
|
410
|
+
Z_list : list[sym.Matrix]
|
|
411
|
+
List of transformation matrices to filter.
|
|
412
|
+
perms : list[tuple[int]]
|
|
413
|
+
List of column index permutations to consider for equivalence.
|
|
414
|
+
|
|
415
|
+
Returns
|
|
416
|
+
-------
|
|
417
|
+
tuple[list[sym.Matrix], list[str]]
|
|
418
|
+
Filtered lists of transformation matrices and their nonzero strings.
|
|
419
|
+
"""
|
|
420
|
+
# If perms is empty, consider all permutations of columns
|
|
421
|
+
if not perms:
|
|
422
|
+
perms = list(itertools.permutations(range(Z_list[0].shape[1])))
|
|
423
|
+
|
|
424
|
+
def normalized_permutation(Z, perm):
|
|
425
|
+
Z_perm = Z[:, perm]
|
|
426
|
+
substitutions = {}
|
|
427
|
+
variable_count = 1
|
|
428
|
+
for column in range(Z_perm.shape[1]):
|
|
429
|
+
for row in range(Z_perm.shape[0]):
|
|
430
|
+
for variable in sorted(Z_perm[row, column].free_symbols, key=str):
|
|
431
|
+
if variable not in substitutions:
|
|
432
|
+
substitutions[variable] = sym.Symbol(
|
|
433
|
+
f"v_{variable_count}", real=True
|
|
434
|
+
)
|
|
435
|
+
variable_count += 1
|
|
436
|
+
return Z_perm.subs(substitutions)
|
|
437
|
+
|
|
438
|
+
def orbit_fingerprint(Z):
|
|
439
|
+
permutation_keys = []
|
|
440
|
+
for perm in perms:
|
|
441
|
+
Z_perm = normalized_permutation(Z, perm)
|
|
442
|
+
column_keys = []
|
|
443
|
+
for column in range(Z_perm.shape[1]):
|
|
444
|
+
positive = tuple(sym.srepr(value) for value in Z_perm[:, column])
|
|
445
|
+
negative = tuple(sym.srepr(-value) for value in Z_perm[:, column])
|
|
446
|
+
column_keys.append(min(positive, negative))
|
|
447
|
+
permutation_keys.append(tuple(column_keys))
|
|
448
|
+
return min(permutation_keys)
|
|
449
|
+
|
|
450
|
+
unique_Z = []
|
|
451
|
+
idx_keep = []
|
|
452
|
+
seen_fingerprints = set()
|
|
453
|
+
for k, Z_k in enumerate(Z_list):
|
|
454
|
+
fingerprint = orbit_fingerprint(Z_k)
|
|
455
|
+
if fingerprint not in seen_fingerprints:
|
|
456
|
+
seen_fingerprints.add(fingerprint)
|
|
457
|
+
unique_Z.append(normalized_permutation(Z_k, perms[0]))
|
|
458
|
+
idx_keep.append(k)
|
|
459
|
+
|
|
460
|
+
return unique_Z, idx_keep
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _sort_wT(wT: Union[sym.Matrix, np.ndarray]):
|
|
464
|
+
if not isinstance(wT, np.ndarray):
|
|
465
|
+
wT = np.array(wT)
|
|
466
|
+
keys = []
|
|
467
|
+
for i in range(wT.shape[0]):
|
|
468
|
+
keys.append(str(sum(wT[i, :] != 0)) +"_"+"-".join(wT[i, :].nonzero()[0].astype(str)))
|
|
469
|
+
|
|
470
|
+
return wT[np.argsort(keys)]
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def _maximize_wT(wT):
|
|
474
|
+
"""
|
|
475
|
+
Need to sort before sending in for accurate row accounting
|
|
476
|
+
Assumes all integer entries in wT
|
|
477
|
+
|
|
478
|
+
Args:
|
|
479
|
+
wT (_type_): _description_
|
|
480
|
+
|
|
481
|
+
Returns:
|
|
482
|
+
_type_: _description_
|
|
483
|
+
"""
|
|
484
|
+
|
|
485
|
+
# Make sure all integer values
|
|
486
|
+
# nz_min = np.min(np.abs(wT[np.nonzero(wT)]))
|
|
487
|
+
# wT = (wT/nz_min).astype(int)
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
# Sort to put rows with identical nz entries
|
|
491
|
+
# next to each other
|
|
492
|
+
wT = _sort_wT(wT)
|
|
493
|
+
|
|
494
|
+
# Identify rows with identical nonzero entries
|
|
495
|
+
nz_entries = [tuple(wT[i].nonzero()[0]) for i in range(wT.shape[0])]
|
|
496
|
+
swap_rows = []
|
|
497
|
+
segment = [0]
|
|
498
|
+
for i in range(1, wT.shape[0]):
|
|
499
|
+
if nz_entries[i] == nz_entries[i-1]:
|
|
500
|
+
segment.append(i)
|
|
501
|
+
else:
|
|
502
|
+
swap_rows.append(segment)
|
|
503
|
+
segment = [i]
|
|
504
|
+
swap_rows.append(segment)
|
|
505
|
+
|
|
506
|
+
# For a fixed set of column signs, the row signs that maximize the total
|
|
507
|
+
# sum are separable: each row must make its own signed row sum positive.
|
|
508
|
+
# A zero-sum row may take either sign, so choose its lexicographically
|
|
509
|
+
# larger representation. Rows with identical supports can then be sorted
|
|
510
|
+
# directly. This is equivalent to enumerating all row signs and row
|
|
511
|
+
# permutations, leaving only the much smaller column-sign search.
|
|
512
|
+
best_w = None
|
|
513
|
+
best_val = -np.inf
|
|
514
|
+
best_key = None
|
|
515
|
+
|
|
516
|
+
# Which columns to invert
|
|
517
|
+
for cols in itertools.product([1, -1], repeat=wT.shape[1]):
|
|
518
|
+
col_vec = np.array(cols).flatten()
|
|
519
|
+
column_signed = wT * col_vec[np.newaxis, :]
|
|
520
|
+
row_signs = []
|
|
521
|
+
signed_rows = []
|
|
522
|
+
for row in column_signed:
|
|
523
|
+
row_sum = int(np.sum(row))
|
|
524
|
+
if row_sum > 0:
|
|
525
|
+
row_sign = 1
|
|
526
|
+
elif row_sum < 0:
|
|
527
|
+
row_sign = -1
|
|
528
|
+
else:
|
|
529
|
+
positive_key = tuple(int(value) for value in row)
|
|
530
|
+
negative_key = tuple(-value for value in positive_key)
|
|
531
|
+
row_sign = 1 if positive_key >= negative_key else -1
|
|
532
|
+
row_signs.append(row_sign)
|
|
533
|
+
signed_rows.append(row_sign * row)
|
|
534
|
+
|
|
535
|
+
row_order = []
|
|
536
|
+
for row_segment in swap_rows:
|
|
537
|
+
row_order.extend(sorted(
|
|
538
|
+
row_segment,
|
|
539
|
+
key=lambda row_index: tuple(
|
|
540
|
+
int(value) for value in signed_rows[row_index]
|
|
541
|
+
),
|
|
542
|
+
reverse=True,
|
|
543
|
+
))
|
|
544
|
+
wT_perm = np.array(signed_rows)[row_order, :].astype(int)
|
|
545
|
+
val = int(np.sum(wT_perm))
|
|
546
|
+
key = tuple(int(value) for value in wT_perm.flatten())
|
|
547
|
+
if val > best_val or (val == best_val and key > best_key):
|
|
548
|
+
best_val = val
|
|
549
|
+
best_key = key
|
|
550
|
+
best_w = (
|
|
551
|
+
wT_perm.copy(),
|
|
552
|
+
np.array(row_signs).copy(),
|
|
553
|
+
col_vec.copy(),
|
|
554
|
+
row_order,
|
|
555
|
+
)
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
return best_w[0], best_key, best_w[1:]
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def _var_col_perms(var_types,
|
|
562
|
+
dyn_modes=["compact", "extended", "harmonic"],
|
|
563
|
+
nd_modes=["free", "frozen", "sigma"],
|
|
564
|
+
dyn_only=False):
|
|
565
|
+
|
|
566
|
+
mode_perms = []
|
|
567
|
+
for dyn_mode in dyn_modes:
|
|
568
|
+
if dyn_mode in var_types:
|
|
569
|
+
mode_perms.append(tuple(itertools.permutations(var_types[dyn_mode], len(var_types[dyn_mode]))))
|
|
570
|
+
|
|
571
|
+
if not dyn_only:
|
|
572
|
+
for nd_mode in nd_modes:
|
|
573
|
+
if nd_mode in var_types:
|
|
574
|
+
mode_perms.append((tuple(var_types[nd_mode]),))
|
|
575
|
+
|
|
576
|
+
perms = itertools.product(*mode_perms)
|
|
577
|
+
return [tuple(itertools.chain.from_iterable(perm)) for perm in perms]
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def _sub_equal_LC(X):
|
|
581
|
+
# All C the same, different from Cj
|
|
582
|
+
C = sym.symbols("C", positive=True, real=True)
|
|
583
|
+
Cj = sym.symbols("C_J", positive=True, real=True)
|
|
584
|
+
for x in X.free_symbols:
|
|
585
|
+
if "c" in str(x).lower() and "j" not in str(x).lower():
|
|
586
|
+
X = X.subs(x, C)
|
|
587
|
+
if "c" in str(x).lower() and "j" in str(x).lower():
|
|
588
|
+
X = X.subs(x, Cj)
|
|
589
|
+
# All L the same
|
|
590
|
+
L = sym.symbols("L", positive=True, real=True)
|
|
591
|
+
for x in X.free_symbols:
|
|
592
|
+
if "l" in str(x).lower():
|
|
593
|
+
X = X.subs(x, L)
|
|
594
|
+
return X
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
# Deterministic symbolic instantiation helper
|
|
598
|
+
def _find_Z_instance_deterministic(Z: sym.Matrix, var_list: list[sym.Symbol],
|
|
599
|
+
max_tries=5, nonzero=[], return_mapping=False):
|
|
600
|
+
"""
|
|
601
|
+
Deterministically substitute symbolic parameters in Z with
|
|
602
|
+
rational values guaranteeing (if possible) a nonzero det.
|
|
603
|
+
"""
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
ordered = sorted([v for v in Z.free_symbols if v in var_list], key=str)
|
|
609
|
+
if not ordered:
|
|
610
|
+
return Z
|
|
611
|
+
|
|
612
|
+
# Identify a valid assignment that yields a non-singular Z
|
|
613
|
+
nonzero = list(set(x for x in [sym.simplify(x) for x in nonzero + [_det_fast(Z)]] if len(x.free_symbols) > 0))
|
|
614
|
+
nonzero = [x for x in nonzero if any(v in x.free_symbols for v in ordered)]
|
|
615
|
+
_, res = _heuristic_upper_bound(ordered, nonzero, [], var_list, debug=False)
|
|
616
|
+
all_Z = []
|
|
617
|
+
for subs in res:
|
|
618
|
+
all_Z.append(Z.subs(subs["variables"]))
|
|
619
|
+
# Choose the transformation that maximizes the row stacked Z
|
|
620
|
+
# purely arbitrarily to break ties and behave deterministically
|
|
621
|
+
return max(all_Z, key=lambda Z: tuple(str(x) for x in tuple(Z)))
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
def _fixed_cost_plus_integer_cost(Z: Union[sym.Matrix, sym.Expr], var_list: list[sym.Expr],
|
|
625
|
+
var_types: dict, wJ: sym.Matrix, nonzero=[]):
|
|
626
|
+
n_nl = len(var_types.get("compact", [])) + len(var_types.get("extended", []))
|
|
627
|
+
|
|
628
|
+
# Variables to substitute concrete values in for
|
|
629
|
+
det = sym.simplify(_det_fast(Z), rational=True)
|
|
630
|
+
if det not in nonzero:
|
|
631
|
+
nonzero = nonzero + [det]
|
|
632
|
+
|
|
633
|
+
# Identify a valid assignment that yields a non-singular Z
|
|
634
|
+
# with all integer entries in wJ^T*Z
|
|
635
|
+
wJT_trans = wJ.transpose()*Z
|
|
636
|
+
|
|
637
|
+
# Identify nonzero entries in wJ^T*Z
|
|
638
|
+
nz_entries = {}
|
|
639
|
+
fixed_cost = 0
|
|
640
|
+
for i in range(wJT_trans.shape[0]):
|
|
641
|
+
for j in var_types.get("compact", []) + var_types.get("extended", []):
|
|
642
|
+
wJval = sym.simplify(wJT_trans[i,j])
|
|
643
|
+
if wJval != 0:
|
|
644
|
+
if len(wJval.free_symbols) == 0:
|
|
645
|
+
if sym.core.numbers.int_valued(wJval):
|
|
646
|
+
fixed_cost += abs(int(wJval))
|
|
647
|
+
else:
|
|
648
|
+
raise ValueError("Fixed Non Integer Present")
|
|
649
|
+
else:
|
|
650
|
+
nz_entries[(i,j)] = wJval
|
|
651
|
+
if len(nz_entries) == 0:
|
|
652
|
+
return fixed_cost, [], [], [], []
|
|
653
|
+
|
|
654
|
+
# Pass to z3 to solve for integer assignments
|
|
655
|
+
# while ensuring det(Z) != 0 and minimizing sum of abs values
|
|
656
|
+
nz_idx = sorted(nz_entries.keys(), key=lambda x: (x[0], x[1]))
|
|
657
|
+
integer_constraints = [nz_entries[(i,j)] for (i,j) in nz_idx]
|
|
658
|
+
nonzero_constraints = nonzero
|
|
659
|
+
var_list = set()
|
|
660
|
+
for expr in integer_constraints + nonzero_constraints:
|
|
661
|
+
var_list = var_list.union(expr.free_symbols)
|
|
662
|
+
var_list = sorted(var_list, key=str)
|
|
663
|
+
return fixed_cost, integer_constraints, nonzero_constraints, var_list, nz_idx
|
|
664
|
+
|
|
665
|
+
|
|
666
|
+
def _find_Z_min_cost(Z: Union[sym.Matrix, sym.Expr], var_list: list[sym.Expr],
|
|
667
|
+
var_types: dict, wJ: sym.Matrix, nonzero=[]):
|
|
668
|
+
fixed_cost, integer_constraints, nonzero_constraints, var_list, _ = _fixed_cost_plus_integer_cost(Z, var_list,
|
|
669
|
+
var_types, wJ, nonzero)
|
|
670
|
+
if integer_constraints == []:
|
|
671
|
+
return fixed_cost
|
|
672
|
+
variable_cost = _calc_min_cost(integer_constraints,nonzero_constraints,[],var_list)[0]
|
|
673
|
+
return fixed_cost + variable_cost
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
def _complete_graph_wjt_cost_certificate(Z: sym.Matrix, wJ: sym.Matrix,
|
|
677
|
+
n_nl: int) -> Optional[int]:
|
|
678
|
+
"""Return an exact L1 lower bound for a recognized complete-graph basis.
|
|
679
|
+
|
|
680
|
+
If ``wJ`` is the signed incidence matrix of the simple complete graph K_n,
|
|
681
|
+
its kernel is the one-dimensional common mode, the final columns of ``Z``
|
|
682
|
+
explicitly span that kernel, and all other columns are nonlinear dynamical
|
|
683
|
+
modes, then every dynamical column has integer edge differences with L1
|
|
684
|
+
norm at least the edge connectivity of K_n, namely ``n - 1``. Invertibility
|
|
685
|
+
prevents any such column from lying in the common-mode kernel. The bound
|
|
686
|
+
``(n - 1)^2`` is achievable only by singleton-cut columns; every basis made
|
|
687
|
+
from those columns belongs to one canonical row/column-sign orbit.
|
|
688
|
+
|
|
689
|
+
``None`` is returned unless every structural precondition is established
|
|
690
|
+
exactly. This deliberately narrow certificate is preferable to applying a
|
|
691
|
+
plausible graph bound to a transformation whose nullspace layout is not
|
|
692
|
+
known.
|
|
693
|
+
"""
|
|
694
|
+
if not isinstance(Z, sym.MatrixBase) or not isinstance(wJ, sym.MatrixBase):
|
|
695
|
+
return None
|
|
696
|
+
n_vertices = wJ.rows
|
|
697
|
+
if n_vertices < 2 or Z.rows != n_vertices or Z.cols != n_vertices:
|
|
698
|
+
return None
|
|
699
|
+
if n_nl != n_vertices - 1:
|
|
700
|
+
return None
|
|
701
|
+
|
|
702
|
+
expected_pairs = set(itertools.combinations(range(n_vertices), 2))
|
|
703
|
+
incidence_pairs = []
|
|
704
|
+
for column in range(wJ.cols):
|
|
705
|
+
nonzero = [row for row in range(n_vertices) if wJ[row, column] != 0]
|
|
706
|
+
if len(nonzero) != 2:
|
|
707
|
+
return None
|
|
708
|
+
values = {sym.simplify(wJ[row, column]) for row in nonzero}
|
|
709
|
+
if values != {sym.Integer(-1), sym.Integer(1)}:
|
|
710
|
+
return None
|
|
711
|
+
incidence_pairs.append(tuple(sorted(nonzero)))
|
|
712
|
+
if len(incidence_pairs) != len(expected_pairs):
|
|
713
|
+
return None
|
|
714
|
+
if set(incidence_pairs) != expected_pairs:
|
|
715
|
+
return None
|
|
716
|
+
|
|
717
|
+
kernel_columns = Z[:, n_nl:]
|
|
718
|
+
if kernel_columns.cols != 1 or kernel_columns.rank() != 1:
|
|
719
|
+
return None
|
|
720
|
+
kernel_image = wJ.transpose() * kernel_columns
|
|
721
|
+
if any(sym.simplify(value) != 0 for value in kernel_image):
|
|
722
|
+
return None
|
|
723
|
+
|
|
724
|
+
return (n_vertices - 1) ** 2
|
|
725
|
+
|
|
726
|
+
|
|
727
|
+
def _decomposed_complete_graph_wjt_cost_certificate(
|
|
728
|
+
Z: sym.Matrix, wJ: sym.Matrix, n_nl: int) -> Optional[int]:
|
|
729
|
+
"""Certify L1 cost for a direct sum of complete quotient-cut spaces.
|
|
730
|
+
|
|
731
|
+
A symbolic column may force some junction-edge differences to zero. Those
|
|
732
|
+
zero edges contract vertices. If the remaining quotient is a simple
|
|
733
|
+
complete graph K_m, any nonconstant integer potential on that column costs
|
|
734
|
+
at least ``m - 1``. This routine accepts a collection of such column
|
|
735
|
+
spaces only when each K_m has exactly ``m - 1`` columns and their potential
|
|
736
|
+
spaces form a direct decomposition modulo the common mode. Under those
|
|
737
|
+
conditions the minimum bases are products of singleton-cut bases and form
|
|
738
|
+
one canonical row/column-sign orbit.
|
|
739
|
+
|
|
740
|
+
The recognition rules are intentionally strict; unrecognized layouts fall
|
|
741
|
+
back to the general Z3 search.
|
|
742
|
+
"""
|
|
743
|
+
complete_bound = _complete_graph_wjt_cost_certificate(Z, wJ, n_nl)
|
|
744
|
+
if complete_bound is not None:
|
|
745
|
+
return complete_bound
|
|
746
|
+
|
|
747
|
+
if not isinstance(Z, sym.MatrixBase) or not isinstance(wJ, sym.MatrixBase):
|
|
748
|
+
return None
|
|
749
|
+
n_vertices = wJ.rows
|
|
750
|
+
if (n_vertices < 2 or Z.rows != n_vertices or Z.cols != n_vertices
|
|
751
|
+
or n_nl != n_vertices - 1):
|
|
752
|
+
return None
|
|
753
|
+
|
|
754
|
+
edges = []
|
|
755
|
+
for column in range(wJ.cols):
|
|
756
|
+
nonzero = [row for row in range(n_vertices) if wJ[row, column] != 0]
|
|
757
|
+
if len(nonzero) != 2:
|
|
758
|
+
return None
|
|
759
|
+
values = {sym.simplify(wJ[row, column]) for row in nonzero}
|
|
760
|
+
if values != {sym.Integer(-1), sym.Integer(1)}:
|
|
761
|
+
return None
|
|
762
|
+
edges.append(tuple(sorted(nonzero)))
|
|
763
|
+
if len(set(edges)) != len(edges) or wJ.transpose().rank() != n_vertices - 1:
|
|
764
|
+
return None
|
|
765
|
+
|
|
766
|
+
kernel_columns = Z[:, n_nl:]
|
|
767
|
+
if kernel_columns.cols != 1 or kernel_columns.rank() != 1:
|
|
768
|
+
return None
|
|
769
|
+
if any(sym.simplify(value) != 0
|
|
770
|
+
for value in wJ.transpose() * kernel_columns):
|
|
771
|
+
return None
|
|
772
|
+
|
|
773
|
+
wJT = sym.simplify(wJ.transpose() * Z[:, :n_nl])
|
|
774
|
+
groups = {}
|
|
775
|
+
total_bound = 0
|
|
776
|
+
for dynamic_column in range(n_nl):
|
|
777
|
+
parent = list(range(n_vertices))
|
|
778
|
+
|
|
779
|
+
def find(vertex):
|
|
780
|
+
while parent[vertex] != vertex:
|
|
781
|
+
parent[vertex] = parent[parent[vertex]]
|
|
782
|
+
vertex = parent[vertex]
|
|
783
|
+
return vertex
|
|
784
|
+
|
|
785
|
+
def union(left, right):
|
|
786
|
+
left_root, right_root = find(left), find(right)
|
|
787
|
+
if left_root != right_root:
|
|
788
|
+
parent[right_root] = left_root
|
|
789
|
+
|
|
790
|
+
for edge_index, (left, right) in enumerate(edges):
|
|
791
|
+
if sym.simplify(wJT[edge_index, dynamic_column]) == 0:
|
|
792
|
+
union(left, right)
|
|
793
|
+
|
|
794
|
+
roots = [find(vertex) for vertex in range(n_vertices)]
|
|
795
|
+
root_order = {root: index for index, root in enumerate(dict.fromkeys(roots))}
|
|
796
|
+
partition = tuple(root_order[root] for root in roots)
|
|
797
|
+
n_quotient_vertices = len(root_order)
|
|
798
|
+
if n_quotient_vertices < 2:
|
|
799
|
+
return None
|
|
800
|
+
|
|
801
|
+
quotient_edges = []
|
|
802
|
+
for edge_index, (left, right) in enumerate(edges):
|
|
803
|
+
left_part, right_part = partition[left], partition[right]
|
|
804
|
+
expression = sym.simplify(wJT[edge_index, dynamic_column])
|
|
805
|
+
if left_part == right_part:
|
|
806
|
+
if expression != 0:
|
|
807
|
+
return None
|
|
808
|
+
continue
|
|
809
|
+
if expression == 0:
|
|
810
|
+
return None
|
|
811
|
+
quotient_edges.append(tuple(sorted((left_part, right_part))))
|
|
812
|
+
expected_edges = set(itertools.combinations(range(n_quotient_vertices), 2))
|
|
813
|
+
if (len(quotient_edges) != len(expected_edges)
|
|
814
|
+
or set(quotient_edges) != expected_edges):
|
|
815
|
+
return None
|
|
816
|
+
|
|
817
|
+
groups.setdefault(partition, []).append(dynamic_column)
|
|
818
|
+
total_bound += n_quotient_vertices - 1
|
|
819
|
+
|
|
820
|
+
subspace_columns = [sym.ones(n_vertices, 1)]
|
|
821
|
+
expected_dimension = 1
|
|
822
|
+
for partition, columns in groups.items():
|
|
823
|
+
n_parts = max(partition) + 1
|
|
824
|
+
if len(columns) != n_parts - 1:
|
|
825
|
+
return None
|
|
826
|
+
expected_dimension += n_parts - 1
|
|
827
|
+
for part in range(n_parts - 1):
|
|
828
|
+
subspace_columns.append(sym.Matrix([
|
|
829
|
+
int(vertex_part == part) for vertex_part in partition
|
|
830
|
+
]))
|
|
831
|
+
if expected_dimension != n_vertices:
|
|
832
|
+
return None
|
|
833
|
+
if sym.Matrix.hstack(*subspace_columns).rank() != n_vertices:
|
|
834
|
+
return None
|
|
835
|
+
|
|
836
|
+
return total_bound
|
|
837
|
+
|
|
838
|
+
|
|
839
|
+
def _find_Z_instance(Z: Union[sym.Matrix, sym.Expr], var_list: list[sym.Expr],
|
|
840
|
+
var_types: dict, wJ: sym.Matrix, nonzero=[],
|
|
841
|
+
apriori_sol=None, debug=False):
|
|
842
|
+
|
|
843
|
+
# If no variables, just return
|
|
844
|
+
if len(Z.free_symbols) == 0:
|
|
845
|
+
return Z
|
|
846
|
+
|
|
847
|
+
n_nl = len(var_types.get("compact", [])) + len(var_types.get("extended", []))
|
|
848
|
+
|
|
849
|
+
# Variables to substitute concrete values in for
|
|
850
|
+
det = sym.simplify(_det_fast(Z), rational=True)
|
|
851
|
+
if det not in nonzero:
|
|
852
|
+
nonzero = nonzero + [det]
|
|
853
|
+
|
|
854
|
+
# No nonzero entries in wJ or no nonlinear variables
|
|
855
|
+
if wJ.shape[0] == 0 or n_nl == 0:
|
|
856
|
+
return _find_Z_instance_deterministic(Z, var_list, max_tries=100, nonzero=nonzero)
|
|
857
|
+
|
|
858
|
+
# Identify a valid assignment that yields a non-singular Z
|
|
859
|
+
# with all integer entries in wJ^T*Z
|
|
860
|
+
ext = var_types.get("extended", [])
|
|
861
|
+
wJT_trans = sym.simplify(wJ.transpose()*Z)
|
|
862
|
+
# Nothing to solve for
|
|
863
|
+
if len(wJT_trans.free_symbols) == 0:
|
|
864
|
+
return _find_Z_instance_deterministic(Z, var_list, max_tries=100, nonzero=nonzero)
|
|
865
|
+
|
|
866
|
+
fixed_cost, integer_constraints, nonzero_constraints, var_list, nz_idx = _fixed_cost_plus_integer_cost(Z, var_list,
|
|
867
|
+
var_types, wJ, nonzero)
|
|
868
|
+
total_cost_certificate = _decomposed_complete_graph_wjt_cost_certificate(
|
|
869
|
+
Z, wJ, n_nl
|
|
870
|
+
)
|
|
871
|
+
variable_cost_certificate = None
|
|
872
|
+
canonical_optimum_is_unique = False
|
|
873
|
+
if total_cost_certificate is not None:
|
|
874
|
+
variable_cost_certificate = max(0, total_cost_certificate - fixed_cost)
|
|
875
|
+
canonical_optimum_is_unique = True
|
|
876
|
+
# Encode symmetry map of row swaps, column sign flips, and row sign flips
|
|
877
|
+
n_terms = len(nz_idx)
|
|
878
|
+
max_row = max(i for (i,j) in nz_idx)
|
|
879
|
+
min_col = min(j for (i,j) in nz_idx)
|
|
880
|
+
max_col = max(j for (i,j) in nz_idx)
|
|
881
|
+
perms = []
|
|
882
|
+
# Make a list of all possible column sign flips,
|
|
883
|
+
# this seems to be the main symmetry in Z3 solutions
|
|
884
|
+
valid_perms = set()
|
|
885
|
+
for row_perm in [range(max_row+1)]:
|
|
886
|
+
new_order = []
|
|
887
|
+
new_nz_idx = [(row_perm[i], j) for (i,j) in nz_idx]
|
|
888
|
+
new_order = sorted(range(n_terms), key=lambda x: (new_nz_idx[x][0], new_nz_idx[x][1]))
|
|
889
|
+
for row_signs in [[1]*(max_row+1)]:
|
|
890
|
+
for col_signs in itertools.product([1, -1], repeat=max_col-min_col+1):
|
|
891
|
+
sign_map = {(i,j): row_signs[i]*col_signs[j - min_col] for (i,j) in nz_idx}
|
|
892
|
+
this_perm = tuple((new_order[k], sign_map[nz_idx[k]]) for k in range(n_terms))
|
|
893
|
+
valid_perms.add(this_perm)
|
|
894
|
+
valid_perms = sorted(valid_perms, key=str)
|
|
895
|
+
def _symmetry_perms(terms):
|
|
896
|
+
perms = []
|
|
897
|
+
for v_perm in valid_perms:
|
|
898
|
+
new_terms = []
|
|
899
|
+
for (idx, sign) in v_perm:
|
|
900
|
+
new_terms.append(sign*terms[idx])
|
|
901
|
+
perms.append(new_terms)
|
|
902
|
+
return perms
|
|
903
|
+
|
|
904
|
+
# Try to find solutions with increasing search space
|
|
905
|
+
for max_result_range in [4, 10]:
|
|
906
|
+
if debug:
|
|
907
|
+
print("Trying max result range:", max_result_range)
|
|
908
|
+
print("for transformation", Z)
|
|
909
|
+
if apriori_sol is None:
|
|
910
|
+
all_sols = find_rational_vars_integer_results(integer_constraints,
|
|
911
|
+
nonzero_constraints, [], var_list,
|
|
912
|
+
heuristic_upper=True,
|
|
913
|
+
symmetry_map=_symmetry_perms,
|
|
914
|
+
max_result_range=max_result_range,
|
|
915
|
+
debug=debug,
|
|
916
|
+
proven_lower_bound=variable_cost_certificate,
|
|
917
|
+
accept_heuristic_optimum=canonical_optimum_is_unique)
|
|
918
|
+
else:
|
|
919
|
+
all_sols = find_rational_vars_integer_results(integer_constraints,
|
|
920
|
+
nonzero_constraints, [], var_list,
|
|
921
|
+
apriori_sol=apriori_sol-fixed_cost,
|
|
922
|
+
heuristic_upper=False,
|
|
923
|
+
symmetry_map=_symmetry_perms,
|
|
924
|
+
max_result_range=max_result_range,
|
|
925
|
+
debug=debug,
|
|
926
|
+
proven_lower_bound=variable_cost_certificate)
|
|
927
|
+
if all_sols or apriori_sol is not None:
|
|
928
|
+
break
|
|
929
|
+
|
|
930
|
+
# Can't beat apriori solution
|
|
931
|
+
if all_sols == []:
|
|
932
|
+
return []
|
|
933
|
+
|
|
934
|
+
# Identify best solution by wJ^T canonicalization
|
|
935
|
+
# Minimize L1 norm, with tiebreaker being max term
|
|
936
|
+
min_key = tuple()
|
|
937
|
+
best_s = None
|
|
938
|
+
for sol in all_sols:
|
|
939
|
+
s = sol["variables"]
|
|
940
|
+
wJT_subs = sym.simplify(wJT_trans.subs(s))
|
|
941
|
+
_, wMax, _ = _maximize_wT(wJT_subs[:, :n_nl])
|
|
942
|
+
n_val = sum(abs(int(x)) for x in wMax)
|
|
943
|
+
max_n_val = max(abs(int(x)) for x in wMax)
|
|
944
|
+
key = (n_val, max_n_val, wMax)
|
|
945
|
+
if key < min_key or min_key == tuple():
|
|
946
|
+
min_key = key
|
|
947
|
+
best_s = s
|
|
948
|
+
if best_s is None:
|
|
949
|
+
return None
|
|
950
|
+
Zsubs = Z.subs(best_s)
|
|
951
|
+
to_sub = [x for x in var_list if x in Zsubs.free_symbols]
|
|
952
|
+
if len(to_sub) > 0:
|
|
953
|
+
Zsubs = _find_Z_instance_deterministic(Zsubs, to_sub, max_tries=100, nonzero=nonzero)
|
|
954
|
+
|
|
955
|
+
return Zsubs
|
|
956
|
+
|
|
957
|
+
|
|
958
|
+
def compact_well_aligned(wT: sym.Matrix, n_c: int):
|
|
959
|
+
|
|
960
|
+
# Nothing to worry about here
|
|
961
|
+
if n_c == 0:
|
|
962
|
+
return True
|
|
963
|
+
|
|
964
|
+
wc = wT[:, :n_c]
|
|
965
|
+
rows, cols = wc.shape
|
|
966
|
+
|
|
967
|
+
# 1 periodic variable -- is there a 1 or -1 there
|
|
968
|
+
# and all other entries are integers (i.e. same periodicity)
|
|
969
|
+
if n_c == 1:
|
|
970
|
+
nz_entries = [sym.Abs(wc[i,0]) for i in range(rows) if wc[i,0].is_nonzero]
|
|
971
|
+
if len(nz_entries) == 0:
|
|
972
|
+
return False
|
|
973
|
+
elif 1 in nz_entries and all(x.is_integer for x in nz_entries):
|
|
974
|
+
return True
|
|
975
|
+
else:
|
|
976
|
+
return False
|
|
977
|
+
|
|
978
|
+
# 2 or more periodic variables --
|
|
979
|
+
# Does each compact variable have at least one junction that
|
|
980
|
+
# depends on it alone (among compact variables)
|
|
981
|
+
# And do all the other rows have only integer entries
|
|
982
|
+
else:
|
|
983
|
+
# Select all rows with a single 1/-1 and rest 0's
|
|
984
|
+
e_rows = []
|
|
985
|
+
for i in range(wc.shape[0]):
|
|
986
|
+
nz_entries = [sym.Abs(wc[i,j]) for j in range(cols) if wc[i,j].is_nonzero]
|
|
987
|
+
if len(nz_entries) == 0:
|
|
988
|
+
continue
|
|
989
|
+
if len(nz_entries) == 1 and nz_entries[0] == 1:
|
|
990
|
+
e_rows.append(i)
|
|
991
|
+
elif any(not x.is_integer for x in nz_entries):
|
|
992
|
+
return False
|
|
993
|
+
# Check if all the single entry rows span the
|
|
994
|
+
# number of compact variables: yes->well aligned
|
|
995
|
+
return len(_linearly_indep_rows(wc[e_rows, :])) == n_c
|
|
996
|
+
|
|
997
|
+
|
|
998
|
+
def compact_alignment_transformation(wT:sym.Matrix, n_c:int):
|
|
999
|
+
|
|
1000
|
+
wc = wT[:, :n_c]
|
|
1001
|
+
all_Zc = []
|
|
1002
|
+
|
|
1003
|
+
# Consider unchanged if it works
|
|
1004
|
+
if compact_well_aligned(wc, n_c):
|
|
1005
|
+
all_Zc.append(sym.eye(n_c))
|
|
1006
|
+
|
|
1007
|
+
# Try all different linearly independent row combinations
|
|
1008
|
+
row_sets = _linearly_indep_row_sets(wc)
|
|
1009
|
+
for rows in row_sets:
|
|
1010
|
+
# Get the appropriate transformation for each set
|
|
1011
|
+
Zc = wc[rows, :].pinv()
|
|
1012
|
+
# Verify it's well-aligned
|
|
1013
|
+
if compact_well_aligned(wc*Zc, n_c):
|
|
1014
|
+
if len(_find_equiv_mats(Zc, all_Zc, shifts=[])) == 0:
|
|
1015
|
+
all_Zc.append(Zc)
|
|
1016
|
+
|
|
1017
|
+
# Return all possible transformations
|
|
1018
|
+
all_Z = []
|
|
1019
|
+
for Zc in all_Zc:
|
|
1020
|
+
Z = sym.eye(wT.shape[1])
|
|
1021
|
+
Z[:n_c, :n_c] = Zc
|
|
1022
|
+
all_Z.append(Z)
|
|
1023
|
+
|
|
1024
|
+
return all_Z
|
|
1025
|
+
|
|
1026
|
+
|
|
1027
|
+
def H_hash(cTransInv, lTrans, wJtTrans, EJ, var_types, try_perms = True, extra_nl:bool=False):
|
|
1028
|
+
"""
|
|
1029
|
+
Produces a hash that represents in the specified basis
|
|
1030
|
+
|
|
1031
|
+
1) a = [nCompact][nExtended][nHarmonic]
|
|
1032
|
+
2) b = number of nonzero entries in L + number of nonzero entries in C
|
|
1033
|
+
3) c = positions of nonzero inductive intermode coupling (= 0 -> 0, != 0 -> 1)
|
|
1034
|
+
4) d = base 2 positions of nonzero capacitive intermode coupling (= 0 -> 0, != 0 -> 1)
|
|
1035
|
+
5) e = wJ_trans in canonical form, in base 3 (-1 -> 0, 0 -> 1, 1 -> 2)
|
|
1036
|
+
Swapping columns to maximize:
|
|
1037
|
+
|
|
1038
|
+
hash = a_b_c_d_e (ex: 3_511_012)
|
|
1039
|
+
|
|
1040
|
+
Keeps the variable transformation that minimizes the hash,
|
|
1041
|
+
after trying all possible permutations of the columns
|
|
1042
|
+
corresponding to different variable types.
|
|
1043
|
+
|
|
1044
|
+
Args:
|
|
1045
|
+
circuit (_type_): _description_
|
|
1046
|
+
edges (_type_): _description_
|
|
1047
|
+
symmetric (bool, optional): _description_. Defaults to True.
|
|
1048
|
+
numerical (bool, optional):
|
|
1049
|
+
eps (float, optional):
|
|
1050
|
+
"""
|
|
1051
|
+
|
|
1052
|
+
# Record number of modes
|
|
1053
|
+
n_nodes = len(functools.reduce(lambda a,b: a+b, var_types.values(), []))
|
|
1054
|
+
ext_var = var_types.get("extended", [])
|
|
1055
|
+
n_ext = len(ext_var)
|
|
1056
|
+
comp_var = var_types.get("compact", [])
|
|
1057
|
+
n_comp = len(comp_var)
|
|
1058
|
+
harm_var = var_types.get("harmonic", [])
|
|
1059
|
+
n_harm = len(harm_var)
|
|
1060
|
+
mode_str = f"{n_comp}{n_ext}{n_harm}"
|
|
1061
|
+
n_nd = n_nodes - n_ext - n_comp - n_harm
|
|
1062
|
+
n_dyn = n_nodes - n_nd
|
|
1063
|
+
n_nl = n_ext + n_comp
|
|
1064
|
+
|
|
1065
|
+
# Truncate to just the dynamical modes
|
|
1066
|
+
L_tilde = lTrans[:n_dyn, :n_dyn]
|
|
1067
|
+
cTransInv = cTransInv[:n_dyn, :n_dyn]
|
|
1068
|
+
wJ = wJtTrans[:, :n_dyn]
|
|
1069
|
+
|
|
1070
|
+
# All different ways to arrange column permutations in Z
|
|
1071
|
+
# that preserve variable types
|
|
1072
|
+
# Try all permutations of dynamical modes only
|
|
1073
|
+
# Note: column shift in Z is row and column shift in L, C
|
|
1074
|
+
# For permutation P and Z, the transformed L2 is
|
|
1075
|
+
# as L2 = (Z*P)^T * L * (Z*P) = P^T * Z^T * L * Z * P
|
|
1076
|
+
# C2inv is
|
|
1077
|
+
# C2inv = [(Z*P)^T * C * (Z*P)]^-1 = (Z*P)^-1 * C^-1 * (Z*P)^T^-1
|
|
1078
|
+
# = P^-1 * Z^-1 * C^-1 * Z^T^-1 * P^T^-1
|
|
1079
|
+
# Recall that P^-1 = P^T for permutation matrices
|
|
1080
|
+
# For wJ^T, we have
|
|
1081
|
+
# wJt2^T = wJ^T * (Z*P) = (wJ^T*Z) * P
|
|
1082
|
+
if try_perms:
|
|
1083
|
+
perms = _var_col_perms(var_types, dyn_only=True)
|
|
1084
|
+
perms = [p[:n_dyn] for p in perms]
|
|
1085
|
+
else:
|
|
1086
|
+
perms = [tuple(range(n_dyn))]
|
|
1087
|
+
|
|
1088
|
+
lowest_hash = ""
|
|
1089
|
+
lowest_perm = tuple(range(n_nodes))
|
|
1090
|
+
for perm in perms:
|
|
1091
|
+
|
|
1092
|
+
L_key = (_nonzero_entries_str(lTrans[perm, perm]),)
|
|
1093
|
+
C_key = (_nonzero_entries_str(cTransInv[perm, perm]),)
|
|
1094
|
+
w_key = (_incidence_square_nonzero_str(
|
|
1095
|
+
wJtTrans[:, perm].transpose(), EJ
|
|
1096
|
+
),)
|
|
1097
|
+
if extra_nl and n_nl > 0:
|
|
1098
|
+
wT_tilde, wT_key_full, _ = _maximize_wT(_sort_wT(wJtTrans[:, perm][:, :n_nl]))
|
|
1099
|
+
n_val = sum(abs(x) for x in wT_key_full)
|
|
1100
|
+
max_n_val = max(abs(x) for x in wT_key_full)
|
|
1101
|
+
w_key += (n_val, max_n_val, wT_key_full)
|
|
1102
|
+
|
|
1103
|
+
|
|
1104
|
+
# Make the hash string
|
|
1105
|
+
Z_hash = (mode_str,) + w_key + (int(L_key[0][0])+int(C_key[0][0]),) + L_key + C_key
|
|
1106
|
+
if lowest_hash == "" or Z_hash < lowest_hash:
|
|
1107
|
+
lowest_hash = Z_hash
|
|
1108
|
+
lowest_perm = perm + tuple(range(n_dyn, n_nodes))
|
|
1109
|
+
|
|
1110
|
+
return lowest_hash, lowest_perm
|
|
1111
|
+
|
|
1112
|
+
|
|
1113
|
+
def incidence_to_square(w, vals):
|
|
1114
|
+
mat = sym.Matrix(np.zeros((w.shape[0], w.shape[0])))
|
|
1115
|
+
for j in range(w.shape[1]):
|
|
1116
|
+
mat += vals[j]*w[:, j]*w[:, j].transpose()
|
|
1117
|
+
return mat
|
|
1118
|
+
|
|
1119
|
+
|
|
1120
|
+
def _generate_block_transformation(var_types: dict[str, list[int]], trans_blocks: list[list[int]], prefix="Z",
|
|
1121
|
+
return_full=True):
|
|
1122
|
+
|
|
1123
|
+
# Record mode types
|
|
1124
|
+
comp = var_types.get("compact", [])
|
|
1125
|
+
n_comp = len(comp)
|
|
1126
|
+
ext = var_types.get("extended", [])
|
|
1127
|
+
n_ext = len(ext)
|
|
1128
|
+
harm = var_types.get("harmonic", [])
|
|
1129
|
+
n_harm = len(harm)
|
|
1130
|
+
n_d = n_comp + n_ext + n_harm
|
|
1131
|
+
n_nd = len(var_types.get("free", []) + var_types.get("frozen", []) + var_types.get("sigma", []))
|
|
1132
|
+
mode_vec = [comp, ext, harm]
|
|
1133
|
+
|
|
1134
|
+
# Create symbolic variables for transformation
|
|
1135
|
+
var_list = []
|
|
1136
|
+
Z_blocks = []
|
|
1137
|
+
Z = sym.eye(n_d+n_nd)
|
|
1138
|
+
var_list = []
|
|
1139
|
+
for block_i, block_j in itertools.product(range(3), range(3)):
|
|
1140
|
+
if trans_blocks[block_i][block_j]:
|
|
1141
|
+
for i in mode_vec[block_i]:
|
|
1142
|
+
for j in mode_vec[block_j]:
|
|
1143
|
+
Z[i, j] = sym.Symbol(f"{prefix}{i}{j}")
|
|
1144
|
+
var_list.append(Z[i,j])
|
|
1145
|
+
|
|
1146
|
+
if return_full:
|
|
1147
|
+
return Z, var_list
|
|
1148
|
+
else:
|
|
1149
|
+
return Z[:n_d, :n_d], var_list
|
|
1150
|
+
|
|
1151
|
+
|
|
1152
|
+
def secondary_decouple(var_types: dict[str, list[int]], mats: list[sym.Matrix], invert: list[bool], **kwargs):
|
|
1153
|
+
"""
|
|
1154
|
+
Performs a secondary decoupling transformation of
|
|
1155
|
+
the form
|
|
1156
|
+
[ I Z_ce 0 0 ]
|
|
1157
|
+
[ 0 Z_e 0 0 ]
|
|
1158
|
+
[ 0 Z_eh Z_hh 0 ]
|
|
1159
|
+
[ 0 0 0 I ]
|
|
1160
|
+
that maximizes the number of nonzero off diagonal elements in the
|
|
1161
|
+
transformed susceptance and inverse capacitance matrices.
|
|
1162
|
+
In case of a tie in number, prefers fewer inductive terms,
|
|
1163
|
+
in line with H_hash.
|
|
1164
|
+
|
|
1165
|
+
The form of the transformation can be adjusted via the trans_blocks kwarg.
|
|
1166
|
+
|
|
1167
|
+
Args:
|
|
1168
|
+
var_types (dict[str, list[int]]): Dictionary mapping mode type to a list
|
|
1169
|
+
of indices that are that mode.
|
|
1170
|
+
mats (list[sym.Matrix]): List of matrices to decouple
|
|
1171
|
+
invert (list[bool]): List of whether to invert each matrix in mats
|
|
1172
|
+
return_instance: bool
|
|
1173
|
+
If there are free parameters in the final transformation,
|
|
1174
|
+
substitute in actual values to get a concrete instance.
|
|
1175
|
+
Defaults to False.
|
|
1176
|
+
kwargs:
|
|
1177
|
+
Z_in (sym.Matrix): Possible initial secondary transformation
|
|
1178
|
+
trans_blocks (list[list[int]]): Blocks of the transformation
|
|
1179
|
+
rows/columns correspond to
|
|
1180
|
+
[compact, extended, harmonic]
|
|
1181
|
+
non-dynamical modes are not transformed
|
|
1182
|
+
prefix (str): Prefix for symbolic variables in the transformation.
|
|
1183
|
+
param_symbols (list[str]): List of strings to identify
|
|
1184
|
+
system parameters in the matrices.
|
|
1185
|
+
Defaults to ["C", "L", "J"].
|
|
1186
|
+
tiebreaker_fn (callable): Function that takes a set of keys
|
|
1187
|
+
and returns a sortable item
|
|
1188
|
+
when choosing transformations.
|
|
1189
|
+
names (list[str]): circuit_quantization: a label for each matrix in mats,
|
|
1190
|
+
used in the term keys (name, i, j). Defaults to "0", "1", ...
|
|
1191
|
+
row_mats (list[sym.Matrix]): circuit_quantization: rectangular matrices M with one
|
|
1192
|
+
column per mode, such as the junction incidence omega_J^T,
|
|
1193
|
+
transformed as M Z rather than by congruence. Their entries
|
|
1194
|
+
(k, j) in noncompact columns j are decoupling terms, after
|
|
1195
|
+
those of mats; compact columns are fixed by the alignment.
|
|
1196
|
+
row_names (list[str]): circuit_quantization: labels for row_mats in the term keys.
|
|
1197
|
+
Defaults to "R0", "R1", ...
|
|
1198
|
+
pattern_order (callable): circuit_quantization: takes the term keys, one
|
|
1199
|
+
(name, i, j) per off-diagonal entry in mats order,
|
|
1200
|
+
and returns (cost, term indices) candidates for
|
|
1201
|
+
maximally_compatible_sol in non-decreasing cost.
|
|
1202
|
+
Defaults to largest subsets first.
|
|
1203
|
+
|
|
1204
|
+
Returns:
|
|
1205
|
+
sym.Matrix: Secondary transformation
|
|
1206
|
+
"""
|
|
1207
|
+
### process kwargs
|
|
1208
|
+
# Blocks of the transformation
|
|
1209
|
+
# rows/columns correspond to [compact, extended, harmonic]
|
|
1210
|
+
# non-dynamical modes are not transformed
|
|
1211
|
+
trans_blocks = kwargs.get("trans_blocks", [[0, 1, 0],
|
|
1212
|
+
[0, 1, 0],
|
|
1213
|
+
[0, 1, 1]])
|
|
1214
|
+
return_tiebreaker = kwargs.get("return_tiebreaker", False)
|
|
1215
|
+
Z_in = kwargs.get("Z_in", None)
|
|
1216
|
+
prefix = kwargs.get("prefix", "Z")
|
|
1217
|
+
param_symbols = kwargs.get("param_symbols", ["C", "L", "J"])
|
|
1218
|
+
|
|
1219
|
+
debug = kwargs.get("debug", False)
|
|
1220
|
+
names = kwargs.get("names", [str(k) for k in range(len(mats))])
|
|
1221
|
+
row_mats = kwargs.get("row_mats", [])
|
|
1222
|
+
row_names = kwargs.get("row_names", [f"R{k}" for k in range(len(row_mats))])
|
|
1223
|
+
pattern_order = kwargs.get("pattern_order", None)
|
|
1224
|
+
|
|
1225
|
+
# Record mode types
|
|
1226
|
+
comp = var_types.get("compact", [])
|
|
1227
|
+
n_comp = len(comp)
|
|
1228
|
+
ext = var_types.get("extended", [])
|
|
1229
|
+
n_ext = len(ext)
|
|
1230
|
+
harm = var_types.get("harmonic", [])
|
|
1231
|
+
n_harm = len(harm)
|
|
1232
|
+
n_d = n_comp + n_harm + n_ext
|
|
1233
|
+
mode_vec = [comp, ext, harm]
|
|
1234
|
+
tiebreaker_fn = kwargs.get("tiebreaker_fn", lambda keys: "".join(["0" if i in keys else "1" for i in range(n_d*(n_d-1)//2)]))
|
|
1235
|
+
|
|
1236
|
+
|
|
1237
|
+
# Generate Possible Transformation
|
|
1238
|
+
if Z_in is None:
|
|
1239
|
+
Z, var_list = _generate_block_transformation(var_types, trans_blocks, prefix=prefix)
|
|
1240
|
+
else:
|
|
1241
|
+
Z = Z_in
|
|
1242
|
+
var_list = [x for x in Z.free_symbols if prefix in str(x)]
|
|
1243
|
+
# Sort variable list for consistent substitution
|
|
1244
|
+
var_list.sort(key=lambda s: s.name)
|
|
1245
|
+
|
|
1246
|
+
# Transform matrices and invert as needed
|
|
1247
|
+
to_decouple = []
|
|
1248
|
+
for mat, inv in zip(mats, invert):
|
|
1249
|
+
transformed = Z[:n_d, :n_d].transpose()*mat[:n_d, :n_d]*Z[:n_d, :n_d]
|
|
1250
|
+
if inv:
|
|
1251
|
+
if transformed.shape[0] > 1:
|
|
1252
|
+
to_decouple.append(sym.inv_quick(transformed))
|
|
1253
|
+
else:
|
|
1254
|
+
to_decouple.append(transformed.inv())
|
|
1255
|
+
else:
|
|
1256
|
+
to_decouple.append(transformed)
|
|
1257
|
+
|
|
1258
|
+
# Symmetric coupling -> only consider upper triangle
|
|
1259
|
+
pairs = [(i, j) for (i, j) in itertools.product(range(n_d), repeat=2) if i < j]
|
|
1260
|
+
targets = [(name, trMat, pairs) for name, trMat in zip(names, to_decouple)]
|
|
1261
|
+
# circuit_quantization: rectangular matrices, entry by entry in noncompact columns
|
|
1262
|
+
noncompact = [j for j in range(n_d) if j not in comp]
|
|
1263
|
+
for name, mat in zip(row_names, row_mats):
|
|
1264
|
+
trMat = mat[:, :n_d]*Z[:n_d, :n_d]
|
|
1265
|
+
targets.append((name, trMat, [(k, j) for k in range(trMat.rows) for j in noncompact]))
|
|
1266
|
+
coupling = []
|
|
1267
|
+
term_keys = [] # (name, i, j) for each entry of coupling
|
|
1268
|
+
zero_keys = []
|
|
1269
|
+
count = 0
|
|
1270
|
+
|
|
1271
|
+
for name, trMat, entries in targets:
|
|
1272
|
+
for (i, j) in entries:
|
|
1273
|
+
term_keys.append((name, i, j))
|
|
1274
|
+
vars_in_eq = [v for v in var_list if v in trMat[i, j].free_symbols]
|
|
1275
|
+
# If it takes more than 1 second to determine equations for decoupling, then
|
|
1276
|
+
# assume it's unsolvable and move on to avoid long computation times
|
|
1277
|
+
ans = utils.run_with_timeout(eq_indep_of_vars, (trMat[i, j], vars_in_eq), timeout=1/60)
|
|
1278
|
+
count += 1
|
|
1279
|
+
if ans is None:
|
|
1280
|
+
coupling.append([])
|
|
1281
|
+
else:
|
|
1282
|
+
eqs, denom = ans
|
|
1283
|
+
if not eqs:
|
|
1284
|
+
zero_keys.append(count)
|
|
1285
|
+
coupling.append(eqs)
|
|
1286
|
+
|
|
1287
|
+
# Nothing to decouple
|
|
1288
|
+
if all(eq == [] for eq in coupling):
|
|
1289
|
+
if return_tiebreaker:
|
|
1290
|
+
return [Z], [tiebreaker_fn(zero_keys)]
|
|
1291
|
+
else:
|
|
1292
|
+
return [Z]
|
|
1293
|
+
|
|
1294
|
+
# We want to keep det(Z) nonzero. Consider least common multiple
|
|
1295
|
+
# of denominators in Z to clear fractions Z*LCM = Z' (integer matrix)
|
|
1296
|
+
# Z^-1 = 1/det(Z) * adj(Z) ->
|
|
1297
|
+
# Z^-1 = (Z'/LCM)^-1 = LCM*Z'^-1 = LCM/det(Z') * adj(Z')
|
|
1298
|
+
# So we want to keep det(Z)/LCM nonzero, as well as LCM itself
|
|
1299
|
+
# Similarly, (Z.T C Z) ^-1 = Z.T^-1 C^-1 Z^-1
|
|
1300
|
+
# = LCM^2/det(Z')^2 * adj(Z').T C^-1 adj(Z')
|
|
1301
|
+
# C is invertible, we only need to keep det(Z)/LCM nonzero
|
|
1302
|
+
Z_common_denom = sym.lcm([elem.as_numer_denom()[1] for elem in Z[:] if elem != 0])
|
|
1303
|
+
Z_poly = sym.cancel(Z*Z_common_denom)
|
|
1304
|
+
if debug:
|
|
1305
|
+
print("Calling maximally compatible sol with coupling:")
|
|
1306
|
+
# Flatten the list of possible substitutions
|
|
1307
|
+
all_keys, all_subs = maximally_compatible_sol(coupling,
|
|
1308
|
+
nonzero_constraints=[_det_fast(Z_poly), Z_common_denom],
|
|
1309
|
+
rational_only=True, stop_at_first=kwargs.get("stop_at_first", True),
|
|
1310
|
+
debug=debug, get_all_sols=True,
|
|
1311
|
+
patterns=None if pattern_order is None else pattern_order(term_keys))
|
|
1312
|
+
# Cannot decouple anything
|
|
1313
|
+
if not all_keys:
|
|
1314
|
+
if return_tiebreaker:
|
|
1315
|
+
return [Z], [tiebreaker_fn(zero_keys)]
|
|
1316
|
+
else:
|
|
1317
|
+
return [Z]
|
|
1318
|
+
|
|
1319
|
+
all_keys = list(itertools.chain.from_iterable([[all_keys[i]]*len(all_subs[i]) for i in range(len(all_keys))]))
|
|
1320
|
+
all_subs = list(itertools.chain.from_iterable(all_subs))
|
|
1321
|
+
|
|
1322
|
+
# Remove transformations that are column permutations or sign-flips of each other
|
|
1323
|
+
perms = _var_col_perms(var_types, dyn_only=True)
|
|
1324
|
+
perms = [p + tuple(range(n_d, Z.shape[0])) for p in perms]
|
|
1325
|
+
unique_Z = []
|
|
1326
|
+
unique_keys = []
|
|
1327
|
+
unique_subs = []
|
|
1328
|
+
# With the unique transformations, sort by tiebreaker function
|
|
1329
|
+
key_order = np.argsort([tiebreaker_fn(keys) for keys in all_keys])
|
|
1330
|
+
all_Z = [Z.subs(all_subs[i]) for i in key_order]
|
|
1331
|
+
_, idx_kept = _remove_permutation_equivalent_transformations(all_Z, perms)
|
|
1332
|
+
unique_Z = [all_Z[j] for j in idx_kept]
|
|
1333
|
+
|
|
1334
|
+
if return_tiebreaker:
|
|
1335
|
+
return unique_Z, [tiebreaker_fn(all_keys[key_order[j]]) for j in idx_kept]
|
|
1336
|
+
else:
|
|
1337
|
+
return unique_Z
|