"""Tick — the book's own small universe. Physics without calculus: from the present state and the forces, work out the next moment, then repeat. acceleration = net force / mass velocity = velocity + acceleration * dt position = position + velocity * dt That three-line update (the semi-implicit, or Euler–Cromer, step) is the one the book teaches. Tick also offers the velocity-Verlet step, which is the same idea with the acceleration averaged over the step, for when a trajectory must stay exact for a long time (orbits, pendulum waves, videos). Both are "symplectic": they do not slowly pump energy into an orbit the way the naive order (position first, with the old velocity) does. Published at /tick/tick.py. Needs only Python 3.9+ and NumPy. from tick import World, Body, Uniform, Drag, Spring, Gravity w = World(dt=0.001) ball = w.add(Body("ball", mass=0.5, pos=(0, 10), vel=(4, 0))) w.add_force(Uniform(g=9.81)) path = w.run(until=lambda w: ball.pos[1] <= 0, every=0.05) """ from __future__ import annotations import math from dataclasses import dataclass, field from typing import Callable, Iterable import numpy as np __all__ = ["Body", "World", "Uniform", "Drag", "Spring", "Gravity", "Pendulum", "vec"] __version__ = "1.0" def vec(values: Iterable[float]) -> np.ndarray: return np.array([float(v) for v in values], dtype=float) @dataclass(eq=False) class Body: """A point with a mass, a position and a velocity (2-D or 3-D).""" name: str mass: float pos: np.ndarray vel: np.ndarray fixed: bool = False def __post_init__(self): self.pos = vec(self.pos) self.vel = vec(self.vel) if self.pos.shape != self.vel.shape: raise ValueError(f"{self.name}: position and velocity must have the same number of components") if self.mass <= 0: raise ValueError(f"{self.name}: mass must be positive") @property def speed(self) -> float: return float(np.linalg.norm(self.vel)) @property def kinetic_energy(self) -> float: return 0.5 * self.mass * float(self.vel @ self.vel) # ---------------------------------------------------------------- forces # A force is an object with .apply(world, forces) that adds a vector to the # entry of each body it acts on, and optionally .energy(world) for its # potential energy (so a run can check that energy is conserved). @dataclass class Uniform: """The same downward pull on every body, proportional to its mass (weight near a planet's surface).""" g: float = 9.81 axis: int = 1 def apply(self, world: "World", forces: dict) -> None: for b in world.bodies: forces[b][self.axis] -= b.mass * self.g def energy(self, world: "World") -> float: return sum(b.mass * self.g * b.pos[self.axis] for b in world.bodies) @dataclass class Drag: """Air resistance against the velocity: k * speed**power, pointing backward along the motion.""" k: float power: float = 2.0 only: tuple = () def apply(self, world: "World", forces: dict) -> None: for b in world.bodies: if self.only and b.name not in self.only: continue s = b.speed if s > 0: forces[b] -= self.k * s ** (self.power - 1) * b.vel @dataclass class Spring: """A spring between two bodies (or a body and a fixed point) obeying Hooke's law.""" a: str b: str | None k: float rest: float = 0.0 anchor: tuple = (0.0, 0.0) def _ends(self, world: "World"): a = world.body(self.a) if self.b is None: return a, None, vec(self.anchor[: len(a.pos)]) b = world.body(self.b) return a, b, b.pos def apply(self, world: "World", forces: dict) -> None: a, b, other = self._ends(world) d = a.pos - other length = float(np.linalg.norm(d)) if length == 0: return f = -self.k * (length - self.rest) * d / length forces[a] += f if b is not None: forces[b] -= f def energy(self, world: "World") -> float: a, _, other = self._ends(world) return 0.5 * self.k * (float(np.linalg.norm(a.pos - other)) - self.rest) ** 2 @dataclass class Gravity: """Newton's universal gravitation between every pair of bodies.""" G: float = 6.6743e-11 soften: float = 0.0 def apply(self, world: "World", forces: dict) -> None: bs = world.bodies for i in range(len(bs)): for j in range(i + 1, len(bs)): a, b = bs[i], bs[j] d = b.pos - a.pos r2 = float(d @ d) + self.soften ** 2 f = self.G * a.mass * b.mass / r2 * d / math.sqrt(r2) forces[a] += f forces[b] -= f def energy(self, world: "World") -> float: bs, e = world.bodies, 0.0 for i in range(len(bs)): for j in range(i + 1, len(bs)): r = math.sqrt(float((bs[j].pos - bs[i].pos) @ (bs[j].pos - bs[i].pos)) + self.soften ** 2) e -= self.G * bs[i].mass * bs[j].mass / r return e # ---------------------------------------------------------------- the world @dataclass class World: dt: float = 1e-3 method: str = "euler-cromer" # or "verlet" bodies: list = field(default_factory=list) forces: list = field(default_factory=list) t: float = 0.0 def add(self, body: Body) -> Body: if any(b.name == body.name for b in self.bodies): raise ValueError(f"a body named {body.name!r} already exists") self.bodies.append(body) return body def add_force(self, force) -> None: self.forces.append(force) def body(self, name: str) -> Body: for b in self.bodies: if b.name == name: return b raise KeyError(name) def net_forces(self) -> dict: out = {b: np.zeros_like(b.pos) for b in self.bodies} for f in self.forces: f.apply(self, out) return out def accelerations(self) -> dict: return {b: (np.zeros_like(b.pos) if b.fixed else f / b.mass) for b, f in self.net_forces().items()} def step(self) -> None: dt = self.dt if self.method == "euler-cromer": acc = self.accelerations() for b in self.bodies: if not b.fixed: b.vel = b.vel + acc[b] * dt b.pos = b.pos + b.vel * dt elif self.method == "verlet": acc = self.accelerations() for b in self.bodies: if not b.fixed: b.pos = b.pos + b.vel * dt + 0.5 * acc[b] * dt * dt new = self.accelerations() for b in self.bodies: if not b.fixed: b.vel = b.vel + 0.5 * (acc[b] + new[b]) * dt else: raise ValueError(f"unknown method {self.method!r}") self.t += dt def energy(self) -> float: """Kinetic energy plus every force's potential energy (forces without one, such as drag, add none).""" e = sum(b.kinetic_energy for b in self.bodies) for f in self.forces: if hasattr(f, "energy"): e += f.energy(self) return e def snapshot(self) -> dict: return {"t": self.t, **{b.name: (b.pos.copy(), b.vel.copy()) for b in self.bodies}} def run(self, until: float | Callable[["World"], bool], every: float | None = None, limit: int = 10_000_000) -> list[dict]: """Step until a time (a number) or a condition (a function) is reached; record a snapshot every `every` seconds.""" stop = (lambda w: w.t >= until - 1e-12) if not callable(until) else until record_every = every if every is not None else self.dt frames = [self.snapshot()] next_record = self.t + record_every for _ in range(limit): if stop(self): break self.step() if self.t >= next_record - 1e-12: frames.append(self.snapshot()) next_record += record_every else: raise RuntimeError("run: step limit reached before the stop condition") if frames[-1]["t"] != self.t: frames.append(self.snapshot()) return frames # ---------------------------------------------------------------- a pendulum, stepped by its angle @dataclass class Pendulum: """A weight on a light rod, stepped by its angle (radians from straight down) with the same update.""" length: float angle: float omega: float = 0.0 g: float = 9.81 damping: float = 0.0 t: float = 0.0 def step(self, dt: float) -> None: alpha = -(self.g / self.length) * math.sin(self.angle) - self.damping * self.omega self.omega += alpha * dt self.angle += self.omega * dt self.t += dt def run(self, duration: float, dt: float = 1e-4, every: float = 1 / 60) -> list[tuple[float, float]]: out = [(self.t, self.angle)] nxt = self.t + every end = self.t + duration while self.t < end - 1e-12: self.step(dt) if self.t >= nxt - 1e-12: out.append((self.t, self.angle)) nxt += every return out @property def bob(self) -> tuple[float, float]: return (self.length * math.sin(self.angle), -self.length * math.cos(self.angle))