Web Analytics
Creating a Simple Pendulum Simulation Using the OSP Library

Creating a Simple Pendulum Simulation Using the OSP Library

This part of the guide demonstrates how to create a simple simulation of a mathematical pendulum using Open Source Physics (.jar) packages, after setting up IntelliJ IDEA and integrating the OSP libraries. We will walk through the project structure, necessary imports, and explain how to display pendulum oscillations in real time.

What Will Be Covered

After this introduction, you will be ready to implement and further customize the simulation—add control elements, change parameters, or even expand the pendulum into 3D using WebEJS or the p5.js port of OSP.

Basic Setup in IntelliJ IDEA

Before diving into simulation development or other Java projects, it is essential to properly configure your development environment. The following steps will guide you through the basic IntelliJ IDEA setup: from JDK integration and plugin installation to customizing keyboard shortcuts and themes.

1. Configuring the JDK

The first and most important step is to add the locally installed Java Development Kit (JDK) to IntelliJ IDEA. This enables compiling and running your Java applications.

  1. Open:
    • Windows: File → Settings → Build, Execution, Deployment → SDKs
    • Linux/macOS: IntelliJ IDEA → Preferences → Build, Execution, Deployment → SDKs
  2. Click on + → Add SDK → JDK.
  3. Select the path to your JDK’s root folder (the one containing bin, lib, etc.):
    • C:\Program Files\Java\jdk-11.0.12 (Windows)
    • /usr/lib/jvm/java-11-openjdk (Linux)
  4. Be sure to enter a descriptive name, e.g., “Java 11”, and click OK.
  5. Finally, go to Project Structure → Project and under Project SDK select the JDK you just added.

2. Installing Plugins

To work with other languages and tools within IntelliJ IDEA, you need to install the appropriate plugins.

  1. Open File → Settings → Plugins (or IntelliJ IDEA → Preferences → Plugins).
  2. Use the search bar to find the desired language or tool (e.g., “Scala”, “Python”, “Docker”).
  3. Click Install, then Restart IDE when installation completes.

3. Customizing Keyboard Shortcuts and Theme

IntelliJ IDEA allows you to choose from multiple predefined keymaps and visual themes, so your workspace is as comfortable as possible.

  1. Keymap: Settings → Keymap – choose “Default”, “Eclipse”, “Visual Studio” or another layout.
  2. Theme: Settings → Appearance & Behavior → Theme – select “Darcula” (dark) or “IntelliJ Light”.

4. Menu Shortcut (Linux)

If you installed IntelliJ IDEA from a .tar.gz package, the IDE will offer to create a desktop entry for easier launching from the GUI menu the first time it runs.

If the IDE does not offer this automatically:

  1. Open a terminal and create a script:
    sudo tee /usr/local/bin/idea << 'EOF'
    #!/usr/bin/env bash
    /opt/idea-community/bin/idea.sh "$@"
    EOF
    sudo chmod +x /usr/local/bin/idea
    
  2. You can now launch IntelliJ using the idea command or find it in your desktop environment’s applications menu.

Versions and Documentation

The current stable version of the OSP libraries is 6.3.0 (February 2025). Previously widely used versions include 6.2.x and 6.1.x (e.g., 6.1.7 from June 2024).

Full user manuals and technical documentation are available on the ComPADRE website. Additionally, online JavaDoc is published for all OSP packages and classes within the OpenSourcePhysics domain. To get started, visit the ComPADRE Programming – Documentation section and the “OSP User’s Guide”.

Download Sources

Installing a Single OSP JAR File

It is sufficient to include just one archive – either osp.jar or osp-guide.jar – in your project.

  1. Download the JAR file:
    If osp_guide.jar is not already on your machine, download it from ComPADRE:
    osp_guide.jar
    Save it in a libs/ folder within your project directory.
  2. Add it to IntelliJ IDEA:
    • Go to File → Project Structure… (or press Ctrl+Alt+Shift+S).
    • Select your module, then open the Dependencies tab.
    • Click +JARs or directories…, locate libs/osp-guide.jar, confirm, and set the scope to Compile.
    • Click Apply and OK.

Optional: Global Library

To use the same OSP JAR archive across multiple projects without duplication, you can register it as a global library:

  1. Open File → Project Structure… → Platform Settings → Global Libraries.
  2. Click +Java and select osp-guide.jar.
  3. Save the change; the library will appear under Global Libraries.
  4. In each project, go to Modules → Dependencies, click +Library → Global Library, and select osp-guide.

After this setup, IntelliJ will place OSP classes on the project’s classpath, making it possible to use:

import org.opensourcephysics.controls.*;
import org.opensourcephysics.display.*;

Creating a Java Project and Integrating OSP Libraries

The following steps describe how to create a new Java project in IntelliJ IDEA, how to add Open Source Physics (.jar) libraries to it, and finally, how to implement an example simulation of a mathematical pendulum.

1. Creating a New Java Project

  1. Launch IntelliJ IDEA.
  2. On the welcome screen, choose New Project.
  3. Select Java and an already installed JDK (e.g., Java 11).
  4. Click Next, enter a project name (e.g., AnimatedPendulum), and click Finish.

2. Adding OSP Libraries

Downloaded .jar files from the OSP distribution (e.g., osp.jar or osp-guide.jar) can be included in the project as follows:

  1. Right-click the module or “External Libraries” and select Open Module Settings (F4).
  2. Switch to the Libraries tab and click +Java.
  3. Select the downloaded .jar files and confirm the scope as Compile.
  4. Click Apply and OK.

3. Package Structure

It is recommended to create a package inside the src folder, for example pendulum, which will contain all the classes related to the simulation.

Mathematical pendulum animation
Animation of the mathematical pendulum
 package pendulum;

import org.opensourcephysics.display.Circle;
import org.opensourcephysics.display.Trail;
import org.opensourcephysics.display.DrawingFrame;
import org.opensourcephysics.display.DrawingPanel;
import org.opensourcephysics.numerics.ODE;
import org.opensourcephysics.numerics.ODESolver;
import org.opensourcephysics.numerics.Euler;

/**
* This class represents a simple mathematical pendulum simulation using
* the Open Source Physics (OSP) library.
*/
public class AnimatedPendulum implements ODE {

// The state vector: [θ (angle), ω (angular velocity), t (time)]
double[] state = new double[3];

// Gravitational acceleration (in m/s^2)
final double gravity = 9.81;

// Length of the pendulum rod (in meters)
final double length = 8.0;

/**
* Constructor initializes the pendulum with an initial angle,
* angular velocity, and time.
*/
public AnimatedPendulum() {
state[0] = Math.PI / 4; // Initial angle (45°)
state[1] = 0;
state[2] = 0;
}

/** Returns the current state of the system. */
@Override
public double[] getState() {
return state;
}

/**
* Computes the rate of change for the state variables.
* dθ/dt = ω
* dω/dt = -(g/L) * sin(θ)
* dt/dt = 1
*/
@Override
public void getRate(double[] state, double[] rate) {
rate[0] = state[1];
rate[1] = - (gravity / length) * Math.sin(state[0]);
rate[2] = 1;
}

/** Main method that sets up and runs the animation loop. */
public static void main(String[] args) {
// Create the pendulum model
AnimatedPendulum model = new AnimatedPendulum();

// Choose Euler solver
ODESolver solver = new Euler(model);

// Set up drawing panel and frame
DrawingPanel panel = new DrawingPanel();
DrawingFrame frame = new DrawingFrame("Pendulum Animation", panel);
frame.setDefaultCloseOperation(DrawingFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

// Trail for the rod
Trail rod = new Trail();
rod.setConnected(true);

// Circle for the bob
Circle bob = new Circle(0, 0, 15);

// Add to panel
panel.addDrawable(rod);
panel.addDrawable(bob);

// Time step
double dt = 0.02;
solver.initialize(dt);

// Animation loop
while (true) {
solver.step();
double theta = model.state[0];
double x = model.length * Math.sin(theta);
double y = -model.length * Math.cos(theta);

// Update rod
rod.clear();
rod.addPoint(0, 0);
rod.addPoint(x, y);

// Update bob
bob.setX(x);
bob.setY(y);

// Render
frame.render();

// Control speed
try {
Thread.sleep((int)(dt * 1000));
} catch(InterruptedException e) {
break;
}
}
}
}
Mathematical pendulum animation with source code
Mathematical pendulum animation with source code

Code Explanation

The AnimatedPendulum class implements the ODE interface. To understand what that entails, let’s first look at the ODE interface itself:

What is the ODE interface in OSP?

In the Open Source Physics (OSP) library, ODE is an interface used to model dynamic systems via ordinary differential equations (ODEs).

It requires two methods:

public interface ODE {
  double[] getState();
  void getRate(double[] state, double[] rate);
}

Method Breakdown:

In AnimatedPendulum we define a double[] state of length 3, storing θ, ω, and t. We initialize state[0] to π/4 radians, and the others to 0.

In the main method we create:

We then add two drawable objects to the panel:

Inside the infinite loop, we call solver.step() to advance the state, compute the new x and y positions, update the rod and bob accordingly, and then render via frame.render(). A brief Thread.sleep() controls animation speed.

This cycle simulates our physical pendulum in real time, solving its ODEs and updating the visualization at each time step.