Tutorial: Building an AC Circuit Analyzer
This chapter is a practical tutorial that will build your AC circuit analysis and programming skills. The goal is to develop a reusable software tool that can solve for all voltages and currents of any steady-state AC circuit consisting of passive components: sinusoidal voltage and current sources, resistors, inductors, and capacitors. To keep the program simple, there is no need to build a user interface. The input circuit to analyze can be built programmatically, by defining components and how they’re connected.
Let’s first discuss how we can model the problem and design our solution. Jumping right into a solution would not be as interesting, useful, or realistic; the solutions to real-world problems are not handed out and often require thinking through the problem from the beginning before writing any code.
Design Discussion¶
Let’s start with the building blocks that will be used to construct and represent the circuit. It makes sense to use classes (or structs, in programming languages like Rust and Go) to represent our two-terminal electric components, but we also need to think about how to represent the connections between those components. Consider:
Does the orientation with which components are connected (positive versus negative terminals) matter?
Yes; it matters in order to establish a convention for voltage polarity and current direction, for the sake of “measuring” the solved voltage/current of a component, as well as for specifying the voltage/current of a sinusoidal voltage/current source.
Is it best to model the components as being connected by wires, or by nodes?
Wires are the more intuitive physical representation, but if wires were to be used, at least of them would be needed to connect component terminals to each other. The situation can be simplified by using a “wire” with ends to connect to terminals. This “-ended wire” is simply a node. Using nodes is also the clear choice to be able to apply KCL easily.
For convenience when applying KCL, each node can list all components attached to it. However, that would not allow us to represent which of the component’s terminals—positive or negative—are attached to a given node. To address this, each component can have attributes positive and negative, specifying which terminal each node is attached to.
We know that any AC circuit can be analyzed by applying KCL and solving a linear system of complex-valued phasor equations in terms of the node voltages. Formulating that system of equations is routine when analyzing circuits by hand, but formalizing that process to be done by a computer requires more thought. Consider:
What does “summing the currents flowing out of each node” mean when developing a program? Does that mean finding a way to represent equations programmatically and then convert them to the standard format for linear systems, , with which solvers are compatible? Or does that mean populating the matrix and vector directly?
For convenience, we can indeed use a symbolic math library (such as Python’s
sympyand itsnsolvesolver) to “write” and solve the equations, without needing to manually put them into the format;sympycan do the heavy lifting.How does one determine when the supernode technique must be used, and apply it programmatically?
The system of equations can be generalized—boiling down the circuit analysis problem to its simplest laws—such that the supernode technique need not be explicitly applied.
In regular KCL, we sum the currents out of each node in terms of the node voltages. When this cannot be done, such as for nodes and connected by voltage source in Figure 1, we must combine them and sum the currents out of the resulting supernode . The voltage source’s characteristic equation, , makes up for the missing KCL equation.
Instead, let’s sum the currents out of each node, and—rather than putting those currents in terms of node voltages—add the characteristic equation for each connected component to the system of equations. This eliminates the need for the supernode technique. This approach is atypical when solving equations by hand, as it requires writing out a larger initial system of equations, but this is a non-issue for a computer.
For every node and component, there will be one unknown (the node’s voltage or the component’s current) and one equation (KCL or the component’s characteristic equation). However, there are two exceptions to this. Firstly, in an -node circuit, only KCL equations are required; the th adds no new information to the system of equations. And secondly, because voltages are relative, a voltage reference is needed to prevent the system from having an infinite number of solutions. Both these points can be addressed by making the th node a ground node, which contributes to the system of equations rather than KCL.
Now that we have formalized the problem and considered the design options, we’re ready to implement. Give it a shot, consulting the following sections for ideas if desired (they use Python, but feel free to use any programming language).
Data Model¶
To start developing our program, we need a way to represent voltage and current values—for the sake of representing solved values, as well as for specifying the voltage/current of a sinusoidal voltage/current source. Python has built-in support for complex numbers, with a dedicated complex type and 1j literal. However, it is more common outside of numerical computation to work with phasors in polar form. As such, we create a Phasor class (polar form), with methods for converting to and from complex numbers:
@dataclass
class Phasor:
magnitude: float
phase_deg: float = 0.0
@property
def phase_rad(self) -> float:
return radians(self.phase_deg)
@classmethod
def from_complex(cls, value: complex) -> Self:
return cls(
magnitude=abs(value),
phase_deg=degrees(atan2(value.real, value.imag)),
)
def to_complex(self) -> complex:
return self.magnitude * (
cos(self.phase_deg) + 1j * sin(self.phase_deg)
)
def __repr__(self) -> str:
return f"{self.magnitude:.6f} @ {self.phase_deg:.3f}°"We also need a way to represent the duality of voltages and currents. They are either unknown variables (Symbols) in our sympy equations to solve for, or solved output values. To represent this, we create Voltage and Current classes, each with both a variable (of type Symbol) and a value (of type Phasor). The Symbol is automatically named depending on whether it represents a node’s voltage or a component’s current, allowing both us and sympy to meaningfully distinguish them. These traits are common to both the Voltage and Current classes, so we first create a shared base class for them called _Symbolic.
Note that a positive value of current indicates flow from the positive terminal to the negative terminal, by convention.
@dataclass(kw_only=True)
class _Symbolic:
value: Phasor | None = None
@property
def variable(self) -> Symbol:
return Symbol(str(self))
@dataclass
class Voltage(_Symbolic):
node_name: str
def __str__(self) -> str:
return f"(node {self.node_name} voltage)"
@dataclass
class Current(_Symbolic):
component_name: str
def __str__(self) -> str:
return f"(component {self.component_name} current)"Building Blocks¶
Now we create the building blocks that we’ll use to represent the circuit: nodes and components. First we create the Node class. Every node contributes a KCL equation and has a Voltage that is free to vary, except the ground node (is_ground=True), whose voltage is fixed at zero.
@dataclass(repr=False)
class Node:
name: str
is_ground: bool = False
voltage: Voltage = field(init=False)
connected_components: list[_BaseComponent] = field(
init=False
)
def __post_init__(self):
self.voltage = Voltage(node_name=self.name)
# Appended to by `BaseComponent.__post_init__`s:
self.connected_components = []
def __hash__(self) -> int:
return hash(self.name)
@property
def equation(self):
if self.is_ground:
return self.voltage.variable
else:
return sum(
c.current.variable
* (1 if c.positive is self else -1)
for c in self.connected_components
)Unlike nodes, which are universal, we have multiple types of component. However, they have much in common: they all have current flowing from a positive terminal to a negative terminal, and they generally have a characteristic equation describing the relationship between that electric current and the voltage difference across the component (that is, between the two connected nodes). The only exception to this will be the voltage and current sources, whose voltage and current variables are obviously fixed. To avoid having to write the same code over and over, we create a _BaseComponent, of which every type of component will be a subclass. Each component must implement the equation method (which really returns a sympy expression, used as the LHS in an equation whose RHS is zero). The frequency (frequency_rad_per_s) is passed to each equation method because it is a global property of the circuit rather than each component, but will be needed by the Inductor and Capacitor components to calculate reactance and admittance, as we will see in the next section.
@dataclass(repr=False)
class _BaseComponent(abc.ABC):
name: str
negative: Node
positive: Node
current: Current = field(init=False)
def __post_init__(self):
self.current = Current(component_name=self.name)
for node in self._connected_nodes:
node.connected_components.append(self)
@property
def _connected_nodes(self) -> list[Node]:
return [self.negative, self.positive]
@abc.abstractmethod
def equation(self, frequency_rad_per_s: float):
raise NotImplementedError
@property
def voltage_difference(self):
return (
self.positive.voltage.variable
- self.negative.voltage.variable
)Component Library¶
Now that we have created our framework, we are able to implement our components and focus on the characteristic equation of each:
@dataclass(repr=False)
class VoltageSource(_BaseComponent):
value: Phasor
def equation(self, frequency_rad_per_s: float):
return self.voltage_difference - self.value.to_complex()
@dataclass(repr=False)
class CurrentSource(_BaseComponent):
value: Phasor
def equation(self, frequency_rad_per_s: float):
return self.current.variable - self.value.to_complex()
@dataclass(repr=False)
class Resistor(_BaseComponent):
resistance_ohm: float
def equation(self, frequency_rad_per_s: float):
return (
self.voltage_difference
- self.current.variable * self.resistance_ohm
)
@dataclass(repr=False)
class Inductor(_BaseComponent):
inductance_h: float
def equation(self, frequency_rad_per_s: float):
reactance = 1j * frequency_rad_per_s * self.inductance_h
return (
self.voltage_difference
- self.current.variable * reactance
)
@dataclass(repr=False)
class Capacitor(_BaseComponent):
capacitance_f: float
def equation(self, frequency_rad_per_s: float):
admittance = 1j * (
frequency_rad_per_s * self.capacitance_f
)
return (
self.voltage_difference * admittance
- self.current.variable
)Rather than using reactance for the capacitor, we use its inverse—admittance—as it conveniently allows the circuit’s frequency to be set to zero to model the circuit under DC conditions, without encountering a division-by-zero error.
The Circuit Solver¶
All that’s left to do is create a circuit solver to determine the voltage and current values. This is done by:
Passing all the circuit’s components to the solver.
Extracting all the circuit’s nodes (taken from the components’
positiveandnegativeterminals).Collecting the unknowns (voltages and currents) and equations (KCL and characteristic equations) from the nodes and components.
Solving the equations for the unknowns using
sympy’snsolve.Assigning the solved values to their respective nodes and components.
@dataclass(repr=False)
class AcCircuitSolver:
frequency_hz: float
components: list[_BaseComponent]
def solve(self) -> None:
connected_nodes = self._get_connected_nodes()
symbolics = self._get_symbolics(connected_nodes)
equations = self._get_equations(connected_nodes)
unknowns = [s.variable for s in symbolics]
initial_guess = [0.0 for s in symbolics]
solution = nsolve(equations, unknowns, initial_guess)
for unknown, solved_value in zip(symbolics, solution):
unknown.value = Phasor.from_complex(
complex(solved_value)
)
def _get_symbolics(
self, connected_nodes: list[Node]
) -> list[_Symbolic]:
symbolics: list[_Symbolic] = []
for n in connected_nodes:
symbolics.append(n.voltage)
for c in self.components:
symbolics.append(c.current)
return symbolics
def _get_equations(self, connected_nodes: list[Node]):
equations = []
for n in connected_nodes:
equations.append(n.equation)
frequency_rad_per_s = 2 * pi * self.frequency_hz
for c in self.components:
equations.append(c.equation(frequency_rad_per_s))
return equations
def _get_connected_nodes(self) -> list[Node]:
nodes: list[Node] = []
for component in self.components:
nodes += component._connected_nodes
# Deduplicate (requires `Node.__hash__`):
nodes = list(set(nodes))
return nodesExample Usage¶
We can apply our solver to the example circuit of Figure 1 from the last chapter. We specify the circuit’s nodes—the positive and negative terminals of both AC voltage sources—giving each a unique name:
vs1p = Node("Vs1p")
vs1n = Node("Vs1n", is_ground=True)
a = Node("Vs2p")
b = Node("Vs2n")Now we specify the two AC voltage sources, the two resistors, the inductor, and the capacitor:
vs1 = VoltageSource("Vs1", vs1n, vs1p, Phasor(magnitude=1))
vs2 = VoltageSource("Vs2", b, a, Phasor(magnitude=2))
r1 = Resistor("R1", b, vs1p, resistance_ohm=4)
r2 = Resistor("R2", vs1n, a, resistance_ohm=5)
l = Inductor("L", a, vs1p, inductance_h=6)
c = Capacitor("C", vs1n, b, capacitance_f=7)Next, we pass the components to the solver, specify the circuit’s frequency (or for DC conditions), and run the solver:
solver = AcCircuitSolver(
frequency_hz=(3 / (2 * pi)),
components=[vs1, vs2, r1, r2, l, c],
)
solver.solve()We can access the solved voltage and current values through the original node and component objects:
print(f"{a.voltage.value = }")
print(f"{b.voltage.value = }")
print(f"{vs2.current.value = }")a.voltage.value = 2.003 @ 89.794°
b.voltage.value = 0.008 @ 19.092°
vs2.current.value = 0.405 @ -82.293°
This chapter is available as a runnable Python notebook and as a Python script.
Additional Exercises¶
Add a plotting feature to the circuit analyzer (e.g., using Python’s
matplotlib).Add the ability to import and analyze the circuit from a file or from a circuit diagram.
Consider how you would adapt the circuit analyzer to support transient simulations and active components (diodes, transistors, etc.).
See here for some inspiration.