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,126 @@
1
+ """scqubits export, adapted from sircuitenum.qpackage_interface (GPL-3.0)."""
2
+
3
+ import math
4
+
5
+ import sympy as sym
6
+
7
+ from .units import farad_to_ghz, henry_to_ghz, subs_constants
8
+
9
+ __all__ = ["scqubits_yaml", "to_scqubits"]
10
+
11
+
12
+ def _scqubits_input(circuit, subs, node_order):
13
+ if circuit.source_nodes:
14
+ raise ValueError("scqubits export does not support voltage-source branches")
15
+ order = tuple(circuit.internal_nodes if node_order is None else node_order)
16
+ if len(order) != len(circuit.internal_nodes) or set(order) != set(circuit.internal_nodes):
17
+ raise ValueError("node_order must contain each internal node exactly once")
18
+ nodes = {node: i + 1 for i, node in enumerate(order)}
19
+ if circuit.ground is not None:
20
+ nodes[circuit.ground] = 0
21
+ rows, indices = [], {}
22
+
23
+ def parameter(name, value):
24
+ value = subs_constants(sym.sympify(value).subs(subs or {}))
25
+ if value.free_symbols:
26
+ raise ValueError(f"Missing substitutions for {name}: {value.free_symbols}")
27
+ if value.is_real is not True or not math.isfinite(float(value)) or float(value) <= 0:
28
+ raise ValueError(f"{name} must be finite and positive")
29
+ return f"{name} = {float(value)!r}"
30
+
31
+ for i, branch in enumerate(circuit.branches):
32
+ edge = f"{nodes[branch.tail]}, {nodes[branch.head]}"
33
+ indices[branch.name] = len(rows)
34
+ if branch.type == "J":
35
+ ej = parameter(f"EJ_{i}", branch.EJ)
36
+ ec = parameter(f"EC_{i}", farad_to_ghz(branch.C))
37
+ rows.append(f"- [JJ, {edge}, {ej}, {ec}]")
38
+ elif branch.type == "L":
39
+ el = parameter(f"EL_{i}", henry_to_ghz(branch.L))
40
+ rows.append(f"- [L, {edge}, {el}]")
41
+ if branch.C != 0 and branch.type != "J":
42
+ ec = parameter(f"EC_{i}", farad_to_ghz(branch.C))
43
+ rows.append(f"- [C, {edge}, {ec}]")
44
+ return "branches:\n" + "\n".join(rows) + "\n", indices
45
+
46
+
47
+ def scqubits_yaml(circuit, *, subs=None, node_order=None):
48
+ """Return scqubits YAML with energy parameters in GHz, without importing scqubits.
49
+
50
+ Supply numeric substitutions for all circuit symbols. Constants are evaluated
51
+ automatically. Ground maps to 0, and node_order (default internal_nodes) maps to
52
+ 1, 2, ... . Parameter names EJ_i, EC_i, EL_i use circuit.branches indices.
53
+ Junction C is included in JJ. Inductor C becomes a parallel capacitor.
54
+
55
+ :param circuit: Circuit without voltage-source branches.
56
+ :param subs: Symbol-to-numeric-value mapping. Physical constants are substituted automatically.
57
+ :param node_order: Complete internal-node order. None uses circuit.internal_nodes.
58
+ :returns: YAML string with energy parameters in GHz.
59
+ :raises ValueError: Unsupported sources, unresolved symbols, invalid values, or node order.
60
+ """
61
+ return _scqubits_input(circuit, subs, node_order)[0]
62
+
63
+
64
+ def to_scqubits(circuit, *, subs=None, node_order=None, symbolic=False,
65
+ transformation_matrix=None, closure_branches=None,
66
+ cutoff=None, trunc_num=None, **kwargs):
67
+ """Build a scqubits Circuit (or SymbolicCircuit when symbolic=True).
68
+
69
+ YAML conversion follows scqubits_yaml. transformation_matrix rows follow
70
+ node_order. closure_branches is an ordered list of original branch names.
71
+ scqubits validates the loop choice. Fluxes and offset charges are left at
72
+ scqubits defaults, since this exports topology and elements, not a Loops gauge.
73
+ Set those parameters on the returned object in its own flux convention.
74
+
75
+ cutoff is a scalar or a dict keyed by scqubits' 1-based mode indices.
76
+ trunc_num optionally enables one subsystem per mode, with scalar or list
77
+ truncations. These numerical options cannot be used with symbolic=True.
78
+ kwargs are forwarded to Circuit or SymbolicCircuit.from_yaml.
79
+
80
+ :param circuit: Circuit to export, without voltage-source branches.
81
+ :param subs: Numeric substitutions for all free element parameters.
82
+ :param node_order: Complete internal-node order. None uses circuit.internal_nodes.
83
+ :param bool symbolic: Return SymbolicCircuit instead of numerical Circuit.
84
+ :param transformation_matrix: Custom transformation, with rows in node_order.
85
+ :param closure_branches: Complete ordered list of closure-branch labels.
86
+ None uses scqubits defaults. Does not transfer this package's loop fluxes.
87
+ :param cutoff: Scalar cutoff or dict keyed by 1-based mode indices.
88
+ :param trunc_num: Scalar or list of subsystem truncation dimensions.
89
+ None leaves hierarchical diagonalization unconfigured.
90
+ :param kwargs: Additional keyword arguments forwarded to the scqubits constructor.
91
+ :returns: scqubits Circuit or SymbolicCircuit.
92
+ :raises ValueError: Invalid export parameters or unsupported circuit features.
93
+ """
94
+ import numpy as np
95
+ import scqubits as scq
96
+
97
+ yaml, indices = _scqubits_input(circuit, subs, node_order)
98
+ if symbolic and (cutoff is not None or trunc_num is not None):
99
+ raise ValueError("cutoff and trunc_num require a numerical Circuit")
100
+ constructor = scq.SymbolicCircuit.from_yaml if symbolic else scq.Circuit
101
+ result = constructor(yaml, from_file=False, **kwargs)
102
+ config = {}
103
+ if transformation_matrix is not None:
104
+ config["transformation_matrix"] = np.asarray(transformation_matrix, dtype=float)
105
+ if closure_branches is not None:
106
+ names = tuple(closure_branches)
107
+ if len(set(names)) != len(names) or set(names) - indices.keys():
108
+ raise ValueError("closure_branches must be distinct circuit branch names")
109
+ config["closure_branches"] = [result.branches[indices[name]] for name in names]
110
+ if config:
111
+ result.configure(**config)
112
+ if not symbolic:
113
+ modes = sorted(result.var_categories["periodic"] + result.var_categories["extended"])
114
+ if cutoff is not None:
115
+ for kind, prefix in (("periodic", "n"), ("extended", "ext")):
116
+ for mode in result.var_categories[kind]:
117
+ setattr(result, f"cutoff_{prefix}_{mode}", cutoff[mode] if isinstance(cutoff, dict) else cutoff)
118
+ if trunc_num is not None:
119
+ dims = [trunc_num] * len(modes) if isinstance(trunc_num, int) else list(trunc_num)
120
+ if len(dims) != len(modes):
121
+ raise ValueError("trunc_num must have one entry per dynamical mode")
122
+ if len(modes) > 1:
123
+ result.configure(system_hierarchy=[[mode] for mode in modes], subsystem_trunc_dims=dims)
124
+ elif modes:
125
+ result.truncated_dim = dims[0]
126
+ return result
@@ -0,0 +1,186 @@
1
+ """End-to-end quantization and its Result."""
2
+
3
+ from collections import Counter
4
+ from dataclasses import dataclass, fields, is_dataclass, replace
5
+
6
+ import sympy as sym
7
+
8
+ from .circuit import Circuit
9
+ from .flux import irrotational_B
10
+ from .hamiltonian import Hamiltonian, hamiltonian
11
+ from .lagrangian import Lagrangian, lagrangian
12
+ from .loops import Loops
13
+ from .modes import Coordinates, decouple, mode_basis, residual_freedom, transform
14
+
15
+ __all__ = ["Result", "quantize", "numerify"]
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class Result:
20
+ """A quantized circuit with its Lagrangian, coordinates, flux assignment, and Hamiltonian.
21
+
22
+ quantize returns a Result, and Result.transform returns a new one in other coordinates.
23
+
24
+ :ivar circuit: The quantized Circuit.
25
+ :ivar loops: The Loops whose external fluxes enter H.
26
+ :ivar lag: Lagrangian matrices of the circuit.
27
+ :ivar coords: Retained Coordinates.
28
+ :ivar B: Branch-by-loop flux assignment, with loops.G * B = I.
29
+ :ivar ham: The Hamiltonian and its coefficient matrices.
30
+ :ivar B_static: Separate assignment of the static loop fluxes, or None.
31
+ :ivar static: Static loop fluxes [Wb] in loops order, or None.
32
+ :ivar residual_S: Product of the S_1 applied by transform, or None.
33
+
34
+ The matrices of lag, coords, and ham are named as follows.
35
+
36
+ .. code-block:: text
37
+
38
+ Omega, Omega_int incidence matrix and its internal rows
39
+ omega_J_int junction columns of Omega_int
40
+ omega_L_int inductor columns of Omega_int
41
+ C_b, Lb_inv branch capacitances, inverse inductances
42
+ C_int, C_int_src internal and drive capacitance blocks
43
+ Lstar_int internal susceptance L*_int
44
+ G, Phi_ext loop matrix and external fluxes [Wb]
45
+ Z, types retained coordinate transformation and mode types
46
+ R retained-coordinate extraction, R Z = I and R Z_2 = 0
47
+ C_tilde, Lstar_tilde, omega_J_tilde, omega_L_tilde transformed objects
48
+ B flux-assignment matrix, irrotational by default
49
+ E_C, E_L, E_Lb frequency-unit matrices [GHz]
50
+ n_g offset charges [Cooper pairs]
51
+ H Hamiltonian H/h [GHz]
52
+ """
53
+
54
+ circuit: Circuit
55
+ loops: Loops
56
+ lag: Lagrangian
57
+ coords: Coordinates
58
+ B: sym.ImmutableMatrix
59
+ ham: Hamiltonian
60
+ B_static: sym.ImmutableMatrix | None = None # assignment of the static bias
61
+ static: sym.ImmutableMatrix | None = None # static loop fluxes [Wb], loops order
62
+
63
+ residual_S: sym.ImmutableMatrix | None = None # cumulative retained frame change
64
+
65
+ @property
66
+ def H(self):
67
+ """The Hamiltonian H/h [GHz], ham.H."""
68
+ return self.ham.H
69
+
70
+ def residual_freedom(self, keep_harmonic=True):
71
+ """Symbolic S_1 with a free entry wherever these coordinates allow mixing, in coords.types order.
72
+
73
+ :param bool keep_harmonic: Preserve harmonic columns when True. Allow
74
+ extended/harmonic mixing when False.
75
+ :returns: Symbolic residual transformation matrix in the current coordinate order.
76
+ """
77
+ return residual_freedom(self.coords, keep_harmonic)
78
+
79
+ def transform(self, S1, *, simplify=False, C_tilde=None, Lstar_tilde=None):
80
+ """The same circuit and loops quantized in coordinates Z S_1.
81
+
82
+ :param S1: Invertible residual transformation with new node matrix Z * S1.
83
+ Must obey allowed mode mixing and compact-period constraints.
84
+ :param bool simplify: Simplify the rebuilt Hamiltonian.
85
+ :param C_tilde: Optional S1^T C~ S1, when already known, as from normal_mode_decoupling.
86
+ It is used as given, without a check.
87
+ :param Lstar_tilde: Optional S1^T L~* S1, likewise.
88
+ :returns: New Result with the same B and static assignment. The original is unchanged.
89
+ :raises ValueError: Disallowed mixing or an invalid transformation.
90
+ """
91
+ from .modes import _check_residual
92
+ S = _check_residual(self.coords.types, sym.ImmutableMatrix(S1))
93
+ coords = transform(self.lag, self.coords, S, C_tilde=C_tilde, Lstar_tilde=Lstar_tilde)
94
+ result = _result(self.circuit, self.loops, self.lag, coords, simplify,
95
+ B=self.B, B_static=self.B_static, static=self.static, check_assignment=False)
96
+ cumulative = S if self.residual_S is None else self.residual_S * S
97
+ return replace(result, residual_S=sym.ImmutableMatrix(cumulative))
98
+
99
+ def _repr_latex_(self):
100
+ counts = ", ".join(f"{t}: {k}" for t, k in Counter(self.coords.types).items())
101
+ return f"$\\displaystyle H_{{\\mathrm{{GHz}}}} = {sym.latex(self.H)} \\quad \\text{{(modes {counts})}}$"
102
+
103
+
104
+ def quantize(circuit, loops, Z_full=None, types=None, *, simplify=False, B=None, B_static=None, static=None):
105
+ """Quantize with an automatic or explicit basis, and optionally simplify the final H.
106
+
107
+ :param circuit: Circuit with SI element values and junction energies in GHz.
108
+ :param loops: Complete Loops basis belonging to this circuit.
109
+ :param Z_full: Square node-to-coordinate matrix, including discarded modes.
110
+ Rows follow circuit.internal_nodes. Omit together with types for an automatic basis.
111
+ :param types: Column mode labels c, e, h, fr, fz, cy. Required with Z_full.
112
+ :param bool simplify: Factor coefficients and simplify trigonometric terms in H.
113
+ :param B: Optional branch-by-loop flux assignment, in circuit.branch_names
114
+ and loops.names order. Must satisfy loops.G * B = I. None selects the
115
+ irrotational assignment. A custom assignment can introduce an EMF drive.
116
+ :param B_static: Optional separate assignment for the static part of the loop fluxes.
117
+ Must satisfy loops.G * B_static = I and be given with static.
118
+ B then places only the offsets loops.Phi_ext - static and alone sets the EMF drive.
119
+ :param static: {loop name: static flux [Wb]} for B_static. Omitted loops have none.
120
+ :returns: Result containing lag, coords, B, ham, and H in GHz.
121
+ :raises ValueError: Mismatched circuit/loops, an invalid coordinate basis, or an invalid assignment.
122
+ """
123
+ if loops.circuit != circuit:
124
+ raise ValueError("loops must belong to the circuit being quantized")
125
+ lag = lagrangian(circuit)
126
+ if Z_full is None and types is None:
127
+ coords = decouple(lag, *mode_basis(lag), check=False) # valid by construction
128
+ elif Z_full is None or types is None:
129
+ raise ValueError("Z_full and types must be supplied together")
130
+ else:
131
+ coords = decouple(lag, Z_full, types)
132
+ if (B_static is None) != (static is None):
133
+ raise ValueError("B_static and static must be supplied together")
134
+ if static is not None:
135
+ unknown = set(static) - set(loops.names)
136
+ if unknown:
137
+ raise ValueError(f"static names unknown loops: {sorted(unknown)}")
138
+ static = sym.ImmutableMatrix([static.get(name, 0) for name in loops.names])
139
+ return _result(circuit, loops, lag, coords, simplify, B=B, B_static=B_static, static=static)
140
+
141
+
142
+ def _check_assignment(loops, B, name):
143
+ if not (loops.G * sym.ImmutableMatrix(B) - sym.eye(loops.G.rows)).applyfunc(sym.cancel).is_zero_matrix:
144
+ raise ValueError(f"{name} must satisfy G * {name} = I") # exact only after cancel, e.g. irrotational B
145
+ sources = [k for k, b in enumerate(loops.circuit.branches) if b.type == "V"]
146
+ if sources and not sym.ImmutableMatrix(B)[sources, :].applyfunc(sym.cancel).is_zero_matrix:
147
+ raise ValueError(f"{name} must not assign flux to a source branch, which is pinned at V(t)")
148
+
149
+
150
+ def _result(circuit, loops, lag, coords, simplify, *, B=None, B_static=None, static=None, check_assignment=True):
151
+ """Flux assignment and Hamiltonian for given coordinates."""
152
+ if B is None:
153
+ B = irrotational_B(lag, coords, loops)
154
+ elif check_assignment:
155
+ _check_assignment(loops, B, "B")
156
+ if B_static is not None:
157
+ B_static = sym.ImmutableMatrix(B_static)
158
+ if check_assignment:
159
+ _check_assignment(loops, B_static, "B_static")
160
+ ham = hamiltonian(lag, coords, loops, B, circuit.t, simplify=simplify, B_static=B_static, static=static)
161
+ return Result(circuit=circuit, loops=loops, lag=lag, coords=coords, B=B, ham=ham,
162
+ B_static=B_static, static=static)
163
+
164
+
165
+ def numerify(obj, values):
166
+ """Substitute element values into every matrix and expression of obj.
167
+
168
+ Works on a Lagrangian, Coordinates, Hamiltonian, or Result. In a Result, lag,
169
+ coords, B, and ham are substituted, while circuit and loops stay as built.
170
+ Physical constants stay symbolic. Follow with subs_constants for those.
171
+ Exact values (integers, Rationals) keep the exact zero tests of mode_basis,
172
+ decouple, and transform valid. Floats suit only end products such as B or H.
173
+
174
+ :param obj: Lagrangian, Coordinates, Hamiltonian, Result, or a SymPy object.
175
+ :param values: {symbol: number} for the element values to substitute.
176
+ :returns: An object of the same type with the values substituted.
177
+ """
178
+ if isinstance(obj, (Circuit, Loops)):
179
+ return obj
180
+ if is_dataclass(obj):
181
+ return replace(obj, **{f.name: numerify(getattr(obj, f.name), values) for f in fields(obj) if f.init})
182
+ if isinstance(obj, tuple):
183
+ return tuple(numerify(x, values) for x in obj)
184
+ if isinstance(obj, (sym.Basic, sym.MatrixBase)):
185
+ return obj.subs(values)
186
+ return obj
@@ -0,0 +1,252 @@
1
+ """How far to shear a harmonic mode onto a junction mode.
2
+
3
+ In a frame where a junction mode ``J`` (a phase inside a cosine) and a harmonic mode ``f`` couple only through
4
+ ``E_L[f, J] x_f x_J``, the shear ``x_f = y_f + a x_J`` by the full amount ``a* = -E_L[f, J] / E_L[f, f]`` removes that
5
+ coupling and puts a charge coupling in its place. When a hierarchical solve truncates between ``f`` and ``J`` the best
6
+ shear is usually partial: the fraction
7
+
8
+ s* = (X + c) / (X + 2 c + P), c = 4 E_C[J, J] / Omega_f, P = (8 E_C[J, J] / Omega_f)^2 <n_J^2>,
9
+
10
+ of ``a*``, with ``X = <dx_J^2>`` and ``<n_J^2>`` the ground-state moments of the junction mode's own Hamiltonian and
11
+ ``Omega_f = sqrt(8 E_C[f, f] E_L[f, f])``. Equivalently ``s* = Omega_f / (Omega_f + omega_eff)``: full shear for a
12
+ frame mode much stiffer than the junction's motion, none for a much softer one. The moments come from a grid solve of
13
+ the one-mode Hamiltonian (a few hundred points, eighth-order stencils), and since the shear changes that Hamiltonian
14
+ and ``Omega_f``, the fractions are iterated to self-consistency.
15
+
16
+ The pairs are given explicitly: the shear only matters for a pair that the solve truncates between, which depends on
17
+ the tree the caller has in mind.
18
+ """
19
+ from dataclasses import dataclass, field
20
+
21
+ import numpy as np
22
+
23
+ __all__ = ["shear_S1", "ShearInfo", "PairShear", "JunctionMoments"]
24
+
25
+
26
+ # Eighth-order central stencils for d/dphi and d^2/dphi^2 (interior points).
27
+ _D1 = np.array([1 / 280, -4 / 105, 1 / 5, -4 / 5, 0.0, 4 / 5, -1 / 5, 4 / 105, -1 / 280])
28
+ _D2 = np.array([-1 / 560, 8 / 315, -1 / 5, 8 / 5, -205 / 72, 8 / 5, -1 / 5, 8 / 315, -1 / 560])
29
+
30
+
31
+ class PhaseGrid:
32
+ """Uniform grid on ``[-extent, extent]`` with eighth-order stencils."""
33
+
34
+ compact = False
35
+
36
+ def __init__(self, extent, points):
37
+ self.extent = float(extent)
38
+ self.points = int(points)
39
+ self.grid = np.linspace(-self.extent, self.extent, self.points)
40
+ self.step = self.grid[1] - self.grid[0]
41
+
42
+ @property
43
+ def size(self):
44
+ return self.points
45
+
46
+ def _stencil(self, coefficients, power):
47
+ return sum(np.eye(self.size, k=offset) * c
48
+ for offset, c in zip(range(-4, 5), coefficients)) / self.step ** power
49
+
50
+ def n(self):
51
+ return -1j * self._stencil(_D1, 1)
52
+
53
+ def n2(self):
54
+ return -self._stencil(_D2, 2)
55
+
56
+ def expiphi(self, k):
57
+ return np.diag(np.exp(1j * k * self.grid))
58
+
59
+ def phi(self):
60
+ return np.diag(self.grid)
61
+
62
+ def edge_weight(self, psi):
63
+ return float(abs(psi[0]) ** 2 + abs(psi[-1]) ** 2)
64
+
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class JunctionMoments:
69
+ """Ground-state moments of junction mode ``J``'s own Hamiltonian in the final frame, and its grid."""
70
+
71
+ J: int
72
+ dx2: float # <(x - <x>)^2>
73
+ n2: float # <n^2>
74
+ center: float
75
+ extent: float
76
+ points: int
77
+ edge_weight: float
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class PairShear:
82
+ """The rule for one (harmonic, junction) pair in the final frame."""
83
+
84
+ f: int
85
+ J: int
86
+ Omega: float # frame-mode frequency sqrt(8 E_C[f, f] E_L[f, f]), GHz
87
+ omega1: float # 4 E_C[J, J] / <dx^2>
88
+ omega2: float # 8 E_C[J, J] sqrt(<n^2> / <dx^2>)
89
+ a_star: float # the full shear -E_L[f, J] / E_L[f, f] of the input frame
90
+ s: float # the fraction s*
91
+ A: float # the applied entry S[f, J] = s* a*
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class ShearInfo:
96
+ """Diagnostics returned by shear_S1. Printing it gives a table.
97
+
98
+ :ivar pairs: One PairShear per (f, J) pair.
99
+ :ivar junctions: {J: JunctionMoments} in the final frame.
100
+ :ivar iterations: Number of iterations run.
101
+ :ivar converged: Whether the fractions changed by at most tol in the last iteration.
102
+ :ivar change: Largest change of any fraction in the last iteration.
103
+ :ivar history: The fractions {(f, J): s*} after each iteration.
104
+ """
105
+
106
+ pairs: list
107
+ junctions: dict
108
+ iterations: int
109
+ converged: bool
110
+ change: float # largest change of any s* in the last iteration
111
+ history: list = field(default_factory=list)
112
+
113
+ def __str__(self):
114
+ lines = [f"shear rule: {self.iterations} iteration(s), " +
115
+ ("converged" if self.converged else "not converged") + f" (last change {self.change:.1e})",
116
+ " f J Omega omega1 omega2 a* s* S[f, J]"]
117
+ for p in self.pairs:
118
+ lines.append(f"{p.f:3d} {p.J:3d} {p.Omega:8.3f} {p.omega1:8.3f} {p.omega2:8.3f} {p.a_star:8.4f} "
119
+ f"{p.s:7.4f} {p.A:12.6g}")
120
+ lines.append(" J <dx^2> <n^2> grid (center, extent, points) edge weight")
121
+ for m in self.junctions.values():
122
+ lines.append(f"{m.J:3d} {m.dx2:8.4f} {m.n2:8.4f} ({m.center:.3f}, {m.extent:.2f}, {m.points})"
123
+ f" {m.edge_weight:.1e}")
124
+ return "\n".join(lines)
125
+
126
+
127
+ def _junction_cosines(ham, J):
128
+ """``(E, k, delta)`` of the cosines on mode ``J``, which must act on ``J`` alone."""
129
+ terms = []
130
+ for E, w, d in ham.cosines:
131
+ if abs(w[J]) <= 1e-12:
132
+ continue
133
+ others = np.delete(w, J)
134
+ if np.any(np.abs(others) > 1e-12):
135
+ raise ValueError(f"mode {J} appears in a cosine with other modes ({w}); the rule needs single-mode "
136
+ "junction cosines")
137
+ terms.append((E, w[J], d))
138
+ return terms
139
+
140
+
141
+ def _grid(EC, EL, terms, extent_scale, max_points):
142
+ """Extent and point count of one mode's grid, from its zero-point width and junction energies."""
143
+ zpf = (2 * EC / EL) ** 0.25
144
+ omega = np.sqrt(8 * EC * EL)
145
+ energy = sum(abs(E) for E, _, _ in terms)
146
+ k_max = max((abs(k) for _, k, _ in terms), default=0.0)
147
+ extent = max(6 * zpf, np.sqrt(2 * (2 * energy + 12 * omega + 4 * EC) / EL)) * extent_scale
148
+ step = zpf / 6
149
+ if k_max > 0:
150
+ step = min(step, np.pi / (6 * k_max))
151
+ return extent, min(int(np.ceil(2 * extent / step)) + 1, max_points)
152
+
153
+
154
+ def _moments(ham, J, *, extent_scale, max_points, edge_tol, widenings=6):
155
+ """Ground-state moments of ``4 E_C n^2 + 1/2 E_L x^2 + b x - sum E cos(k x + delta)`` for mode ``J``.
156
+
157
+ The offset charge of an extended mode is a gauge choice and drops out. The grid is centered on the minimum of the
158
+ quadratic part and widened until the ground state's weight on the two end points is below ``edge_tol``.
159
+ """
160
+ EC, EL, b = ham.E_C[J, J], ham.E_L[J, J], ham.flux_linear[J]
161
+ if EC <= 0 or EL <= 0:
162
+ raise ValueError(f"junction mode {J} needs positive E_C and E_L in this frame, got {EC}, {EL}")
163
+ terms = _junction_cosines(ham, J)
164
+ extent, points = _grid(EC, EL, terms, extent_scale, max_points)
165
+ center = -b / EL
166
+ for _ in range(widenings):
167
+ grid = PhaseGrid(extent, points)
168
+ x = center + grid.grid
169
+ V = 0.5 * EL * x**2 + b * x - sum(E * np.cos(k * x + d) for E, k, d in terms)
170
+ H = 4 * EC * np.real(grid.n2()) + np.diag(V)
171
+ _, vec = np.linalg.eigh(H)
172
+ psi = vec[:, 0] / np.linalg.norm(vec[:, 0])
173
+ edge = grid.edge_weight(psi)
174
+ if edge <= edge_tol:
175
+ break
176
+ extent, points = 1.5 * extent, int(np.ceil(1.5 * points))
177
+ else:
178
+ raise ValueError(f"junction mode {J}: the ground state still reaches the grid edge (weight {edge:.1e}) on "
179
+ f"±{extent / 1.5:.3g}; raise extent_scale")
180
+ p = psi**2
181
+ mean = p @ x
182
+ dx2 = p @ (x - mean) ** 2
183
+ n2 = psi @ (np.real(grid.n2()) @ psi)
184
+ return JunctionMoments(J, float(dx2), float(n2), float(center), float(extent), int(points), float(edge))
185
+
186
+
187
+ def shear_S1(ham, pairs, *, tol=1e-6, maxiter=50, extent_scale=1.0, max_points=400, edge_tol=1e-8):
188
+ """Shear each harmonic mode ``f`` onto junction mode ``J`` by the rule's fraction, for the given ``(f, J)`` pairs.
189
+
190
+ :param ham: NumericHamiltonian in a frame where each pair couples through ``E_L[f, J]`` and not through ``E_C``.
191
+ :param pairs: ``(f, J)`` mode indices in ``ham.types`` order: ``f`` harmonic (``"h"``), ``J`` a junction mode
192
+ (``"e"``) whose cosines act on it alone, ``E_L[f, J] != 0``, ``E_C[f, J] == 0``. A frame mode may be paired
193
+ with several junctions and a junction with several frame modes.
194
+ :param tol: Stop when no fraction changes by more than ``tol`` between iterations.
195
+ :param maxiter: At most this many iterations (each one grid solve per junction).
196
+ :param extent_scale, max_points, edge_tol: The junction grids (sized from each mode's zero-point width and
197
+ junction energies, widened until the ground state's edge weight is below ``edge_tol``).
198
+ :returns: ``(S, info)``: ``S`` with ``x_old = S x_new``, the identity plus ``S[f, J] = s* a*``, for
199
+ ``ham.transformed(S)`` or ``Result.transform(S)``; ``info`` a ShearInfo (printable table).
200
+ :raises ValueError: An invalid pair, or one the rule does not cover.
201
+ """
202
+ pairs = [(int(f), int(J)) for f, J in pairs]
203
+ if not pairs:
204
+ raise ValueError("give at least one (f, J) pair")
205
+ if len(set(pairs)) != len(pairs):
206
+ raise ValueError("a pair is given twice")
207
+ N = ham.size
208
+ scale_L, scale_C = np.max(np.abs(ham.E_L)), np.max(np.abs(ham.E_C))
209
+ a_star = {}
210
+ for f, J in pairs:
211
+ if not (0 <= f < N and 0 <= J < N) or f == J:
212
+ raise ValueError(f"pair ({f}, {J}): mode indices must be distinct and below {N}")
213
+ if ham.types[f] != "h" or ham.E_L[f, f] <= 0:
214
+ raise ValueError(f"pair ({f}, {J}): mode {f} must be harmonic with E_L[f, f] > 0, "
215
+ f"got type {ham.types[f]!r}")
216
+ if ham.types[J] != "e" or not _junction_cosines(ham, J):
217
+ raise ValueError(f"pair ({f}, {J}): mode {J} must be an extended junction mode (in a cosine), "
218
+ f"got type {ham.types[J]!r}")
219
+ if abs(ham.E_L[f, J]) <= 1e-12 * scale_L:
220
+ raise ValueError(f"pair ({f}, {J}): E_L[f, J] = 0, nothing to shear")
221
+ if abs(ham.E_C[f, J]) > 1e-12 * scale_C:
222
+ raise ValueError(f"pair ({f}, {J}): E_C[f, J] = {ham.E_C[f, J]}; the rule needs the pair coupled through "
223
+ "E_L only")
224
+ a_star[f, J] = -ham.E_L[f, J] / ham.E_L[f, f]
225
+ junction_modes = sorted({J for _, J in pairs})
226
+ s = {pair: 0.0 for pair in pairs}
227
+ S = np.eye(N)
228
+ history, change, converged = [], np.inf, False
229
+ for iteration in range(1, maxiter + 1):
230
+ sheared = ham.transformed(S)
231
+ moments = {J: _moments(sheared, J, extent_scale=extent_scale, max_points=max_points, edge_tol=edge_tol)
232
+ for J in junction_modes}
233
+ rows, new = [], {}
234
+ for f, J in pairs:
235
+ m, EC = moments[J], sheared.E_C[J, J]
236
+ Omega = np.sqrt(8 * sheared.E_C[f, f] * sheared.E_L[f, f])
237
+ c = 4 * EC / Omega
238
+ P = (8 * EC / Omega) ** 2 * m.n2
239
+ new[f, J] = (m.dx2 + c) / (m.dx2 + 2 * c + P)
240
+ rows.append((f, J, Omega, 4 * EC / m.dx2, 8 * EC * np.sqrt(m.n2 / m.dx2)))
241
+ change = max(abs(new[p] - s[p]) for p in pairs)
242
+ s = new
243
+ history.append(dict(s))
244
+ S = np.eye(N)
245
+ for f, J in pairs:
246
+ S[f, J] = s[f, J] * a_star[f, J]
247
+ if change <= tol:
248
+ converged = True
249
+ break
250
+ info_pairs = [PairShear(f, J, float(Om), float(w1), float(w2), float(a_star[f, J]), float(s[f, J]),
251
+ float(S[f, J])) for f, J, Om, w1, w2 in rows]
252
+ return S, ShearInfo(info_pairs, moments, iteration, converged, float(change), history)
@@ -0,0 +1,91 @@
1
+ """Physical constants and unit conversions.
2
+
3
+ Circuit inputs are SI (F, H, V, Wb, s).
4
+ Energies and the Hamiltonian are ordinary frequencies E/h in GHz.
5
+ Constants remain symbolic until subs_constants() is called.
6
+ """
7
+
8
+ import sympy as sym
9
+
10
+ __all__ = [
11
+ "subs_constants", "farad_to_ghz", "ghz_to_farad", "henry_to_ghz", "ghz_to_henry", "weber_to_phase",
12
+ "phase_to_weber",
13
+ ]
14
+
15
+ # Keep SI h distinct from the GHz conversion symbol displayed as h.
16
+ e, h, hbar, Phi0 = sym.symbols("e h_SI hbar Phi_0", positive=True)
17
+ phi0 = Phi0 / (2 * sym.pi) # reduced flux quantum [Wb], eq:dimless_defs
18
+ e_num = sym.Rational("1.602176634e-19") # elementary charge [C]
19
+ h_num = sym.Rational("6.62607015e-34") # Planck constant [J s]
20
+ hbar_num = h_num / (2 * sym.pi)
21
+ Phi0_num = h_num / (2 * e_num) # flux quantum [Wb]
22
+ phi0_num = Phi0_num / (2 * sym.pi)
23
+ GHz = sym.Integer(10) ** 9
24
+ h_GHz = sym.Symbol("h", positive=True) # h in GHz-based formulas: joules per GHz, 10^9 h_SI
25
+ h_GHz_num = h_num * GHz
26
+
27
+
28
+ def subs_constants(expr):
29
+ """Substitute exact constants in a SymPy expression or matrix. Use .evalf() for decimals.
30
+
31
+ :param expr: SymPy expression or matrix containing symbolic physical constants.
32
+ :returns: Expression or matrix with exact numerical constants substituted.
33
+ """
34
+ return sym.sympify(expr).subs({e: e_num, h: h_num, hbar: hbar_num, Phi0: Phi0_num, h_GHz: h_GHz_num}, simultaneous=True)
35
+
36
+
37
+ # eq:EC_EL_scalar: h E_C = e^2 / 2C
38
+ def farad_to_ghz(C):
39
+ """Convert capacitance in farads.
40
+
41
+ :param C: Capacitance in farads, a scalar or SymPy expression.
42
+ :returns: Charging energy E_C/h in GHz, with physical constants kept symbolic.
43
+ """
44
+ return e**2 / (2 * h_GHz * C)
45
+
46
+
47
+ def ghz_to_farad(E_C):
48
+ """Convert charging energy in GHz to capacitance in farads.
49
+
50
+ :param E_C: Charging energy E_C/h in GHz, a scalar or SymPy expression.
51
+ :returns: Capacitance in farads, with physical constants kept symbolic.
52
+ """
53
+ return e**2 / (2 * h_GHz * E_C)
54
+
55
+
56
+ # eq:EC_EL_scalar: h E_L = phi0^2 / L
57
+ def henry_to_ghz(L):
58
+ """Convert inductance in henries.
59
+
60
+ :param L: Inductance in henries, a scalar or SymPy expression.
61
+ :returns: Inductive energy E_L/h in GHz, with physical constants kept symbolic.
62
+ """
63
+ return phi0**2 / (h_GHz * L)
64
+
65
+
66
+ def ghz_to_henry(E_L):
67
+ """Convert inductive energy in GHz to inductance in henries.
68
+
69
+ :param E_L: Inductive energy E_L/h in GHz, a scalar or SymPy expression.
70
+ :returns: Inductance in henries, with physical constants kept symbolic.
71
+ """
72
+ return phi0**2 / (h_GHz * E_L)
73
+
74
+
75
+ # eq:dimless_defs: varphi = Phi / phi0
76
+ def weber_to_phase(Phi):
77
+ """Convert flux in webers.
78
+
79
+ :param Phi: Flux in webers, a scalar or SymPy expression.
80
+ :returns: Dimensionless phase 2*pi*Phi/Phi0, with physical constants kept symbolic.
81
+ """
82
+ return Phi / phi0
83
+
84
+
85
+ def phase_to_weber(varphi):
86
+ """Convert dimensionless phase.
87
+
88
+ :param varphi: Dimensionless phase, a scalar or SymPy expression.
89
+ :returns: Flux in webers, with physical constants kept symbolic.
90
+ """
91
+ return varphi * phi0