Skip to content

mohammadijoo/Prolog-Double-Pendulum-Chaos-Simulator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Prolog Double Pendulum Chaos Simulator

A desktop GUI application written in SWI-Prolog using the XPCE graphical toolkit to demonstrate chaotic dynamics through the classical double pendulum.

The simulator renders a white double pendulum on a dark background and draws the trajectory of the outer endpoint. The motion is deterministic, but for many initial conditions it becomes irregular and highly sensitive to small changes in the starting angles or angular velocities. This is the visual demonstration of the butterfly effect, also called sensitive dependence on initial conditions.


Table of contents

  1. Project overview
  2. Technologies used
  3. GUI layout
  4. Chaos theory background
  5. Real-world chaotic phenomena
  6. Double pendulum dynamics
  7. Why the double pendulum is chaotic
  8. Numerical integration method
  9. Repository structure
  10. Code architecture
  11. Install SWI-Prolog and XPCE
  12. Verify the installation
  13. Run the project
  14. Suggested initial conditions
  15. Troubleshooting
  16. Simulation video
  17. References
  18. License

Project overview

The Prolog Double Pendulum Chaos Simulator is an educational and engineering-style simulator for visualizing nonlinear motion, instability, and chaotic divergence in a double pendulum.

The user enters initial conditions such as:

  • Initial angle of the first link, $\theta_1$
  • Initial angle of the second link, $\theta_2$
  • Initial angular velocity of the first link, $\omega_1$
  • Initial angular velocity of the second link, $\omega_2$
  • Link lengths, $L_1$ and $L_2$
  • Masses, $m_1$ and $m_2$
  • Gravity, $g$
  • Optional damping
  • Small angular perturbation that can be used to test sensitivity to initial conditions
  • Numerical time step $\Delta t$
  • Maximum number of trajectory points shown

After pressing Play / Pause, the GUI animates the double pendulum and draws the path of the outer endpoint. The trajectory is not a simple sinusoid or closed harmonic curve. For many initial conditions, the path becomes irregular, tangled, and strongly dependent on the starting configuration.

The simulator automatically stops after 10 minutes of simulated time and returns to the waiting state.


Technologies used

SWI-Prolog

SWI-Prolog is a mature, open-source Prolog implementation widely used in education, research, symbolic computation, logic programming, and knowledge-based applications.

This project uses SWI-Prolog for:

  • GUI control logic
  • Simulation state management
  • Numerical integration
  • Drawing commands
  • Event handling
  • User input parsing
  • Runtime logging

XPCE

XPCE is the native GUI toolkit available with SWI-Prolog. It provides windows, dialogs, buttons, text fields, graphical canvases, shapes, timers, and event messages.

This project uses XPCE for:

  • The desktop application window
  • The top animation canvas
  • The bottom control pane
  • Text input boxes
  • Play / Pause and Reset buttons
  • Real-time drawing of links, bobs, pivots, grid lines, and trajectories
  • Timer-based animation

GUI layout

The application follows the requested layout concept:

+---------------------------------------------------------------+
|                                                               |
|  Top pane: 85% of app height                                  |
|                                                               |
|  +-----------------------------+-----------------------------+|
|  | Left pane: 50% width        | Right pane: 50% width       ||
|  | MATLAB-like view            | CAD-like view               ||
|  | trajectory of outer bob     | mechanical double pendulum  ||
|  | grid + axes + path          | pivots + links + bobs       ||
|  +-----------------------------+-----------------------------+|
|                                                               |
+---------------------------------------------------------------+
| Bottom pane: 15% of app height                                |
| Initial conditions | equation | Play/Pause | clock | log       |
+---------------------------------------------------------------+

Left pane: MATLAB-like trajectory view

The left pane shows:

  • A coordinate grid
  • Horizontal and vertical axes
  • The current double pendulum shape
  • The outer endpoint trajectory
  • Energy drift information

This view is intended to resemble the type of phase/trajectory visualization commonly used in MATLAB, scientific plotting, and control-system simulation.

Right pane: CAD-like mechanism view

The right pane shows:

  • A mechanical drawing style double pendulum
  • Pivot support
  • Link 1 and link 2
  • Bob masses $m_1$ and $m_2$
  • White links, pivots, bobs, and motion/status logs

This view is intended to look more like a mechanism/CAD sketch, emphasizing the physical links and joints.

Bottom pane

The bottom pane contains:

  • Text fields for initial conditions and parameters
  • Play / Pause button
  • Reset button
  • Main dynamic model summary
  • Clock counter
  • Motion log

The clock counts up to 600 seconds, corresponding to 10 minutes of simulation time.


Chaos theory background

Chaos theory studies deterministic systems whose long-term behavior is highly sensitive to initial conditions. A chaotic system is not random in the sense of being governed by probability at every instant. Instead, it follows deterministic laws, but small differences in the starting state can grow rapidly and produce very different future trajectories.

A chaotic system usually has these properties:

  1. Determinism
    The system follows definite equations of motion. If the exact state and equations were known with infinite precision, the future state would be determined.

  2. Nonlinearity
    The equations contain nonlinear couplings such as products, trigonometric functions, squared velocities, or feedback terms. Nonlinearity allows energy transfer between modes and can amplify differences.

  3. Sensitive dependence on initial conditions
    Two states that begin very close together can separate quickly. This is the butterfly effect.

  4. Aperiodic long-term behavior
    The motion may not settle into a simple repeating orbit. It can remain bounded but irregular.

  5. Phase-space stretching and folding
    Chaotic flows often stretch nearby states apart while folding trajectories back into a bounded region. This mechanism creates complex attractors or complicated reachable sets.

The butterfly effect

The phrase butterfly effect is commonly associated with Edward Lorenz's work on weather prediction. It describes how a very small perturbation, such as a tiny change in a starting variable, can lead to a large difference later.

In this simulator, the butterfly effect is demonstrated by changing the initial state only slightly and observing how the white double pendulum trajectory changes over time. For example, compare two runs that differ only by a tiny change in the first initial angle:

$$ x_A(0) = [\theta_1,; \theta_2,; \omega_1,; \omega_2]^T $$

$$ x_B(0) = [\theta_1 + \delta,; \theta_2,; \omega_1,; \omega_2]^T $$

where $\delta$ is very small. At first, the runs can look almost identical. After some time, the endpoint trajectory may become very different, showing that long-term prediction is practically difficult unless the initial state is known with extremely high precision.


Real-world chaotic phenomena

Chaos appears in many real-world systems. The important point is that chaos does not mean the system has no rules. It means that deterministic rules can produce practically unpredictable motion.

Weather and atmosphere

Weather is one of the most famous chaotic systems. Atmospheric motion is governed by fluid dynamics, thermodynamics, pressure gradients, rotation of Earth, moisture, and radiative transfer. Even with powerful computers, small uncertainty in the initial state limits long-term forecast accuracy.

Ocean currents and climate interaction

Ocean circulation involves nonlinear fluid motion, density gradients, salinity, temperature, and wind forcing. Vortices and turbulent mixing can create sensitive dependence on initial conditions.

Turbulence

Turbulence in fluids is a major example of nonlinear complex motion. Although the Navier-Stokes equations are deterministic, turbulent eddies interact across scales and produce irregular motion.

Population dynamics

Some biological population models, such as the logistic map under certain parameter values, can show chaotic behavior. Small differences in population size or growth rate can lead to large long-term differences.

Electrical circuits

Nonlinear circuits, such as Chua's circuit, can show chaotic oscillations. These systems are useful for studying nonlinear dynamics experimentally.

Robotics and mechanical systems

Mechanical systems with impacts, friction, flexible links, backlash, underactuation, or strong nonlinear coupling can show complex behavior. The double pendulum is a clean educational example of this type of nonlinear mechanical behavior.

Spacecraft and orbital dynamics

Multi-body gravitational systems can become chaotic. Long-term prediction of some orbital configurations is difficult because tiny perturbations can accumulate over time.

Human body and biological signals

Heart rhythms, neural activity, and some biomechanical systems can exhibit nonlinear and chaotic-like behavior. This does not mean they are random; it means that nonlinear feedback and coupling can create complex dynamics.


Double pendulum dynamics

A double pendulum consists of two pendulum links connected in series:

  • Link 1 rotates about a fixed pivot.
  • Link 2 rotates about the end of link 1.
  • Each link has a mass/bob.
  • Gravity acts downward.

The state variables are:

Symbol Meaning
$\theta_1$ angle of link 1 from the downward vertical
$\theta_2$ angle of link 2 from the downward vertical
$\omega_1$ angular velocity of link 1
$\omega_2$ angular velocity of link 2

The state vector is:

$$ x = [\theta_1,; \theta_2,; \omega_1,; \omega_2]^T $$

The first-order state-space form is:

$$ \dot{\theta}_1 = \omega_1 $$

$$ \dot{\theta}_2 = \omega_2 $$

$$ \dot{\omega}_1 = f_1(\theta_1,\theta_2,\omega_1,\omega_2,m_1,m_2,L_1,L_2,g) $$

$$ \dot{\omega}_2 = f_2(\theta_1,\theta_2,\omega_1,\omega_2,m_1,m_2,L_1,L_2,g) $$

For angles measured from the downward vertical direction, the implemented equations are:

$$ \Delta = \theta_1 - \theta_2 $$

$$ D = 2m_1 + m_2 - m_2\cos(2\theta_1 - 2\theta_2) $$

$$ \dot{\omega}_1 = \frac{ -g(2m_1+m_2)\sin(\theta_1) -m_2g\sin(\theta_1-2\theta_2) -2m_2\sin(\Delta)\left(\omega_2^2L_2+\omega_1^2L_1\cos(\Delta)\right) }{L_1D} -c\omega_1 $$

$$ \dot{\omega}_2 = \frac{ 2\sin(\Delta)\left( \omega_1^2L_1(m_1+m_2) +g(m_1+m_2)\cos(\theta_1) +\omega_2^2L_2m_2\cos(\Delta) \right) }{L_2D} -c\omega_2 $$

where:

Symbol Meaning
$m_1, m_2$ masses
$L_1, L_2$ link lengths
$g$ gravitational acceleration
$c$ optional damping coefficient

When $c = 0$, the model is ideal and conservative apart from numerical integration error. When $c > 0$, a small viscous damping term is applied.

Cartesian positions

The position of the first bob is:

$$ x_1 = L_1\sin(\theta_1) $$

$$ y_1 = L_1\cos(\theta_1) $$

The position of the second bob is:

$$ x_2 = x_1 + L_2\sin(\theta_2) $$

$$ y_2 = y_1 + L_2\cos(\theta_2) $$

The simulator draws the trajectory of $(x_2,y_2)$, the endpoint of the outer link.

Energy

The simulator also estimates total mechanical energy to help diagnose numerical drift.

Kinetic energy:

$$ T = \frac{1}{2}m_1(v_{x1}^2+v_{y1}^2) + \frac{1}{2}m_2(v_{x2}^2+v_{y2}^2) $$

Potential energy:

$$ V = -m_1gL_1\cos(\theta_1) - m_2g\left(L_1\cos(\theta_1)+L_2\cos(\theta_2)\right) $$

Total energy:

$$ E = T + V $$

A small energy drift is normal in numerical simulation, especially for long runs or large time steps.


Why the double pendulum is chaotic

The double pendulum is chaotic because it is nonlinear, coupled, and capable of transferring energy between rotational modes.

1. Nonlinear trigonometric coupling

The equations contain terms such as:

$$ \sin(\theta_1 - \theta_2) $$

$$ \cos(\theta_1 - \theta_2) $$

$$ \sin(\theta_1 - 2\theta_2) $$

These terms make the acceleration of each link depend nonlinearly on both angles.

2. Velocity-squared terms

The angular accelerations contain terms such as:

$$ \omega_1^2 $$

$$ \omega_2^2 $$

These terms represent centripetal and inertial coupling. They strongly affect the motion when the pendulum rotates quickly.

3. Energy exchange between links

Energy can move back and forth between link 1 and link 2. Sometimes link 2 swings gently; sometimes it flips over rapidly. This energy exchange can amplify small differences in angle or angular velocity.

4. Nearby initial states separate

If two runs start with:

$$ \Delta \theta_1 = 0.05^\circ $$

but all other parameters are equal, the first few seconds may look similar. Later, the endpoint trajectory can become completely different. In the GUI, this sensitivity is observed by restarting the white-on-dark pendulum with slightly different initial conditions and comparing the resulting endpoint path.

5. Bounded but irregular trajectory

The pendulum remains mechanically bounded by its link lengths, but the endpoint trajectory can become highly irregular. This is a typical signature of deterministic chaos: bounded motion without simple periodic repetition.


Numerical integration method

The simulator uses a classical fourth-order Runge-Kutta method, usually written as RK4.

For a state equation:

$$ \dot{x} = f(x,t) $$

RK4 computes:

$$ k_1 = f(x_n,t_n) $$

$$ k_2 = f\left(x_n + \frac{h}{2}k_1,t_n+\frac{h}{2}\right) $$

$$ k_3 = f\left(x_n + \frac{h}{2}k_2,t_n+\frac{h}{2}\right) $$

$$ k_4 = f(x_n + hk_3,t_n+h) $$

$$ x_{n+1} = x_n + \frac{h}{6}(k_1 + 2k_2 + 2k_3 + k_4) $$

In this project, h is the user-defined dt s value. The default is:

dt = 0.02 seconds

For smoother and more accurate simulation, use smaller time steps such as 0.01. For faster but less accurate simulation, use larger time steps such as 0.03 or 0.04.


Repository structure

prolog-double-pendulum-chaos-simulator/
│
├── run.pl
├── README.md
├── LICENSE
├── .gitignore
├── CONTRIBUTING.md
│
├── src/
│   ├── double_pendulum_gui.pl
│   └── double_pendulum_physics.pl
│
├── docs/
│   ├── EQUATIONS.md
│   └── DEVELOPMENT_NOTES.md
│
├── examples/
│   └── initial_conditions.txt
│
└── screenshots/
    └── .gitkeep

Code architecture

run.pl

The project entry point.

Responsibilities:

  • Loads the physics source file.
  • Loads the GUI source file.
  • Starts the GUI through SWI-Prolog initialization.

Main usage:

swipl -q -f none run.pl

src/double_pendulum_physics.pl

Contains the mathematical and numerical model.

Important predicates:

deg_to_rad/2

Converts degrees to radians.

deg_to_rad(+Degrees, -Radians)

rad_to_deg/2

Converts radians to degrees.

rad_to_deg(+Radians, -Degrees)

derivatives/3

Computes the double pendulum state derivative.

derivatives(+State, +Params, -Derivative)

Input state:

state(Theta1, Theta2, Omega1, Omega2)

Input parameters:

params(M1, M2, L1, L2, G, Damping)

Output derivative:

deriv(DTheta1, DTheta2, DOmega1, DOmega2)

rk4_step/4

Advances the system by one time step using RK4.

rk4_step(+State, +Params, +Dt, -NextState)

bob_positions/7

Computes the Cartesian positions of the two bobs.

bob_positions(+State, +Params, -X1, -Y1, -X2, -Y2)

total_energy/3

Computes total mechanical energy.

total_energy(+State, +Params, -Energy)

endpoint_separation/4

Computes the physical distance between the outer endpoints of the primary and perturbed pendulums.

endpoint_separation(+StateA, +StateB, +Params, -Distance)

angular_separation/3

Computes a state-space separation value between two double-pendulum states.

angular_separation(+StateA, +StateB, -Distance)

src/double_pendulum_gui.pl

Contains the XPCE GUI and animation loop.

Important predicates:

main/0

Builds and opens the desktop GUI.

main.

build_gui/0

Creates:

  • Main frame
  • Top drawing canvas
  • Bottom control dialog
  • Text input fields
  • Play / Pause button
  • Reset button
  • Clock label
  • Formula label
  • Log label

toggle_simulation/0

Handles Play / Pause behavior:

  • Starts a new simulation if no simulation exists.
  • Pauses the timer if the simulation is running.
  • Restarts the timer if the simulation is paused.

start_new_simulation/0

Reads the input fields, creates primary and perturbed states, creates the XPCE timer, and starts the animation loop.

simulation_tick/0

Called repeatedly by the XPCE timer.

Responsibilities:

  • Advance both pendulums using RK4.
  • Update the simulation clock.
  • Append endpoint trajectory points.
  • Redraw both top panes.
  • Update logs.
  • Stop automatically at 600 seconds.

reset_simulation/0

Stops the timer, clears simulation state, resets the clock, and returns the GUI to the waiting state.

Drawing predicates

The GUI file includes drawing helpers such as:

draw_line/7
draw_circle/7
draw_text/7
draw_grid/5
draw_pendulum/9
draw_trail/3

These wrap XPCE drawing objects such as line, circle, box, and text.


Install SWI-Prolog and XPCE

This project requires SWI-Prolog with XPCE GUI support.

Windows

  1. Open the official SWI-Prolog stable download page:
    https://www.swi-prolog.org/download/stable
  2. Download the Windows 64-bit installer.
  3. Run the installer.
  4. During installation, enable adding SWI-Prolog to the system PATH if the installer offers this option.
  5. Open Command Prompt or PowerShell.
  6. Verify:
swipl --version

macOS

Recommended options:

Option A: official macOS bundle

  1. Open the official stable download page:
    https://www.swi-prolog.org/download/stable
  2. Download the macOS bundle.
  3. Install it like a normal macOS application.
  4. Ensure the swipl command is available from Terminal.

Option B: Homebrew

brew update
brew install swi-prolog
swipl --version

If swipl is not found after installing the macOS app bundle, use Homebrew or add the SWI-Prolog command-line tools path to your shell configuration.

Linux

Linux installation depends on the distribution.

Ubuntu / Debian

sudo apt update
sudo apt install swi-prolog
swipl --version

For newer builds, use the official SWI-Prolog PPA or Flatpak instructions from the SWI-Prolog download page.

Fedora

sudo dnf install pl
swipl --version

If the package name is not available as pl, search:

dnf search swi-prolog

Arch Linux

sudo pacman -S swi-prolog
swipl --version

XPCE requirement

XPCE is required for this GUI project. On most full SWI-Prolog desktop installations, XPCE is included. On some minimal Linux packages, the GUI components may be packaged separately or may require additional X11/Wayland libraries.


Verify the installation

1. Check SWI-Prolog version

swipl --version

Expected result:

SWI-Prolog version ...

2. Start the Prolog REPL

swipl

You should see a prompt similar to:

?-

3. Verify XPCE loads

At the Prolog prompt:

?- use_module(library(pce)).

Expected result:

true.

4. Optional: open XPCE manual browser

?- manpce.

If a GUI documentation window opens, XPCE is working.

5. Exit SWI-Prolog

?- halt.

Run the project

Clone the repository or download the project files.

git clone https://github.com/YOUR_USERNAME/prolog-double-pendulum-chaos-simulator.git
cd prolog-double-pendulum-chaos-simulator

Windows

From PowerShell or Command Prompt:

swipl -q -f none run.pl

macOS

From Terminal:

swipl -q -f none run.pl

Linux

From a terminal:

swipl -q -f none run.pl

Running from the SWI-Prolog REPL

swipl

Then:

?- [run].
?- main.

Suggested initial conditions

Try the following values to produce visible chaotic behavior.

Example 1: strong chaotic behavior

theta1 deg      120
theta2 deg      -10
omega1 rad/s    0.0
omega2 rad/s    0.0
L1 m            1.0
L2 m            1.0
m1 kg           1.0
m2 kg           1.0
g m/s^2         9.81
damping         0.000
perturb deg     0.05
dt s            0.02
trail points    1500

Example 2: smaller perturbation

theta1 deg      120
theta2 deg      -10
omega1 rad/s    0.0
omega2 rad/s    0.0
perturb deg     0.005
dt s            0.01

The first trajectory may look regular at first, but a slightly changed initial condition can produce a visibly different path later.

Example 3: high-energy motion

theta1 deg      170
theta2 deg      80
omega1 rad/s    0.0
omega2 rad/s    0.0
perturb deg     0.05
dt s            0.01

Example 4: damped motion

theta1 deg      130
theta2 deg      -30
omega1 rad/s    0.0
omega2 rad/s    0.0
damping         0.02
perturb deg     0.05
dt s            0.02

With damping, the system eventually loses energy, but the early transient motion can still show strong sensitivity.


Troubleshooting

Problem: swipl is not recognized

Windows

Cause: SWI-Prolog is not in the system PATH.

Fix:

  1. Reinstall SWI-Prolog and enable the option to add it to PATH, or
  2. Add the SWI-Prolog bin directory manually to the Windows environment variables.

Typical path:

C:\Program Files\swipl\bin

Then restart PowerShell or Command Prompt.

macOS / Linux

Run:

which swipl

If no path appears, install SWI-Prolog again or fix your shell PATH.


Problem: use_module(library(pce)). fails

Cause: XPCE is not installed or the installed SWI-Prolog package is minimal/headless.

Fix:

  • Install the full SWI-Prolog distribution.
  • On Linux, check whether your distribution has a separate GUI/XPCE package.
  • Use the official SWI-Prolog stable installer/bundle if the distribution package is incomplete.

Problem: GUI does not open on Linux server or WSL

Cause: XPCE needs a graphical display. A headless server or WSL terminal may not have an available X11/Wayland display.

Fix options:

  • Run the project on a desktop Linux session.
  • Use WSLg on Windows 11.
  • Install and configure an X server for older WSL setups.
  • Check:
echo $DISPLAY

If DISPLAY is empty, GUI windows cannot open.


Problem: animation is slow

Possible causes:

  • Too many trajectory points.
  • Very small time step.
  • Old hardware.
  • Large application window.

Fix:

  • Reduce trail points from 1500 to 500.
  • Increase dt s from 0.01 to 0.02 or 0.03.
  • Avoid resizing the window extremely large.

Problem: animation is unstable or energy drift is large

Possible causes:

  • Time step is too large.
  • Initial conditions are very high energy.
  • The model is near fast rotations or flips.

Fix:

  • Reduce dt s to 0.01 or 0.005.
  • Keep damping at 0.000 for ideal dynamics, or use small damping such as 0.005 to reduce numerical blow-up.
  • Avoid extremely large angular velocities at the start.

Problem: the trajectory does not look chaotic

Possible causes:

  • The selected initial condition is close to regular or low-energy motion.
  • The damping value is too high.
  • The simulation time is too short to reveal sensitive dependence.

Fix:

  • Try theta1 deg = 120, theta2 deg = -10.
  • Set damping = 0.000.
  • Try a second run with a slightly different value, such as theta1 deg = 120.05, and compare the endpoint trajectory.
  • Run for a longer time.

Problem: too many lines appear in the trajectory view

Cause: The trajectory history is long.

Fix:

  • Reduce trail points.
  • Press Reset and start again.

Problem: window opens but labels look different across systems

XPCE uses native drawing and fonts. Font rendering can differ between Windows, macOS, and Linux.

Fix:

  • This does not affect the simulation.
  • If desired, edit draw_text/7 in src/double_pendulum_gui.pl and replace helvetica with another font available on your system.

Simulation video

Below is a link to the simulation video on YouTube.

Prolog Double Pendulum Chaos Simulator

Example double-pendulum videos

The following videos show double-pendulum chaotic motion examples and can be useful as visual references:


References

SWI-Prolog and XPCE

Theory

  • Classical mechanics textbooks on Lagrangian dynamics
  • Nonlinear dynamics and chaos textbooks
  • Numerical analysis references for Runge-Kutta integration

License

This project is released under the MIT License. See LICENSE.

About

In this repository you can find GUI App for "Double Pendulum Chaos Simulator" which is written in Prolog. There is also a YouTube link for its simulation at the end of repo description.

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

7 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages