Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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 n−1n - 1 of them would be needed to connect nn component terminals to each other. The situation can be simplified by using a “wire” with nn ends to connect to nn terminals. This “nn-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, Ax=bA \mathbf{x} = \mathbf{b}, with which solvers are compatible? Or does that mean populating the matrix AA and vector b\mathbf{b} directly?

    For convenience, we can indeed use a symbolic math library (such as Python’s sympy and its nsolve solver) to “write” and solve the equations, without needing to manually put them into the Ax=bA \mathbf{x} = \mathbf{b} format; sympy can 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 aa and bb connected by voltage source Vs2V_{s2} in Figure 1, we must combine them and sum the currents out of the resulting supernode abab. The voltage source’s characteristic equation, Vs2=Va−VbV_{s2} = V_a - V_b, 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 nn-node circuit, only n−1n - 1 KCL equations are required; the nnth 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 nnth node a ground node, which contributes V=0V = 0 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/cur­rent 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:

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.

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.

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.

Component Library

Now that we have created our framework, we are able to implement our components and focus on the characteristic equation of each:

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:

  1. Passing all the circuit’s components to the solver.

  2. Extracting all the circuit’s nodes (taken from the components’ positive and negative terminals).

  3. Collecting the unknowns (voltages and currents) and equations (KCL and characteristic equations) from the nodes and components.

  4. Solving the equations for the unknowns using sympy’s nsolve.

  5. Assigning the solved values to their respective nodes and components.

Example 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:

Now we specify the two AC voltage sources, the two resistors, the inductor, and the capacitor:

Next, we pass the components to the solver, specify the circuit’s frequency (or 0 Hz0 \ \mathrm{Hz} for DC conditions), and run the solver:

We can access the solved voltage and current values through the original node and component objects:

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

  1. Add a plotting feature to the circuit analyzer (e.g., using Python’s matplotlib).

  2. Add the ability to import and analyze the circuit from a file or from a circuit diagram.

  3. Consider how you would adapt the circuit analyzer to support transient simulations and active components (diodes, transistors, etc.).

See here for some inspiration.