|
| 1 | +"""Base classes for first order dynamical systems. |
| 2 | +
|
| 3 | +In this module, we introduce the base classes for |
| 4 | +first order dynamical systems, and the corresponding |
| 5 | +abstract classes for system and initial condition. |
| 6 | +""" |
| 7 | + |
| 8 | +from abc import ABC, abstractmethod |
| 9 | +from functools import cached_property |
| 10 | +from typing import Any |
| 11 | + |
| 12 | +import numpy as np |
| 13 | +import pandas as pd |
| 14 | +from numpy import typing as npt |
| 15 | +from pydantic import BaseModel, Field |
| 16 | + |
| 17 | +from hamilflow.models.utils.typing import TypeTime |
| 18 | + |
| 19 | + |
| 20 | +class FirstOrderSystem(BaseModel, ABC): |
| 21 | + """The base params for a first order dynamical system. |
| 22 | +
|
| 23 | + Create your own system by inheriting from this class |
| 24 | + and adding your own params. |
| 25 | +
|
| 26 | + ```python |
| 27 | + class MyCustomSystem(FirstOrderSystem): |
| 28 | + # your fields here |
| 29 | + omega: float |
| 30 | + ``` |
| 31 | + """ |
| 32 | + |
| 33 | + |
| 34 | +class FirstOrderIC(BaseModel, ABC): |
| 35 | + """The base initial condition for a first order dynamical system. |
| 36 | +
|
| 37 | + :cvar x0: the initial state of the system |
| 38 | + :cvar t0: the initial time (default to 0.0) |
| 39 | + """ |
| 40 | + |
| 41 | + x0: float | list[float] = Field(...) |
| 42 | + t0: float = Field(default=0.0) |
| 43 | + |
| 44 | + |
| 45 | +class FirstOrderDynamicsBase(ABC): |
| 46 | + """Base class to generate time series data for a first order dynamical system. |
| 47 | +
|
| 48 | + :param system: all the params that defines the system. |
| 49 | + :param initial_condition: the initial condition of the system. |
| 50 | + """ |
| 51 | + |
| 52 | + def __init__( |
| 53 | + self, |
| 54 | + system: FirstOrderSystem, |
| 55 | + initial_condition: FirstOrderIC, |
| 56 | + ) -> None: |
| 57 | + |
| 58 | + self.system = system |
| 59 | + self.ic = initial_condition |
| 60 | + |
| 61 | + @cached_property |
| 62 | + def definition(self) -> dict[str, dict[str, Any]]: |
| 63 | + """Model params and initial conditions defined as a dictionary. |
| 64 | +
|
| 65 | + :return: dictionary containing system and initial condition parameters. |
| 66 | + """ |
| 67 | + return { |
| 68 | + "system": self.system.model_dump(), |
| 69 | + "initial_condition": self.ic.model_dump(), |
| 70 | + } |
| 71 | + |
| 72 | + @abstractmethod |
| 73 | + def derivatives( |
| 74 | + self, |
| 75 | + state: npt.NDArray[np.float64], |
| 76 | + t: float, |
| 77 | + ) -> npt.NDArray[np.float64]: |
| 78 | + """Return the derivative of the state with respect to time. |
| 79 | +
|
| 80 | + :param state: the current state of the system. |
| 81 | + :param t: the current time. |
| 82 | + :return: the derivative of the state with respect to time. |
| 83 | + """ |
| 84 | + |
| 85 | + def step( |
| 86 | + self, |
| 87 | + state: npt.NDArray[np.float64], |
| 88 | + t: float, |
| 89 | + dt: float, |
| 90 | + ) -> tuple[npt.NDArray[np.float64], float]: |
| 91 | + """Advances the system by one time step (dt) using |
| 92 | + 4th-Order Runge-Kutta (RK4) integration. |
| 93 | +
|
| 94 | + :param state: the current state of the system. |
| 95 | + :param t: the current time. |
| 96 | + :param dt: the time step size. |
| 97 | + :return: the new state of the system and the new time. |
| 98 | + """ |
| 99 | + k1 = self.derivatives(state, t) |
| 100 | + k2 = self.derivatives(state + 0.5 * dt * k1, t + 0.5 * dt) |
| 101 | + k3 = self.derivatives(state + 0.5 * dt * k2, t + 0.5 * dt) |
| 102 | + k4 = self.derivatives(state + dt * k3, t + dt) |
| 103 | + |
| 104 | + new_state = state + (dt / 6.0) * (k1 + 2 * k2 + 2 * k3 + k4) |
| 105 | + new_t = t + dt |
| 106 | + |
| 107 | + return new_state, new_t |
| 108 | + |
| 109 | + def __call__(self, t: TypeTime) -> pd.DataFrame: |
| 110 | + """Generate time series data for the dynamical system. |
| 111 | +
|
| 112 | + :param t: sequence of time steps. |
| 113 | + :return: values of the variables including time `t` and state `x`. |
| 114 | + """ |
| 115 | + t_arr = np.asarray(t) |
| 116 | + |
| 117 | + current_state = np.asarray(self.ic.x0, dtype=np.float64) |
| 118 | + current_t = self.ic.t0 |
| 119 | + |
| 120 | + effective_t = [current_t] |
| 121 | + history = [current_state] |
| 122 | + for target_t in t_arr: |
| 123 | + dt = target_t - current_t |
| 124 | + if dt > 0: |
| 125 | + current_state, current_t = self.step(current_state, current_t, dt) |
| 126 | + effective_t.append(current_t) |
| 127 | + history.append(current_state) |
| 128 | + |
| 129 | + data = np.asarray(history) |
| 130 | + |
| 131 | + if data.ndim == 1: |
| 132 | + columns = ["x"] |
| 133 | + else: |
| 134 | + columns = [f"x{i+1}" for i in range(data.shape[1])] |
| 135 | + |
| 136 | + return ( |
| 137 | + pd.DataFrame(data, columns=columns).assign(t=effective_t).sort_index(axis=1) |
| 138 | + ) |
0 commit comments