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,64 @@
|
|
|
1
|
+
"""Symbolic quantization of lumped superconducting circuits.
|
|
2
|
+
|
|
3
|
+
Build a :class:`Circuit` from :class:`Branch` elements, choose :class:`Loops`,
|
|
4
|
+
and call :func:`quantize` for the symbolic Hamiltonian ``H/h`` in GHz.
|
|
5
|
+
|
|
6
|
+
circuit.py Branch, Circuit, incidence
|
|
7
|
+
loops.py loop bases and external fluxes
|
|
8
|
+
lagrangian.py capacitance, inductance, and incidence matrices
|
|
9
|
+
modes.py mode classification, decoupling, residual freedom
|
|
10
|
+
numerical.py numerical coordinate searches
|
|
11
|
+
shear.py partial shears of harmonic modes onto junction modes
|
|
12
|
+
flux.py irrotational flux assignment
|
|
13
|
+
hamiltonian.py frequency-unit Hamiltonian
|
|
14
|
+
quantize.py end-to-end quantization and Result
|
|
15
|
+
io.py JSON interchange (kronfree-spec)
|
|
16
|
+
numeric_spec.py floating-point Hamiltonians evaluated from a spec
|
|
17
|
+
qpackage_interface.py scqubits export
|
|
18
|
+
draw.py Schemdraw circuit diagrams (optional: ``[draw]``)
|
|
19
|
+
units.py constants and unit converters
|
|
20
|
+
|
|
21
|
+
Extension, imported explicitly:
|
|
22
|
+
|
|
23
|
+
circuit_quantization.optimize exact symbolic coordinate search (optional: ``[optimize]``)
|
|
24
|
+
|
|
25
|
+
The Result docstring lists the matrix names.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from importlib.metadata import PackageNotFoundError as _PackageNotFoundError, version as _version
|
|
29
|
+
|
|
30
|
+
from .circuit import Branch, Circuit
|
|
31
|
+
from .draw import draw_circuit_diagram
|
|
32
|
+
from .flux import B_from_shares
|
|
33
|
+
from .io import load_spec, save_spec, to_spec, load_record, to_record
|
|
34
|
+
from .loops import Loops
|
|
35
|
+
from .modes import (
|
|
36
|
+
compact_charge_decoupling,
|
|
37
|
+
normal_mode_decoupling,
|
|
38
|
+
)
|
|
39
|
+
from .numerical import cost_normal_modes, numerical_S1
|
|
40
|
+
from .numeric_spec import normal_mode_transformation, numeric_hamiltonian
|
|
41
|
+
from .quantize import Result, quantize
|
|
42
|
+
from .qpackage_interface import scqubits_yaml, to_scqubits
|
|
43
|
+
from .units import (
|
|
44
|
+
farad_to_ghz,
|
|
45
|
+
ghz_to_farad,
|
|
46
|
+
ghz_to_henry,
|
|
47
|
+
henry_to_ghz,
|
|
48
|
+
phase_to_weber,
|
|
49
|
+
subs_constants,
|
|
50
|
+
weber_to_phase,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
try:
|
|
54
|
+
__version__ = _version("circuit-quantization")
|
|
55
|
+
except _PackageNotFoundError: # run from a source tree that is not installed
|
|
56
|
+
__version__ = "unknown"
|
|
57
|
+
|
|
58
|
+
__all__ = [
|
|
59
|
+
"B_from_shares", "Branch", "Circuit", "Loops", "Result", "compact_charge_decoupling", "cost_normal_modes",
|
|
60
|
+
"draw_circuit_diagram", "farad_to_ghz", "ghz_to_farad", "ghz_to_henry", "henry_to_ghz", "load_record",
|
|
61
|
+
"load_spec", "normal_mode_decoupling", "normal_mode_transformation", "numeric_hamiltonian", "numerical_S1",
|
|
62
|
+
"phase_to_weber", "quantize", "save_spec", "scqubits_yaml", "subs_constants", "to_record", "to_scqubits",
|
|
63
|
+
"to_spec", "weber_to_phase",
|
|
64
|
+
]
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""Circuit description and incidence matrix."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
|
|
6
|
+
import networkx as nx
|
|
7
|
+
import sympy as sym
|
|
8
|
+
|
|
9
|
+
from .units import Phi0, e, ghz_to_farad, ghz_to_henry, h, hbar, h_GHz
|
|
10
|
+
|
|
11
|
+
__all__ = ["Branch", "Circuit", "incidence"]
|
|
12
|
+
|
|
13
|
+
# Branch order of eq:Omega_columns.
|
|
14
|
+
TYPES = ("C", "J", "L", "V")
|
|
15
|
+
INDUCTIVE = ("J", "L")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _variables(values):
|
|
19
|
+
"""Unique free symbols in value order, excluding physical constants."""
|
|
20
|
+
constants = {e, h, hbar, Phi0, h_GHz}
|
|
21
|
+
return tuple(dict.fromkeys(
|
|
22
|
+
symbol for value in values if value is not None
|
|
23
|
+
for symbol in sorted(sym.sympify(value).free_symbols - constants, key=sym.default_sort_key)
|
|
24
|
+
))
|
|
25
|
+
|
|
26
|
+
# Generate symbols for branch parameters
|
|
27
|
+
def parameter(name, energy_symbols=False):
|
|
28
|
+
"""Symbol for an omitted value; the first letter of name selects C, J (for E_J), L, or V.
|
|
29
|
+
|
|
30
|
+
C1 -> C_1, CJ1 -> C_J1, J1 -> E_J1, L1 -> L_1, V1 -> V_1.
|
|
31
|
+
energy_symbols turns C and L into GHz energies E_C1, E_CJ1, E_L1, converted to SI.
|
|
32
|
+
"""
|
|
33
|
+
kind = name[0]
|
|
34
|
+
if kind == "J" or (energy_symbols and kind in ("C", "L")):
|
|
35
|
+
symbol = sym.Symbol(f"E_{name}", positive=True)
|
|
36
|
+
else:
|
|
37
|
+
label = f"{kind}_{name[1:]}" if name[1:] else kind
|
|
38
|
+
symbol = sym.Symbol(label, **({"real": True} if kind == "V" else {"positive": True}))
|
|
39
|
+
if energy_symbols and kind == "C":
|
|
40
|
+
return ghz_to_farad(symbol)
|
|
41
|
+
if energy_symbols and kind == "L":
|
|
42
|
+
return ghz_to_henry(symbol)
|
|
43
|
+
return symbol
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class Branch:
|
|
47
|
+
"""One oriented branch, tail -> head.
|
|
48
|
+
|
|
49
|
+
C [F] is an attribute any branch may carry.
|
|
50
|
+
At most one of L [H], EJ [GHz], or V [V] makes it an inductor, junction, or source.
|
|
51
|
+
V is the source node's potential relative to ground.
|
|
52
|
+
Floats are converted to exact rationals, so identities such as G B = I
|
|
53
|
+
and vanishing cross blocks hold exactly.
|
|
54
|
+
|
|
55
|
+
With no values supplied, infer C/J/L/V from the name's first letter and
|
|
56
|
+
generate symbols: C1 -> C_1, L1 -> L_1, J1 -> (C_J1, E_J1), V1 -> V_1.
|
|
57
|
+
Omitted junction C is generated even when EJ is supplied. Inductor C defaults
|
|
58
|
+
to zero. energy_symbols=True generates E_C1, E_CJ1, E_L1 instead, converting
|
|
59
|
+
these GHz energies to SI internally. Explicit values always retain the
|
|
60
|
+
units above. All generated symbols are positive except real-valued voltages.
|
|
61
|
+
|
|
62
|
+
:param str name: Unique branch label. With all values omitted, its first letter
|
|
63
|
+
selects C, J, L, or V and its suffix names the generated symbols.
|
|
64
|
+
:param tail: Hashable label of the positive-incidence endpoint.
|
|
65
|
+
:param head: Hashable label of the negative-incidence endpoint.
|
|
66
|
+
:param C: Capacitance in farads. Omitted junction capacitance is generated.
|
|
67
|
+
Omitted inductor or source capacitance is zero.
|
|
68
|
+
:param L: Inductance in henries, or None if not an inductor.
|
|
69
|
+
:param EJ: Josephson energy E/h in GHz, or None if not a junction.
|
|
70
|
+
:param V: Source-node voltage relative to ground, in volts, or None.
|
|
71
|
+
:param bool energy_symbols: Generate capacitance/inductance energy symbols in
|
|
72
|
+
GHz and convert internally to SI. Does not change explicit input units.
|
|
73
|
+
:raises ValueError: Invalid element values, incompatible types, or a self-loop.
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
name: str
|
|
77
|
+
tail: object
|
|
78
|
+
head: object
|
|
79
|
+
C: object = None
|
|
80
|
+
L: object = None
|
|
81
|
+
EJ: object = None
|
|
82
|
+
V: object = None
|
|
83
|
+
energy_symbols: bool = field(default=False, kw_only=True)
|
|
84
|
+
|
|
85
|
+
# Make any necessary symbols and verify valid branches
|
|
86
|
+
def __post_init__(self):
|
|
87
|
+
self._set_default_values()
|
|
88
|
+
self._check_branch()
|
|
89
|
+
|
|
90
|
+
def _set_default_values(self):
|
|
91
|
+
"""Generate symbols for omitted values, then convert floats to exact rationals."""
|
|
92
|
+
name = self.name[0] + self.name[1:].lstrip("_") if self.name else "" # J_1 -> J1
|
|
93
|
+
if self.C is None and self.L is None and self.EJ is None and self.V is None:
|
|
94
|
+
if name[:1] not in TYPES:
|
|
95
|
+
raise ValueError("A branch without values needs a name starting with C, J, L, or V")
|
|
96
|
+
attr = {"C": "C", "J": "EJ", "L": "L", "V": "V"}[name[0]]
|
|
97
|
+
object.__setattr__(self, attr, parameter(name, self.energy_symbols))
|
|
98
|
+
# Omitted C is generated for a junction and zero for an inductor or source.
|
|
99
|
+
if self.C is None:
|
|
100
|
+
object.__setattr__(self, "C", parameter("C" + name, self.energy_symbols) if self.type == "J" else 0)
|
|
101
|
+
for attr in ("C", "L", "EJ", "V"):
|
|
102
|
+
value = getattr(self, attr)
|
|
103
|
+
if value is not None:
|
|
104
|
+
object.__setattr__(self, attr, sym.nsimplify(sym.sympify(value), rational=True))
|
|
105
|
+
|
|
106
|
+
def _check_branch(self):
|
|
107
|
+
# No self loops
|
|
108
|
+
if self.tail == self.head:
|
|
109
|
+
raise ValueError(f"Branch {self.name!r} is a self-loop")
|
|
110
|
+
# Voltage sources only have V
|
|
111
|
+
if self.V is not None and (self.C != 0 or self.L is not None or self.EJ is not None):
|
|
112
|
+
raise ValueError(f"Source branch {self.name!r} may carry only V")
|
|
113
|
+
# At most one of L, EJ
|
|
114
|
+
if self.L is not None and self.EJ is not None:
|
|
115
|
+
raise ValueError(f"Branch {self.name!r} may carry at most one of L, EJ")
|
|
116
|
+
# Valid capacitance, inductance, and Josephson energy values; only explicit numbers are
|
|
117
|
+
# checked, so symbolic values such as C_J*(1 + epsilon) are accepted as given.
|
|
118
|
+
if self.C.is_number and self.C.is_negative:
|
|
119
|
+
raise ValueError(f"Branch {self.name!r}: C must be 0 or positive")
|
|
120
|
+
if self.type in ("C", "J") and self.C == 0:
|
|
121
|
+
raise ValueError(f"Branch {self.name!r}: a {self.type} branch needs C > 0")
|
|
122
|
+
for attr in ("L", "EJ"):
|
|
123
|
+
value = getattr(self, attr)
|
|
124
|
+
if value is not None and value.is_number and not value.is_positive:
|
|
125
|
+
raise ValueError(f"Branch {self.name!r}: {attr} must be positive")
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def variables(self):
|
|
129
|
+
"""Parameter symbols in C, L, EJ, V order. Numeric values contribute none."""
|
|
130
|
+
return _variables((self.C, self.L, self.EJ, self.V))
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def type(self):
|
|
134
|
+
if self.EJ is not None:
|
|
135
|
+
return "J"
|
|
136
|
+
if self.L is not None:
|
|
137
|
+
return "L"
|
|
138
|
+
if self.V is not None:
|
|
139
|
+
return "V"
|
|
140
|
+
return "C"
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _ordered(nodes):
|
|
144
|
+
"""Distinct nodes in natural order of their string labels: 2 < 10, "q2" < "q10"."""
|
|
145
|
+
|
|
146
|
+
def key(node):
|
|
147
|
+
return [(0, int(part), "") if part.isdigit() else (1, 0, part)
|
|
148
|
+
for part in re.split(r"(\d+)", str(node)) if part]
|
|
149
|
+
|
|
150
|
+
return sorted(dict.fromkeys(nodes), key=key)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _graph(circuit):
|
|
154
|
+
"""Undirected multigraph keyed by branch name, so parallel branches stay distinct."""
|
|
155
|
+
G = nx.MultiGraph()
|
|
156
|
+
for i,b in enumerate(circuit.branches):
|
|
157
|
+
G.add_edge(b.tail, b.head, key=b.name, inductive=b.type in INDUCTIVE, source=b.type == "V", has_capacitance =b.C != 0,
|
|
158
|
+
rank=i + len(circuit.branches) * (b.type not in INDUCTIVE) + len(circuit.branches) * (b.type == "V")) # J, L before C then V then branch order as tiebreaker
|
|
159
|
+
return G
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@dataclass(frozen=True)
|
|
163
|
+
class Circuit:
|
|
164
|
+
"""Connected branches plus an optional reference ground.
|
|
165
|
+
|
|
166
|
+
Nodes are ordered int | gnd | src. A floating circuit has no gnd node.
|
|
167
|
+
|
|
168
|
+
:param branches: Iterable of Branch objects forming one connected graph.
|
|
169
|
+
:param ground: Label of a node on some branch, or None for a floating circuit.
|
|
170
|
+
:param t: SymPy time symbol used for time-dependent fluxes and voltages.
|
|
171
|
+
:raises ValueError: Empty/disconnected graph, duplicate labels, or invalid source connections.
|
|
172
|
+
"""
|
|
173
|
+
|
|
174
|
+
branches: tuple
|
|
175
|
+
ground: object = None
|
|
176
|
+
t: sym.Symbol = field(default=sym.Symbol("t", real=True))
|
|
177
|
+
graph: nx.MultiGraph = field(init=False, repr=False, compare=False)
|
|
178
|
+
source_nodes: tuple = field(init=False, repr=False)
|
|
179
|
+
internal_nodes: tuple = field(init=False, repr=False)
|
|
180
|
+
|
|
181
|
+
# Verify valid circuit and make graph representation
|
|
182
|
+
def __post_init__(self):
|
|
183
|
+
self._sort_nodes_and_branches()
|
|
184
|
+
object.__setattr__(self, "graph", _graph(self))
|
|
185
|
+
self._check_circuit()
|
|
186
|
+
|
|
187
|
+
def _sort_nodes_and_branches(self):
|
|
188
|
+
# Sort by type C | J | L | V, keeping user order within a type (eq:Omega_columns).
|
|
189
|
+
# And seperate internal nodes from source nodes, sorting by natural string within each sector.
|
|
190
|
+
branches = tuple(sorted(self.branches, key=lambda b: TYPES.index(b.type)))
|
|
191
|
+
all_nodes = {b.tail for b in branches} | {b.head for b in branches}
|
|
192
|
+
sources = []
|
|
193
|
+
for b in branches:
|
|
194
|
+
if b.type == "V":
|
|
195
|
+
sources.append(b.head if b.tail == self.ground else b.tail)
|
|
196
|
+
internal = [n for n in all_nodes if n not in sources and n != self.ground]
|
|
197
|
+
object.__setattr__(self, "source_nodes", tuple(_ordered(sources)))
|
|
198
|
+
object.__setattr__(self, "internal_nodes", tuple(_ordered(internal)))
|
|
199
|
+
object.__setattr__(self, "branches", branches)
|
|
200
|
+
|
|
201
|
+
def _check_circuit(self):
|
|
202
|
+
# Nonempty connected graph, ground on it, at least one internal node
|
|
203
|
+
if not self.branches or not nx.is_connected(self.graph):
|
|
204
|
+
raise ValueError("Circuit branches must form a nonempty connected graph")
|
|
205
|
+
if self.ground is not None and self.ground not in self.graph:
|
|
206
|
+
raise ValueError(f"Ground {self.ground!r} is on no branch; use ground=None for a floating circuit")
|
|
207
|
+
if not self.internal_nodes:
|
|
208
|
+
raise ValueError("Circuit has no internal nodes")
|
|
209
|
+
# Distinct string labels, so the natural node order is well defined
|
|
210
|
+
if len({str(n) for n in self.graph}) != len(self.graph):
|
|
211
|
+
raise ValueError("Two different nodes have the same string label, e.g. 1 and '1'")
|
|
212
|
+
# Branches have unique names
|
|
213
|
+
branches = self.branches
|
|
214
|
+
if len(set(self.branch_names)) != len(branches):
|
|
215
|
+
raise ValueError("Branch names must be unique")
|
|
216
|
+
# Source nodes must connect to ground and carry no other branches
|
|
217
|
+
# Source nodes must only be connected to internal nodes by capacitors
|
|
218
|
+
sources = []
|
|
219
|
+
for b in branches:
|
|
220
|
+
if b.type == "V":
|
|
221
|
+
if self.ground not in (b.tail, b.head):
|
|
222
|
+
raise ValueError(f"Source {b.name!r} must connect to ground")
|
|
223
|
+
sources.append(b.head if b.tail == self.ground else b.tail)
|
|
224
|
+
if len(set(sources)) != len(sources):
|
|
225
|
+
raise ValueError("Each source node carries exactly one source")
|
|
226
|
+
for b in branches:
|
|
227
|
+
if b.type in INDUCTIVE and {b.tail, b.head} & set(sources):
|
|
228
|
+
raise ValueError(f"Only capacitors may end on a source node: {b.name!r}")
|
|
229
|
+
|
|
230
|
+
@property
|
|
231
|
+
def nodes(self):
|
|
232
|
+
ground = () if self.ground is None else (self.ground,)
|
|
233
|
+
return self.internal_nodes + ground + self.source_nodes
|
|
234
|
+
|
|
235
|
+
@property
|
|
236
|
+
def branch_names(self):
|
|
237
|
+
return tuple(b.name for b in self.branches)
|
|
238
|
+
|
|
239
|
+
@property
|
|
240
|
+
def variables(self):
|
|
241
|
+
"""Unique parameter symbols in branch order, then each branch's value order."""
|
|
242
|
+
return tuple(dict.fromkeys(v for b in self.branches for v in b.variables))
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def incidence(circuit, *, elem=None):
|
|
246
|
+
"""Incidence matrix Omega, +1 at each branch's tail and -1 at its head.
|
|
247
|
+
|
|
248
|
+
:param circuit: Circuit whose ordered nodes and branches define the matrix.
|
|
249
|
+
:param elem: Optional branch type C, J, L, or V, to select the columns of that type.
|
|
250
|
+
:returns: Immutable integer matrix with node rows and branch columns.
|
|
251
|
+
"""
|
|
252
|
+
row = {node: i for i, node in enumerate(circuit.nodes)}
|
|
253
|
+
branches = [b for b in circuit.branches if elem is None or b.type == elem]
|
|
254
|
+
Omega = sym.zeros(len(circuit.nodes), len(branches))
|
|
255
|
+
for k, b in enumerate(branches):
|
|
256
|
+
Omega[row[b.tail], k] = 1
|
|
257
|
+
Omega[row[b.head], k] = -1
|
|
258
|
+
return sym.ImmutableMatrix(Omega)
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Schemdraw diagrams, adapted from sircuitenum.visualize (Eli Weissler, Mohit Bhat).
|
|
2
|
+
|
|
3
|
+
The parallel-branch fan-out is ported under GPL-3.0, as LICENSE describes.
|
|
4
|
+
Enumeration-specific graph tables are replaced by NetworkX or explicit layouts.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import networkx as nx
|
|
8
|
+
|
|
9
|
+
__all__ = ["draw_circuit_diagram"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def draw_circuit_diagram(circuit, out=None, *, layout="planar", scale=4., spread=.4,
|
|
13
|
+
label=True, node_labels=True, label_loc=None, flux_labels=None,
|
|
14
|
+
grounds=None, element_positions=None):
|
|
15
|
+
"""Return a Schemdraw Drawing, optionally saved to SVG, PDF, or PNG.
|
|
16
|
+
|
|
17
|
+
layout: 'planar' (spring fallback), 'spring', 'polygon', or {node: (x, y)}.
|
|
18
|
+
Explicit positions are multiplied by scale. Automatic layouts have shortest
|
|
19
|
+
edge length scale. spread sets parallel-lane spacing as a fraction of that
|
|
20
|
+
length. label controls branch names, and label_loc overrides node label sides.
|
|
21
|
+
flux_labels maps text (including $math$) to (x, y) positions, multiplied by
|
|
22
|
+
scale just like explicit node positions. These are display-only annotations.
|
|
23
|
+
grounds splits the ground node into one terminal per node wired to ground:
|
|
24
|
+
'below' puts each terminal one scale-length beneath its node, 'radial' puts it
|
|
25
|
+
one scale-length outward from the centroid of the other nodes, and a dict
|
|
26
|
+
{node: (x, y)} gives every terminal explicitly, multiplied by scale. With split
|
|
27
|
+
grounds the layout omits the ground node. Floating circuits ignore grounds.
|
|
28
|
+
element_positions maps a branch name to where its element sits along the
|
|
29
|
+
branch, as a fraction from its tail (default 0.5). Wire fills the rest. This
|
|
30
|
+
separates elements on crossing branches.
|
|
31
|
+
Voltage sources have + toward the source node.
|
|
32
|
+
Boxed junctions include intrinsic C. An inductor's C is shown in parallel.
|
|
33
|
+
Install the optional dependencies with ``pip install '.[draw]'``.
|
|
34
|
+
|
|
35
|
+
:param circuit: Circuit to draw.
|
|
36
|
+
:param out: Optional output path (SVG, PDF, or PNG).
|
|
37
|
+
:param layout: Layout name or a dict mapping every node to an (x, y) position.
|
|
38
|
+
:param float scale: Positive coordinate scale, default 4.
|
|
39
|
+
:param float spread: Positive parallel-branch separation factor, default 0.4.
|
|
40
|
+
:param bool label: Show branch labels.
|
|
41
|
+
:param bool node_labels: Show node labels.
|
|
42
|
+
:param label_loc: Optional node-to-label-side mapping (top, bottom, left, right).
|
|
43
|
+
:param flux_labels: Optional mapping from annotation text to (x, y) coordinates.
|
|
44
|
+
:param grounds: None (one ground symbol), 'below', 'radial', or {node: (x, y)}.
|
|
45
|
+
:param element_positions: Optional {branch name: fraction strictly between 0 and 1}.
|
|
46
|
+
:returns: Schemdraw Drawing, renderable inline in notebooks.
|
|
47
|
+
:raises ValueError: Invalid layout, positions, scale, spacing, grounds, or element positions.
|
|
48
|
+
"""
|
|
49
|
+
import numpy as np
|
|
50
|
+
import schemdraw
|
|
51
|
+
import schemdraw.elements as elm
|
|
52
|
+
from schemdraw.segments import Segment
|
|
53
|
+
|
|
54
|
+
if scale <= 0 or spread <= 0:
|
|
55
|
+
raise ValueError("scale and spread must be positive")
|
|
56
|
+
if grounds is not None and not isinstance(grounds, dict) and grounds not in ("below", "radial"):
|
|
57
|
+
raise ValueError("grounds must be None, 'below', 'radial', or a node-position dict")
|
|
58
|
+
if not isinstance(layout, dict) and layout not in ("planar", "spring", "polygon"):
|
|
59
|
+
raise ValueError("layout must be planar, spring, polygon, or a node-position dict")
|
|
60
|
+
element_positions = dict(element_positions or {})
|
|
61
|
+
unknown = set(element_positions) - set(circuit.branch_names)
|
|
62
|
+
if unknown:
|
|
63
|
+
raise ValueError(f"element_positions names unknown branches: {sorted(unknown)}")
|
|
64
|
+
if not all(0 < float(t) < 1 for t in element_positions.values()):
|
|
65
|
+
raise ValueError("element positions must be fractions strictly between 0 and 1")
|
|
66
|
+
ground = circuit.ground
|
|
67
|
+
split = grounds is not None and ground is not None
|
|
68
|
+
nodes = [n for n in circuit.nodes if not (split and n == ground)]
|
|
69
|
+
# Edges first: node order follows the branches, as automatic layouts depend on it.
|
|
70
|
+
graph = nx.Graph((b.tail, b.head) for b in circuit.branches if not (split and ground in (b.tail, b.head)))
|
|
71
|
+
graph.add_nodes_from(nodes) # nodes reached only through ground
|
|
72
|
+
if isinstance(layout, dict):
|
|
73
|
+
if set(nodes) - set(layout):
|
|
74
|
+
raise ValueError("layout must give a position for every circuit node")
|
|
75
|
+
pos = {n: np.asarray(layout[n], dtype=float) * scale for n in nodes}
|
|
76
|
+
else:
|
|
77
|
+
if len(nodes) == 1:
|
|
78
|
+
pos = {nodes[0]: np.zeros(2)}
|
|
79
|
+
elif layout == "planar" and nx.is_planar(graph) and nx.is_connected(graph):
|
|
80
|
+
pos = nx.planar_layout(graph)
|
|
81
|
+
elif layout in ("planar", "spring"):
|
|
82
|
+
pos = nx.spring_layout(graph, seed=0)
|
|
83
|
+
else:
|
|
84
|
+
pos = nx.circular_layout(graph)
|
|
85
|
+
# Put ground below the circuit; retain labels instead of renumbering nodes.
|
|
86
|
+
center = np.mean(list(pos.values()), axis=0)
|
|
87
|
+
pos = {n: p - center for n, p in pos.items()}
|
|
88
|
+
if ground in pos:
|
|
89
|
+
x, y = pos[ground]
|
|
90
|
+
if x or y:
|
|
91
|
+
rotation = np.array([[-y, x], [-x, -y]]) / np.hypot(x, y)
|
|
92
|
+
pos = {n: rotation @ p for n, p in pos.items()}
|
|
93
|
+
pairs = list(graph.edges) or [(a, b) for i, a in enumerate(nodes) for b in nodes[i + 1:]]
|
|
94
|
+
if pairs:
|
|
95
|
+
shortest = min(np.linalg.norm(pos[a] - pos[b]) for a, b in pairs)
|
|
96
|
+
pos = {n: p * scale / shortest for n, p in pos.items()}
|
|
97
|
+
if any(p.shape != (2,) or not np.isfinite(p).all() for p in pos.values()):
|
|
98
|
+
raise ValueError("node positions must be finite (x, y) pairs")
|
|
99
|
+
if len({tuple(p) for p in pos.values()}) != len(pos):
|
|
100
|
+
raise ValueError("node positions must be distinct")
|
|
101
|
+
|
|
102
|
+
terminals = {} # grounded node -> position of its own ground symbol
|
|
103
|
+
if split:
|
|
104
|
+
grounded = [n for n in nodes if any({n, ground} == {b.tail, b.head} for b in circuit.branches)]
|
|
105
|
+
centroid = np.mean(list(pos.values()), axis=0)
|
|
106
|
+
for n in grounded:
|
|
107
|
+
if isinstance(grounds, dict):
|
|
108
|
+
if n not in grounds:
|
|
109
|
+
raise ValueError(f"grounds must give a terminal position for grounded node {n!r}")
|
|
110
|
+
terminals[n] = np.asarray(grounds[n], dtype=float) * scale
|
|
111
|
+
else:
|
|
112
|
+
outward = pos[n] - centroid
|
|
113
|
+
if grounds == "below" or np.linalg.norm(outward) < 1e-9 * scale:
|
|
114
|
+
outward = np.array([0., -1.])
|
|
115
|
+
terminals[n] = pos[n] + scale * outward / np.linalg.norm(outward)
|
|
116
|
+
if any(t.shape != (2,) or not np.isfinite(t).all() for t in terminals.values()):
|
|
117
|
+
raise ValueError("ground terminal positions must be finite (x, y) pairs")
|
|
118
|
+
points = list(pos.values()) + list(terminals.values())
|
|
119
|
+
if any(np.linalg.norm(p - q) < 1e-6 * scale for i, p in enumerate(points) for q in points[i + 1:]):
|
|
120
|
+
raise ValueError("ground terminals must not coincide with each other or with nodes; "
|
|
121
|
+
"try grounds='radial', another layout, or explicit grounds positions")
|
|
122
|
+
|
|
123
|
+
def place(node, other):
|
|
124
|
+
"""Drawing position of node on a branch to other; split ground goes to other's terminal."""
|
|
125
|
+
return terminals[other] if split and node == ground else pos[node]
|
|
126
|
+
|
|
127
|
+
# Group by unordered endpoints without comparing heterogeneous node labels.
|
|
128
|
+
groups = {}
|
|
129
|
+
for b in circuit.branches:
|
|
130
|
+
group = groups.setdefault(frozenset((b.tail, b.head)), [])
|
|
131
|
+
group.append((b, b.type, b.name))
|
|
132
|
+
if b.type == "L" and b.C != 0:
|
|
133
|
+
group.append((b, "C", f"$C_{{{b.name}}}$"))
|
|
134
|
+
ends = {key: (place(g[0][0].tail, g[0][0].head), place(g[0][0].head, g[0][0].tail))
|
|
135
|
+
for key, g in groups.items()}
|
|
136
|
+
min_r = min(np.linalg.norm(a - b) for a, b in ends.values())
|
|
137
|
+
drawing = schemdraw.Drawing(show=False, canvas="matplotlib", fontsize=11)
|
|
138
|
+
elements = {"C": elm.Capacitor, "J": elm.Josephson, "L": elm.Inductor2, "V": elm.SourceV}
|
|
139
|
+
for key, group in groups.items():
|
|
140
|
+
first = group[0][0]
|
|
141
|
+
a, b = ends[key]
|
|
142
|
+
direction = b - a
|
|
143
|
+
normal = np.array([-direction[1], direction[0]]) / np.linalg.norm(direction)
|
|
144
|
+
if len(group) > 1:
|
|
145
|
+
drawing.add(elm.Wire().at(a).to(a + direction / 4))
|
|
146
|
+
drawing.add(elm.Wire().at(b).to(b - direction / 4))
|
|
147
|
+
for i, (branch, kind, name) in enumerate(group):
|
|
148
|
+
start, end = a, b
|
|
149
|
+
if len(group) > 1:
|
|
150
|
+
offset = (i - (len(group) - 1) / 2) * spread * min_r * normal
|
|
151
|
+
start, end = a + direction / 4 + offset, b - direction / 4 + offset
|
|
152
|
+
# Common leads and perpendicular rails, as in sircuitenum.
|
|
153
|
+
drawing.add(elm.Wire().at(a + direction / 4).to(start))
|
|
154
|
+
drawing.add(elm.Wire().at(b - direction / 4).to(end))
|
|
155
|
+
t = float(element_positions.get(branch.name, .5))
|
|
156
|
+
if branch.tail != first.tail: # a, b follow the group's first branch
|
|
157
|
+
t = 1 - t
|
|
158
|
+
if t != .5: # body on [t - h, t + h] of the lane, wire on the rest
|
|
159
|
+
h, lane = min(t, 1 - t), end - start
|
|
160
|
+
body_start, body_end = start + (t - h) * lane, start + (t + h) * lane
|
|
161
|
+
drawing.add(elm.Wire().at(start).to(body_start))
|
|
162
|
+
drawing.add(elm.Wire().at(body_end).to(end))
|
|
163
|
+
start, end = body_start, body_end
|
|
164
|
+
if kind == "V" and first.tail != circuit.ground:
|
|
165
|
+
start, end = end, start # SourceV has its + at end; V means V_source - V_ground.
|
|
166
|
+
element = elements[kind]().endpoints(start, end)
|
|
167
|
+
if kind == "J":
|
|
168
|
+
gap = (float("nan"), float("nan"))
|
|
169
|
+
element.segments[0] = Segment([(-.25, 0), gap, (.25, 0)])
|
|
170
|
+
element.segments.append(Segment([(-.25, -.25), (.25, -.25), (.25, .25),
|
|
171
|
+
(-.25, .25), (-.25, -.25), (.25, .25),
|
|
172
|
+
gap, (-.25, .25), (.25, -.25)]))
|
|
173
|
+
name = f"{name}, $C_{{{name}}}$"
|
|
174
|
+
if label:
|
|
175
|
+
element.label(name)
|
|
176
|
+
drawing.add(element)
|
|
177
|
+
sides = {"top": (0, 1), "right": (1, 0), "bottom": (0, -1), "left": (-1, 0)}
|
|
178
|
+
for node, point in pos.items():
|
|
179
|
+
dot = elm.Dot(radius=.07).at(point)
|
|
180
|
+
if node_labels:
|
|
181
|
+
neighbors = [far - near for near, far in
|
|
182
|
+
(pair if np.array_equal(pair[0], point) else pair[::-1] for pair in ends.values())
|
|
183
|
+
if np.array_equal(near, point)]
|
|
184
|
+
directions = [v / np.linalg.norm(v) for v in neighbors]
|
|
185
|
+
side = min(sides, key=lambda s: max((np.dot(sides[s], v) for v in directions), default=0))
|
|
186
|
+
dot.label(str(node), loc=(label_loc or {}).get(node, "left" if node == circuit.ground else side))
|
|
187
|
+
drawing.add(dot)
|
|
188
|
+
if node == ground and not split:
|
|
189
|
+
drawing.add(elm.Ground().at(point))
|
|
190
|
+
for point in terminals.values():
|
|
191
|
+
drawing.add(elm.Ground().at(point))
|
|
192
|
+
for text, point in (flux_labels or {}).items():
|
|
193
|
+
point = np.asarray(point, dtype=float)
|
|
194
|
+
if point.shape != (2,) or not np.isfinite(point).all():
|
|
195
|
+
raise ValueError("flux label positions must be finite (x, y) pairs")
|
|
196
|
+
drawing.add(elm.Label().at(point * scale).label(text))
|
|
197
|
+
if out is not None:
|
|
198
|
+
drawing.save(str(out))
|
|
199
|
+
return drawing
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""External-flux assignment."""
|
|
2
|
+
|
|
3
|
+
from .modes import _cancel
|
|
4
|
+
import sympy as sym
|
|
5
|
+
|
|
6
|
+
__all__ = ["irrotational_B", "B_from_shares"]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def irrotational_B(lag, coords, loops):
|
|
10
|
+
"""Irrotational flux assignment B = (I - Omega_int^T Z C~^{-1} Z^T Omega_int C_b) G^+.
|
|
11
|
+
|
|
12
|
+
The irrotational assignment keeps the time derivative of the external flux out of H
|
|
13
|
+
[You, Sauls, and Koch, Phys. Rev. B 99, 174512 (2019)].
|
|
14
|
+
|
|
15
|
+
Evaluated as B = G^+ - Omega_int^T Z X with X = C~^{-1} Z^T Omega_int C_b G^+,
|
|
16
|
+
so the only rational-function matrix built is the small N_d x N_ell block X.
|
|
17
|
+
The omitted homogeneous term is Omega_int^T W with coords.R * W = 0,
|
|
18
|
+
equivalently Z^T C_int W = 0. Z^+ W = 0 is not the
|
|
19
|
+
correct condition after truncation. Choosing W = 0 leaves this formula unchanged.
|
|
20
|
+
|
|
21
|
+
Source branches are pinned at V(t) and never enter H, so flux assigned to one
|
|
22
|
+
would be dropped. G^+ is therefore the right inverse over the passive branches
|
|
23
|
+
only, and the source rows of B are zero.
|
|
24
|
+
|
|
25
|
+
:param lag: Node Lagrangian matrices.
|
|
26
|
+
:param coords: Decoupled retained coordinates.
|
|
27
|
+
:param loops: Complete cycle basis and branch ordering for the circuit.
|
|
28
|
+
:returns: Branch-by-loop flux assignment matrix B, satisfying G * B = I.
|
|
29
|
+
"""
|
|
30
|
+
G, Z, Omega_int = loops.G, coords.Z, lag.Omega_int
|
|
31
|
+
passive = [k for k, b in enumerate(loops.circuit.branches) if b.type != "V"]
|
|
32
|
+
G_p = G[:, passive]
|
|
33
|
+
G_p_plus = G_p.T * (G_p * G_p.T).inv() # eq:G_right_inverse on passive branches
|
|
34
|
+
G_plus = sym.zeros(G.cols, G.rows)
|
|
35
|
+
for i, k in enumerate(passive):
|
|
36
|
+
G_plus[k, :] = G_p_plus[i, :]
|
|
37
|
+
drive = _cancel(Z.T * Omega_int * lag.C_b * G_plus)
|
|
38
|
+
X = _cancel(coords.C_tilde_inv * drive)
|
|
39
|
+
return _cancel(G_plus - Omega_int.T * Z * X)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def B_from_shares(circuit, loops, shares):
|
|
43
|
+
"""Flux assignment B (branches, loops) from ``shares[loop][branch]``.
|
|
44
|
+
|
|
45
|
+
:raises ValueError: unless ``loops.G * B`` is the identity.
|
|
46
|
+
"""
|
|
47
|
+
branches = list(circuit.branch_names)
|
|
48
|
+
B = sym.zeros(len(branches), len(loops.names))
|
|
49
|
+
for j, loop in enumerate(loops.names):
|
|
50
|
+
for branch, value in shares.get(loop, {}).items():
|
|
51
|
+
B[branches.index(branch), j] = sym.sympify(value)
|
|
52
|
+
if (sym.simplify(sym.Matrix(loops.G) * B - sym.eye(len(loops.names)))) != sym.zeros(*[len(loops.names)] * 2):
|
|
53
|
+
raise ValueError("shares do not satisfy G * B = I")
|
|
54
|
+
return sym.ImmutableMatrix(B)
|