Skip to content
Snippets Groups Projects
system.py 1.11 KiB
Newer Older
nguyed99's avatar
nguyed99 committed
This module contains base class for a n-body gravitational system.
nguyed99's avatar
nguyed99 committed
from collections.abc import Callable
nguyed99's avatar
nguyed99 committed
from dataclasses import dataclass
nguyed99's avatar
nguyed99 committed
import numpy as np
nguyed99's avatar
nguyed99 committed
@dataclass
class GravitationalSystem:
nguyed99's avatar
nguyed99 committed
    r0: np.ndarray[float]  # shape = (N,d)
    v0: np.ndarray[float]  # shape = (N,d)
nguyed99's avatar
nguyed99 committed
    m: np.ndarray[float]  # shape = N
    t: np.ndarray[float]  # shape = n_time_steps
nguyed99's avatar
nguyed99 committed
    force: Callable
    solver: Callable
nguyed99's avatar
nguyed99 committed

    def __post_init__(self):
        "Checking dimensions of inputs"
        assert self.r0.shape == self.v0.shape
        assert self.m.shape[0] == self.r0.shape[0]

nguyed99's avatar
nguyed99 committed
        solvers = ['verlet', 'bht']
nguyed99's avatar
nguyed99 committed
        assert self.solver.__name__ in solvers

nguyed99's avatar
nguyed99 committed
    def simulation(self):
nguyed99's avatar
nguyed99 committed
        """
nguyed99's avatar
nguyed99 committed
        Using integrator to compute trajectory in phase space
nguyed99's avatar
nguyed99 committed
        """
        p = np.zeros((len(self.t), *self.v0.shape))
        q = np.zeros((len(self.t), *self.r0.shape))
        q[0] = self.r0
        p[0] = self.m * self.v0

        for i in range(1, len(self.t)):
nguyed99's avatar
nguyed99 committed
            dt = self.t[i] - self.t[i - 1]
            p[i], q[i] = self.solver(self.force, q[i - 1], p[i - 1], self.m, dt)
nguyed99's avatar
nguyed99 committed

nguyed99's avatar
nguyed99 committed
        return self.t, p, q