Harmonic Oscillator
Simulation of a damped harmonic oscillator, modeling a spring-mass-damper system.
You can also find this example as a single file in the GitHub repository.

The equation of motion that defines the harmonic oscillator is given by
MATHDISPLAY0ENDMATH
where MATHINLINE1ENDMATH is the damping, MATHINLINE2ENDMATH the spring constant (stiffness) and MATHINLINE3ENDMATH the mass. The corresponding block diagram can be translated into a netlist by using the blocks and the connection class provided by PathSim.
First let's import the Simulation and Connection classes and the required blocks from the block library:
Then let's define the system parameters:
Now we can construct the system by instantiating the blocks we need (from the block diagram above) with their corresponding parameters and collect them together in a list:
Afterwards, the connections between the blocks can be defined. The first argument of the Connection class is the source block and its port (Sc[1] would be port 1 of the instance of the Scope block).
Finally we can instantiate the Simulation with the blocks, connections and some additional parameters such as the timestep. In this case, no special ODE solver is specified, so PathSim uses the default SSPRK22 integrator which is a fixed step 2nd order explicit Runge-Kutta method. A good starting point for non stiff linear systems like this.
12:43:44 - INFO - LOGGING (log: True) 12:43:44 - INFO - BLOCKS (total: 7, dynamic: 2, static: 5, eventful: 0) 12:43:44 - INFO - GRAPH (nodes: 7, edges: 9, alg. depth: 4, loop depth: 0, runtime: 0.093ms)
Then we can run the simulation for some duration:
12:43:44 - INFO - STARTING -> TRANSIENT (Duration: 25.00s) 12:43:44 - INFO - -------------------- 1% | 0.0s<0.4s | 6414.1 it/s 12:43:44 - INFO - ####---------------- 20% | 0.1s<0.3s | 6980.6 it/s 12:43:44 - INFO - ########------------ 40% | 0.1s<0.2s | 8323.6 it/s 12:43:44 - INFO - ############-------- 60% | 0.2s<0.1s | 8940.9 it/s 12:43:44 - INFO - ################---- 80% | 0.3s<0.1s | 8344.8 it/s 12:43:44 - INFO - #################### 100% | 0.3s<--:-- | 8677.9 it/s 12:43:44 - INFO - FINISHED -> TRANSIENT (total steps: 2500, successful: 2500, runtime: 331.41 ms)
Due to the object oriented and decentralized nature of PathSim, the Scope block holds the recorded time series data from the simulation internally. It can be plotted directly in an external matplotlib window using the plot method:
which looks like an exponentially decaying sinusoid.