Wednesday, December 2, 2026

Making Engineering Fun with Julia: An Interactive RLC Circuit Simulator...

Electrical / Electronics engineering becomes much more interesting when we can see equations come alive.

Recently, I developed an interactive Series RLC Circuit Transient Simulator using Julia and GLMakie. The application allows us to change resistance, inductance, and capacitance through sliders and observe how these parameters influence the circuit's transient response.

The project combines circuit theory, numerical methods, and interactive visualization in a single application.

Watch...



The Mathematics Behind the Circuit

A series RLC circuit consists of a resistor, an inductor, and a capacitor connected in series. When a DC step voltage is applied, the circuit current and capacitor voltage evolve over time.

Using Kirchhoff's Voltage Law:

$$ V_s = Ri + L\frac{di}{dt} + V_c $$

The capacitor relationship is:

$$ i = C\frac{dV_c}{dt} $$

These equations can be expressed as a system of first-order differential equations:

$$ \frac{di}{dt} = \frac{V_s - Ri - V_c}{L} $$ $$ \frac{dV_c}{dt} = \frac{i}{C} $$

The simulator uses these equations to calculate the circuit's behavior at every time step.

Enter Runge–Kutta: Solving Differential Equations Numerically

Many engineering systems are described by differential equations that are difficult or inconvenient to solve analytically. Numerical methods provide a way to approximate their solutions.

This project uses the fourth-order Runge–Kutta method (RK4).

The simplest numerical method, Euler's method, estimates the next value using the slope at the beginning of a time interval. RK4 improves this estimate by evaluating the slope four times:

  • (k_1): slope at the beginning of the interval

  • (k_2): slope at the midpoint, using the first estimate

  • (k_3): another midpoint estimate

  • (k_4): slope at the end of the interval

The weighted average of these four slopes gives the next state:

$$ x_{n+1} = x_n + \frac{\Delta t}{6} \left(k_1 + 2k_2 + 2k_3 + k_4\right) $$

In our simulator, the state vector is:

$$ x = \begin{bmatrix} i \\ V_c \end{bmatrix} $$

It contains the circuit current and capacitor voltage. RK4 advances both quantities together through time.

The simulation uses a time step of (10^{-5}) seconds. A sufficiently small time step helps capture the rapid changes that occur during the transient response.

What Can We Observe?

The application presents four engineering plots:

  1. Capacitor voltage — how the capacitor charges and approaches its steady-state voltage.

  2. Circuit current — how current rises, oscillates, and eventually settles.

  3. Component voltages — the voltage drops across the resistor, inductor, and capacitor.

  4. Stored energy — how energy moves between the inductor's magnetic field and the capacitor's electric field.

The component-voltage plot demonstrates Kirchhoff's Voltage Law:


V_r+V_l+V_c=V_s

The energy plot is particularly interesting. The inductor stores magnetic energy, while the capacitor stores electric energy:

$$ E_L = \frac{1}{2}Li^2 $$ $$ E_C = \frac{1}{2}CV_c^2 $$

The total stored energy changes as the circuit responds to the input, while the resistor dissipates energy as heat.

Interactive Engineering with Julia

The real excitement begins when we move the sliders.

Changing resistance affects damping. Changing inductance or capacitance changes the natural frequency of the circuit. The simulator recalculates the response and updates the plots dynamically.

Julia makes this kind of project approachable because its mathematical syntax closely resembles the equations we write on paper. With GLMakie, we can connect numerical calculations to interactive graphical elements without building a separate application in another language.

From Circuit Theory to Scientific Computing

This small project demonstrates a powerful idea: engineering concepts can be explored through computation rather than only through textbook examples.

The same approach can be extended to:

  • Parallel RLC circuits

  • Resonance and frequency response

  • PID control systems

  • Mechanical spring-mass-damper systems

  • Heat transfer and fluid simulation

A few equations, a numerical solver, and an interactive interface can turn an abstract engineering topic into a virtual laboratory.

For me, this is one of the most enjoyable aspects of scientific computing with Julia — the ability to experiment with mathematics and immediately see the physical consequences of changing a parameter.

Source Code...


using GLMakie

############################
# 1. Simulation Parameters & ODE
############################

Vs = 10.0           # DC step voltage (Volt)
t_start = 0.0
t_end = 0.1
dt = 1e-5

t = collect(t_start:dt:t_end)
t_ms = t .* 1000.0

function rlc_derivatives(x, R, L, C, Vs)
    current = x[1]
    voltage = x[2]
    di_dt = (Vs - R * current - voltage) / L
    dVc_dt = current / C
    return [di_dt, dVc_dt]
end

function rk4_step(x, dt, R, L, C, Vs)
    k1 = rlc_derivatives(x, R, L, C, Vs)
    k2 = rlc_derivatives(x .+ 0.5 * dt .* k1, R, L, C, Vs)
    k3 = rlc_derivatives(x .+ 0.5 * dt .* k2, R, L, C, Vs)
    k4 = rlc_derivatives(x .+ dt .* k3, R, L, C, Vs)
    return x .+ (dt / 6.0) .* (k1 .+ 2.0 .* k2 .+ 2.0 .* k3 .+ k4)
end

function simulate_rlc(t, R, L, C, Vs)
    N = length(t)
    step_dt = t[2] - t[1]
    i = zeros(N)
    Vc = zeros(N)
    x = [0.0, 0.0]

    for k in 1:N
        i[k] = x[1]
        Vc[k] = x[2]
        if k < N
            x = rk4_step(x, step_dt, R, L, C, Vs)
        end
    end

    Vr = R .* i
    Vl = Vs .- Vr .- Vc
    E_inductor = 0.5 .* L .* i.^2
    E_capacitor = 0.5 .* C .* Vc.^2
    E_total = E_inductor .+ E_capacitor

    omega0 = 1.0 / sqrt(L * C)
    alpha = R / (2.0 * L)
    zeta = alpha / omega0

    regime = if zeta < 0.99
        "Underdamped"
    elseif zeta <= 1.01
        "Near Critical Damping"
    else
        "Overdamped"
    end

    return (
        i = i,
        Vc = Vc,
        Vr = Vr,
        Vl = Vl,
        E_inductor = E_inductor,
        E_capacitor = E_capacitor,
        E_total = E_total,
        omega0 = omega0,
        zeta = zeta,
        regime = regime
    )
end

############################
# 2. Interactive Figure & Sliders
############################

fig = Figure(size = (1250, 920), fontsize = 15, figure_padding = 20)

sg = SliderGrid(
    fig[1, 1:2],
    (label = "Resistance R (Ω)", range = 1.0:1.0:150.0, format = "{:.1f} Ω", startvalue = 20.0),
    (label = "Inductance L (mH)", range = 10.0:5.0:500.0, format = "{:.0f} mH", startvalue = 100.0),
    (label = "Capacitance C (μF)", range = 20.0:10.0:500.0, format = "{:.0f} μF", startvalue = 100.0),
    width = 900
)

R_obs = sg.sliders[1].value
L_obs = lift(val -> val * 1e-3, sg.sliders[2].value)
C_obs = lift(val -> val * 1e-6, sg.sliders[3].value)

sim_obs = lift(R_obs, L_obs, C_obs) do R, L, C
    simulate_rlc(t, R, L, C, Vs)
end

header_text = lift(sim_obs, R_obs, sg.sliders[2].value, sg.sliders[3].value) do sim, R, L_mH, C_uF
    "Series RLC Transient ($(sim.regime)) — R=$(round(R, digits=1)) Ω, L=$(round(L_mH, digits=0)) mH, C=$(round(C_uF, digits=0)) μF | ζ=$(round(sim.zeta, digits=3)), ω₀=$(round(sim.omega0, digits=1)) rad/s"
end

Label(fig[0, 1:2], header_text, fontsize = 18, font = :bold)

# Derived reactive observables for plotting
Vc_obs = lift(s -> s.Vc, sim_obs)
i_obs = lift(s -> s.i, sim_obs)
Vr_obs = lift(s -> s.Vr, sim_obs)
Vl_obs = lift(s -> s.Vl, sim_obs)
El_obs = lift(s -> s.E_inductor, sim_obs)
Ec_obs = lift(s -> s.E_capacitor, sim_obs)
Et_obs = lift(s -> s.E_total, sim_obs)

############################
# 3. Four Engineering Plots
############################

# Plot 1: Capacitor Voltage
ax1 = Axis(fig[2, 1], title = "Capacitor Voltage", xlabel = "Time (ms)", ylabel = "Voltage (V)")
lines!(ax1, t_ms, Vc_obs, color = :royalblue, linewidth = 2.5, label = "Vc(t)")
hlines!(ax1, [Vs], color = :gray50, linestyle = :dash, linewidth = 1.5, label = "Step Input ($(Vs) V)")
axislegend(ax1, position = :rb)

# Plot 2: Circuit Current
ax2 = Axis(fig[2, 2], title = "Circuit Current", xlabel = "Time (ms)", ylabel = "Current (A)")
lines!(ax2, t_ms, i_obs, color = :crimson, linewidth = 2.5, label = "i(t)")
hlines!(ax2, [0.0], color = :gray50, linestyle = :dot, linewidth = 1.2)
axislegend(ax2, position = :rt)

# Plot 3: Component Voltages
ax3 = Axis(fig[3, 1], title = "Component Voltages (Vr + Vl + Vc = Vs)", xlabel = "Time (ms)", ylabel = "Voltage (V)")
lines!(ax3, t_ms, Vr_obs, color = :darkorange, linewidth = 2.0, linestyle = :solid, label = "Resistor (Vr)")
lines!(ax3, t_ms, Vl_obs, color = :seagreen, linewidth = 2.0, linestyle = :dash, label = "Inductor (Vl)")
lines!(ax3, t_ms, Vc_obs, color = :royalblue, linewidth = 2.0, linestyle = :dot, label = "Capacitor (Vc)")
axislegend(ax3, position = :rt)

# Plot 4: Stored Energy
ax4 = Axis(fig[3, 2], title = "Stored Energy", xlabel = "Time (ms)", ylabel = "Energy (J)")
lines!(ax4, t_ms, El_obs, color = :seagreen, linewidth = 2.2, label = "Inductor Energy")
lines!(ax4, t_ms, Ec_obs, color = :royalblue, linewidth = 2.2, label = "Capacitor Energy")
lines!(ax4, t_ms, Et_obs, color = :black, linewidth = 1.8, linestyle = :dash, label = "Total Stored Energy")
axislegend(ax4, position = :rt)

# Keep y-limits readable across slider sweeps
on(sim_obs) do sim
    ylims!(ax2, extrema(sim.i) .* 1.15)
    ylims!(ax3, extrema(vcat(sim.Vr, sim.Vl, sim.Vc)) .* 1.15)
    ylims!(ax4, (0.0, max(maximum(sim.E_total) * 1.15, 1e-4)))
end
notify(sim_obs)

colgap!(fig.layout, 24)
rowgap!(fig.layout, 18)

screen = display(fig)
wait(screen)

Thursday, November 26, 2026

2014: Elon Musk Opens the Patent Wall. 1991: Bill Gates Warns Against It - Two different people. Two different philosophies. One question for every engineer...

In 2014, Elon Musk announced that Tesla would not initiate patent lawsuits against those using its technology in good faith.

His reasoning was simple: Tesla's mission was to accelerate the world's transition to sustainable energy. Why should patents prevent other engineers from contributing to that mission?

Musk believed that a growing electric-vehicle ecosystem would benefit everyone—including Tesla.

And engineers celebrated.

Now rewind to 1991.

Bill Gates, in an internal Microsoft memo, warned that if software patents had been widely taken out on existing ideas, the industry could have come to a complete standstill.

He understood the danger of turning fundamental ideas into corporate property.

Yet Microsoft later became an aggressive participant in the patent system.

The irony

Gates recognised the patent wall. Musk chose to open a door through it.

One warned that patents could suffocate innovation; the other demonstrated that a technology leader could choose openness over exclusivity.

What if Bharat had patented Zero?

Imagine if ancient Bharat had patented zero—the mathematical concept that transformed the decimal place-value system and became one of the foundations of modern computing.

What if every engineer, mathematician, and programmer had needed permission to use it?

The binary world of 0s and 1s, the digital revolution, the internet, and today's computing ecosystem would have faced an absurd barrier at their very foundation.

Bharat did not build a patent wall around zero. It gave the world a stepping stone.

The engineer's perspective

A patent can protect an invention. But it cannot guarantee innovation.

The engineer wants to solve problems, build upon existing knowledge, and create something better. The patent wall can turn that creative process into a legal obstacle course.

The question is not whether inventors deserve protection. They do.

The question is whether protecting an invention should become a means of controlling an entire technological ecosystem.

Musk's 2014 decision reminded us that true technological leadership is not merely about owning ideas—it is about enabling others to build upon them.

The future belongs to those who turn ideas into stepping stones, not walls.

And here I am... my write-up of 2011...

Saturday, November 21, 2026

A C++ serial task executor - influenced by earlier Android AsyncTask's serialexecutor...

AI-generated content but worth the effort...

This project is a C++20 re-creation of early Android AsyncTask (SERIAL_EXECUTOR): background work runs strictly one task at a time in FIFO order on a dedicated worker thread, while UI/progress/completion callbacks are marshaled back to a main/UI thread loop so you don't race on UI state.


High-Level Architecture & Threading Model


There are two distinct threads in the application:
  1. Main / UI Thread (main.cpp + MainThreadLoop)

    • Starts tasks via task.execute(params), triggering onPreExecute() immediately on the caller thread.

    • Drains queued UI callbacks (onProgressUpdate, onPostExecute) inside MainThreadLoop::pumpUntil(...).

  2. Background Worker Thread (SerialExecutor)

    • Owns a single std::thread (worker_) and a FIFO queue (std::deque<std::function<void()>>).

    • Executes one background callable to completion before popping the next one.

Plaintext
Main / UI Thread                          SerialExecutor Worker Thread
───────────────────                       ────────────────────────────
task1.execute(url1)
  └─▶ onPreExecute()  ──(enqueues)──▶ [ url1 task ]  ──▶ doInBackground(url1)
task2.execute(url2)                                        ├─ publishProgress() ──┐
  └─▶ onPreExecute()  ──(enqueues)──▶ [ url2 task ]  ◀─┘  (waits for url1)    │
                                                                               ▼
pumpUntil(...) ◀──────────────(posts callbacks)──────────────────── [ MainThreadLoop ]
  ├─ onProgressUpdate(25%, 50%...)                                     queue
  └─ onPostExecute(result)
       └─ ++completed; notifyWake()


Component-by-Component Breakdown


A. SerialExecutor (SerialExecutor.h / SerialExecutor.cpp)

  • FIFO Queue + Synchronization: Protects queue_ and stopping_ with a std::mutex, using std::condition_variable (cv_) so the worker sleeps with zero CPU spin when idle and wakes immediately when a task arrives or shutdown begins.

  • Why std::deque? Efficient O(1) push at the back (push_back) and O(1) pop at the front (pop_front), matching Android's ArrayDeque FIFO behavior.

  • Exception Containment: runLoop() wraps next_task() in try / catch (std::exception) and catch (...). If one background task throws, the worker logs it and keeps running subsequent tasks rather than terminating the thread and leaving queued work stuck forever.

  • Graceful Shutdown: shutdown() sets stopping_ = true under the lock, calls cv_.notify_all(), and joins worker_. Any task already queued before shutdown() is still drained before runLoop() exits; execute() rejects new tasks once stopping.


B. MainThreadLoop (MainThreadLoop.h / MainThreadLoop.cpp)

  • Acts as a lightweight stand-in for Android's Looper / Handler.

  • post(callback): Thread-safe producer method. Background threads (or any thread) push UI callbacks onto callbacks_ and call cv_.notify_one().

  • pumpUntil(should_stop): Runs on the main thread. Waits until either callbacks_ is non-empty or should_stop() returns true. It drains callbacks one at a time on the calling thread, exiting only once the queue is empty and should_stop() is true.

  • notifyWake(): Calls cv_.notify_all() to re-evaluate the condition variable predicate—essential when should_stop() depends on an external atomic counter (completed.load() >= 2) updated inside a callback.


C. AsyncTask<Params, Progress, Result> (async_task.h)

  • Template Parameters:

    • Params: Input passed to execute() and doInBackground().

    • Progress: Type passed to publishProgress() and received by onProgressUpdate().

    • Result: Return value of doInBackground() and input to onPostExecute().

  • Lifecycle Flow in execute(Params params):

    1. Calls onPreExecute() synchronously on the caller/UI thread.

    2. Enqueues a lambda onto SerialExecutor that runs doInBackground(std::move(p)) on the worker thread.

    3. Inside doInBackground, subclasses can call publishProgress(pct), which posts a lambda to MainThreadLoop so onProgressUpdate runs on the UI thread.

    4. Once doInBackground returns res, another lambda is posted to MainThreadLoop to invoke onPostExecute(std::move(res)) on the UI thread.


D. DownloadTask & main() (main.cpp)

  • DownloadTask specializes AsyncTask<std::string, int, std::string>, simulating progress steps (25, 50, 75, 100) every 150 ms.

  • Because SerialExecutor has only one worker thread, task2 starts only after task1 finishes doInBackground—even though both onPreExecute() calls run right away.

  • main() pumps MainThreadLoop until completed reaches 2, then shuts down SerialExecutor cleanly.


The Source Code...


MainThreadLoop.h
#pragma once

#include <condition_variable>
#include <deque>
#include <functional>
#include <mutex>

class MainThreadLoop {
public:
void post(std::function<void()> callback);

// Drains callbacks until `should_stop()` returns true and the queue is empty.
void pumpUntil(const std::function<bool()>& should_stop);
void notifyWake();

private:
std::mutex mutex_;
std::condition_variable cv_;
std::deque<std::function<void()>> callbacks_;
};

MainThreadLoop.cpp
#include "MainThreadLoop.h"

#include <utility>

void MainThreadLoop::post(std::function<void()> callback) {
if (!callback) {
return;
}
{
std::lock_guard<std::mutex> lock(mutex_);
callbacks_.push_back(std::move(callback));
}
cv_.notify_one();
}

void MainThreadLoop::pumpUntil(const std::function<bool()>& should_stop) {
while (true) {
std::function<void()> cb;
{
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [this, &should_stop] {
return !callbacks_.empty() || (should_stop && should_stop());
});

if (callbacks_.empty() && should_stop && should_stop()) {
return;
}

if (!callbacks_.empty()) {
cb = std::move(callbacks_.front());
callbacks_.pop_front();
}
}
if (cb) {
cb();
}
}
}

void MainThreadLoop::notifyWake() {
cv_.notify_all();
}

SerialExecutor.h
#pragma once

#include <condition_variable>
#include <deque>
#include <functional>
#include <mutex>
#include <thread>

class SerialExecutor {
public:
SerialExecutor();
~SerialExecutor();

SerialExecutor(const SerialExecutor&) = delete;
SerialExecutor& operator=(const SerialExecutor&) = delete;

void execute(std::function<void()> task);
void shutdown();

private:
void runLoop();

std::mutex mutex_;
std::condition_variable cv_;
std::deque<std::function<void()>> queue_;
bool stopping_ = false;
std::thread worker_;
};

SerialExecutor.cpp
#include "SerialExecutor.h"

#include <exception>
#include <iostream>
#include <utility>

SerialExecutor::SerialExecutor()
: worker_([this] { runLoop(); }) {}

SerialExecutor::~SerialExecutor() {
shutdown();
}

void SerialExecutor::execute(std::function<void()> task) {
if (!task) {
return;
}
{
std::lock_guard<std::mutex> lock(mutex_);
if (stopping_) {
return;
}
queue_.push_back(std::move(task));
}
cv_.notify_one();
}

void SerialExecutor::shutdown() {
{
std::lock_guard<std::mutex> lock(mutex_);
if (stopping_) {
return;
}
stopping_ = true;
}
cv_.notify_all();
if (worker_.joinable()) {
worker_.join();
}
}

void SerialExecutor::runLoop() {
while (true) {
std::function<void()> next_task;
{
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [this] {
return stopping_ || !queue_.empty();
});

if (queue_.empty() && stopping_) {
return;
}

next_task = std::move(queue_.front());
queue_.pop_front();
}

try {
next_task();
} catch (const std::exception& ex) {
std::cerr << "[SerialExecutor] Task threw: " << ex.what() << "\n";
} catch (...) {
std::cerr << "[SerialExecutor] Task threw unknown exception\n";
}
}
}

Asynctask.h

#pragma once

#include "MainThreadLoop.h"
#include "SerialExecutor.h"

#include <utility>

template <typename Params, typename Progress, typename Result>
class AsyncTask {
public:
AsyncTask(SerialExecutor& executor, MainThreadLoop& main_loop)
: executor_(executor), main_loop_(main_loop) {}

virtual ~AsyncTask() = default;

AsyncTask(const AsyncTask&) = delete;
AsyncTask& operator=(const AsyncTask&) = delete;

void execute(Params params) {
onPreExecute();

executor_.execute([this, p = std::move(params)]() mutable {
Result res = doInBackground(std::move(p));
main_loop_.post([this, r = std::move(res)]() mutable {
onPostExecute(std::move(r));
});
});
}

protected:
virtual void onPreExecute() {}
virtual Result doInBackground(Params params) = 0;
virtual void onProgressUpdate(const Progress& progress) {}
virtual void onPostExecute(Result result) {}

void publishProgress(Progress progress) {
main_loop_.post([this, prog = std::move(progress)]() {
onProgressUpdate(prog);
});
}

private:
SerialExecutor& executor_;
MainThreadLoop& main_loop_;
};

Main.cpp

#include "AsyncTask.h"
#include "MainThreadLoop.h"
#include "SerialExecutor.h"

#include <atomic>
#include <chrono>
#include <iostream>
#include <string>
#include <thread>

class DownloadTask : public AsyncTask<std::string, int, std::string> {
public:
DownloadTask(SerialExecutor& exec,
MainThreadLoop& ui,
std::atomic<int>& completed_counter)
: AsyncTask(exec, ui),
ui_(ui),
completed_counter_(completed_counter) {}

protected:
void onPreExecute() override {
std::cout << "[UI] Starting download task...\n";
}

std::string doInBackground(std::string url) override {
for (int pct : {25, 50, 75, 100}) {
std::this_thread::sleep_for(std::chrono::milliseconds(150));
publishProgress(pct);
}
return "Downloaded: " + url;
}

void onProgressUpdate(const int& progress) override {
std::cout << "[UI] Progress: " << progress << "%\n";
}

void onPostExecute(std::string result) override {
std::cout << "[UI] Done -> " << result << "\n";
++completed_counter_;
ui_.notifyWake();
}

private:
MainThreadLoop& ui_;
std::atomic<int>& completed_counter_;
};

int main() {
SerialExecutor serial_executor;
MainThreadLoop main_loop;
std::atomic<int> completed{0};

DownloadTask task1(serial_executor, main_loop, completed);
DownloadTask task2(serial_executor, main_loop, completed);

task1.execute("https://example.com/file1.zip");
task2.execute("https://example.com/file2.zip");

main_loop.pumpUntil([&completed] {
return completed.load() >= 2;
});

serial_executor.shutdown();
return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 4.4)
project(SerialTaskExecutor LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(Threads REQUIRED)

add_executable(SerialTaskExecutor main.cpp
SerialExecutor.cpp
SerialExecutor.h
MainThreadLoop.cpp
MainThreadLoop.h
AsyncTask.h)

target_link_libraries(SerialTaskExecutor PRIVATE Threads::Threads)

Result...

[UI] Starting download task...
[UI] Starting download task...
[UI] Progress: 25%
[UI] Progress: 50%
[UI] Progress: 75%
[UI] Progress: 100%
[UI] Done -> Downloaded: https://example.com/file1.zip
[UI] Progress: 25%
[UI] Progress: 50%
[UI] Progress: 75%
[UI] Progress: 100%
[UI] Done -> Downloaded: https://example.com/file2.zip