Posts tagged algorithms

Simulating the Belousov–Zhabotinsky Reaction: Building a Non-Equilibrium Chemical Oscillator in VB.NET

Why do chemical oscillators challenge classical thermodynamic intuition?

In classical thermodynamics, closed systems evolve monotonically toward maximum entropy and static equilibrium. However, in 1951, Soviet biochemist Boris Belousov discovered a chemical mixture—later refined by Anatol Zhabotinsky—that defies static equilibrium for extended periods. Known as the Belousov–Zhabotinsky (BZ) reaction, this bromate-malonic acid-cerium system exhibits sustained, non-linear temporal oscillations and self-organizing spatial spiral waves.

Instead of settling immediately into a uniform state, the reaction cycles repeatedly between oxidized and reduced states through an autocatalytic feedback loop. In 1974, Richard Field, Endre Körös, and Richard Noyes reduced this complex 18-step reaction mechanism into a mathematically tractable three-variable system of coupled ordinary differential equations known as the Oregonator model:

dx/dτ = (1 / ϵ) · (qy − xy + x(1 − x))

dy/dτ = (1 / ϵ′) · (−qy − xy + fz)

dz/dτ = x − z

Where:

  • x represents the dimensionless concentration of bromous acid (HBrO2), the autocatalytic activator.
  • y represents the bromide ion (Br−), the inhibitor species.
  • z represents the oxidized metal catalyst (Ce4+ or ferroin), the recovery variable.
  • ϵ, ϵ′, q, and f are dimensionless kinetic rate constants derived from the underlying elementary reaction rates.

Because ϵ ≪ 1, the Oregonator is a stiff dynamical system: the activator x spikes rapidly on a fast timescale, while the catalyst z recovers slowly, creating a classic relaxation oscillation (a stable limit cycle in phase space).

How can VB.NET solve stiff chemical kinetics without external libraries?

Simulating stiff differential equations with standard explicit forward-Euler integration quickly blows up into numerical instability unless the time step Δτ is infinitesimally small. While scientific computing is typically dominated by Python or C++, VB.NET (.NET 8) offers strong performance for deterministic numerical integration when structured using stack-allocated value types (Structure) and a 4th-Order Runge-Kutta (RK4) solver.

By encapsulating the chemical state vector (x, y, z) in an immutable Structure, we avoid heap allocations inside tight integration loops while accurately tracking the limit cycle trajectory:

Option Strict On
Option Explicit On
Option Infer On

Imports System

Public ReadOnly Structure OregonatorState
    Public ReadOnly X As Double ' HBrO2 (Activator)
    Public ReadOnly Y As Double ' Br-   (Inhibitor)
    Public ReadOnly Z As Double ' Ce4+  (Oxidized Catalyst)

    Public Sub New(x As Double, y As Double, z As Double)
        Me.X = x
        Me.Y = y
        Me.Z = z
    End Sub

    Public Shared Operator +(a As OregonatorState, b As OregonatorState) As OregonatorState
        Return New OregonatorState(a.X + b.X, a.Y + b.Y, a.Z + b.Z)
    End Operator

    Public Shared Operator *(s As Double, a As OregonatorState) As OregonatorState
        Return New OregonatorState(s * a.X, s * a.Y, s * a.Z)
    End Operator

    Public Overrides Function ToString() As String
        Return $"HBrO2={X:F5}, Br-={Y:F5}, Ce4+={Z:F5}"
    End Function
End Structure

Public Module BelousovZhabotinskySimulator
    ' Dimensionless Oregonator kinetic parameters in the oscillatory regime
    Private Const Epsilon As Double = 0.01
    Private Const EpsilonPrime As Double = 0.0001
    Private Const Q As Double = 0.0008
    Private Const F As Double = 1.0 ' Stoichiometric factor (oscillatory window: 0.5 < f < 2.4)

    ' Coupled non-linear ODE derivatives: dS/dtau
    Private Function ComputeDerivatives(s As OregonatorState) As OregonatorState
        Dim dx As Double = (1.0 / Epsilon) * (Q * s.Y - s.X * s.Y + s.X * (1.0 - s.X))
        Dim dy As Double = (1.0 / EpsilonPrime) * (-Q * s.Y - s.X * s.Y + F * s.Z)
        Dim dz As Double = s.X - s.Z
        Return New OregonatorState(dx, dy, dz)
    End Function

    ' 4th-Order Runge-Kutta (RK4) integration step
    Public Function StepRK4(current As OregonatorState, dt As Double) As OregonatorState
        Dim k1 As OregonatorState = ComputeDerivatives(current)
        Dim k2 As OregonatorState = ComputeDerivatives(current + (0.5 * dt) * k1)
        Dim k3 As OregonatorState = ComputeDerivatives(current + (0.5 * dt) * k2)
        Dim k4 As OregonatorState = ComputeDerivatives(current + dt * k3)

        Return current + (dt / 6.0) * (k1 + 2.0 * k2 + 2.0 * k3 + k4)
    End Function

    Public Sub Main()
        ' Initial non-equilibrium concentrations
        Dim state As New OregonatorState(0.001, 0.001, 0.001)
        Dim dt As Double = 0.00005 ' Fine step to resolve fast boundary layer (EpsilonPrime = 10^-4)
        Dim totalSteps As Integer = 400_000

        Console.WriteLine("Time(tau) | Activator (HBrO2) | Inhibitor (Br-) | Catalyst (Ce4+)")
        Console.WriteLine(New String("-"c, 68))

        For stepIndex As Integer = 0 To totalSteps
            If stepIndex Mod 40_000 = 0 Then
                Dim tau As Double = stepIndex * dt
                Console

Source Code: View and run the full VB.NET (.NET 8) implementation on GitHub: ratawil/BelousovZhabotinskyOscillator

Simulating Landauer’s Principle: Building a Reversible Logic Engine in VB.NET

What is the thermodynamic cost of standard irreversible code?

Every time a traditional program executes a standard logical And or Or operation, it destroys information. In 1961, physicist Rolf Landauer proved that erasing a single bit of information in any physical computing system requires a minimum dissipation of heat energy governed by the laws of thermodynamics:

Emin = kB · T · ln(2)

Where kB is the exact SI Boltzmann constant (1.380649 × 10−23 J·K−1) and T is the ambient temperature in Kelvin. At room temperature (300 K), erasing one bit generates at least 2.87 × 10−21 Joules of heat.

Standard imperative code violates logical reversibility constantly. Consider a two-input And gate: it maps four possible input states—(0,0), (0,1), (1,0), and (1,1)—onto just two output states (0 or 1). If the output is 0, it is mathematically impossible to reconstruct which of the three zero-yielding inputs produced it. Assuming uniformly distributed inputs, a single And operation erases H(X|Y) = (3/4) log2(3) ≈ 1.189 bits of Shannon entropy, imposing a hard physical floor on energy efficiency.

How can VB.NET model zero-entropy reversible computation?

In 1973, Charles Bennett demonstrated that any classical computation can be performed with zero theoretical energy dissipation if every step is logically reversible—meaning the mapping between input states and output states is strictly bijective (one-to-one). Instead of overwriting variables in place, reversible systems transform state through universal reversible primitives such as the 3-bit Toffoli gate (CCNOT).

VB.NET is well-suited for building a deterministic, bit-level reversible state engine. By leveraging stack-allocated ReadOnly Structure value types alongside explicit bitwise operators (Xor, And), we can model bijective state transitions with zero heap allocations—eliminating background garbage collection overhead while auditing exact entropy loss:

Option Strict On
Imports System

Public ReadOnly Structure TriBitState
    Public ReadOnly A As Boolean
    Public ReadOnly B As Boolean
    Public ReadOnly C As Boolean

    Public Sub New(a As Boolean, b As Boolean, c As Boolean)
        Me.A = a
        Me.B = b
        Me.C = c
    End Sub

    ' Universal Reversible Toffoli Gate (CCNOT): (A, B, C) -> (A, B, C XOR (A AND B))
    ' Because it is an involution, applying ApplyToffoli() twice restores the exact input state.
    Public Function ApplyToffoli() As TriBitState
        Return New TriBitState(A, B, C Xor (A And B))
    End Function

    Public Overrides Function ToString() As String
        Return $"({Convert.ToInt32(A)}, {Convert.ToInt32(B)}, {Convert.ToInt32(C)})"
    End Function
End Structure

Public Module LandauerAuditor
    ' Exact SI Boltzmann constant (J/K)
    Public Const BoltzmannConstant As Double = 1.380649E-23
    Private Const IrreversibleAndEntropyLossBits As Double = 1.1887218755408671 ' (3/4) * log2(3)

    Public Function CalculateMinimumHeatJoules(erasedBits As Double, temperatureKelvin As Double) As Double
        Return erasedBits * BoltzmannConstant * temperatureKelvin * Math.Log(2.0)
    End Function

    Public Sub Main()
        Dim initial As New TriBitState(True, True, False)
        Dim forward As TriBitState = initial.ApplyToffoli()
        Dim reversed As TriBitState = forward.ApplyToffoli()

        Console.WriteLine($"Initial State:  {initial}")
        Console.WriteLine($"Forward Gate:   {forward}  (0 bits erased)")
        Console.WriteLine($"Reversed Gate:  {reversed}  (Exact state recovered)")

        ' Compare against 1 billion irreversible AND operations at 300K
        Dim totalErasedBits As Double = 1_000_000_000.0 * IrreversibleAndEntropyLossBits
        Dim dissipatedJoules As Double = CalculateMinimumHeatJoules(totalErasedBits, 300.0)
        Console.WriteLine($"Landauer Heat Floor (10^9 AND ops @ 300K): {dissipatedJoules:E4} J")
    End Sub
End Module

Because the Toffoli gate preserves control bits A and B while flipping target bit C only when both controls are True, the operation is its own inverse. Calling ApplyToffoli() a second time mathematically guarantees the recovery of the original TriBitState without maintaining external history logs.

What does reversible software architecture teach us about modern computing limits?

While modern silicon CMOS transistors still dissipate several orders of magnitude more energy per switching cycle than Landauer’s theoretical floor, simulating reversible logic highlights a fundamental principle in systems engineering: mutating state in place destroys diagnostic truth.

In distributed systems and financial engines, overwriting database rows directly is the architectural equivalent of an irreversible logic gate—once overwritten, the causal path that produced the state is lost. Patterns like Event Sourcing and append-only immutable ledgers apply the philosophy of reversible computing at the macro scale: by preserving every state transition as an explicit, non-destructive delta, systems gain deterministic replayability, auditability, and fault recovery without sacrificing state integrity.

https://github.com/ratawil/LandauerReversibleEngine

Go to Top