Circuits and subcircuits¶
A Circuit owns the top-level ordered elements of a design. A Subcircuit
owns a reusable definition and also acts as a factory for instances of that
definition.
Explicit construction¶
from nimphel import Circuit, Component, ComponentKind
resistor = Component(
target="resistor",
pins=("p", "n"),
kind=ComponentKind.RESISTOR,
)
circuit = Circuit(name="divider")
first = circuit.add(resistor(("vin", "vout"), r="1k"))
second = circuit.add(resistor(("vout", 0), r="2k"))
assert first.ref == "R1"
assert second.ref == "R2"
add() returns the attached element. extend() attaches an iterable in
order:
Context construction¶
A context makes its container the target of component and subcircuit factories:
with Circuit(name="divider") as circuit:
resistor(("vin", "vout"), r="1k")
resistor(("vout", 0), r="2k")
Nested contexts use the innermost scope and restore the previous one on exit, including when an exception is raised.
Direct Element construction is never registered implicitly.
Reference allocation¶
Each container owns an independent reference scope:
explicit = resistor.new(("vin", "vout"), {"r": "1k"}, ref="R5")
circuit = Circuit(elements=[explicit])
automatic = circuit.add(resistor(("vout", 0), r="2k"))
assert automatic.ref == "R6"
Rules:
- Explicit references are preserved.
- Duplicate references in one scope are rejected.
- Explicit references advance the matching allocator.
- Removed references are not automatically reused.
- Nested subcircuits may use the same local reference names as their parent.
Change an owned reference through the container:
Direct assignment to explicit.ref is rejected while the instance is owned.
Define a subcircuit¶
from nimphel import Subcircuit
with Subcircuit(
name="divider",
ports=("vin", "vout", "gnd"),
) as divider:
resistor(("vin", "vout"), r="1k")
resistor(("vout", "gnd"), r="2k")
The definition has its own reference scope. Register the definition, then call it to create top-level instances:
with Circuit(name="top") as top:
top.add(divider)
first = divider(("input_a", "output_a", 0))
second = divider(("input_b", "output_b", 0))
assert first.ref == "X1"
assert second.ref == "X2"
A subcircuit call validates its port bindings and required parameters just like a component call.
Reuse definitions¶
One definition object can have only one owner. Clone it before registering an independent copy elsewhere:
Usually a single circuit registers one definition and creates many instances from it; those instances are always fresh and do not require cloning.
Validate hierarchy¶
Integrity validation checks:
- duplicate definition names;
- undefined subcircuit targets;
- instance-to-port count mismatches;
- recursive dependency cycles.
All discovered problems are reported together in CircuitValidationError.