Capacitor
Bases: Component
Capacitor de 2 terminais; portas: a (positivo), b (negativo).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ref
|
str
|
Reference designator (e.g., "1" for C1) |
required |
value
|
str | float
|
Legacy stringly-typed value (backward compat) |
''
|
capacitance
|
float | ParameterRef | None
|
Typed capacitance value (float or ParameterRef) |
None
|
Use either value OR capacitance, not both.
Source code in spicelab/core/components.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | |
Circuit
dataclass
Logical circuit composed of components, nets and raw SPICE directives.
Source code in spicelab/core/circuit.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 | |
add(*components)
Append one or more components to the circuit.
Source code in spicelab/core/circuit.py
52 53 54 55 56 | |
add_directive(line)
Append a raw SPICE directive (.model, .param ...).
Source code in spicelab/core/circuit.py
58 59 60 61 62 | |
add_directive_once(line)
Add a directive if an identical line (ignoring whitespace) is absent.
Source code in spicelab/core/circuit.py
64 65 66 67 68 69 70 71 | |
build_netlist()
Return a SPICE netlist representation of this circuit.
Source code in spicelab/core/circuit.py
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 | |
connect(a, b)
Connect a port to another port or to a logical net.
Uses Union-Find for O(α(n)) amortized net merging (M2 optimization).
Source code in spicelab/core/circuit.py
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |
connect_with_label(port, net, label=None)
Connect port to net while recording a display label.
Source code in spicelab/core/circuit.py
126 127 128 129 130 131 132 | |
connectivity_dataframe(*, sort=True, include_type=True)
Return a pandas DataFrame describing component/net connectivity.
Columns: component, type (optional), port and net. The
returned DataFrame is ideal for Jupyter notebooks where an interactive
table is easier to scan than the plain text summary.
Source code in spicelab/core/circuit.py
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 | |
from_netlist(path)
classmethod
Load a circuit from a plain SPICE netlist file.
Source code in spicelab/core/circuit.py
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 | |
hash(*, extra=None)
Return a deterministic short hash for this circuit.
Wrapper around spicelab.core.types.circuit_hash so callers do not need
to import the helper directly. extra can include engine/version/analysis
args to bind caches firmly to execution context.
Source code in spicelab/core/circuit.py
224 225 226 227 228 229 230 231 232 233 | |
save_netlist(path)
Persist the netlist to path and return the resolved Path.
Source code in spicelab/core/circuit.py
214 215 216 217 218 219 | |
summary()
Return a human-readable summary of the circuit and connectivity.
Source code in spicelab/core/circuit.py
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 | |
summary_table(*, indent=2)
Return a fixed-width table describing component connections.
Source code in spicelab/core/circuit.py
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 | |
to_dot()
Return a Graphviz DOT representation of the circuit.
Source code in spicelab/core/circuit.py
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | |
validate(strict=False)
Validate circuit topology and component values.
Performs checks: - Ground reference exists - No floating nodes (connected to only one component) - No unusual component values - No voltage source shorts (parallel voltage sources)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strict
|
bool
|
If True, treat warnings as errors |
False
|
Returns:
| Type | Description |
|---|---|
ValidationResult
|
ValidationResult with errors and warnings |
Example
result = circuit.validate() if result.has_issues(): ... print(result) if not result.is_valid: ... raise ValueError("Circuit has errors")
Source code in spicelab/core/circuit.py
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 | |
Inductor
Bases: Component
Indutor de 2 terminais; portas: a (positivo), b (negativo).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ref
|
str
|
Reference designator (e.g., "1" for L1) |
required |
value
|
str | float
|
Legacy stringly-typed value (backward compat) |
''
|
inductance
|
float | ParameterRef | None
|
Typed inductance value (float or ParameterRef) |
None
|
Use either value OR inductance, not both.
Source code in spicelab/core/components.py
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | |
Ipulse
Bases: Component
Fonte de corrente PULSE(I1 I2 TD TR TF PW PER).
Source code in spicelab/core/components.py
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 | |
Ipwl
Bases: Component
Fonte de corrente PWL(args_raw).
Source code in spicelab/core/components.py
409 410 411 412 413 414 415 416 417 418 419 | |
JFET
Bases: Component
Junction Field-Effect Transistor (N-channel or P-channel).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ref
|
str
|
Reference designator (e.g., "1" for J1) |
required |
model
|
str
|
SPICE model name (e.g., "2N5457", "J2N5459") |
required |
Ports
d: drain g: gate s: source
Source code in spicelab/core/components.py
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 | |
MutualInductance
Bases: Component
Mutual inductance coupling between two inductors.
This component does not have physical ports - it references existing inductors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ref
|
str
|
Reference designator (e.g., "1" for K1) |
required |
l1
|
str
|
Reference to first inductor (e.g., "L1") |
required |
l2
|
str
|
Reference to second inductor (e.g., "L2") |
required |
coupling
|
float
|
Coupling coefficient (0 to 1, typically 0.95-0.999) |
required |
Example
Create two inductors and couple them
l1 = Inductor("1", "10m") l2 = Inductor("2", "10m") k1 = MutualInductance("1", l1="L1", l2="L2", coupling=0.99)
Source code in spicelab/core/components.py
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 | |
Net
dataclass
Logical node. Name is optional and used for debug; '0' is reserved for GND.
Source code in spicelab/core/net.py
18 19 20 21 22 | |
OpAmpIdeal
Bases: Component
Op-amp ideal de 3 pinos (inp, inn, out) modelado por VCVS de alto ganho.
Carta: E out 0 inp inn
Source code in spicelab/core/components.py
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 | |
Resistor
Bases: Component
Resistor de 2 terminais; portas: a (positivo), b (negativo).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ref
|
str
|
Reference designator (e.g., "1" for R1) |
required |
value
|
str | float
|
Legacy stringly-typed value (backward compat) |
''
|
resistance
|
float | ParameterRef | None
|
Typed resistance value (float or ParameterRef) |
None
|
Use either value OR resistance, not both.
Source code in spicelab/core/components.py
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | |
SubcktInstance
Bases: Component
Subcircuit instance (X element).
SPICE card: X
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ref
|
str
|
Reference designator |
required |
subckt_name
|
str
|
Name of the subcircuit to instantiate |
required |
nodes
|
list[str]
|
List of node names to connect to subcircuit ports |
required |
params
|
dict[str, str | float] | None
|
Optional dict of parameter overrides |
None
|
Example
Instantiate an op-amp subcircuit
x1 = SubcktInstance("1", "LM741", ["inp", "inn", "vcc", "vee", "out"])
With parameters
x2 = SubcktInstance("2", "RES_VAR", ["a", "b"], params={"R": "1k"})
Source code in spicelab/core/components.py
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 | |
TLine
Bases: Component
Lossless transmission line (T element).
SPICE card: T Parameters: Reference designator Characteristic impedance (ohms) Time delay (e.g., "1n" for 1ns) p1p, p1n: Port 1 positive and negative
p2p, p2n: Port 2 positive and negative
Bases: Lossy transmission line (O element) - LTRA model. Requires a .model statement with LTRA parameters. Parameters: Reference designator LTRA model name p1p, p1n: Port 1 positive and negative
p2p, p2n: Port 2 positive and negative
Bases: Uniform distributed RC line (U element) - URC model. SPICE card: U Parameters: Reference designator URC model name Line length parameter n1: Node 1
n2: Node 2
n3: Node 3 (typically ground reference)
Bases: Ideal transformer using coupled inductors. SPICE implementation uses two inductors coupled via K element.
The turns ratio determines the inductance ratio (L2/L1 = n^2). Parameters: Reference designator (e.g., "1" for XFMR1) Secondary/Primary turns ratio (n = Ns/Np) Primary inductance value (default "1m") Coupling coefficient (default 0.9999 for ideal) p1: Primary positive
p2: Primary negative
s1: Secondary positive
s2: Secondary negative xfmr = Transformer("1", turns_ratio=10) The spice_card method returns multiple lines (L1, L2, K statements).
Bases: Fonte de tensão DC; portas: p (positivo), n (negativo).
Bases: Explicit voltage measurement point marker. This is a virtual component that doesn't generate a SPICE card.
It serves as a marker for voltage measurement between two nodes. In SPICE, voltages are measured directly as V(node) or V(node1, node2).
This class provides a semantic way to mark measurement points. Parameters: Reference designator/name for the probe If True, measures voltage between p and n.
If False, measures p relative to ground. p: Positive measurement point
n: Negative/reference measurement point vprobe = VoltageProbe("out") vprobe_diff = VoltageProbe("diff", differential=True)
Bases: Fonte de tensão PULSE(V1 V2 TD TR TF PW PER).
Bases: Fonte de tensão PWL(args_raw).
Bases: Zener diode for voltage reference/regulation. Same as regular Diode but semantically distinct for clarity. Parameters: Reference designator Zener model name (e.g., "1N4733" for 5.1V Zener) a: anode
c: cathode (connected to reference voltage in reverse bias) Include the core public API (Circuit, Component base types, net utilities). This section will be populated by Example: Logical circuit composed of components, nets and raw SPICE directives. Append one or more components to the circuit. Append a raw SPICE directive ( Add a directive if an identical line (ignoring whitespace) is absent. Return a SPICE netlist representation of this circuit. Connect a port to another port or to a logical net. Uses Union-Find for O(α(n)) amortized net merging (M2 optimization). Connect Return a pandas DataFrame describing component/net connectivity. Columns: Load a circuit from a plain SPICE netlist file. Return a deterministic short hash for this circuit. Wrapper around Persist the netlist to Return a human-readable summary of the circuit and connectivity. Return a fixed-width table describing component connections. Return a Graphviz DOT representation of the circuit. Validate circuit topology and component values. Performs checks:
- Ground reference exists
- No floating nodes (connected to only one component)
- No unusual component values
- No voltage source shorts (parallel voltage sources) Parameters: If True, treat warnings as errors Returns: ValidationResult with errors and warnings result = circuit.validate()
if result.has_issues():
... print(result)
if not result.is_valid:
... raise ValueError("Circuit has errors")
Name
Type
Description
Default
ref
str
required
z0
str | float
required
td
str | float
required
Ports
Source code in
spicelab/core/components.py1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
class TLine(Component):
"""Lossless transmission line (T element).
SPICE card: T<ref> <p1+> <p1-> <p2+> <p2-> Z0=<z0> TD=<td>
Args:
ref: Reference designator
z0: Characteristic impedance (ohms)
td: Time delay (e.g., "1n" for 1ns)
Ports:
p1p, p1n: Port 1 positive and negative
p2p, p2n: Port 2 positive and negative
"""
def __init__(
self,
ref: str,
z0: str | float,
td: str | float,
) -> None:
super().__init__(ref=ref, value="")
self.z0 = z0
self.td = td
self._ports = (
Port(self, "p1p", PortRole.POSITIVE),
Port(self, "p1n", PortRole.NEGATIVE),
Port(self, "p2p", PortRole.POSITIVE),
Port(self, "p2n", PortRole.NEGATIVE),
)
def spice_card(self, net_of: NetOf) -> str:
p1p, p1n, p2p, p2n = self.ports
return (
f"T{self.ref} {net_of(p1p)} {net_of(p1n)} {net_of(p2p)} {net_of(p2n)} "
f"Z0={self.z0} TD={self.td}"
)
TLineLossy
Component
Name
Type
Description
Default
ref
str
required
model
str
required
Ports
Source code in
spicelab/core/components.py1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
class TLineLossy(Component):
"""Lossy transmission line (O element) - LTRA model.
SPICE card: O<ref> <p1+> <p1-> <p2+> <p2-> <model>
Requires a .model statement with LTRA parameters.
Args:
ref: Reference designator
model: LTRA model name
Ports:
p1p, p1n: Port 1 positive and negative
p2p, p2n: Port 2 positive and negative
"""
def __init__(self, ref: str, model: str) -> None:
super().__init__(ref=ref, value=model)
self._ports = (
Port(self, "p1p", PortRole.POSITIVE),
Port(self, "p1n", PortRole.NEGATIVE),
Port(self, "p2p", PortRole.POSITIVE),
Port(self, "p2n", PortRole.NEGATIVE),
)
def spice_card(self, net_of: NetOf) -> str:
p1p, p1n, p2p, p2n = self.ports
return f"O{self.ref} {net_of(p1p)} {net_of(p1n)} {net_of(p2p)} {net_of(p2n)} {self.value}"
TLineRC
Component
Name
Type
Description
Default
ref
str
required
model
str
required
length
str | float
1
Ports
Source code in
spicelab/core/components.py1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
class TLineRC(Component):
"""Uniform distributed RC line (U element) - URC model.
SPICE card: U<ref> <n1> <n2> <n3> <model> L=<len>
Args:
ref: Reference designator
model: URC model name
length: Line length parameter
Ports:
n1: Node 1
n2: Node 2
n3: Node 3 (typically ground reference)
"""
def __init__(self, ref: str, model: str, length: str | float = 1) -> None:
super().__init__(ref=ref, value=model)
self.length = length
self._ports = (
Port(self, "n1", PortRole.NODE),
Port(self, "n2", PortRole.NODE),
Port(self, "n3", PortRole.NODE),
)
def spice_card(self, net_of: NetOf) -> str:
n1, n2, n3 = self.ports
return f"U{self.ref} {net_of(n1)} {net_of(n2)} {net_of(n3)} {self.value} L={self.length}"
Transformer
Component
Name
Type
Description
Default
ref
str
required
turns_ratio
float
required
l_primary
str
'1m'
coupling
float
0.9999
Ports
Example
Create 1:10 step-up transformer
Note
Source code in
spicelab/core/components.py1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
class Transformer(Component):
"""Ideal transformer using coupled inductors.
SPICE implementation uses two inductors coupled via K element.
The turns ratio determines the inductance ratio (L2/L1 = n^2).
Args:
ref: Reference designator (e.g., "1" for XFMR1)
turns_ratio: Secondary/Primary turns ratio (n = Ns/Np)
l_primary: Primary inductance value (default "1m")
coupling: Coupling coefficient (default 0.9999 for ideal)
Ports:
p1: Primary positive
p2: Primary negative
s1: Secondary positive
s2: Secondary negative
Example:
# Create 1:10 step-up transformer
xfmr = Transformer("1", turns_ratio=10)
Note:
The spice_card method returns multiple lines (L1, L2, K statements).
"""
def __init__(
self,
ref: str,
turns_ratio: float,
l_primary: str = "1m",
coupling: float = 0.9999,
) -> None:
if turns_ratio <= 0:
raise ValueError(f"Turns ratio must be positive, got {turns_ratio}")
if not 0 < coupling <= 1:
raise ValueError(f"Coupling must be 0 < k <= 1, got {coupling}")
super().__init__(ref=ref, value=str(turns_ratio))
self.turns_ratio = turns_ratio
self.l_primary = l_primary
self.coupling = coupling
self._ports = (
Port(self, "p1", PortRole.POSITIVE),
Port(self, "p2", PortRole.NEGATIVE),
Port(self, "s1", PortRole.POSITIVE),
Port(self, "s2", PortRole.NEGATIVE),
)
def spice_card(self, net_of: NetOf) -> str:
p1, p2, s1, s2 = self.ports
# L2 = L1 * n^2 for ideal transformer
l_sec = f"{float(self.l_primary.rstrip('m')) * self.turns_ratio**2}m"
lines = [
f"L{self.ref}p {net_of(p1)} {net_of(p2)} {self.l_primary}",
f"L{self.ref}s {net_of(s1)} {net_of(s2)} {l_sec}",
f"K{self.ref} L{self.ref}p L{self.ref}s {self.coupling}",
]
return "\n".join(lines)
Vdc
ComponentSource code in
spicelab/core/components.py137
138
139
140
141
142
143
144
145
146
147
class Vdc(Component):
"""Fonte de tensão DC; portas: p (positivo), n (negativo)."""
def __init__(self, ref: str, value: str | float = "") -> None:
super().__init__(ref=ref, value=value)
self._ports = (Port(self, "p", PortRole.POSITIVE), Port(self, "n", PortRole.NEGATIVE))
def spice_card(self, net_of: NetOf) -> str:
p, n = self.ports
# Para DC, escrevemos o valor diretamente
return f"V{self.ref} {net_of(p)} {net_of(n)} {self.value}"
VoltageProbe
Component
Name
Type
Description
Default
ref
str
required
differential
bool
False
Ports
Example
Single-ended measurement (relative to ground)
Differential measurement
Source code in
spicelab/core/components.py1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
class VoltageProbe(Component):
"""Explicit voltage measurement point marker.
This is a virtual component that doesn't generate a SPICE card.
It serves as a marker for voltage measurement between two nodes.
In SPICE, voltages are measured directly as V(node) or V(node1, node2).
This class provides a semantic way to mark measurement points.
Args:
ref: Reference designator/name for the probe
differential: If True, measures voltage between p and n.
If False, measures p relative to ground.
Ports:
p: Positive measurement point
n: Negative/reference measurement point
Example:
# Single-ended measurement (relative to ground)
vprobe = VoltageProbe("out")
# Differential measurement
vprobe_diff = VoltageProbe("diff", differential=True)
"""
def __init__(self, ref: str, differential: bool = False) -> None:
super().__init__(ref=ref, value="probe")
self.differential = differential
self._ports = (
Port(self, "p", PortRole.POSITIVE),
Port(self, "n", PortRole.NEGATIVE),
)
def spice_card(self, net_of: NetOf) -> str:
# VoltageProbe is a virtual component - no SPICE element generated
# Voltage measurement happens via .PROBE or direct node reference
return f"* Voltage probe {self.ref}: V({net_of(self.ports[0])})"
Vpulse
ComponentSource code in
spicelab/core/components.py177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
class Vpulse(Component):
"""Fonte de tensão PULSE(V1 V2 TD TR TF PW PER)."""
def __init__(
self,
ref: str,
v1: str | float,
v2: str | float,
td: str | float,
tr: str | float,
tf: str | float,
pw: str | float,
per: str | float,
) -> None:
super().__init__(ref=ref, value="")
self.v1, self.v2, self.td, self.tr, self.tf, self.pw, self.per = (
v1,
v2,
td,
tr,
tf,
pw,
per,
)
self._ports = (Port(self, "p", PortRole.POSITIVE), Port(self, "n", PortRole.NEGATIVE))
def spice_card(self, net_of: NetOf) -> str:
p, n = self.ports
return (
f"V{self.ref} {net_of(p)} {net_of(n)} "
f"PULSE({self.v1} {self.v2} {self.td} {self.tr} {self.tf} {self.pw} {self.per})"
)
Vpwl
ComponentSource code in
spicelab/core/components.py396
397
398
399
400
401
402
403
404
405
406
class Vpwl(Component):
"""Fonte de tensão PWL(args_raw)."""
def __init__(self, ref: str, args_raw: str) -> None:
super().__init__(ref=ref, value="")
self.args_raw = args_raw
self._ports = (Port(self, "p", PortRole.POSITIVE), Port(self, "n", PortRole.NEGATIVE))
def spice_card(self, net_of: NetOf) -> str:
p, n = self.ports
return f"V{self.ref} {net_of(p)} {net_of(n)} PWL({self.args_raw})"
ZenerDiode
Component
Name
Type
Description
Default
ref
str
required
model
str
required
Ports
Source code in
spicelab/core/components.py944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
class ZenerDiode(Component):
"""Zener diode for voltage reference/regulation.
SPICE card: D<ref> <anode> <cathode> <model>
Same as regular Diode but semantically distinct for clarity.
Args:
ref: Reference designator
model: Zener model name (e.g., "1N4733" for 5.1V Zener)
Ports:
a: anode
c: cathode (connected to reference voltage in reverse bias)
"""
def __init__(self, ref: str, model: str) -> None:
super().__init__(ref=ref, value=model)
self._ports = (
Port(self, "a", PortRole.POSITIVE),
Port(self, "c", PortRole.NEGATIVE),
)
def spice_card(self, net_of: NetOf) -> str:
a, c = self.ports
return f"D{self.ref} {net_of(a)} {net_of(c)} {self.value}"
Core API
mkdocstrings from the spicelab.core package.Source code in
spicelab/core/circuit.py 31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
@dataclass
class Circuit:
"""Logical circuit composed of components, nets and raw SPICE directives."""
name: str
_net_ids: dict[Net, int] = field(default_factory=dict, init=False)
_port_to_net: dict[Port, Net] = field(default_factory=dict, init=False)
_components: list[Component] = field(default_factory=list, init=False)
_directives: list[str] = field(default_factory=list, init=False)
# metadata captured when loading from existing netlists
_subckt_defs: dict[str, str] = field(default_factory=dict, init=False)
_subckt_instances: list[dict[str, object]] = field(default_factory=list, init=False)
_port_labels: dict[Port, str] = field(default_factory=dict, init=False)
# Union-Find for O(α(n)) net merging (M2 performance optimization)
_net_union: UnionFind[Net] = field(default_factory=UnionFind, init=False)
# Cache invalidation version counter
_cache_version: int = field(default=0, init=False)
# ----------------------------------------------------------------------------------
# Building blocks
# ----------------------------------------------------------------------------------
def add(self, *components: Component) -> Circuit:
"""Append one or more components to the circuit."""
self._components.extend(components)
return self
def add_directive(self, line: str) -> Circuit:
"""Append a raw SPICE directive (``.model``, ``.param`` ...)."""
self._directives.append(line.rstrip("\n"))
return self
def add_directive_once(self, line: str) -> Circuit:
"""Add a directive if an identical line (ignoring whitespace) is absent."""
normalized = line.strip()
for existing in self._directives:
if existing.strip() == normalized:
return self
return self.add_directive(line)
def connect(self, a: Port, b: Net | Port) -> Circuit:
"""Connect a port to another port or to a logical net.
Uses Union-Find for O(α(n)) amortized net merging (M2 optimization).
"""
self._invalidate_cache()
if isinstance(b, Port):
net_a = self._port_to_net.get(a)
net_b = self._port_to_net.get(b)
if net_a and net_b and net_a is not net_b:
# Merge using Union-Find: O(α(n)) instead of O(n)
# Ensure both nets are in union-find
if net_a not in self._net_union:
is_named_a = getattr(net_a, "name", None) is not None
self._net_union.make_set(net_a, net_a if is_named_a else None)
if net_b not in self._net_union:
is_named_b = getattr(net_b, "name", None) is not None
self._net_union.make_set(net_b, net_b if is_named_b else None)
# Prefer named net as canonical
prefer = None
if getattr(net_a, "name", None):
prefer = net_a
elif getattr(net_b, "name", None):
prefer = net_b
self._net_union.union(net_a, net_b, prefer=prefer)
else:
shared = net_a or net_b or Net()
self._port_to_net[a] = shared
self._port_to_net[b] = shared
# Register in union-find
if shared not in self._net_union:
is_named = getattr(shared, "name", None) is not None
self._net_union.make_set(shared, shared if is_named else None)
self._port_labels.pop(b, None)
else:
self._port_to_net[a] = b
# Register named net in union-find
if b not in self._net_union:
is_named = getattr(b, "name", None) is not None
self._net_union.make_set(b, b if is_named else None)
self._port_labels.pop(a, None)
return self
def _invalidate_cache(self) -> None:
"""Invalidate cached properties when circuit is modified."""
self._cache_version += 1
# Clear cached net IDs
self._net_ids.clear()
def connect_with_label(self, port: Port, net: Net, label: str | None = None) -> Circuit:
"""Connect ``port`` to ``net`` while recording a display label."""
self.connect(port, net)
if label:
self._port_labels[port] = label
return self
# ----------------------------------------------------------------------------------
# Net handling
# ----------------------------------------------------------------------------------
def _assign_node_ids(self) -> None:
"""Assign node IDs, using Union-Find for canonical net resolution."""
self._net_ids.clear()
self._net_ids[GND] = 0
next_id = 1
seen: set[Net] = {GND}
def canonical_nets_from_components() -> Iterable[Net]:
for comp in self._components:
for port in comp.ports:
net = self._port_to_net.get(port)
if net is not None:
# Use canonical net for proper merging
yield self._get_canonical_net(net)
for net in canonical_nets_from_components():
if net in seen:
continue
seen.add(net)
if getattr(net, "name", None) and net.name != "0":
# preserve named nets but still assign an id for bookkeeping
self._net_ids[net] = next_id
else:
self._net_ids[net] = next_id
next_id += 1
def _net_of(self, port: Port) -> str:
net = self._port_to_net.get(port)
if net is None:
raise ValueError(f"Unconnected port: {port.owner.ref}.{port.name}")
# Use Union-Find to get the canonical net (handles merged nets)
canonical_net = self._get_canonical_net(net)
if canonical_net is GND or getattr(canonical_net, "name", None) == "0":
return "0"
if getattr(canonical_net, "name", None):
return str(canonical_net.name)
node_id = self._net_ids.get(canonical_net)
if node_id is None:
raise RuntimeError("Node IDs not assigned")
return str(node_id)
def _get_canonical_net(self, net: Net) -> Net:
"""Get the canonical net for a possibly-merged net using Union-Find."""
if net not in self._net_union:
return net
return self._net_union.get_canonical(net)
# ----------------------------------------------------------------------------------
# Netlist helpers
# ----------------------------------------------------------------------------------
def build_netlist(self) -> str:
"""Return a SPICE netlist representation of this circuit."""
self._assign_node_ids()
lines: list[str] = [f"* {self.name}"]
for comp in self._components:
card = comp.spice_card(self._net_of)
# components such as AnalogMux may emit multi-line cards
for ln in card.splitlines():
if ln.strip():
lines.append(ln)
for directive in self._directives:
lines.extend(directive.splitlines())
if not any(line.strip().lower() == ".end" for line in lines):
lines.append(".end")
return "\n".join(lines) + "\n"
def save_netlist(self, path: str | Path) -> Path:
"""Persist the netlist to ``path`` and return the resolved ``Path``."""
p = Path(path)
p.write_text(self.build_netlist(), encoding="utf-8")
return p
# ----------------------------------------------------------------------------------
# Hash (deterministic) - part of M1 contract
# ----------------------------------------------------------------------------------
def hash(self, *, extra: dict[str, object] | None = None) -> str: # pragma: no cover - thin
"""Return a deterministic short hash for this circuit.
Wrapper around ``spicelab.core.types.circuit_hash`` so callers do not need
to import the helper directly. ``extra`` can include engine/version/analysis
args to bind caches firmly to execution context.
"""
from .types import circuit_hash # local import to avoid cycle during module init
return circuit_hash(self, extra=extra)
# ----------------------------------------------------------------------------------
# Validation (M4 DX improvement)
# ----------------------------------------------------------------------------------
def validate(self, strict: bool = False) -> ValidationResult:
"""Validate circuit topology and component values.
Performs checks:
- Ground reference exists
- No floating nodes (connected to only one component)
- No unusual component values
- No voltage source shorts (parallel voltage sources)
Args:
strict: If True, treat warnings as errors
Returns:
ValidationResult with errors and warnings
Example:
>>> result = circuit.validate()
>>> if result.has_issues():
... print(result)
>>> if not result.is_valid:
... raise ValueError("Circuit has errors")
"""
from ..validators.circuit_validation import validate_circuit
return validate_circuit(self, strict=strict)
# ----------------------------------------------------------------------------------
# Introspection helpers
# ----------------------------------------------------------------------------------
def _net_label(self, net: Net | None) -> str:
if net is None:
return "<unconnected>"
# Use canonical net for merged nets
canonical = self._get_canonical_net(net)
if canonical is GND or getattr(canonical, "name", None) == "0":
return "0"
if getattr(canonical, "name", None):
return str(canonical.name)
node_id = self._net_ids.get(canonical)
if node_id is None:
self._assign_node_ids()
node_id = self._net_ids.get(canonical)
return f"N{node_id:03d}" if node_id is not None else "<unnamed>"
def summary(self) -> str:
"""Return a human-readable summary of the circuit and connectivity."""
self._assign_node_ids()
lines: list[str] = []
warnings: list[str] = []
lines.append(f"Circuit: {self.name}")
lines.append(f"Components ({len(self._components)}):")
for comp in self._components:
port_descriptions: list[str] = []
for port in comp.ports:
net = self._port_to_net.get(port)
label = self._port_labels.get(port) or self._net_label(net)
if label == "<unconnected>":
warnings.append(f"Port {comp.ref}.{port.name} is unconnected")
port_descriptions.append(f"{port.name}->{label}")
port_info = ", ".join(port_descriptions) if port_descriptions else "<no ports>"
lines.append(f" - {comp.ref} ({type(comp).__name__}): {port_info}")
net_names = sorted({self._net_label(net) for net in self._port_to_net.values() if net})
if net_names:
lines.append(f"Nets ({len(net_names)}): {', '.join(net_names)}")
if warnings:
lines.append("Warnings:")
for msg in warnings:
lines.append(f" * {msg}")
else:
lines.append("Warnings: none")
return "\n".join(lines)
def to_dot(self) -> str:
"""Return a Graphviz DOT representation of the circuit."""
self._assign_node_ids()
lines: list[str] = ["graph circuit {", " rankdir=LR;"]
comp_ids: dict[Component, str] = {}
for idx, comp in enumerate(self._components, start=1):
comp_id = f"comp_{idx}"
comp_ids[comp] = comp_id
label = f"{comp.ref}\\n{type(comp).__name__}"
lines.append(f' "{comp_id}" [shape=box,label="{label}"];')
net_ids: dict[Net | None, str] = {}
net_counter = 1
def _net_node(net: Net | None) -> str:
nonlocal net_counter
if net in net_ids:
return net_ids[net]
node_id = f"net_{net_counter}"
net_counter += 1
label = self._net_label(net)
shape = "ellipse" if label != "<unconnected>" else "point"
net_ids[net] = node_id
lines.append(f' "{node_id}" [shape={shape},label="{label}"];')
return node_id
for comp in self._components:
comp_id = comp_ids[comp]
for port in comp.ports:
net = self._port_to_net.get(port)
net_id = _net_node(net)
lines.append(f' "{comp_id}" -- "{net_id}" [label="{port.name}",fontsize=10];')
lines.append("}")
return "\n".join(lines)
# ----------------------------------------------------------------------------------
# Notebook-friendly helpers
# ----------------------------------------------------------------------------------
def connectivity_dataframe(self, *, sort: bool = True, include_type: bool = True):
"""Return a pandas DataFrame describing component/net connectivity.
Columns: ``component``, ``type`` (optional), ``port`` and ``net``. The
returned DataFrame is ideal for Jupyter notebooks where an interactive
table is easier to scan than the plain text summary.
"""
try:
import pandas as pd
except Exception as exc: # pragma: no cover - optional dependency guard
raise RuntimeError("pandas is required for connectivity_dataframe()") from exc
self._assign_node_ids()
rows: list[dict[str, object]] = []
for comp in self._components:
for order, port in enumerate(comp.ports):
net = self._port_to_net.get(port)
label = self._port_labels.get(port) or self._net_label(net)
rows.append(
{
"component": comp.ref,
"type": type(comp).__name__,
"port": port.name,
"net": label,
"_order": order,
}
)
if not rows:
columns = ["component", "port", "net"]
if include_type:
columns.insert(1, "type")
return pd.DataFrame(columns=columns)
df = pd.DataFrame(rows)
if sort:
df = df.sort_values(["component", "_order", "port"]).reset_index(drop=True)
if not include_type:
df = df.drop(columns=["type"])
return df.drop(columns=["_order"])
def summary_table(self, *, indent: int = 2) -> str:
"""Return a fixed-width table describing component connections."""
df = self.connectivity_dataframe()
if df.empty:
return "(circuit is empty)"
headers = list(df.columns)
display_names = {col: col.capitalize() for col in headers}
widths = {
col: max(len(display_names[col]), *(len(str(val)) for val in df[col]))
for col in headers
}
def fmt_row(row: dict[str, object]) -> str:
cells = [str(row[col]).ljust(widths[col]) for col in headers]
return " " * indent + " ".join(cells)
header_line = " " * indent + " ".join(
display_names[col].ljust(widths[col]) for col in headers
)
sep_line = " " * indent + " ".join("-" * widths[col] for col in headers)
body = "\n".join(fmt_row(df.iloc[idx]) for idx in range(len(df)))
return f"{header_line}\n{sep_line}\n{body}"
# ----------------------------------------------------------------------------------
# Netlist import
# ----------------------------------------------------------------------------------
@classmethod
def from_netlist(cls, path: str | Path) -> Circuit:
"""Load a circuit from a plain SPICE netlist file."""
p = Path(path)
text = p.read_text(encoding="utf-8")
from spicelab.io.spice_parser import parse_lines_to_ast, preprocess_netlist
lines = preprocess_netlist(text)
ast = parse_lines_to_ast(lines)
name = p.stem
if lines and lines[0].lstrip().startswith("*"):
maybe_title = lines[0].lstrip()[1:].strip()
if maybe_title:
name = maybe_title
circ = cls(name=name)
for node in ast:
kind_obj = node.get("type")
kind = str(kind_obj) if isinstance(kind_obj, str) else None
raw_obj = node.get("raw")
raw = str(raw_obj) if isinstance(raw_obj, str) else ""
if kind == "subckt":
header = raw.splitlines()[0]
parts = header.split()
if len(parts) >= 2:
circ._subckt_defs[parts[1]] = raw
circ.add_directive(raw)
continue
if kind == "comment" or kind == "directive":
circ.add_directive(raw)
continue
if kind != "component":
continue
tokens_obj = node.get("tokens")
tokens: list[str] = [str(t) for t in tokens_obj] if isinstance(tokens_obj, list) else []
if not tokens:
continue
card = tokens[0]
letter = cast(str | None, node.get("letter"))
ref = cast(str | None, node.get("ref"))
try:
comp = cls._component_from_tokens(letter, ref, tokens)
if comp is None:
circ.add_directive(raw)
continue
circ.add(comp)
circ._connect_from_tokens(comp, tokens[1:])
if letter == "X":
circ._subckt_instances.append(
{"inst": card, "subckt": tokens[-1], "tokens": tokens}
)
except Exception as exc: # pragma: no cover - defensive fallback
log.warning("Failed to parse component '%s': %s", card, exc)
circ.add_directive(raw)
return circ
# ----------------------------------------------------------------------------------
# Helpers for from_netlist
# ----------------------------------------------------------------------------------
@staticmethod
def _component_from_tokens(
letter: str | None, ref: str | None, tokens: list[str]
) -> Component | None:
if not letter or not ref:
return None
letter = letter.upper()
value = " ".join(tokens[3:]) if len(tokens) > 3 else ""
if letter == "R":
return Resistor(ref=ref, value=value)
if letter == "C":
return Capacitor(ref=ref, value=value)
if letter == "L":
return Inductor(ref=ref, value=value)
if letter == "V":
return Vdc(ref=ref, value=value)
if letter == "I":
return Idc(ref=ref, value=value)
if letter == "E":
gain = " ".join(tokens[5:]) if len(tokens) > 5 else ""
return VCVS(ref=ref, gain=gain)
if letter == "G":
gm = " ".join(tokens[5:]) if len(tokens) > 5 else ""
return VCCS(ref=ref, gm=gm)
if letter == "F":
gain = " ".join(tokens[4:]) if len(tokens) > 4 else ""
ctrl = tokens[3] if len(tokens) > 3 else ""
return CCCS(ref=ref, ctrl_vsrc=ctrl, gain=gain)
if letter == "H":
r = " ".join(tokens[4:]) if len(tokens) > 4 else ""
ctrl = tokens[3] if len(tokens) > 3 else ""
return CCVS(ref=ref, ctrl_vsrc=ctrl, r=r)
if letter == "D":
model = tokens[3] if len(tokens) > 3 else ""
return Diode(ref=ref, model=model)
if letter == "S":
model = " ".join(tokens[5:]) if len(tokens) > 5 else ""
return VSwitch(ref=ref, model=model)
if letter == "W":
model = " ".join(tokens[4:]) if len(tokens) > 4 else ""
ctrl = tokens[3] if len(tokens) > 3 else ""
return ISwitch(ref=ref, ctrl_vsrc=ctrl, model=model)
# Subcircuits and unsupported devices are preserved as directives
return None
def _connect_from_tokens(self, component: Component, node_tokens: list[str]) -> None:
port_iter = iter(component.ports)
for node_name in node_tokens:
try:
port = next(port_iter)
except StopIteration:
break
net = self._get_or_create_net(node_name)
self.connect(port, net)
def _get_or_create_net(self, name: str) -> Net:
if name == "0":
return GND
for net in self._port_to_net.values():
if getattr(net, "name", None) == name:
return net
new = Net(name)
return new
add(*components)
Source code in
spicelab/core/circuit.py52
53
54
55
56
def add(self, *components: Component) -> Circuit:
"""Append one or more components to the circuit."""
self._components.extend(components)
return self
add_directive(line)
.model, .param ...).Source code in
spicelab/core/circuit.py58
59
60
61
62
def add_directive(self, line: str) -> Circuit:
"""Append a raw SPICE directive (``.model``, ``.param`` ...)."""
self._directives.append(line.rstrip("\n"))
return self
add_directive_once(line)
Source code in
spicelab/core/circuit.py64
65
66
67
68
69
70
71
def add_directive_once(self, line: str) -> Circuit:
"""Add a directive if an identical line (ignoring whitespace) is absent."""
normalized = line.strip()
for existing in self._directives:
if existing.strip() == normalized:
return self
return self.add_directive(line)
build_netlist()
Source code in
spicelab/core/circuit.py192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
def build_netlist(self) -> str:
"""Return a SPICE netlist representation of this circuit."""
self._assign_node_ids()
lines: list[str] = [f"* {self.name}"]
for comp in self._components:
card = comp.spice_card(self._net_of)
# components such as AnalogMux may emit multi-line cards
for ln in card.splitlines():
if ln.strip():
lines.append(ln)
for directive in self._directives:
lines.extend(directive.splitlines())
if not any(line.strip().lower() == ".end" for line in lines):
lines.append(".end")
return "\n".join(lines) + "\n"
connect(a, b)
Source code in
spicelab/core/circuit.py 73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def connect(self, a: Port, b: Net | Port) -> Circuit:
"""Connect a port to another port or to a logical net.
Uses Union-Find for O(α(n)) amortized net merging (M2 optimization).
"""
self._invalidate_cache()
if isinstance(b, Port):
net_a = self._port_to_net.get(a)
net_b = self._port_to_net.get(b)
if net_a and net_b and net_a is not net_b:
# Merge using Union-Find: O(α(n)) instead of O(n)
# Ensure both nets are in union-find
if net_a not in self._net_union:
is_named_a = getattr(net_a, "name", None) is not None
self._net_union.make_set(net_a, net_a if is_named_a else None)
if net_b not in self._net_union:
is_named_b = getattr(net_b, "name", None) is not None
self._net_union.make_set(net_b, net_b if is_named_b else None)
# Prefer named net as canonical
prefer = None
if getattr(net_a, "name", None):
prefer = net_a
elif getattr(net_b, "name", None):
prefer = net_b
self._net_union.union(net_a, net_b, prefer=prefer)
else:
shared = net_a or net_b or Net()
self._port_to_net[a] = shared
self._port_to_net[b] = shared
# Register in union-find
if shared not in self._net_union:
is_named = getattr(shared, "name", None) is not None
self._net_union.make_set(shared, shared if is_named else None)
self._port_labels.pop(b, None)
else:
self._port_to_net[a] = b
# Register named net in union-find
if b not in self._net_union:
is_named = getattr(b, "name", None) is not None
self._net_union.make_set(b, b if is_named else None)
self._port_labels.pop(a, None)
return self
connect_with_label(port, net, label=None)
port to net while recording a display label.Source code in
spicelab/core/circuit.py126
127
128
129
130
131
132
def connect_with_label(self, port: Port, net: Net, label: str | None = None) -> Circuit:
"""Connect ``port`` to ``net`` while recording a display label."""
self.connect(port, net)
if label:
self._port_labels[port] = label
return self
connectivity_dataframe(*, sort=True, include_type=True)
component, type (optional), port and net. The
returned DataFrame is ideal for Jupyter notebooks where an interactive
table is easier to scan than the plain text summary.Source code in
spicelab/core/circuit.py361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
def connectivity_dataframe(self, *, sort: bool = True, include_type: bool = True):
"""Return a pandas DataFrame describing component/net connectivity.
Columns: ``component``, ``type`` (optional), ``port`` and ``net``. The
returned DataFrame is ideal for Jupyter notebooks where an interactive
table is easier to scan than the plain text summary.
"""
try:
import pandas as pd
except Exception as exc: # pragma: no cover - optional dependency guard
raise RuntimeError("pandas is required for connectivity_dataframe()") from exc
self._assign_node_ids()
rows: list[dict[str, object]] = []
for comp in self._components:
for order, port in enumerate(comp.ports):
net = self._port_to_net.get(port)
label = self._port_labels.get(port) or self._net_label(net)
rows.append(
{
"component": comp.ref,
"type": type(comp).__name__,
"port": port.name,
"net": label,
"_order": order,
}
)
if not rows:
columns = ["component", "port", "net"]
if include_type:
columns.insert(1, "type")
return pd.DataFrame(columns=columns)
df = pd.DataFrame(rows)
if sort:
df = df.sort_values(["component", "_order", "port"]).reset_index(drop=True)
if not include_type:
df = df.drop(columns=["type"])
return df.drop(columns=["_order"])
from_netlist(path)
classmethod
Source code in
spicelab/core/circuit.py432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
@classmethod
def from_netlist(cls, path: str | Path) -> Circuit:
"""Load a circuit from a plain SPICE netlist file."""
p = Path(path)
text = p.read_text(encoding="utf-8")
from spicelab.io.spice_parser import parse_lines_to_ast, preprocess_netlist
lines = preprocess_netlist(text)
ast = parse_lines_to_ast(lines)
name = p.stem
if lines and lines[0].lstrip().startswith("*"):
maybe_title = lines[0].lstrip()[1:].strip()
if maybe_title:
name = maybe_title
circ = cls(name=name)
for node in ast:
kind_obj = node.get("type")
kind = str(kind_obj) if isinstance(kind_obj, str) else None
raw_obj = node.get("raw")
raw = str(raw_obj) if isinstance(raw_obj, str) else ""
if kind == "subckt":
header = raw.splitlines()[0]
parts = header.split()
if len(parts) >= 2:
circ._subckt_defs[parts[1]] = raw
circ.add_directive(raw)
continue
if kind == "comment" or kind == "directive":
circ.add_directive(raw)
continue
if kind != "component":
continue
tokens_obj = node.get("tokens")
tokens: list[str] = [str(t) for t in tokens_obj] if isinstance(tokens_obj, list) else []
if not tokens:
continue
card = tokens[0]
letter = cast(str | None, node.get("letter"))
ref = cast(str | None, node.get("ref"))
try:
comp = cls._component_from_tokens(letter, ref, tokens)
if comp is None:
circ.add_directive(raw)
continue
circ.add(comp)
circ._connect_from_tokens(comp, tokens[1:])
if letter == "X":
circ._subckt_instances.append(
{"inst": card, "subckt": tokens[-1], "tokens": tokens}
)
except Exception as exc: # pragma: no cover - defensive fallback
log.warning("Failed to parse component '%s': %s", card, exc)
circ.add_directive(raw)
return circ
hash(*, extra=None)
spicelab.core.types.circuit_hash so callers do not need
to import the helper directly. extra can include engine/version/analysis
args to bind caches firmly to execution context.Source code in
spicelab/core/circuit.py224
225
226
227
228
229
230
231
232
233
def hash(self, *, extra: dict[str, object] | None = None) -> str: # pragma: no cover - thin
"""Return a deterministic short hash for this circuit.
Wrapper around ``spicelab.core.types.circuit_hash`` so callers do not need
to import the helper directly. ``extra`` can include engine/version/analysis
args to bind caches firmly to execution context.
"""
from .types import circuit_hash # local import to avoid cycle during module init
return circuit_hash(self, extra=extra)
save_netlist(path)
path and return the resolved Path.Source code in
spicelab/core/circuit.py214
215
216
217
218
219
def save_netlist(self, path: str | Path) -> Path:
"""Persist the netlist to ``path`` and return the resolved ``Path``."""
p = Path(path)
p.write_text(self.build_netlist(), encoding="utf-8")
return p
summary()
Source code in
spicelab/core/circuit.py284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
def summary(self) -> str:
"""Return a human-readable summary of the circuit and connectivity."""
self._assign_node_ids()
lines: list[str] = []
warnings: list[str] = []
lines.append(f"Circuit: {self.name}")
lines.append(f"Components ({len(self._components)}):")
for comp in self._components:
port_descriptions: list[str] = []
for port in comp.ports:
net = self._port_to_net.get(port)
label = self._port_labels.get(port) or self._net_label(net)
if label == "<unconnected>":
warnings.append(f"Port {comp.ref}.{port.name} is unconnected")
port_descriptions.append(f"{port.name}->{label}")
port_info = ", ".join(port_descriptions) if port_descriptions else "<no ports>"
lines.append(f" - {comp.ref} ({type(comp).__name__}): {port_info}")
net_names = sorted({self._net_label(net) for net in self._port_to_net.values() if net})
if net_names:
lines.append(f"Nets ({len(net_names)}): {', '.join(net_names)}")
if warnings:
lines.append("Warnings:")
for msg in warnings:
lines.append(f" * {msg}")
else:
lines.append("Warnings: none")
return "\n".join(lines)
summary_table(*, indent=2)
Source code in
spicelab/core/circuit.py404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
def summary_table(self, *, indent: int = 2) -> str:
"""Return a fixed-width table describing component connections."""
df = self.connectivity_dataframe()
if df.empty:
return "(circuit is empty)"
headers = list(df.columns)
display_names = {col: col.capitalize() for col in headers}
widths = {
col: max(len(display_names[col]), *(len(str(val)) for val in df[col]))
for col in headers
}
def fmt_row(row: dict[str, object]) -> str:
cells = [str(row[col]).ljust(widths[col]) for col in headers]
return " " * indent + " ".join(cells)
header_line = " " * indent + " ".join(
display_names[col].ljust(widths[col]) for col in headers
)
sep_line = " " * indent + " ".join("-" * widths[col] for col in headers)
body = "\n".join(fmt_row(df.iloc[idx]) for idx in range(len(df)))
return f"{header_line}\n{sep_line}\n{body}"
to_dot()
Source code in
spicelab/core/circuit.py319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
def to_dot(self) -> str:
"""Return a Graphviz DOT representation of the circuit."""
self._assign_node_ids()
lines: list[str] = ["graph circuit {", " rankdir=LR;"]
comp_ids: dict[Component, str] = {}
for idx, comp in enumerate(self._components, start=1):
comp_id = f"comp_{idx}"
comp_ids[comp] = comp_id
label = f"{comp.ref}\\n{type(comp).__name__}"
lines.append(f' "{comp_id}" [shape=box,label="{label}"];')
net_ids: dict[Net | None, str] = {}
net_counter = 1
def _net_node(net: Net | None) -> str:
nonlocal net_counter
if net in net_ids:
return net_ids[net]
node_id = f"net_{net_counter}"
net_counter += 1
label = self._net_label(net)
shape = "ellipse" if label != "<unconnected>" else "point"
net_ids[net] = node_id
lines.append(f' "{node_id}" [shape={shape},label="{label}"];')
return node_id
for comp in self._components:
comp_id = comp_ids[comp]
for port in comp.ports:
net = self._port_to_net.get(port)
net_id = _net_node(net)
lines.append(f' "{comp_id}" -- "{net_id}" [label="{port.name}",fontsize=10];')
lines.append("}")
return "\n".join(lines)
validate(strict=False)
Name
Type
Description
Default
strict
bool
False
Type
Description
ValidationResult
Example
Source code in
spicelab/core/circuit.py238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
def validate(self, strict: bool = False) -> ValidationResult:
"""Validate circuit topology and component values.
Performs checks:
- Ground reference exists
- No floating nodes (connected to only one component)
- No unusual component values
- No voltage source shorts (parallel voltage sources)
Args:
strict: If True, treat warnings as errors
Returns:
ValidationResult with errors and warnings
Example:
>>> result = circuit.validate()
>>> if result.has_issues():
... print(result)
>>> if not result.is_valid:
... raise ValueError("Circuit has errors")
"""
from ..validators.circuit_validation import validate_circuit
return validate_circuit(self, strict=strict)