Populations Package

The Populations package defines various agent population models with different behavioral patterns and dynamics. Each population type implements specific movement patterns, interaction rules, and physical properties suitable for different simulation scenarios.

Population Module

This module contains implementations of various agent population types for multi-agent simulations. Each population type defines different dynamics and behaviors for groups of agents.

Available Population Types

Population

Abstract base class defining the interface for all population types.

BrownianMotion

Implements biased Brownian motion with drift and diffusion components.

FixedPopulation

Represents stationary agents with fixed positions.

SimpleIntegrators

Single integrator dynamics (velocity-controlled agents).

DampedDoubleIntegrators

Double integrator dynamics (position and velocity states, controlled in acceleration).

LightSensitive_PTW

Persistent turning walker model with light sensitivity for biological agents.

Examples

Basic usage of a Brownian motion population:

from swarmsim.Populations import BrownianMotion

# Create population from configuration
population = BrownianMotion('config.yaml')

# Reset to initial conditions
population.reset()

# Access current state
positions = population.x

# Get dynamics components
drift = population.get_drift()
diffusion = population.get_diffusion()

Package Overview

Population models in SwarmSim provide:

  • Diverse Behavioral Models: From simple random motion to complex multi-physics dynamics

  • Scalable Implementations: Efficient algorithms for large populations

  • Configurable Properties: Flexible parameter settings for different scenarios

  • Integration Support: Seamless integration with integrators and interactions

  • Physical Realism: Scientifically grounded models for various domains

All population classes inherit from the base population interface, ensuring consistent integration with other simulation components.

Core Modules

Base Population Interface

The foundation class that defines the standard interface for all population implementations.

class swarmsim.Populations.population.Population(config, name=None)[source]

Bases: ABC

Abstract base class that defines the structure for agent populations in a multi-agent system.

This class provides the foundational framework for implementing different types of agent populations with configurable initial conditions and parameters. It handles the loading of configuration files, initialization of agent states, and provides abstract methods for defining population dynamics.

Parameters:
  • config (str) – Path to a YAML configuration file.

  • name (str, optional) – Name identifier for the population. If None, defaults to the class name.

Variables:
  • id (str) – Identifier for the population instance.

  • config (str or dict) – Either a path to a YAML configuration file containing population parameters, or a dictionary with configuration parameters.

  • init_config (dict) – Configuration parameters specifically for initial conditions.

  • param_config (dict or None) – Configuration parameters for population-specific parameters.

  • N (int) – Number of agents in the population.

  • state_dim (int) – Dimensionality of the state space for each agent.

  • input_dim (int) – Dimensionality of the input space for each agent. Defaults to state_dim if not specified.

  • lim_i (np.ndarray) – Lower limits for the state of each agent. Defaults to ['-inf'].

  • lim_s (np.ndarray) – Upper limits for the state of each agent. Defaults to ['inf'].

  • params (dict of np.ndarray or None) – Dictionary containing population-specific parameters for each agent.

  • params_shapes (dict of tuple or None) – Dictionary defining the expected shapes for each parameter.

  • x (np.ndarray or None) – Current state of all agents, shape (N, state_dim).

  • u (np.ndarray or None) – Current control input for all agents, shape (N, input_dim).

  • f (np.ndarray or None) – Current environmental forces acting on all agents, shape (N, input_dim).

Config Requirements:
  • The configuration must contain the following required parameters

  • N (int) – Number of agents in the population.

  • state_dim (int) – Dimensionality of the state space.

  • input_dim (int, optional) – Dimensionality of the input space. Defaults to state_dim.

  • lim_i (list of float, optional) – Lower limits for the state of each agent. Defaults to ['-inf'].

  • lim_s (list of float, optional) – Upper limits for the state of each agent. Defaults to ['inf'].

  • initial_conditions (dict, optional) – Configuration for initial agent states. See get_states utility function for details.

  • parameters (dict, optional) – Configuration for population-specific parameters. See get_parameters utility function for details.

Notes

  • Subclasses must implement the abstract methods get_drift() and get_diffusion().

  • The initial_conditions dictionary handles specifying initial conditions using various modes:

    • "random": Generate random initial positions

    • "file": Load initial positions from a CSV file

  • Initial condition shapes can be:

    • "box": Uniform distribution within specified limits

    • "circle": Uniform distribution within a circular region

  • The parameters dictionary handles specifying population-specific parameters using various modes:

    • "random": Generate random parameter values

    • "file": Load parameter values from a CSV file

Examples

Example YAML configuration for a population:

MyPopulation:
    N: 100
    state_dim: 2
    input_dim: 2
    initial_conditions:
        mode: "random"
        random:
            shape: "box"
            box:
                lower_bounds: [0, 0]
                upper_bounds: [10, 10]
    parameters:
        mode: "file"
        file:
            file_path: "path/to/parameter/file.csv"

This configuration creates a population of 100 agents in a 2D space with random initial positions in a 10x10 box and parameters defined in the path/to/parameter/file.csv file.

__init__(config, name=None)[source]

Initialize the population using the parameters specified in the configuration dictionary or file.

Parameters:
  • config (str or dict) – Either a path to a YAML configuration file containing population parameters, or a dictionary with configuration parameters.

  • name (str, optional) – Name identifier for the population. If None, defaults to the class name.

Raises:
  • TypeError – If config is neither a string filepath nor a dictionary.

  • ValueError – If required parameters ‘N’ or ‘state_dim’ are missing from the configuration.

reset()[source]

Reset agent parameters, states, and control inputs.

This method reinitializes all population parameters, agent states, control inputs, and external forces based on the configuration. It should be called before starting a new simulation or when resetting the simulation state.

Notes

  • Regenerates parameters

  • Resets agent states to initial conditions

  • Resets to 0 control inputs and external forces

abstractmethod get_drift()[source]

Compute the deterministic drift component of the population dynamics.

This abstract method must be implemented by subclasses to define the deterministic part of the agent dynamics. The drift typically includes intrinsic motion patterns, external forces, and control inputs.

Returns:

np.ndarray – Array of shape (N, state_dim) representing the drift for each agent.

Notes

Subclasses should implement this method to return the drift term in the stochastic differential equation: dx = drift * dt + diffusion * dW, where dW is a Wiener process.

abstractmethod get_diffusion()[source]

Compute the stochastic diffusion component of the population dynamics.

This abstract method must be implemented by subclasses to define the stochastic part of the agent dynamics.

Returns:

np.ndarray – Array of shape (N, state_dim) representing the diffusion component for each agent.

Notes

Subclasses should implement this method to return the diffusion term in the stochastic differential equation: dx = drift * dt + diffusion * dW, where dW is a Wiener process.

Key Features:

  • Standardized Interface: Consistent API across all population types

  • State Management: Handle agent positions, velocities, and properties

  • Integration Support: Compatible with various numerical integrators

  • Scalable Architecture: Efficient for populations from tens to millions of agents

Brownian Motion Population

Implementation of Brownian motion dynamics for stochastic agent behavior.

class swarmsim.Populations.brownian_motion.BrownianMotion(config_path, name=None)[source]

Bases: Population

Implements a biased Brownian motion model with average velocity mu and diffusion coefficient D.

This model simulates agent movement with a constant drift (mu) and stochastic diffusion (D), influenced by external forces (f) and control inputs (u).

Parameters:

config_path (str) – Path to the YAML configuration file containing population parameters.

Variables:
  • x (np.ndarray, shape (N, state_dim)) – Current state of the agents, where N is the number of agents and state_dim is the dimensionality of the state space.

  • mu (np.ndarray, shape (N, state_dim)) – Average velocity of each agent along the axes.

  • D (np.ndarray, shape (N, state_dim)) – Diffusion coefficient determining the magnitude of stochastic motion.

  • N (int) – Number of agents in the population.

  • f (np.ndarray, shape (N, state_dim)) – External forces affecting each agent, such as environmental influences.

  • u (np.ndarray, shape (N, state_dim)) – Control input applied to the agents.

  • id (str) – Identifier for the population.

  • config (dict) – Dictionary containing the parsed configuration parameters.

Config requirements:
  • The YAML configuration file must contain the following parameters under the population’s section

  • x0_mode (str) – Mode for generating initial conditions. Options: - "From_File" : Load from a CSV file. - "Random" : Generate randomly.

  • If ``x0_mode=”From_File”``

    x0_file_pathstr

    Path to the CSV file containing initial conditions.

  • If ``x0_mode=”Random”``

    Nint

    Number of agents in the population.

    state_dimint

    Dimensions of the state space.

  • D (list of list or callable) – Command to generate the diffusion coefficient, either as a list of predefined values or as a function that initializes D.

  • mu (list of list or callable) – Command to generate the average velocity (mu), either as a list of values or as a function that initializes mu.

  • id (str) – Identifier for the population.

Notes

  • For more details on how initial conditions are generated, see the get_initial_conditions method in the Population class.

  • The drift component (mu) and diffusion component (D) can be either predefined lists or dynamically generated using callable expressions from the YAML configuration.

Examples

Example YAML configuration:

BrownianMotion:
    x0_mode: "Random"
    N: 100
    state_dim: 2
    mu: [[0.5, 0.0], [0.3, 0.2], [0.1, 0.5]]
    D: [[0.01, 0.01], [0.02, 0.02], [0.01, 0.03]]
    id: "BM_population"

This defines a BrownianMotion population with 100 agents in a 2D space, assigned predefined drift velocities (mu) and diffusion coefficients (D).

__init__(config_path, name=None)[source]

Initializes the BrownianMotion population by loading parameters from a configuration file.

Parameters:

config_path (str) – Path to the YAML configuration file containing initialization parameters.

reset()[source]

Resets the state of the population to its initial conditions.

This method reinitializes the agent states, external forces, and control inputs.

get_drift()[source]

Computes the deterministic drift component of agent motion.

The drift is given by:

drift = mu + f + u

where: - mu is the average velocity, - f represents external forces (e.g., interactions, environment), - u is the control input applied to the agents.

Returns:

np.ndarray – Array of shape (N, state_dim) representing the drift velocity of each agent.

get_diffusion()[source]

Computes the stochastic diffusion component of agent motion.

The diffusion follows a standard Wiener process with coefficient D.

Returns:

np.ndarray – Array of shape (N, state_dim, state_dim) representing the diffusion coefficients for each agent.

Key Features:

  • Stochastic Dynamics: Random motion with configurable noise intensity

  • Temperature Control: Thermal energy effects on agent motion

  • Drift Capabilities: Directional bias in random motion

  • Multi-dimensional Support: 1D, 2D, and 3D motion simulation

Applications: - Molecular dynamics simulation - Animal foraging behavior - Financial market modeling - Diffusion processes

Simple Integrator Population

Agent populations with first-order (velocity-based) dynamics.

class swarmsim.Populations.simple_integrators.SimpleIntegrators(config_path, name=None)[source]

Bases: Population

First-order integrator dynamics with velocity constraints.

This population model implements simple first-order integrator dynamics where the rate of change of agent positions is directly controlled by the sum of control inputs and external forces, subject to velocity magnitude constraints. This model is suitable for kinematic systems or overdamped dynamics.

The system dynamics are governed by:

\[\frac{d\mathbf{x}}{dt} = \text{clip}(\mathbf{u} + \mathbf{f}, -v_{max}, v_{max})\]

where: - \(\mathbf{x}\) is the agent position/state vector - \(\mathbf{u}\) is the control input (desired velocity) - \(\mathbf{f}\) is the external force/influence - \(v_{max}\) is the maximum allowed velocity magnitude per component

Parameters:
  • config_path (str) – Path to the YAML configuration file containing population parameters.

  • name (str, optional) – Name identifier for the population. Defaults to class name if None.

Variables:
  • x (np.ndarray, shape (N, state_dim)) – Current state/position of agents.

  • v_max (float) – Maximum allowed velocity magnitude per state component. Default: float('inf') (no velocity limit).

  • N (int) – Number of agents in the population, inherited from Population.

  • f (np.ndarray, shape (N, state_dim)) – External forces/influences applied to agents, inherited from Population.

  • u (np.ndarray, shape (N, state_dim)) – Control inputs (desired velocities), inherited from Population.

  • state_dim (int) – Dimension of the state space, inherited from Population.

Config Requirements:
  • The YAML configuration file must contain the following parameters under the population’s section

  • initial_conditions (dict) – Initial conditions for the population, including positions and velocities.

  • parameters (dict) – Parameter configuration for damping and diffusion:

  • id (str, optional) – Population identifier. Defaults to class name.

  • N (int) – Number of agents in the population.

  • state_dim (int) – Dimension of the state space, inherited from Population.

  • v_max (float, optional) – Maximum velocity magnitude per component. Default: inf (no limit).

Notes

System Characteristics:

  • No Inertia: Agents respond instantaneously to control inputs

  • Velocity Saturation: Motion is bounded by velocity constraints

  • Deterministic: No stochastic diffusion (overdamped regime)

  • Direct Control: Control input directly sets velocity (subject to limits)

Examples

Basic Configuration:

SimpleIntegrators:
    x0_mode: "Random"
    N: 100
    state_dim: 2
    v_max: 2.0
    id: "mobile_robots"
__init__(config_path, name=None)[source]

Initialize the population using the parameters specified in the configuration dictionary or file.

Parameters:
  • config (str or dict) – Either a path to a YAML configuration file containing population parameters, or a dictionary with configuration parameters.

  • name (str, optional) – Name identifier for the population. If None, defaults to the class name.

Raises:
  • TypeError – If config is neither a string filepath nor a dictionary.

  • ValueError – If required parameters ‘N’ or ‘state_dim’ are missing from the configuration.

get_drift()[source]

Compute the deterministic drift component of the population dynamics.

This abstract method must be implemented by subclasses to define the deterministic part of the agent dynamics. The drift typically includes intrinsic motion patterns, external forces, and control inputs.

Returns:

np.ndarray – Array of shape (N, state_dim) representing the drift for each agent.

Notes

Subclasses should implement this method to return the drift term in the stochastic differential equation: dx = drift * dt + diffusion * dW, where dW is a Wiener process.

get_diffusion()[source]

Compute the stochastic diffusion component of the population dynamics.

This abstract method must be implemented by subclasses to define the stochastic part of the agent dynamics.

Returns:

np.ndarray – Array of shape (N, state_dim) representing the diffusion component for each agent.

Notes

Subclasses should implement this method to return the diffusion term in the stochastic differential equation: dx = drift * dt + diffusion * dW, where dW is a Wiener process.

Key Features:

  • First-order Dynamics: Position directly controlled by velocity

  • Lightweight Implementation: Minimal computational overhead

  • Direct Control: Immediate response to control inputs

  • Ideal for Basic Simulations: Perfect for proof-of-concept studies

Applications: - Basic flocking simulations - Simple robot coordination - Traffic flow modeling - Social dynamics studies

Double Integrator Population

Agent populations with second-order (acceleration-based) dynamics.

class swarmsim.Populations.double_integrators.DampedDoubleIntegrators(config_path, name=None)[source]

Bases: Population

Damped second-order integrator dynamics for agent populations.

This population model implements damped double integrator dynamics, where each agent has both position and velocity states. The dynamics include damping, external forces, control inputs, and stochastic noise. This model is commonly used for modeling vehicles, robots, or particles with inertial behavior.

The system dynamics are governed by:

\[\begin{split}\frac{d}{dt} \begin{bmatrix} \mathbf{p} \\ \mathbf{v} \end{bmatrix} = \begin{bmatrix} \mathbf{v} \\ -\gamma \mathbf{v} + \mathbf{u} + \mathbf{f} \end{bmatrix} + \mathbf{D} \, d\mathbf{W}\end{split}\]

where: - \(\mathbf{p}\) is the position vector - \(\mathbf{v}\) is the velocity vector - \(\gamma\) is the damping coefficient - \(\mathbf{u}\) is the control input - \(\mathbf{f}\) is the external force - \(\mathbf{D}\) is the diffusion matrix - \(d\mathbf{W}\) is white noise

Parameters:
  • config_path (str) – Path to the YAML configuration file containing population parameters.

  • name (str, optional) – Name identifier for the population. Defaults to class name if None.

Variables:
  • x (np.ndarray, shape (N, state_dim)) – Current state of agents with positions and velocities concatenated. Format: [pos_x, pos_y, vel_x, vel_y] for 2D systems.

  • damping (np.ndarray, shape (N,) or None) – Damping coefficient for each agent affecting velocity decay.

  • D (np.ndarray, shape (N, state_dim) or None) – Diffusion coefficients for position and velocity noise. Typically zero for positions, non-zero for velocities.

  • N (int) – Number of agents in the population, inherited from Population.

  • f (np.ndarray, shape (N, state_dim)) – External forces applied to agents, inherited from Population.

  • u (np.ndarray, shape (N, state_dim)) – Control inputs applied to agents, inherited from Population.

  • input_dim (int) – Dimension of the spatial coordinates (typically 2 for 2D systems).

  • params_shapes (dict) – Defines expected shapes for population parameters.

Config Requirements:
  • The YAML configuration file must contain the following parameters under the population’s section

  • initial_conditions (dict) – Initial conditions for the population, including positions and velocities.

  • parameters (dict) – Parameter configuration for damping and diffusion:

  • id (str, optional) – Population identifier. Defaults to class name.

  • state_dim (int) – Dimension of the state space, inherited from Population.

  • N (int) – Number of agents in the population.

Raises:
  • FileNotFoundError – If the configuration file is not found.

  • KeyError – If required parameters are missing from the configuration.

  • ValueError – If parameter shapes are incompatible with the population size.

Examples

Basic Configuration:

DampedDoubleIntegrators:
    x0_mode: "Random"
    N: 50
    state_dim: 2
    id: "vehicles"
    parameters:
        params_mode: "Fixed"
        params_names: ["damping", "D"]
        params_values:
            damping: 0.1
            D: 0.05
__init__(config_path, name=None)[source]

Initialize the population using the parameters specified in the configuration dictionary or file.

Parameters:
  • config (str or dict) – Either a path to a YAML configuration file containing population parameters, or a dictionary with configuration parameters.

  • name (str, optional) – Name identifier for the population. If None, defaults to the class name.

Raises:
  • TypeError – If config is neither a string filepath nor a dictionary.

  • ValueError – If required parameters ‘N’ or ‘state_dim’ are missing from the configuration.

reset()[source]

Resets the state of the population to its initial conditions.

This method reinitializes the agent states, external forces, and control inputs.

get_drift()[source]

Compute the deterministic drift term for damped double integrator dynamics.

This method implements the drift component of the stochastic differential equation governing damped double integrator motion. The drift includes velocity propagation to position and damped acceleration dynamics with control and external forces.

Returns:

np.ndarray, shape (N, state_dim) – Drift vector for all agents, containing velocity and acceleration terms. Format: [velocity_x, velocity_y, acceleration_x, acceleration_y] for 2D.

Notes

Drift Structure:

The drift term consists of two components:

  1. Position Drift: Current velocity becomes position rate of change

  2. Velocity Drift: Damped acceleration with control and external forces

Mathematical Form:

\[ \begin{align}\begin{aligned}\frac{d\mathbf{p}}{dt} = \mathbf{v}\\\frac{d\mathbf{v}}{dt} = -\gamma \mathbf{v} + \mathbf{u} + \mathbf{f}\end{aligned}\end{align} \]

where: - \(\mathbf{p}\) is position - \(\mathbf{v}\) is velocity - \(\gamma\) is damping coefficient - \(\mathbf{u}\) is control input - \(\mathbf{f}\) is external force

Damping Effects:

The damping term \(-\gamma \mathbf{v}\) provides: - Velocity-dependent resistance (like air resistance) - Exponential decay toward equilibrium - Stabilization of the system dynamics

Force Integration:

The method combines control and external forces: - Control Forces: Deliberate actuator inputs - External Forces: Environmental influences and inter-agent interactions

get_diffusion()[source]

Compute the diffusion term for stochastic double integrator dynamics.

This method returns the diffusion matrix that scales the white noise in the stochastic differential equation. For double integrators, noise typically affects velocities rather than positions directly, modeling random accelerations from unmodeled forces or actuator noise.

Returns:

np.ndarray, shape (N, 2*state_dim) – Diffusion coefficients for all agents and state components. Typically structured as [0, 0, D_vel, D_vel] for 2D systems.

Key Features:

  • Second-order Dynamics: Realistic inertial behavior

  • Force-based Control: Control through acceleration/force inputs

  • Momentum Conservation: Physically realistic motion patterns

  • Advanced Dynamics: Support for complex mechanical behaviors

Applications: - Robotic system simulation - Vehicle dynamics modeling - Spacecraft coordination - Physical system simulation

Fixed Population

Static agent populations for environment elements and obstacles.

class swarmsim.Populations.fixed_population.FixedPopulation(config, name=None)[source]

Bases: Population

Stationary population with agents at fixed spatial locations.

This population model implements immobile agents that remain at their initial positions throughout the simulation. The population is useful for modeling static obstacles, landmarks, reference points, or stationary infrastructure elements that other populations can interact with.

The system dynamics are trivial:

\[\frac{d\mathbf{x}}{dt} = \mathbf{u}\]
\[\text{diffusion} = \mathbf{0}\]

where: - \(\mathbf{x}\) remains constant (typically \(\mathbf{u} = \mathbf{0}\)) - No stochastic component affects the population

Parameters:

config_path (str) – Path to the YAML configuration file containing population parameters.

Variables:
  • x (np.ndarray, shape (N, state_dim)) – Fixed positions of agents, set during initialization and typically unchanged.

  • N (int) – Number of stationary agents in the population.

  • f (np.ndarray, shape (N, state_dim)) – External forces (typically ignored for fixed populations).

  • u (np.ndarray, shape (N, state_dim)) – Control input (typically zero for truly fixed populations).

  • state_dim (int) – Spatial dimension of the agent positions.

Config Requirements:
  • The YAML configuration file must contain the following parameters under the population’s section

  • x0_mode (str) – Initial condition mode. Options: "From_File", "Random"

  • If ``x0_mode=”From_File”``

    x0_file_pathstr

    Path to CSV file containing exact positions for stationary agents. This is the preferred method for precisely placed obstacles or landmarks.

  • If ``x0_mode=”Random”``

    Nint

    Number of stationary agents to place randomly.

    state_dimint

    Spatial dimension (2 for 2D, 3 for 3D).

  • id (str, optional) – Population identifier. Defaults to class name.

Notes

Use Cases:

Fixed populations are commonly used for:

  • Static Obstacles: Walls, barriers, immobile hazards

  • Landmarks: Navigation reference points, beacons

  • Infrastructure: Buildings, stations, charging points

  • Environmental Features: Trees, rocks, geographic features

  • Sensors: Fixed monitoring stations, cameras

  • Reference Points: Target locations, waypoints

Interaction Considerations:

While fixed populations don’t move, they can:

  • Exert forces on other populations (through interactions)

  • Serve as sources of attraction or repulsion

  • Act as collision/avoidance targets

  • Provide spatial references for navigation

get_drift()[source]

No movement on average.

Returns:

drift: numpy array (num_agents x dim_state) Dirft of the population

get_diffusion()[source]

No stochasticity.

Returns:

diffusion: numpy array (num_agents x dim_state) Diffusion of the population

Key Features:

  • Static Positions: Agents remain at fixed locations

  • Environmental Elements: Represent obstacles, landmarks, or resources

  • Interaction Sources: Provide forces/interactions without moving

  • Computational Efficiency: No integration required

Applications: - Environmental obstacles - Resource locations - Sensor networks - Infrastructure elements

Persistent Turning Walker

Specialized population model for correlated random walks with turning behavior.

class swarmsim.Populations.parsistent_turning_walker.LightSensitive_PTW(config_path, name=None)[source]

Bases: Population

Light-sensitive Persistent Turning Walker population model.

This population implements a sophisticated bio-inspired locomotion model based on persistent turning walkers that respond to external light stimuli. The model captures the complex dynamics of motile organisms (like Euglena) that exhibit persistent motion with turning behavior modulated by environmental light conditions.

The system state consists of position, velocity magnitude, orientation, and angular velocity, governed by the following dynamics:

\[ \begin{align}\begin{aligned}\frac{dx}{dt} = v \cos(\theta)\\\frac{dy}{dt} = v \sin(\theta)\\\frac{dv}{dt} = \theta_s(\mu_s - v) + \alpha_s u + \beta_s \dot{u}^+ + \gamma_s \dot{u}^- + \sigma_s \, dW_v\\\frac{d\theta}{dt} = \omega\\\frac{d\omega}{dt} = \theta_w(\mu_w - \omega) + \text{sign}(\omega)(\alpha_w u + \beta_w \dot{u}^+ + \gamma_w \dot{u}^-) + \sigma_w \, dW_\omega\end{aligned}\end{align} \]

where: - \((x, y)\) is the agent position - \(v\) is the speed magnitude - \(\theta\) is the orientation angle - \(\omega\) is the angular velocity - \(u\) is the light stimulus intensity - \(\dot{u}^+, \dot{u}^-\) are positive and negative stimulus derivatives - \(\theta_s, \mu_s, \alpha_s, \beta_s, \gamma_s, \sigma_s\) are speed parameters - \(\theta_w, \mu_w, \alpha_w, \beta_w, \gamma_w, \sigma_w\) are turning parameters

Parameters:
  • config_path (str) – Path to the YAML configuration file containing population parameters.

  • name (str, optional) – Name identifier for the population. Defaults to class name if None.

Variables:
  • x (np.ndarray, shape (N, 5)) – State of agents: [x_pos, y_pos, velocity, theta, omega].

  • u_old (np.ndarray, shape (N, input_dim) or None) – Previous timestep control input for computing derivatives.

  • sigma_s (theta_s, mu_s, alpha_s, beta_s, gamma_s,) – Speed dynamics parameters for each agent.

  • sigma_w (theta_w, mu_w, alpha_w, beta_w, gamma_w,) – Turning dynamics parameters for each agent.

  • dt (float) – Integration timestep for computing input derivatives.

  • params_shapes (dict) – Defines expected shapes for all model parameters.

Config Requirements:
  • The YAML configuration file must contain the following parameters under the population’s section

  • initial_conditions (dict) – Initial conditions for the population, including positions and velocities.

  • parameters (dict) – Parameter configuration for damping and diffusion:

  • id (str, optional) – Population identifier. Defaults to class name.

  • state_dim (int) – Dimension of the state space, inherited from Population.

  • N (int) – Number of agents in the population.

  • dt (float) – Integration timestep for derivative calculations.

Notes

Biological Inspiration:

This model is inspired by the locomotion of Euglena gracilis and similar photo-responsive microorganisms that exhibit:

  • Persistent Motion: Sustained movement with characteristic speeds

  • Phototaxis: Movement in response to light gradients

  • Turning Behavior: Modulation of orientation based on stimuli

  • Adaptive Responses: Different reactions to increasing vs decreasing light

Parameter Interpretation:

Speed Parameters: - theta_s: Speed relaxation rate (return to preferred speed) - mu_s: Preferred/natural swimming speed - alpha_s: Direct light response on speed - beta_s: Response to increasing light intensity - gamma_s: Response to decreasing light intensity - sigma_s: Speed noise amplitude

Turning Parameters: - theta_w: Angular velocity relaxation rate - mu_w: Preferred angular velocity (bias for turning) - alpha_w: Direct light response on turning - beta_w: Turning response to increasing light - gamma_w: Turning response to decreasing light - sigma_w: Angular noise amplitude

State Variables:

The 5D state vector represents: 1. x, y: Spatial position coordinates 2. v: Instantaneous speed magnitude (always ≥ 0) 3. θ: Orientation angle (wrapped to [0, 2π]) 4. ω: Angular velocity (rate of orientation change)

Light Response Mechanism:

The model distinguishes between: - Current stimulus: Direct response to light intensity - Positive changes: Response to increasing light (photo-attraction) - Negative changes: Response to decreasing light (photo-avoidance)

Examples

Basic Euglena-like Configuration:

LightSensitive_PTW:
    x0_mode: "Random"
    N: 100
    state_dim: 5
    dt: 0.01
    id: "euglena"
    parameters:
        params_mode: "Fixed"
        params_names: ["theta_s", "mu_s", "alpha_s", "beta_s", "gamma_s", "sigma_s",
                      "theta_w", "mu_w", "alpha_w", "beta_w", "gamma_w", "sigma_w"]
        params_values:
            theta_s: 1.0
            mu_s: 2.0
            alpha_s: 0.5
            beta_s: 1.0
            gamma_s: -0.5
            sigma_s: 0.1
            theta_w: 2.0
            mu_w: 0.0
            alpha_w: 0.2
            beta_w: 0.8
            gamma_w: -0.3
            sigma_w: 0.2
__init__(config_path, name=None)[source]

Initialize the population using the parameters specified in the configuration dictionary or file.

Parameters:
  • config (str or dict) – Either a path to a YAML configuration file containing population parameters, or a dictionary with configuration parameters.

  • name (str, optional) – Name identifier for the population. If None, defaults to the class name.

Raises:
  • TypeError – If config is neither a string filepath nor a dictionary.

  • ValueError – If required parameters ‘N’ or ‘state_dim’ are missing from the configuration.

reset()[source]

Resets the state of the population to its initial conditions.

This method reinitializes the agent states, external forces, and control inputs.

get_drift()[source]

Compute the deterministic drift for persistent turning walker dynamics.

This method implements the complete drift dynamics for light-sensitive persistent turning walkers, including position propagation, speed regulation, orientation change, and angular velocity dynamics with light stimulus responses.

Returns:

np.ndarray, shape (N, 5) – Drift vector for all agents containing: [dx/dt, dy/dt, dv/dt, dθ/dt, dω/dt]

Notes

State Variable Processing:

The method extracts and processes state variables:

  • Speed Constraint: Ensures velocity magnitude is non-negative

  • Angle Wrapping: Keeps orientation in [0, 2π] range

  • Derivative Computation: Calculates input rate of change

Dynamics Components:

  1. Position Dynamics: \(\frac{dx}{dt} = v \cos(\theta)\), \(\frac{dy}{dt} = v \sin(\theta)\)

  2. Speed Dynamics: \(\frac{dv}{dt} = \theta_s(\mu_s - v) + \alpha_s u + \beta_s \dot{u}^+ + \gamma_s \dot{u}^-\)

  3. Orientation Dynamics: \(\frac{d\theta}{dt} = \omega\)

  4. Angular Velocity Dynamics: \(\frac{d\omega}{dt} = \theta_w(\mu_w - \omega) + \text{sign}(\omega)[\alpha_w u + \beta_w \dot{u}^+ + \gamma_w \dot{u}^-]\)

Light Response Processing:

The method computes stimulus derivatives and separates positive/negative changes:

  • \(\dot{u} = \frac{u(t) - u(t-\Delta t)}{\Delta t}\)

  • \(\dot{u}^+ = \max(\dot{u}, 0)\) (increasing light)

  • \(\dot{u}^- = \min(\dot{u}, 0)\) (decreasing light)

Sign-Dependent Turning:

Angular velocity dynamics include sign-dependent responses to maintain biological realism in turning behavior asymmetries.

get_diffusion()[source]

Compute the diffusion matrix for stochastic persistent turning walker dynamics.

This method returns the diffusion coefficients that scale white noise in the stochastic differential equation. For persistent turning walkers, noise affects the speed and angular velocity dynamics while position and orientation change deterministically through their respective rates.

Returns:

np.ndarray, shape (N, 5) – Diffusion coefficients for all state variables: [0, 0, σ_s, 0, σ_w] where only speed and angular velocity have noise.

Notes

Noise Structure:

The diffusion reflects the biological noise sources:

  • Position (x, y): Zero noise - positions change deterministically via velocity

  • Speed (v): σ_s noise - models metabolic fluctuations, swimming variability

  • Orientation (θ): Zero noise - angle changes deterministically via angular velocity

  • Angular Velocity (ω): σ_w noise - models turning decision variability

Key Features:

  • Correlated Motion: Non-Markovian random walks

  • Turning Dynamics: Realistic directional changes

  • Persistence Control: Adjustable correlation in movement direction

  • Biological Realism: Models animal movement patterns

Applications: - Animal tracking and behavior - Biological cell movement - Search and exploration strategies - Navigation algorithm testing

Usage Examples

Basic Population Setup

from swarmsim.Populations import BrownianMotion, DoubleIntegrators
import numpy as np

# Create Brownian motion population
brownian_pop = BrownianMotion(
    n=100,                    # Number of agents
    x_dim=2,                  # 2D simulation
    diffusion_coefficient=0.1, # Noise strength
    drift_velocity=np.array([0.1, 0.0])  # Slight rightward drift
)

# Create double integrator population
double_int_pop = DoubleIntegrators(
    n=50,
    x_dim=3,                  # 3D simulation
    mass=1.0,                 # Agent mass
    damping=0.1               # Velocity damping
)

Multi-Population Simulation

from swarmsim.Populations import (BrownianMotion, SimpleIntegrators,
                                 FixedPopulation)
import numpy as np

# Create diverse population mix
prey = BrownianMotion(n=200, x_dim=2, diffusion_coefficient=0.2)
predators = SimpleIntegrators(n=10, x_dim=2, max_speed=2.0)
obstacles = FixedPopulation(
    positions=np.array([[5, 5], [10, 10], [15, 5]]),  # Fixed obstacle locations
    x_dim=2
)

populations = [prey, predators, obstacles]

Population Parameter Configuration

from swarmsim.Populations import DoubleIntegrators
from swarmsim.Utils import get_parameters

# Define parameter configuration
param_config = {
    'mode': 'generate',
    'generate': {
        'mass': {
            'sampler': 'lognormal',
            'args': {'mean': 0, 'sigma': 0.3}  # Mass variation
        },
        'max_force': {
            'sampler': 'uniform',
            'args': {'low': 0.5, 'high': 2.0}  # Force limits
        }
    }
}

# Generate diverse parameters
params = get_parameters(
    param_config,
    {'mass': (), 'max_force': ()},
    num_samples=100
)

# Create population with diverse properties
population = DoubleIntegrators(
    n=100,
    x_dim=2,
    mass=params['mass'],
    max_force=params['max_force']
)

Advanced Population Dynamics

from swarmsim.Populations import PersistentTurningWalker
import numpy as np

# Create realistic animal movement model
animal_population = PersistentTurningWalker(
    n=50,
    x_dim=2,
    step_length=0.1,           # Average step size
    turning_angle_std=0.3,     # Turning variability
    persistence_time=10.0,     # Correlation time
    boundary_behavior='reflect' # Boundary handling
)

# Simulate foraging behavior
for step in range(1000):
    # Animals move with correlated random walks
    animal_population.step()

    # Add environmental responses
    if step % 100 == 0:
        # Occasional strong turning (predator response)
        animal_population.add_turning_bias(angle=np.pi/2, strength=2.0)

Population Interactions

from swarmsim.Populations import SimpleIntegrators
from swarmsim.Interactions import LennardJones

# Create interacting populations
fish_school = SimpleIntegrators(n=100, x_dim=2)

# Add inter-agent interactions
interaction = LennardJones(
    epsilon=1.0,    # Interaction strength
    sigma=1.0,      # Interaction range
    cutoff=3.0      # Computational cutoff
)

# Simulation with interactions
for step in range(1000):
    # Compute interaction forces
    forces = interaction.compute_forces(fish_school.x)

    # Apply forces and integrate
    fish_school.apply_forces(forces)
    fish_school.step()

Performance Optimization

Population implementations are optimized for performance:

  • Vectorized Operations: Extensive use of NumPy for computational efficiency

  • Memory Management: Efficient memory layouts for large populations

  • Adaptive Algorithms: Computational complexity scales appropriately

  • Parallel Support: Compatible with parallel processing frameworks

Model Selection Guide

Choose population models based on your simulation requirements:

Population Model Selection

Model Type

Computational Cost

Physical Realism

Best Applications

Brownian Motion

Very Low

Moderate

Diffusion, stochastic processes

Simple Integrators

Low

Low-Moderate

Basic flocking, rapid prototyping

Double Integrators

Moderate

High

Robotics, vehicle dynamics

Fixed Population

Minimal

N/A

Environmental elements

Turning Walker

Low-Moderate

High (biological)

Animal behavior, search patterns

Best Practices

  1. Model Selection: Choose the simplest model that captures essential behaviors

  2. Parameter Tuning: Use biologically or physically realistic parameter ranges

  3. Population Size: Balance realism with computational requirements

  4. Integration: Ensure compatibility with chosen integrator and time step

  5. Validation: Compare simulation results with theoretical or experimental data