Tutorial: Numpy simultions of 1D gas#

import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interactive

import matplotlib.animation as animation
from IPython.display import HTML
class GasSimulation:

    def __init__(self, N=100, L=10.0, dt=0.05, steps=200):

        self.N = N  # Number of particles
        self.L = L  # Length of the box
        self.dt = dt  # Time step
        self.steps = steps # Simulation time steps
    
        # Generate position and velocities to be updated during simulations 
        self.x = L/2
        self.v = np.random.randn(N) #Normally distributed velocity
        self.history = np.zeros((steps, N))  # Pre-allocate array for efficiency
    
    def run(self):

        for i in range(self.steps):

            self.x += self.v * self.dt  # Update positions
            
            # Elastic collisions with walls
            self.v[self.x <= 0] *= -1
            self.v[self.x >= self.L] *= -1
            self.x = np.clip(self.x, 0, self.L)  # Keep within bounds
            
            self.history[i, :] = self.x  # Store positions
# Run simulation and animate
sim = GasSimulation(N=10)
sim.run()

print(sim.history.shape) # Need some tools to analyze this
(200, 10)

Post-processing functions for simulation#

def animate(sim):
    fig, ax = plt.subplots()
    ax.set_xlim(0, sim.L)
    ax.set_ylim(-0.1, 0.1)
    particles, = ax.plot(sim.history[0], np.zeros(sim.N), 'bo', markersize=4)  # Initialize with first frame
    
    def update(frame):
        particles.set_xdata(sim.history[frame])
        return particles,
    
    ani = animation.FuncAnimation(fig, update, frames=sim.steps, interval=50, blit=True)
    plt.close()
    return HTML(ani.to_jshtml())
# Run simulation and animate
sim = GasSimulation(N=10)
sim.run()
animate(sim)

Write a function that would plot \(p(x,t)\) of gas particles#

def pdf_xt(sim):

    x = sim.x

    #
    #
    #pxt = 

    return pxt