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,704 @@
1
+ """Save and load symbolic Hamiltonians in the version 1 kronfree-spec format.
2
+
3
+ The JSON contains Hamiltonian coefficients in GHz, not a serialized Result.
4
+ Loading constructs SymPy expressions without running quantization or evaluating
5
+ Python/Julia source code. Parameter symbols have real=True assumptions.
6
+ :doc:`/exporting` describes the format.
7
+ """
8
+
9
+ from collections.abc import Sequence
10
+ from dataclasses import dataclass
11
+ from importlib.metadata import PackageNotFoundError, version
12
+ import json
13
+ import math
14
+ from numbers import Real
15
+ from os import PathLike
16
+ from pathlib import Path
17
+ import random
18
+ import re
19
+ import unicodedata
20
+
21
+ import sympy as sym
22
+ from sympy.printing.julia import JuliaCodePrinter
23
+
24
+ from .units import subs_constants
25
+
26
+ __all__ = ["HamiltonianSpec", "load_spec", "to_spec", "save_spec", "to_record", "load_record"]
27
+
28
+
29
+ _FUNCTIONS = {
30
+ "sqrt": sym.sqrt, "exp": sym.exp, "cos": sym.cos, "sin": sym.sin,
31
+ "tan": sym.tan, "cosh": sym.cosh, "sinh": sym.sinh, "tanh": sym.tanh,
32
+ "log": sym.log, "abs": sym.Abs, "sign": sym.sign, "conj": sym.conjugate,
33
+ "real": sym.re, "imag": sym.im,
34
+ }
35
+ _CONSTANTS = {"pi": sym.pi, "π": sym.pi, "ℯ": sym.E}
36
+ _KEYWORDS = set("baremodule begin break catch const continue do else elseif end export false finally for function global if import let local macro module quote return struct true try using while where abstract primitive mutable type in isa outer public".split())
37
+ _RESERVED = set(_FUNCTIONS) | set(_CONSTANTS) | _KEYWORDS | {"im", "e", "cis", "cispi", "Inf", "NaN"}
38
+ _IDENTIFIER = re.compile(r"(?:[^\W\d]|_)\w*", re.UNICODE)
39
+ _TOKEN = re.compile(
40
+ r"(?P<number>(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?)"
41
+ r"|(?P<name>(?:[^\W\d]|_)\w*)|(?P<op>\.[+*/^\-]|//|[+*/^(),\-])",
42
+ re.UNICODE,
43
+ )
44
+ _PRECEDENCE = {"+": 10, "-": 10, "*": 20, "/": 20, "//": 25, "^": 40}
45
+ # Julia 1.13 Base.Unicode._julia_charmap, applied before NFC (not NFKC).
46
+ # Only the letter mappings can occur in our portable identifier subset.
47
+ _JULIA_CHARMAP = str.maketrans({"ɛ": "ε", "µ": "μ", "·": "⋅", "·": "⋅", "−": "-", "ℏ": "ħ"})
48
+
49
+
50
+ class _SpecPrinter(JuliaCodePrinter):
51
+ def _print_Float(self, expr):
52
+ # Default SymPy printing uses 15 decimal digits for a binary64 Float,
53
+ # insufficient to recover all 53 bits; retain two guard digits.
54
+ return str(expr.evalf(math.ceil(expr._prec * math.log10(2)) + 2))
55
+
56
+ def _print_Exp1(self, expr):
57
+ # SymPy's default e spelling is reserved but not accepted by Julia's
58
+ # coefficient loader; its supported constant spelling is ℯ.
59
+ return "ℯ"
60
+
61
+
62
+ def _fail(field, message):
63
+ raise ValueError(f"spec: {field}: {message}")
64
+
65
+
66
+ def _name(name, field):
67
+ # Use a portable subset of Julia identifiers, including Greek letters.
68
+ if not isinstance(name, str) or not _IDENTIFIER.fullmatch(name) or name in _RESERVED or not name.strip("_"):
69
+ _fail(field, f"invalid or reserved parameter name {name!r}")
70
+ _canonical_name(name, field)
71
+
72
+
73
+ def _canonical_name(name, field):
74
+ canonical = unicodedata.normalize("NFC", name.translate(_JULIA_CHARMAP))
75
+ if name != canonical:
76
+ _fail(field, f"identifier {name!r} is not canonical in Julia; use {canonical!r}")
77
+
78
+
79
+ def _tokens(source, field):
80
+ tokens = []
81
+ pos = 0
82
+ while pos < len(source):
83
+ if source[pos].isspace():
84
+ pos += 1
85
+ continue
86
+ match = _TOKEN.match(source, pos)
87
+ if match is None:
88
+ _fail(field, f"unsupported expression syntax near {source[pos:pos + 24]!r}")
89
+ if match.lastgroup == "name":
90
+ _canonical_name(match.group(), field)
91
+ tokens.append((match.lastgroup, match.group()))
92
+ pos = match.end()
93
+ return tokens
94
+
95
+
96
+ def _real_expression(expr, field):
97
+ if expr.has(sym.I, sym.oo, -sym.oo, sym.zoo, sym.nan) or expr.is_real is False:
98
+ _fail(field, "expression must be real and finite")
99
+ return expr
100
+
101
+
102
+ class _ExpressionParser:
103
+ """Small scalar Julia grammar; no eval, sympify(string), or parse_expr.
104
+
105
+ Julia's // binds more tightly than * and /; ^ is right associative and
106
+ binds more tightly than unary signs. Dotted arithmetic is scalar here.
107
+ """
108
+
109
+ def __init__(self, source, symbols, field):
110
+ self.tokens = _tokens(source, field) + [("end", "")]
111
+ self.symbols = symbols
112
+ self.field = field
113
+ self.index = 0
114
+ self.syntax = None
115
+
116
+ def peek(self):
117
+ kind, token = self.tokens[self.index]
118
+ return token[1:] if kind == "op" and token.startswith(".") else token
119
+
120
+ def take(self, expected):
121
+ if self.peek() != expected:
122
+ _fail(self.field, f"expected {expected!r}, got {self.peek()!r}")
123
+ self.index += 1
124
+
125
+ def expression(self, minimum=0):
126
+ kind, _ = self.tokens[self.index]
127
+ token = self.peek()
128
+ self.index += 1
129
+ if token in ("+", "-"):
130
+ value = self.expression(30)
131
+ syntax = (token, self.syntax)
132
+ if token == "-":
133
+ value = -value
134
+ elif token == "(":
135
+ value = self.expression()
136
+ syntax = self.syntax
137
+ self.take(")")
138
+ elif kind == "number":
139
+ # Preserve all printed decimal digits (and at least binary64 precision).
140
+ if any(c in token for c in ".eE"):
141
+ mantissa = re.split("[eE]", token)[0]
142
+ digits = len(re.sub(r"[^0-9]", "", mantissa))
143
+ value = sym.Float(token, max(15, digits))
144
+ else:
145
+ value = sym.Integer(token)
146
+ syntax = ("number", value)
147
+ elif kind == "name":
148
+ if self.peek() == "(":
149
+ if token not in _FUNCTIONS:
150
+ _fail(self.field, f"function {token!r} is not allowed")
151
+ self.take("(")
152
+ args = [self.expression()]
153
+ arg_syntax = [self.syntax]
154
+ while self.peek() == ",":
155
+ self.take(",")
156
+ args.append(self.expression())
157
+ arg_syntax.append(self.syntax)
158
+ self.take(")")
159
+ syntax = (token, *arg_syntax)
160
+ if token == "log" and len(args) == 2:
161
+ value = sym.log(args[1], args[0]) # Julia log(base, x).
162
+ elif len(args) == 1:
163
+ value = _FUNCTIONS[token](args[0])
164
+ else:
165
+ _fail(self.field, f"wrong number of arguments for {token}")
166
+ elif token in _CONSTANTS:
167
+ value = _CONSTANTS[token]
168
+ syntax = ("name", token)
169
+ elif token in self.symbols:
170
+ value = self.symbols[token]
171
+ syntax = ("name", token)
172
+ else:
173
+ _fail(self.field, f"undeclared or forbidden symbol {token!r}")
174
+ else:
175
+ _fail(self.field, f"expected a number, parameter, or function; got {token!r}")
176
+ value = _real_expression(value, self.field)
177
+ while self.peek() in _PRECEDENCE and _PRECEDENCE[self.peek()] >= minimum:
178
+ operator = self.peek()
179
+ self.index += 1
180
+ right = self.expression(_PRECEDENCE[operator] + (operator != "^"))
181
+ syntax = (operator, syntax, self.syntax)
182
+ if operator == "+":
183
+ value += right
184
+ elif operator == "-":
185
+ value -= right
186
+ elif operator == "*":
187
+ value *= right
188
+ elif operator in ("/", "//"):
189
+ if operator == "//" and (value.is_Rational is not True or right.is_Rational is not True):
190
+ _fail(self.field, "// requires rational numeric operands; use / for symbolic division")
191
+ value /= right
192
+ else:
193
+ value **= right
194
+ value = _real_expression(value, self.field)
195
+ self.syntax = syntax
196
+ return value
197
+
198
+
199
+ def _expression(source, symbols, field, *, with_syntax=False):
200
+ if not isinstance(source, str) or not source.strip():
201
+ _fail(field, "expected a nonempty expression string")
202
+ try:
203
+ parser = _ExpressionParser(source, symbols, field)
204
+ result = parser.expression()
205
+ parser.take("")
206
+ return (result, parser.syntax) if with_syntax else result
207
+ except (TypeError, ZeroDivisionError, OverflowError, RecursionError) as error:
208
+ _fail(field, f"invalid expression ({type(error).__name__})")
209
+
210
+
211
+ def _check_symmetric(rows, syntax, symbols, field):
212
+ """Mirror Julia's syntactic gate and three-point relative comparison.
213
+
214
+ Inspect and evaluate the source, not simplified SymPy expressions: abs(x)^2
215
+ simplifies to x^2 and sqrt(-x)^2 to -x, hiding nonanalyticity/domain failures.
216
+ All allowed names are real and complex constructs are already forbidden,
217
+ so abs/sign are the only possible nonanalytic calls in this grammar;
218
+ real sqrt/log/power domain failures are caught during sampled evaluation.
219
+ """
220
+ for i in range(len(rows)):
221
+ for j in range(i + 1, len(rows)):
222
+ left, right = rows[i][j], rows[j][i]
223
+ if left == right or syntax[i][j] == syntax[j][i]:
224
+ continue
225
+ pair = f"{field}[{i},{j}] = {left!r} and {field}[{j},{i}] = {right!r}"
226
+ tokens = _tokens(left, field) + _tokens(right, field)
227
+ if any(kind == "name" and name in ("abs", "sign") for kind, name in tokens):
228
+ _fail(field, f"must be symmetric, but {pair} are not identical and not real-analytic")
229
+ deps = sorted({name for kind, name in tokens if kind == "name" and name in symbols})
230
+ # Same seed, interval, count and tolerance as Julia _test_points;
231
+ # Python's RNG stream is independent of Julia's implementation.
232
+ rng = random.Random(0x6B66)
233
+ for _ in range(3):
234
+ point = {name: sym.Float(0.5 + 1.5 * rng.random()) for name in deps}
235
+ try:
236
+ a = float(_expression(left, point, field))
237
+ b = float(_expression(right, point, field))
238
+ if not (math.isfinite(a) and math.isfinite(b)):
239
+ raise ValueError("nonfinite value")
240
+ except (ValueError, TypeError, OverflowError) as error:
241
+ _fail(field, f"must be symmetric, but {pair} cannot be evaluated at a test point ({error})")
242
+ if abs(a - b) > 1e-12 * max(abs(a), abs(b)):
243
+ _fail(field, f"must be symmetric, but {pair} differ")
244
+
245
+
246
+ def _object(value, required, optional, field):
247
+ if not isinstance(value, dict):
248
+ _fail(field, "expected an object")
249
+ for key in value:
250
+ if not isinstance(key, str) or (key not in required | optional and not key.startswith("_")):
251
+ _fail(field, f"unknown key {key!r}")
252
+ for key in sorted(required - value.keys()):
253
+ _fail(field, f"missing required key {key!r}")
254
+
255
+
256
+ def _array(value, size, field):
257
+ if not isinstance(value, list) or (size is not None and len(value) != size):
258
+ _fail(field, "expected an array" + (f" of length {size}" if size is not None else ""))
259
+ return value
260
+
261
+
262
+ @dataclass(frozen=True)
263
+ class HamiltonianSpec:
264
+ """Immutable Hamiltonian coefficients, with real parameter symbols.
265
+
266
+ :param parameters: Declared symbols in file order, each with real=True.
267
+ :param modes: Pairs of descriptive mode name and type (c, e, h).
268
+ :param E_C: Charging-energy matrix in GHz.
269
+ :param E_L: Inductive-energy matrix in GHz.
270
+ :param flux_linear: Column of linear phase coefficients in GHz.
271
+ :param n_g: Column of offset charges in Cooper-pair units.
272
+ :param cosines: Tuples (energy, numeric omega tuple, phase offset).
273
+ :param constant: Additive energy in GHz.
274
+ """
275
+
276
+ parameters: tuple[sym.Symbol, ...]
277
+ modes: tuple[tuple[str, str], ...]
278
+ E_C: sym.ImmutableMatrix
279
+ E_L: sym.ImmutableMatrix
280
+ flux_linear: sym.ImmutableMatrix
281
+ n_g: sym.ImmutableMatrix
282
+ cosines: tuple[tuple[sym.Expr, tuple[sym.Expr, ...], sym.Expr], ...]
283
+ constant: sym.Expr
284
+
285
+ def hamiltonian(self) -> sym.Expr:
286
+ """Rebuild H/h in GHz without quantizing a circuit.
287
+
288
+ :returns: SymPy expression in real varphi_1...varphi_N and n_1...n_N,
289
+ indexed by mode order. Mode names are descriptive labels.
290
+ """
291
+ size = len(self.modes)
292
+ phase = sym.ImmutableMatrix(sym.symbols(f"varphi_1:{size + 1}", real=True))
293
+ charge = sym.ImmutableMatrix(sym.symbols(f"n_1:{size + 1}", real=True)) - self.n_g
294
+ result = 4 * (charge.T * self.E_C * charge)[0]
295
+ result += (phase.T * self.E_L * phase)[0] / 2 + (phase.T * self.flux_linear)[0]
296
+ result -= sum(energy * sym.cos(sum(w * p for w, p in zip(omega, phase)) + offset)
297
+ for energy, omega, offset in self.cosines)
298
+ return result + self.constant
299
+
300
+
301
+ def _unique_object(pairs):
302
+ result = {}
303
+ for key, value in pairs:
304
+ if key in result:
305
+ _fail("JSON", f"duplicate key {key!r}")
306
+ result[key] = value
307
+ return result
308
+
309
+
310
+ def _read_document(source):
311
+ if isinstance(source, PathLike):
312
+ source = Path(source).read_text(encoding="utf-8")
313
+ elif isinstance(source, str) and source.strip() and source.lstrip()[0] not in '{["-0123456789' and source.strip() not in ("null", "true", "false"):
314
+ source = Path(source).read_text(encoding="utf-8")
315
+ if isinstance(source, str):
316
+ try:
317
+ source = json.loads(source, object_pairs_hook=_unique_object,
318
+ parse_constant=lambda value: _fail("JSON", f"nonfinite number {value}"))
319
+ except json.JSONDecodeError as error:
320
+ _fail("JSON", str(error))
321
+ return source
322
+
323
+
324
+ def load_spec(source) -> HamiltonianSpec:
325
+ """Read and validate a Hamiltonian dictionary, JSON string, or file path.
326
+
327
+ :param source: JSON-ready dict, JSON text, or str/PathLike file path.
328
+ Strings beginning with a JSON value delimiter are treated as JSON.
329
+ Use pathlib.Path for a filename that would otherwise be ambiguous.
330
+ :returns: Immutable HamiltonianSpec, independent of the input dictionary.
331
+ :raises ValueError: Invalid format, expression, or unsupported feature.
332
+ :raises OSError: A source file cannot be read.
333
+ """
334
+ source = _read_document(source)
335
+ required = {"format", "version", "parameters", "modes", "E_C", "E_L", "flux_linear", "n_g", "cosines"}
336
+ _object(source, required, {"units", "constant", "charge_cosines"}, "document")
337
+ if source["format"] != "kronfree-spec":
338
+ _fail("format", 'expected "kronfree-spec"')
339
+ if type(source["version"]) is not int or source["version"] != 1:
340
+ _fail("version", "expected integer 1")
341
+ if source.get("units", "GHz") != "GHz":
342
+ _fail("units", 'expected "GHz"')
343
+ if _array(source.get("charge_cosines", []), None, "charge_cosines"):
344
+ _fail("charge_cosines", "phase-slip terms are not supported")
345
+ modes = []
346
+ for i, mode in enumerate(_array(source["modes"], None, "modes")):
347
+ field = f"modes[{i}]"
348
+ _object(mode, {"name", "type"}, set(), field)
349
+ if not isinstance(mode["name"], str) or not mode["name"]:
350
+ _fail(field, "name must be a nonempty string")
351
+ if mode["type"] not in ("c", "e", "h"):
352
+ _fail(field, "type must be c, e, or h")
353
+ modes.append((mode["name"], mode["type"]))
354
+ size = len(modes)
355
+ if not size or len({name for name, _ in modes}) != size:
356
+ _fail("modes", "mode names must be unique and modes must be nonempty")
357
+ coordinates = {f"{base}_{i}" for base in ("varphi", "n") for i in range(1, size + 1)}
358
+ symbols = {}
359
+ for name in _array(source["parameters"], None, "parameters"):
360
+ _name(name, "parameters")
361
+ if name in symbols or name in coordinates:
362
+ _fail("parameters", f"duplicate or coordinate parameter name {name!r}")
363
+ symbols[name] = sym.Symbol(name, real=True)
364
+
365
+ def matrix(key):
366
+ rows = _array(source[key], size, key)
367
+ parsed = [[
368
+ _expression(value, symbols, f"{key}[{i},{j}]", with_syntax=True)
369
+ for j, value in enumerate(_array(row, size, f"{key}[{i}]"))
370
+ ] for i, row in enumerate(rows)]
371
+ _check_symmetric(rows, [[syntax for _, syntax in row] for row in parsed], symbols, key)
372
+ return sym.ImmutableMatrix([[value for value, _ in row] for row in parsed])
373
+
374
+ def vector(key):
375
+ return sym.ImmutableMatrix(size, 1, [
376
+ _expression(value, symbols, f"{key}[{i}]")
377
+ for i, value in enumerate(_array(source[key], size, key))
378
+ ])
379
+
380
+ ec, el, flux, ng = matrix("E_C"), matrix("E_L"), vector("flux_linear"), vector("n_g")
381
+ cosines = []
382
+ for i, cosine in enumerate(_array(source["cosines"], None, "cosines")):
383
+ field = f"cosines[{i}]"
384
+ _object(cosine, {"energy", "omega", "offset"}, set(), field)
385
+ omega = []
386
+ for j, value in enumerate(_array(cosine["omega"], size, field + ".omega")):
387
+ if type(value) not in (int, float) or (isinstance(value, float) and not math.isfinite(value)):
388
+ _fail(field + ".omega", f"mode {modes[j][0]} requires a finite number")
389
+ if modes[j][1] == "c" and value != int(value):
390
+ _fail(field + ".omega", f"compact mode {modes[j][0]} requires an integer")
391
+ omega.append(sym.Integer(value) if value == int(value) else sym.Float(value))
392
+ cosines.append((_expression(cosine["energy"], symbols, field + ".energy"), tuple(omega),
393
+ _expression(cosine["offset"], symbols, field + ".offset")))
394
+ return HamiltonianSpec(tuple(symbols.values()), tuple(modes), ec, el, flux, ng, tuple(cosines),
395
+ _expression(source.get("constant", "0"), symbols, "constant"))
396
+
397
+
398
+ def _tolerance(value, name):
399
+ if isinstance(value, bool) or not isinstance(value, Real):
400
+ _fail(name, f"expected a finite nonnegative real number, got {value!r}")
401
+ value = float(value)
402
+ if not math.isfinite(value) or value < 0:
403
+ _fail(name, f"expected a finite nonnegative real number, got {value!r}")
404
+ return value
405
+
406
+
407
+ def to_spec(res, *, subs=None, simplify=True, mode_names=None, zero_rtol=1e-12, zero_atol=0.0) -> dict:
408
+ """Convert a quantization Result into a JSON-ready Hamiltonian dictionary.
409
+
410
+ :param res: Quantization Result. Only its retained dynamical modes are saved.
411
+ :param subs: Optional SymPy substitution mapping, applied before exact SI
412
+ physical constants are evaluated. It does not mutate res.
413
+ :param bool simplify: Combine rational denominators and cancel before printing
414
+ (default True).
415
+ :param mode_names: Optional sequence of unique, nonempty labels, in retained
416
+ mode order. Defaults to varphi_1...varphi_N. The names do not rename coordinates
417
+ or compact-sector parameters (use subs for parameter renaming).
418
+ :param float zero_rtol: Relative round-off tolerance (default 1e-12). In a
419
+ fully numeric E_C or E_L, after symmetrization, an entry containing a
420
+ SymPy Float whose magnitude is at most max(zero_rtol * scale, zero_atol)
421
+ is written as exact 0, scale being the largest absolute entry of that
422
+ matrix. Symmetric pairs are decided together. In each cosine, a Float
423
+ omega entry at most zero_rtol times the largest absolute entry of that
424
+ omega is written as 0. On a compact mode it must also be at most
425
+ zero_rtol itself, so a non-integer compact entry is still rejected.
426
+ Exact entries and matrices with free symbols are never zeroed.
427
+ :param float zero_atol: Absolute tolerance in GHz for E_C and E_L entries
428
+ (default 0.0). It is not applied to the dimensionless omega. Pass
429
+ zero_rtol=0 and zero_atol=0 to disable zeroing.
430
+ :returns: Version 1 kronfree-spec dictionary with coefficients in GHz.
431
+ :raises ValueError: Unsupported expression, parameter name, or cosine
432
+ vector, numeric matrix asymmetry above 1e-10 of its scale, or a
433
+ negative, nonfinite, or nonnumeric tolerance.
434
+ """
435
+ zero_rtol, zero_atol = _tolerance(zero_rtol, "zero_rtol"), _tolerance(zero_atol, "zero_atol")
436
+ size = len(res.coords.types)
437
+ if mode_names is None:
438
+ mode_names = [f"varphi_{i + 1}" for i in range(size)]
439
+ if isinstance(mode_names, (str, bytes)) or not isinstance(mode_names, Sequence):
440
+ _fail("mode_names", "expected a sequence of labels")
441
+ if len(mode_names) != size or any(not isinstance(name, str) or not name for name in mode_names):
442
+ _fail("mode_names", f"expected {size} nonempty string labels")
443
+ if len(set(mode_names)) != size:
444
+ _fail("mode_names", "labels must be unique")
445
+ symbols = {}
446
+
447
+ def prepare(expr):
448
+ expr = sym.sympify(expr)
449
+ if subs is not None:
450
+ expr = expr.subs(subs)
451
+ expr = subs_constants(expr)
452
+ # Combine nested denominators before polynomial expansion: cancel alone
453
+ # can take minutes on substituted coupled-circuit charging energies.
454
+ return sym.cancel(sym.together(expr)) if simplify else expr
455
+
456
+ def coefficient(expr, field):
457
+ expr = _real_expression(prepare(expr), field)
458
+ by_name = {}
459
+ for symbol in expr.free_symbols:
460
+ _name(symbol.name, field)
461
+ if symbol.is_real is False:
462
+ _fail(field, f"parameter {symbol.name!r} must be real")
463
+ previous = by_name.get(symbol.name, symbols.get(symbol.name))
464
+ if previous is not None and previous != symbol:
465
+ _fail(field, f"distinct symbols share the name {symbol.name!r}")
466
+ by_name[symbol.name] = symbol
467
+ try:
468
+ printed = _SpecPrinter().doprint(expr)
469
+ except (TypeError, ValueError, NotImplementedError) as error:
470
+ _fail(field, f"cannot print expression: {error}")
471
+ for kind, token in _tokens(printed, field):
472
+ if kind == "name" and token in by_name:
473
+ symbols.setdefault(token, by_name[token])
474
+ _expression(printed, {name: sym.Symbol(name, real=True) for name in symbols}, field)
475
+ return printed
476
+
477
+ def matrix(values, field):
478
+ values = sym.Matrix(values).applyfunc(prepare)
479
+ if not values.free_symbols:
480
+ numbers = [[complex(x.evalf()) for x in row] for row in values.tolist()]
481
+ scale = max((abs(x) for row in numbers for x in row), default=0)
482
+ threshold = max(zero_rtol * scale, zero_atol)
483
+ for i in range(values.rows):
484
+ for j in range(i, values.cols):
485
+ a, b = numbers[i][j], numbers[j][i]
486
+ if abs(a - b) > 1e-10 * scale:
487
+ _fail(field, f"must be symmetric; asymmetry at [{i},{j}] = {values[i,j]} and [{j},{i}] = {values[j,i]}")
488
+ average = values[i, j] if i == j else (values[i, j] + values[j, i]) / 2
489
+ # Only floating-point residue is zeroed, never an exact entry.
490
+ if abs(a + b) / 2 <= threshold and (values[i,j].has(sym.Float) or values[j,i].has(sym.Float)):
491
+ average = sym.S.Zero
492
+ values[i, j] = values[j, i] = average
493
+ return [[coefficient(values[i, j], f"{field}[{i},{j}]") for j in range(values.cols)] for i in range(values.rows)]
494
+
495
+ def vector(values, field):
496
+ return [coefficient(value, f"{field}[{i}]") for i, value in enumerate(values)]
497
+
498
+ modes = [{"name": name, "type": typ} for name, typ in zip(mode_names, res.coords.types)]
499
+ data = {"format": "kronfree-spec", "version": 1, "units": "GHz", "parameters": [], "modes": modes}
500
+ data["E_C"], data["E_L"] = matrix(res.ham.E_C, "E_C"), matrix(res.ham.E_L, "E_L")
501
+ linear = res.coords.omega_L_tilde * res.ham.E_Lb * res.ham.varphi_b[list(res.lag.L), :]
502
+ data["flux_linear"], data["n_g"] = vector(linear, "flux_linear"), vector(res.ham.n_g, "n_g")
503
+ offsets = res.ham.varphi_b[list(res.lag.J), :]
504
+ cosines = []
505
+ for k, branch in enumerate(res.lag.J):
506
+ field = f"junction {res.circuit.branch_names[branch]}"
507
+ values = []
508
+ for j, mode in enumerate(modes):
509
+ value = prepare(res.coords.omega_J_tilde[j, k])
510
+ if value.free_symbols or value.is_number is not True or value.is_real is not True or value.is_finite is not True:
511
+ _fail(f"{field}, mode {mode['name']}", "omega must be a finite real number without free symbols")
512
+ values.append(value)
513
+ scale = max((abs(float(value)) for value in values), default=0)
514
+ omega = []
515
+ for value, mode in zip(values, modes):
516
+ where = f"{field}, mode {mode['name']}"
517
+ # Zero Float residue relative to this omega; on a compact mode also
518
+ # relative to the integer lattice, so the integer check below
519
+ # still rejects any entry that is not within zero_rtol of 0.
520
+ limit = zero_rtol * (min(scale, 1) if mode["type"] == "c" else scale)
521
+ if value.has(sym.Float) and abs(float(value)) <= limit:
522
+ value = sym.S.Zero
523
+ integer = value.is_integer is True or (isinstance(value, sym.Float) and (value % 1).is_zero)
524
+ if mode["type"] == "c" and not integer:
525
+ _fail(where, f"omega {value} on a compact mode must be an integer")
526
+ number = int(value) if integer else float(value)
527
+ if isinstance(number, float) and (not math.isfinite(number) or (number == 0 and value != 0)):
528
+ _fail(where, "omega cannot be represented as a finite nonzero JSON number")
529
+ omega.append(number)
530
+ cosines.append({"energy": coefficient(res.lag.EJ[k], field + ".energy"), "omega": omega,
531
+ "offset": coefficient(offsets[k], field + ".offset")})
532
+ data["cosines"], data["constant"], data["parameters"] = cosines, "0", list(symbols)
533
+ try:
534
+ package_version = version("circuit-quantization")
535
+ except PackageNotFoundError:
536
+ package_version = "unknown"
537
+ data["_generator"] = {"package": "circuit-quantization", "version": package_version,
538
+ "branches": list(res.circuit.branch_names)}
539
+ load_spec(data) # Share the importer validation before writing any file.
540
+ return data
541
+
542
+
543
+ def save_spec(res, path, **kwargs) -> dict:
544
+ """Write a quantization Result as UTF-8 JSON and return the dictionary.
545
+
546
+ :param res: Quantization Result to export.
547
+ :param path: Destination str or PathLike, overwritten only after validation.
548
+ :param kwargs: Forwarded to to_spec (subs, simplify, mode_names,
549
+ zero_rtol, and zero_atol).
550
+ :returns: The JSON-ready dictionary written to path.
551
+ """
552
+ data = to_spec(res, **kwargs)
553
+ text = json.dumps(data, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
554
+ Path(path).write_text(text, encoding="utf-8")
555
+ return data
556
+
557
+
558
+ def _source_commit(root):
559
+ """HEAD commit of root when it is the top of a git checkout of this project, else None.
560
+
561
+ An installed package can sit inside an unrelated repository, whose commit would mislead.
562
+ """
563
+ import subprocess
564
+ import tomllib
565
+
566
+ root = Path(root).resolve()
567
+ try:
568
+ with open(root / "pyproject.toml", "rb") as file:
569
+ name = tomllib.load(file).get("project", {}).get("name")
570
+ except (OSError, tomllib.TOMLDecodeError):
571
+ return None
572
+ if name != "circuit-quantization" or not (root / "src" / "circuit_quantization").is_dir():
573
+ return None
574
+ try:
575
+ git = lambda *args: subprocess.run(["git", *args], cwd=root, capture_output=True, text=True,
576
+ check=True, timeout=2).stdout.strip()
577
+ if Path(git("rev-parse", "--show-toplevel")).resolve() != root:
578
+ return None
579
+ return git("rev-parse", "HEAD") or None
580
+ except (OSError, subprocess.SubprocessError):
581
+ return None
582
+
583
+
584
+ def to_record(res, path=None, *, subs=None, **kwargs):
585
+ """Export a rebuildable Result alongside its ordinary kronfree-spec fields.
586
+
587
+ Optional ``subs`` records numeric parameter values. If ``path`` is given,
588
+ write JSON there. Always return the dictionary. Expressions use the same
589
+ restricted grammar as the spec. Nodes must be JSON scalars or tuples of
590
+ JSON scalars. Arbitrary Python objects and undefined functions are unsupported.
591
+ Other keyword arguments (simplify, mode_names, zero_rtol, zero_atol) are
592
+ forwarded to to_spec.
593
+ """
594
+ data = to_spec(res, subs=subs, **kwargs)
595
+ symbols = {}
596
+
597
+ def expression(value):
598
+ if value is None:
599
+ return None
600
+ value = sym.sympify(value)
601
+ for symbol in sorted(value.free_symbols, key=sym.default_sort_key):
602
+ if symbol not in symbols:
603
+ symbols[symbol] = sym.Symbol(f"p{len(symbols)}")
604
+ text = _SpecPrinter().doprint(value.xreplace(symbols))
605
+ _expression(text, {p.name: s for s, p in symbols.items()}, "record expression")
606
+ return text
607
+
608
+ def matrix(value):
609
+ if value is None:
610
+ return None
611
+ return {"rows": value.rows, "cols": value.cols, "entries": [expression(x) for x in value]}
612
+
613
+ def node(value):
614
+ if value is None or type(value) in (str, int, bool):
615
+ return value
616
+ if isinstance(value, tuple):
617
+ return {"tuple": [node(x) for x in value]}
618
+ raise ValueError(f"unsupported record node {value!r}")
619
+
620
+ branches = [{"name": b.name, "tail": node(b.tail), "head": node(b.head),
621
+ **{key: expression(getattr(b, key)) for key in ("C", "L", "EJ", "V")}}
622
+ for b in res.circuit.branches]
623
+ data["_circuit"] = {
624
+ "branches": branches, "ground": node(res.circuit.ground), "t": expression(res.circuit.t),
625
+ "loops": {"G": matrix(res.loops.G), "names": list(res.loops.names),
626
+ "closure_branches": res.loops.closure_branches, "Phi_ext": matrix(res.loops.Phi_ext)},
627
+ "B": matrix(res.B), "B_static": matrix(res.B_static), "static": matrix(res.static),
628
+ }
629
+ data["_frame"] = {"Z_full": matrix(res.coords.Z_full), "types_full": list(res.coords.types_full),
630
+ "S": matrix(res.residual_S)}
631
+ data["_values"] = [{"symbol": expression(key), "value": expression(value)}
632
+ for key, value in (subs or {}).items()]
633
+ data["_circuit"]["symbols"] = [
634
+ {"id": placeholder.name, "name": symbol.name,
635
+ "assumptions": dict(symbol._assumptions_orig)} for symbol, placeholder in symbols.items()]
636
+ commit = _source_commit(Path(__file__).resolve().parents[2])
637
+ if commit:
638
+ data["_generator"]["git_commit"] = commit
639
+ if path is not None:
640
+ Path(path).write_text(json.dumps(data, indent=2, ensure_ascii=False, allow_nan=False) + "\n", encoding="utf-8")
641
+ return data
642
+
643
+
644
+ def load_record(source):
645
+ """Rebuild a Result from to_record output, without evaluating loaded code.
646
+
647
+ Spec fields are validated first, including rejection of unknown nonmetadata
648
+ keys. Circuit/frame metadata are then checked through the quantization API.
649
+ Recorded substitutions are reapplied after rebuilding the symbolic circuit.
650
+ """
651
+ from dataclasses import replace
652
+ from .circuit import Branch, Circuit
653
+ from .loops import Loops
654
+ from .quantize import numerify, quantize
655
+
656
+ data = _read_document(source)
657
+ load_spec(data)
658
+ try:
659
+ circuit_data, frame = data["_circuit"], data["_frame"]
660
+ symbols = {}
661
+ for item in circuit_data["symbols"]:
662
+ _name(item["id"], "record symbol id")
663
+ if item["id"] in symbols:
664
+ _fail("record symbols", "duplicate symbol id")
665
+ if not isinstance(item["name"], str) or not isinstance(item["assumptions"], dict):
666
+ _fail("record symbols", "invalid name or assumptions")
667
+ if any(type(v) is not bool for v in item["assumptions"].values()):
668
+ _fail("record symbols", "assumptions must be booleans")
669
+ symbols[item["id"]] = sym.Symbol(item["name"], **item["assumptions"])
670
+
671
+ def expression(text):
672
+ return None if text is None else _expression(text, symbols, "record expression")
673
+
674
+ def matrix(value):
675
+ if value is None:
676
+ return None
677
+ rows, cols = value["rows"], value["cols"]
678
+ if type(rows) is not int or type(cols) is not int or min(rows, cols) < 0:
679
+ _fail("record matrix", "invalid dimensions")
680
+ return sym.ImmutableMatrix(rows, cols, [expression(x) for x in value["entries"]])
681
+
682
+ def node(value):
683
+ if value is None or type(value) in (str, int, bool):
684
+ return value
685
+ if isinstance(value, dict) and set(value) == {"tuple"}:
686
+ return tuple(node(x) for x in value["tuple"])
687
+ _fail("record node", "invalid node label")
688
+
689
+ branches = [Branch(b["name"], node(b["tail"]), node(b["head"]),
690
+ **{key: expression(b[key]) for key in ("C", "L", "EJ", "V")})
691
+ for b in circuit_data["branches"]]
692
+ circuit = Circuit(branches, ground=node(circuit_data["ground"]), t=expression(circuit_data["t"]))
693
+ loops_data = circuit_data["loops"]
694
+ loops = Loops(circuit, matrix(loops_data["G"]), loops_data["names"], loops_data["closure_branches"],
695
+ dict(zip(loops_data["names"], matrix(loops_data["Phi_ext"]))))
696
+ static = matrix(circuit_data["static"])
697
+ result = quantize(circuit, loops, matrix(frame["Z_full"]), tuple(frame["types_full"]),
698
+ B=matrix(circuit_data["B"]), B_static=matrix(circuit_data["B_static"]),
699
+ static=None if static is None else dict(zip(loops.names, static)))
700
+ result = replace(result, residual_S=matrix(frame["S"]))
701
+ values = {expression(item["symbol"]): expression(item["value"]) for item in data.get("_values", [])}
702
+ return numerify(result, values) if values else result
703
+ except (KeyError, TypeError, IndexError) as error:
704
+ _fail("record", f"malformed metadata: {error}")