Automating Circuit Analysis with Python: From Ohm’s Law to Complex Networks

Automate circuit analysis using Python—from Ohm’s Law to complex AC networks with real examples.


Electrical circuit analysis forms the backbone of electrical and electronic engineering. Traditionally performed manually or with commercial simulation software, circuit analysis can now be effectively automated using Python. This article presents a comprehensive guide to circuit analysis automation, starting from basic Ohm’s Law to handling complex multi-loop and multi-node circuits using Python programming.

Python offers a flexible, cost-effective, and highly customizable environment for automating both DC and AC circuit analysis. With libraries like SymPy, NumPy, and SciPy, engineers and students can model, solve, and visualize electrical circuits with ease.

Introduction to Circuit Analysis

Circuit analysis is the process of determining voltage, current, and power in electrical components. It uses principles such as:

  • Ohm’s Law: V=IRV = IR

  • Kirchhoff’s Current Law (KCL): Sum of currents at a node is zero

  • Kirchhoff’s Voltage Law (KVL): Sum of voltages in a loop is zero

  • Impedance for AC circuits: Z=R+jXZ = R + jX

  • Superposition, Thevenin/Norton Equivalents, Mesh and Nodal Analysis

Why Use Python for Circuit Analysis?

Python is:

  • Open-source and widely adopted in academia and industry

  • Equipped with symbolic computation (SymPy) for analytical solutions

  • Strong in numerical methods (NumPy, SciPy) for matrix-based analysis

  • Easily extensible with graph-based libraries for network analysis

  • Great for visualization with Matplotlib and Plotly

Python Libraries for Circuit Modeling

Library Purpose
NumPy Matrix and vector operations
SymPy Symbolic algebra and equation solving
SciPy Numerical solvers
Matplotlib Graph plotting
NetworkX Graph representation of circuits
PySpice Python interface to NGSpice

Step 1: Automating Ohm’s Law

Example: Calculate current through a resistor

V = 12  # volts
R = 6   # ohms
I = V / R
print(f"Current: {I} A")

Output:

Current: 2.0 A

This basic level forms the foundation for automated calculations and can be scaled up using functions or object-oriented designs.

Step 2: Series and Parallel Circuits

Series Resistors

Req=R1+R2+...+RnR_{eq} = R_1 + R_2 + ... + R_n

R_series = sum([10, 15, 5])
print(f"Equivalent Resistance (Series): {R_series} Ω")

Parallel Resistors

1Req=1R1+1R2+...+1Rn\frac{1}{R_{eq}} = \frac{1}{R_1} + \frac{1}{R_2} + ... + \frac{1}{R_n}

from functools import reduce

resistors = [10, 20, 30]
R_parallel = 1 / sum(1/r for r in resistors)
print(f"Equivalent Resistance (Parallel): {R_parallel:.2f} Ω")

Step 3: Nodal Analysis Using Python

Nodal analysis uses KCL to solve circuits with multiple nodes by expressing the node voltages as unknowns.

Example Circuit:

  • V1V_1 connected to Node A through 10 Ω

  • Node A connected to ground through 20 Ω

  • Node A connected to 5V voltage source through 30 Ω

Let’s form the admittance matrix:

V1VA10+VA020+VA530=0\frac{V_1 - V_A}{10} + \frac{V_A - 0}{20} + \frac{V_A - 5}{30} = 0
from sympy import symbols, Eq, solve

VA = symbols('VA')
eq = Eq((12 - VA)/10 + VA/20 + (VA - 5)/30, 0)
sol = solve(eq, VA)
print(f"Node A Voltage: {sol[0]:.2f} V")

Step 4: Mesh (Loop) Analysis

Mesh analysis uses KVL to analyze loop currents in a planar circuit.

Example: Two loops with shared resistor

from sympy import symbols, Eq, solve

I1, I2 = symbols('I1 I2')
eq1 = Eq(10*I1 + 5*(I1 - I2), 12)
eq2 = Eq(5*(I2 - I1) + 20*I2, 0)

sol = solve((eq1, eq2), (I1, I2))
print(f"I1 = {sol[I1]:.2f} A, I2 = {sol[I2]:.2f} A")

This symbolic solution can be extended to 3 or more loops by automating matrix generation.

Step 5: Solving Complex AC Circuits

AC circuits use phasor representation and complex impedance:

Z=R+jωL+1jωCZ = R + j\omega L + \frac{1}{j\omega C}

Example: Series RLC Circuit with sinusoidal source

import numpy as np

R = 10  # ohms
L = 0.1  # H
C = 100e-6  # F
f = 50  # Hz
omega = 2 * np.pi * f

Z = complex(R, omega*L - 1/(omega*C))  # total impedance
V = 230
I = V / Z

print(f"Current Magnitude: {abs(I):.2f} A")
print(f"Current Phase: {np.angle(I, deg=True):.2f} degrees")

Step 6: Using SymPy for Symbolic Circuit Analysis

To derive symbolic expressions for current and voltage:

from sympy import symbols, Eq, solve

R, V = symbols('R V')
I = V / R
print(f"Current Expression: {I}")

You can also solve for unknown component values:

eq = Eq(V / 10, 2)
sol = solve(eq, V)
print(f"Required Voltage: {sol[0]} V")

Step 7: Building a Python Circuit Solver

Build a system that takes:

  • List of nodes

  • List of components (resistors, sources)

  • Connectivity matrix

Example: Automatically solve node voltages for an n-node circuit using NumPy matrix algebra:

import numpy as np

# Conductance matrix G and current vector I
G = np.array([[1/10 + 1/20, -1/20],
              [-1/20, 1/20 + 1/30]])
I = np.array([1.2, 0.5])  # Net current injections

V = np.linalg.solve(G, I)
print(f"Node Voltages: {V}")

Visualization with Matplotlib

Visualize voltage levels across nodes or current in branches:

import matplotlib.pyplot as plt

nodes = ['A', 'B']
voltages = [V[0], V[1]]

plt.bar(nodes, voltages, color='teal')
plt.ylabel("Voltage (V)")
plt.title("Node Voltage Distribution")
plt.grid(True)
plt.show()

FAQs

Q1: Can Python replace tools like LTspice or MATLAB Simulink?

Python is ideal for analytical and numerical solutions. For waveform-based time-domain simulation, LTspice and Simulink are better. Python is excellent for solving equations, running optimization, and automating batch analysis.

Q2: What’s the benefit of symbolic analysis?

Symbolic computation lets you derive general formulas, helpful for teaching, design, or parametric studies.

Q3: How can I model dependent sources?

Use SymPy to define controlled sources as functions of voltages or currents and solve accordingly.

Q4: Can I analyze non-linear elements like diodes?

Yes, using iterative solvers like Newton-Raphson in SciPy.optimize.fsolve() for solving non-linear I-V equations.

Q5: Is there a GUI for visual circuit input?

You can integrate with tools like KiCAD, or create a visual circuit builder using libraries like Tkinter, PyQt, or dash-cytoscape.

Conclusion

Automating circuit analysis with Python empowers engineers and students with the flexibility to model, solve, and optimize circuits from first principles. Whether you're working on a simple Ohm's Law problem or a complex AC network, Python offers:

  • Full control over calculations

  • Integration with data analysis and ML workflows

  • Custom simulation tools for repeated analysis

With practice and the right approach, Python can become a powerful part of any electrical engineer’s toolkit.

Prasun Barua is an Engineer (Electrical & Electronic) and Member of the European Energy Centre (EEC). His first published book Green Planet is all about green technologies and science. His other …

Post a Comment

© Prasun Barua . All rights reserved. Developed by Jago Desain