Interactions Package

The Interactions package implements various force models and interaction mechanisms between agents in multi-agent simulations. These interactions form the foundation of collective behaviors such as flocking, schooling, herding, and complex emergent patterns.

Interactions Module

The interactions module defines different types of interactions between agents in multi-agent shepherding simulations. These interactions influence agent behaviors by applying forces such as repulsion or attraction.

Available Interactions

  • Interaction : Abstract base class that defines the interface for all interaction models.

  • HarmonicRepulsion : Implements a finite-range harmonic repulsion force.

  • PowerLawRepulsion : Implements a power-law repulsion force, where force decays with distance.

Usage

To use an interaction model, import it and instantiate with a configuration file:

from swarmsim.interactions import HarmonicRepulsion
interaction = HarmonicRepulsion(target_population, source_population, config="config.yaml")
forces = interaction.get\_interaction()

Examples

Example YAML configuration:

harmonic_repulsion:
    strength: 1.5
    max_distance: 10.0

power_law_repulsion:
    strength: 2.0
    max_distance: 5.0
    p: 3.0

This sets up two different repulsion models with distinct behaviors.

class swarmsim.Interactions.Interaction(target_population, source_population, config_path, name=None)[source]

Bases: ABC

Abstract base class for modeling interactions between agent populations.

This class provides the framework for implementing various types of inter-agent interactions such as repulsion, attraction, alignment, and collision avoidance. It defines how one population (source) influences another population (target) through force computations.

Parameters:
  • target_population (Population) – The population that receives the interaction forces.

  • source_population (Population) – The population that generates the interaction forces.

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

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

Variables:
  • target_population (Population) – The population affected by the interaction forces.

  • source_population (Population) – The population generating the interaction forces.

  • config (dict) – Configuration parameters specific to this interaction type.

  • param_config (dict) – Parameter configuration for interaction-specific parameters.

  • id (str) – Identifier for this interaction instance.

  • params (dict of np.ndarray or None) – Dictionary containing interaction-specific parameters.

  • params_shapes (dict of tuple or None) – Dictionary defining expected shapes for interaction parameters.

Config Requirements:
  • The YAML configuration file should contain parameters under the interaction’s section

  • id (str, optional) – Identifier for the interaction. Defaults to the class name.

  • parameters (dict, optional) – Configuration for interaction-specific parameters.

Notes

  • Subclasses must implement the abstract method get_interaction().

  • Interactions are computed at each simulation timestep.

Examples

Example YAML configuration for an interaction:

HarmonicRepulsion:
    id: "repulsion_interaction"
    parameters:
        params_mode: "Random"
        params_names: ["strength", "range"]
        params_limits:
            strength: [1.0, 5.0]
            range: [0.5, 2.0]

Example of implementing a custom interaction:

class CustomInteraction(Interaction):
    def get_interaction(self):
        # Compute interaction forces here

        return forces
__init__(target_population, source_population, config_path, name=None)[source]

Initialize the Interaction with target and source populations.

Parameters:
  • target_population (Population) – The population that will be affected by the interaction forces.

  • source_population (Population) – The population that will generate the interaction forces.

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

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

Raises:

FileNotFoundError – If the configuration file cannot be found.

abstractmethod get_interaction()[source]

Compute the interaction forces between source and target populations.

This abstract method must be implemented by subclasses to define the specific interaction. It calculates the forces that the source population exerts on the target population based on their current states and interaction parameters.

Returns:

np.ndarray – Array of shape (N_target, state_dim) representing the interaction forces applied to each agent in the target population, where N_target is the number of agents in the target population and state_dim is the spatial dimension.

Notes

The returned forces will be added to the target population’s force accumulator and integrated by the numerical integrator.

Raises:

NotImplementedError – If called directly from the base class without implementation.

reset()[source]

Reset the interaction parameters to their initial values.

This method reinitializes interaction-specific parameters based on the configuration. It should be called before starting a new simulation.

class swarmsim.Interactions.HarmonicRepulsion(target_population, source_population, config_path, name=None)[source]

Bases: Interaction

Harmonic repulsion interaction with finite interaction range.

This interaction implements a linearly decaying repulsive force between agents from two different populations. The repulsion follows a harmonic potential that provides short-range repulsion up to a finite interaction range.

The repulsion force magnitude follows:

\[ \begin{align}\begin{aligned}F_i = \sum_{j \in population} F_{ij}(r_{ij})\\\begin{split}F_{ij}(r_{ij}) = \begin{cases} -k (r_{max} - r_{ij}) \hat{r}_{ij} & \text{if } r_{ij} < r_{max} \\ 0 & \text{if } r_{ij} \geq r_{max} \end{cases}\end{split}\end{aligned}\end{align} \]

where: - \(F_i\) is the total force on agent i - \(k\) is the strength parameter - \(r_{max}\) is the maximum interaction distance - \(r_{ij}\) is the distance between agents i and j - \(\hat{r}_{ij}\) is the unit vector joining agents i and j

Parameters:
  • target_population (Population) – The population that receives repulsion forces.

  • source_population (Population) – The population that generates repulsion forces.

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

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

Variables:
  • target_population (Population) – Population affected by repulsion forces.

  • source_population (Population) – Population generating repulsion forces.

  • strength (np.ndarray or None) – Repulsion strength parameter(s), shape depends on parameter configuration.

  • distance (np.ndarray or None) – Maximum interaction distance parameter(s), shape depends on parameter configuration.

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

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

  • strength (float or list) – Repulsion strength parameter(s)

  • distance (float or list) – Maximum interaction distance parameter(s)

  • parameters (dict) – Parameter configuration for the harmonic repulsion. Typical structure:

    • mode : str - Parameter assignment mode

Notes

Force Characteristics:

  • Linear Decay: Force decreases linearly with distance until cutoff

  • Finite Range: No interaction beyond maximum distance

  • Pairwise Computation: All source-target agent pairs are evaluated

  • Vectorized: Efficient computation using NumPy broadcasting

Parameter Flexibility:

Parameters can be configured as: - Fixed values: Same for all interactions - Random ranges: Sampled for each agent or interaction - Population-dependent: Different values for different populations

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

  • KeyError – If required interaction parameters are missing in the configuration file.

__init__(target_population, source_population, config_path, name=None)[source]

Initialize the Interaction with target and source populations.

Parameters:
  • target_population (Population) – The population that will be affected by the interaction forces.

  • source_population (Population) – The population that will generate the interaction forces.

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

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

Raises:

FileNotFoundError – If the configuration file cannot be found.

get_interaction()[source]

Compute harmonic repulsion forces between source and target populations.

This method calculates the repulsive forces that source population agents exert on target population agents using the harmonic repulsion model. Forces decay linearly with distance and have finite interaction range.

Returns:

np.ndarray – Repulsion forces array of shape (N_target, D) where: - N_target is the number of agents in the target population - D is the spatial dimension (typically 2 or 3) Each row represents the total repulsion force on one target agent.

Notes

Algorithm Steps:

  1. Distance Computation: Calculate pairwise distances between all source-target pairs

  2. Range Filtering: Identify agent pairs within interaction range

  3. Force Calculation: Apply harmonic repulsion formula for nearby pairs

  4. Force Summation: Sum contributions from all source agents for each target

Numerical Stability:

  • Minimum distance threshold (1e-6) prevents division by zero

  • Vectorized operations ensure computational efficiency

  • Broadcasting handles different parameter shapes automatically

reset()[source]

Reset the interaction parameters to their initial values.

This method reinitializes interaction-specific parameters based on the configuration. It should be called before starting a new simulation.

class swarmsim.Interactions.PowerLawRepulsion(target_population, source_population, config_path, name=None)[source]

Bases: Interaction

Pure power-law repulsion interaction with finite range cutoff.

This interaction implements a repulsive force that decays according to an inverse power law with respect to inter-agent distance. Unlike the more general PowerLawInteraction, this class focuses specifically on repulsion with a clean cutoff mechanism that ensures zero force at the maximum interaction distance.

The repulsion force follows:

\[F(r) = k \left( \frac{1}{r^p} - \frac{1}{r_{max}^p} \right)\]

for \(r < r_{max}\), and \(F(r) = 0\) for \(r \geq r_{max}\), where: - \(k\) is the repulsion strength parameter - \(r\) is the inter-agent distance - \(p\) is the power law exponent - \(r_{max}\) is the maximum interaction distance

The subtraction term ensures the force smoothly approaches zero at the cutoff distance, preventing discontinuous force jumps that can cause numerical instabilities.

Parameters:
  • target_population (Population) – The population that receives repulsion forces.

  • source_population (Population) – The population that generates repulsion forces.

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

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

Variables:
  • target_population (Population) – Population affected by power-law repulsion forces.

  • source_population (Population) – Population generating power-law repulsion forces.

  • strength (np.ndarray or None) – Repulsion strength parameter for each agent in the target population.

  • max_distance (np.ndarray or None) – Maximum interaction distance for each agent in the target population.

  • p (int) – Power law exponent controlling the decay rate of repulsion. Higher values create steeper decay (stronger short-range repulsion).

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

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

  • parameters (dict) – Parameter configuration for the power-law repulsion:

  • p (int) – Power law exponent for the repulsion force. Common values:

Notes

Force Characteristics:

  • Monotonic Decay: Force decreases monotonically with distance

  • Finite Range: Zero force beyond max_distance

  • Customizable Steepness: Power exponent controls interaction range vs strength

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

  • KeyError – If required interaction parameters are missing in the configuration file.

  • ValueError – If power exponent p is not positive or if parameter shapes are incompatible.

Examples

Soft Repulsion Configuration:

PowerLawRepulsion:
    id: "soft_repulsion"
    p: 2
    parameters:
        mode: "Fixed"
        names: ["strength", "max_distance"]
        values:
            strength: 1.0
            max_distance: 3.0
__init__(target_population, source_population, config_path, name=None)[source]

Initialize the Interaction with target and source populations.

Parameters:
  • target_population (Population) – The population that will be affected by the interaction forces.

  • source_population (Population) – The population that will generate the interaction forces.

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

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

Raises:

FileNotFoundError – If the configuration file cannot be found.

get_interaction()[source]

Compute power-law repulsion forces between source and target populations.

This method calculates repulsive forces using the power-law formula with a smooth cutoff mechanism. The computation handles distance calculations, applies the power-law kernel, and includes numerical stability measures to prevent instabilities.

Returns:

np.ndarray – Repulsion forces array of shape (N_target, 2) where: - N_target is the number of agents in the target population - Each row represents the total repulsion force on one target agent in 2D space Force vectors point away from source agents (repulsive direction).

Notes

Algorithm Steps:

  1. Distance Computation: Calculate pairwise distances between all source-target pairs

  2. Cutoff Application: Apply smooth cutoff using reference force at max_distance

  3. Kernel Evaluation: Compute power-law repulsion kernel with bounds

  4. Force Assembly: Convert scalar forces to vector forces using relative positions

  5. Force Summation: Sum contributions from all source agents

Mathematical Implementation:

The force kernel is computed as:

\[K(r) = k \cdot \text{clip}\left( \frac{1}{r^p} - \frac{1}{r_{max}^p}, 0, F_{max} \right)\]

where: - \(k\) is the strength parameter - \(r\) is the inter-agent distance (with minimum threshold) - \(p\) is the power law exponent - \(r_{max}\) is the maximum interaction distance - \(F_{max} = 1000\) is the force magnitude cap

reset()[source]

Reset the interaction parameters to their initial values.

This method reinitializes interaction-specific parameters based on the configuration. It should be called before starting a new simulation.

class swarmsim.Interactions.PowerLawInteraction(target_population, source_population, config_path, name=None)[source]

Bases: Interaction

Power-law interaction with configurable attraction and repulsion components.

This interaction models a repulsive force that decays according to a power-law function with respect to the distance between agents. The strength of the force is determined by the power exponent p and is active within a defined maximum interaction range.

Parameters:
  • target_population (Population) – The population that receives interaction forces.

  • source_population (Population) – The population that generates interaction forces.

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

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

Variables:
  • target_population (Population) – Population affected by power-law forces.

  • source_population (Population) – Population generating power-law forces.

  • strength_attr (np.ndarray or None) – Attraction strength parameter(s).

  • strength_rep (np.ndarray or None) – Repulsion strength parameter(s).

  • max_distance (np.ndarray or None) – Maximum interaction distance parameter(s).

  • p_attr (int) – Power exponent for attraction term.

  • p_rep (int) – Power exponent for repulsion term.

  • is_attractive (bool) – Whether to allow attractive forces (negative values).

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

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

  • parameters (dict) – Parameter configuration for the power-law interaction:

    • mode : str - Parameter assignment mode

    • names : list - Parameter names [“strength_attr”, “strength_rep”, “max_distance”]

    • limits or values : dict - Parameter ranges or fixed values

  • p_attr (int) – Power exponent for the attraction term (typically 6-8).

  • p_rep (int) – Power exponent for the repulsion term (typically 12-16).

  • is_attractive (bool) – Whether to allow attractive forces. If False, forces are clipped to non-negative values.

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

  • KeyError – If required interaction parameters are missing in the configuration file.

  • ValueError – If parameter shapes are incompatible with population sizes.

Examples

Lennard-Jones-like Configuration:

PowerLawInteraction:
    id: "lj_like_interaction"
    p_attr: 6
    p_rep: 12
    is_attractive: true
    parameters:
        params_mode: "Fixed"
        params_names: ["strength_attr", "strength_rep", "max_distance"]
        params_values:
            strength_attr: 1.0
            strength_rep: 4.0
            max_distance: 5.0

Pure Repulsion Configuration:

PowerLawInteraction:
    id: "repulsion_only"
    p_attr: 6
    p_rep: 3
    is_attractive: false
    parameters:
        params_mode: "Fixed"
        params_names: ["strength_attr", "strength_rep", "max_distance"]
        params_values:
            strength_attr: 0.0
            strength_rep: 2.0
            max_distance: 3.0

Usage in Simulation:

from swarmsim.Interactions import PowerLawInteraction
from swarmsim.Populations import BrownianMotion

# Create populations
agents = BrownianMotion('agent_config.yaml')

# Create power-law self-interaction
interaction = PowerLawInteraction(
    target_population=agents,
    source_population=agents,
    config_path='powerlaw_config.yaml'
)

# Initialize parameters
interaction.reset()

# Compute forces
forces = interaction.get_interaction()

Force Profile Analysis:

import numpy as np
import matplotlib.pyplot as plt

# Plot force vs distance
r = np.linspace(0.5, 5.0, 100)
k_rep, k_attr = 4.0, 1.0
p_rep, p_attr = 12, 6

force = k_rep / r**p_rep - k_attr / r**p_attr

plt.plot(r, force)
plt.axhline(0, color='k', linestyle='--', alpha=0.5)
plt.xlabel('Distance')
plt.ylabel('Force')
plt.title('Power-Law Force Profile')

Equilibrium Distance Calculation:

The equilibrium distance where force is zero occurs when:

\[\frac{k_{rep}}{r_{eq}^{p_{rep}}} = \frac{k_{attr}}{r_{eq}^{p_{attr}}}\]

Solving for \(r_{eq}\):

\[r_{eq} = \left(\frac{k_{rep}}{k_{attr}}\right)^{\frac{1}{p_{rep} - p_{attr}}}\]
__init__(target_population, source_population, config_path, name=None)[source]

Initialize the Interaction with target and source populations.

Parameters:
  • target_population (Population) – The population that will be affected by the interaction forces.

  • source_population (Population) – The population that will generate the interaction forces.

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

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

Raises:

FileNotFoundError – If the configuration file cannot be found.

get_interaction()[source]

Computes the repulsion force exerted by source_population on target_population using a power-law function.

The repulsion force is computed as:

F_repulsion = strength * (1/distance^p - 1/max_distance^p)

where:
  • distance is the Euclidean distance between agents in target_population and source_population.

  • max_distance defines the interaction cutoff beyond which no force is applied.

  • p controls how rapidly the force decays with distance.

Returns:

np.ndarray – A (N1, D) array representing the repulsion force applied to each agent in target_population, where N1 is the number of agents in target_population and D is the dimensionality of the state space.

Notes

  • The function prevents division by zero by setting a minimum distance (1e-6).

  • The force is capped at 10 to avoid numerical instabilities.

reset()[source]

Reset the interaction parameters to their initial values.

This method reinitializes interaction-specific parameters based on the configuration. It should be called before starting a new simulation.

class swarmsim.Interactions.LennardJones(target_population, source_population, config_path, name=None)[source]

Bases: Interaction

Lennard-Jones interaction potential for agent-agent interactions.

This interaction implements the classic Lennard-Jones potential, which models both attractive and repulsive forces between agents. The potential combines a strong short-range repulsion (r^-12 term) with a weaker long-range attraction (r^-6 term), commonly used to model molecular interactions and agent clustering.

The interaction force deriving from a Lennard-Jones potential is:

\[F(r) = 24\epsilon \frac{1}{r^2} \left[ 2\left(\frac{\sigma}{r}\right)^{12} - \left(\frac{\sigma}{r}\right)^6 \right]\]

where: - \(\epsilon\) is the depth of the potential well (energy scale) - \(\sigma\) is the distance at which the potential is zero (length scale) - \(r\) is the distance between agents

Parameters:
  • target_population (Population) – The population that receives Lennard-Jones forces.

  • source_population (Population) – The population that generates Lennard-Jones forces.

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

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

Variables:
  • target_population (Population) – Population affected by Lennard-Jones forces.

  • source_population (Population) – Population generating Lennard-Jones forces.

  • epsilon (np.ndarray or None) – Energy scale parameter(s), shape depends on parameter configuration.

  • sigma (np.ndarray or None) – Length scale parameter(s), shape depends on parameter configuration.

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

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

  • parameters (dict) – Parameter configuration for the Lennard-Jones interaction. Typical structure:

    • mode : str - Parameter assignment mode (e.g., “Random”, “Fixed”)

    • names : list - List of parameter names [“epsilon”, “sigma”]

    • limits or values : dict - Parameter ranges or fixed values

Notes

Force Characteristics:

  • Equilibrium Distance: Force is zero at \(r = 2^{1/6}\sigma \approx 1.122\sigma\)

  • Attractive Region: \(r > 2^{1/6}\sigma\) (negative force, particles attract)

  • Repulsive Region: \(r < 2^{1/6}\sigma\) (positive force, particles repel)

  • Long-Range: Force decays as \(r^{-7}\) for large distances

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

  • KeyError – If required interaction parameters are missing in the configuration file.

  • ValueError – If parameter shapes are incompatible with population sizes.

__init__(target_population, source_population, config_path, name=None)[source]

Initialize the Interaction with target and source populations.

Parameters:
  • target_population (Population) – The population that will be affected by the interaction forces.

  • source_population (Population) – The population that will generate the interaction forces.

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

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

Raises:

FileNotFoundError – If the configuration file cannot be found.

get_interaction()[source]

Compute Lennard-Jones interaction forces between source and target populations.

This method calculates the attractive and repulsive forces between agents according to the Lennard-Jones potential. The computation handles both the attractive long-range and repulsive short-range components of the interaction.

Returns:

np.ndarray – Lennard-Jones forces array of shape (N_target, 2) where: - N_target is the number of agents in the target population - Each row represents the total LJ force on one target agent in 2D space Force vectors point away from source agents for repulsion, toward them for attraction.

Notes

Algorithm Steps:

  1. Distance Computation: Calculate pairwise distances between all source-target pairs

  2. Force Magnitude: Evaluate Lennard-Jones force equation for each pair

  3. Force Direction: Compute unit vectors for force direction

  4. Vector Forces: Combine magnitude and direction for vector forces

  5. Force Summation: Sum contributions from all source agents

reset()[source]

Reset the interaction parameters to their initial values.

This method reinitializes interaction-specific parameters based on the configuration. It should be called before starting a new simulation.

Package Overview

Interaction models in SwarmSim provide:

  • Physical Force Models: Realistic force-based interactions between agents

  • Species-Specific Interactions: Different behaviors between different agent types

  • Scalable Algorithms: Efficient computation for large populations

  • Configurable Parameters: Flexible tuning for different behaviors

  • Cutoff Mechanisms: Computational optimization through interaction limits

All interaction classes inherit from the base interaction interface, ensuring consistent integration with simulators and populations.

Core Modules

Base Interaction Interface

The foundation class defining the standard interface for all interaction implementations.

class swarmsim.Interactions.interaction.Interaction(target_population, source_population, config_path, name=None)[source]

Bases: ABC

Abstract base class for modeling interactions between agent populations.

This class provides the framework for implementing various types of inter-agent interactions such as repulsion, attraction, alignment, and collision avoidance. It defines how one population (source) influences another population (target) through force computations.

Parameters:
  • target_population (Population) – The population that receives the interaction forces.

  • source_population (Population) – The population that generates the interaction forces.

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

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

Variables:
  • target_population (Population) – The population affected by the interaction forces.

  • source_population (Population) – The population generating the interaction forces.

  • config (dict) – Configuration parameters specific to this interaction type.

  • param_config (dict) – Parameter configuration for interaction-specific parameters.

  • id (str) – Identifier for this interaction instance.

  • params (dict of np.ndarray or None) – Dictionary containing interaction-specific parameters.

  • params_shapes (dict of tuple or None) – Dictionary defining expected shapes for interaction parameters.

Config Requirements:
  • The YAML configuration file should contain parameters under the interaction’s section

  • id (str, optional) – Identifier for the interaction. Defaults to the class name.

  • parameters (dict, optional) – Configuration for interaction-specific parameters.

Notes

  • Subclasses must implement the abstract method get_interaction().

  • Interactions are computed at each simulation timestep.

Examples

Example YAML configuration for an interaction:

HarmonicRepulsion:
    id: "repulsion_interaction"
    parameters:
        params_mode: "Random"
        params_names: ["strength", "range"]
        params_limits:
            strength: [1.0, 5.0]
            range: [0.5, 2.0]

Example of implementing a custom interaction:

class CustomInteraction(Interaction):
    def get_interaction(self):
        # Compute interaction forces here

        return forces
__init__(target_population, source_population, config_path, name=None)[source]

Initialize the Interaction with target and source populations.

Parameters:
  • target_population (Population) – The population that will be affected by the interaction forces.

  • source_population (Population) – The population that will generate the interaction forces.

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

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

Raises:

FileNotFoundError – If the configuration file cannot be found.

reset()[source]

Reset the interaction parameters to their initial values.

This method reinitializes interaction-specific parameters based on the configuration. It should be called before starting a new simulation.

abstractmethod get_interaction()[source]

Compute the interaction forces between source and target populations.

This abstract method must be implemented by subclasses to define the specific interaction. It calculates the forces that the source population exerts on the target population based on their current states and interaction parameters.

Returns:

np.ndarray – Array of shape (N_target, state_dim) representing the interaction forces applied to each agent in the target population, where N_target is the number of agents in the target population and state_dim is the spatial dimension.

Notes

The returned forces will be added to the target population’s force accumulator and integrated by the numerical integrator.

Raises:

NotImplementedError – If called directly from the base class without implementation.

Key Features:

  • Standardized Interface: Consistent API across all interaction types

  • Force Computation: Efficient pairwise and collective force calculations

  • Species Support: Handle multi-species interaction scenarios

  • Performance Optimization: Built-in computational efficiency features

Lennard-Jones Interaction

Classic molecular interaction model combining attraction and repulsion.

class swarmsim.Interactions.lennard_jones.LennardJones(target_population, source_population, config_path, name=None)[source]

Bases: Interaction

Lennard-Jones interaction potential for agent-agent interactions.

This interaction implements the classic Lennard-Jones potential, which models both attractive and repulsive forces between agents. The potential combines a strong short-range repulsion (r^-12 term) with a weaker long-range attraction (r^-6 term), commonly used to model molecular interactions and agent clustering.

The interaction force deriving from a Lennard-Jones potential is:

\[F(r) = 24\epsilon \frac{1}{r^2} \left[ 2\left(\frac{\sigma}{r}\right)^{12} - \left(\frac{\sigma}{r}\right)^6 \right]\]

where: - \(\epsilon\) is the depth of the potential well (energy scale) - \(\sigma\) is the distance at which the potential is zero (length scale) - \(r\) is the distance between agents

Parameters:
  • target_population (Population) – The population that receives Lennard-Jones forces.

  • source_population (Population) – The population that generates Lennard-Jones forces.

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

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

Variables:
  • target_population (Population) – Population affected by Lennard-Jones forces.

  • source_population (Population) – Population generating Lennard-Jones forces.

  • epsilon (np.ndarray or None) – Energy scale parameter(s), shape depends on parameter configuration.

  • sigma (np.ndarray or None) – Length scale parameter(s), shape depends on parameter configuration.

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

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

  • parameters (dict) – Parameter configuration for the Lennard-Jones interaction. Typical structure:

    • mode : str - Parameter assignment mode (e.g., “Random”, “Fixed”)

    • names : list - List of parameter names [“epsilon”, “sigma”]

    • limits or values : dict - Parameter ranges or fixed values

Notes

Force Characteristics:

  • Equilibrium Distance: Force is zero at \(r = 2^{1/6}\sigma \approx 1.122\sigma\)

  • Attractive Region: \(r > 2^{1/6}\sigma\) (negative force, particles attract)

  • Repulsive Region: \(r < 2^{1/6}\sigma\) (positive force, particles repel)

  • Long-Range: Force decays as \(r^{-7}\) for large distances

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

  • KeyError – If required interaction parameters are missing in the configuration file.

  • ValueError – If parameter shapes are incompatible with population sizes.

__init__(target_population, source_population, config_path, name=None)[source]

Initialize the Interaction with target and source populations.

Parameters:
  • target_population (Population) – The population that will be affected by the interaction forces.

  • source_population (Population) – The population that will generate the interaction forces.

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

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

Raises:

FileNotFoundError – If the configuration file cannot be found.

reset()[source]

Reset the interaction parameters to their initial values.

This method reinitializes interaction-specific parameters based on the configuration. It should be called before starting a new simulation.

get_interaction()[source]

Compute Lennard-Jones interaction forces between source and target populations.

This method calculates the attractive and repulsive forces between agents according to the Lennard-Jones potential. The computation handles both the attractive long-range and repulsive short-range components of the interaction.

Returns:

np.ndarray – Lennard-Jones forces array of shape (N_target, 2) where: - N_target is the number of agents in the target population - Each row represents the total LJ force on one target agent in 2D space Force vectors point away from source agents for repulsion, toward them for attraction.

Notes

Algorithm Steps:

  1. Distance Computation: Calculate pairwise distances between all source-target pairs

  2. Force Magnitude: Evaluate Lennard-Jones force equation for each pair

  3. Force Direction: Compute unit vectors for force direction

  4. Vector Forces: Combine magnitude and direction for vector forces

  5. Force Summation: Sum contributions from all source agents

Power Law Repulsion

Simple repulsive interaction following power law decay.

class swarmsim.Interactions.power_law_repulsion.PowerLawRepulsion(target_population, source_population, config_path, name=None)[source]

Bases: Interaction

Pure power-law repulsion interaction with finite range cutoff.

This interaction implements a repulsive force that decays according to an inverse power law with respect to inter-agent distance. Unlike the more general PowerLawInteraction, this class focuses specifically on repulsion with a clean cutoff mechanism that ensures zero force at the maximum interaction distance.

The repulsion force follows:

\[F(r) = k \left( \frac{1}{r^p} - \frac{1}{r_{max}^p} \right)\]

for \(r < r_{max}\), and \(F(r) = 0\) for \(r \geq r_{max}\), where: - \(k\) is the repulsion strength parameter - \(r\) is the inter-agent distance - \(p\) is the power law exponent - \(r_{max}\) is the maximum interaction distance

The subtraction term ensures the force smoothly approaches zero at the cutoff distance, preventing discontinuous force jumps that can cause numerical instabilities.

Parameters:
  • target_population (Population) – The population that receives repulsion forces.

  • source_population (Population) – The population that generates repulsion forces.

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

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

Variables:
  • target_population (Population) – Population affected by power-law repulsion forces.

  • source_population (Population) – Population generating power-law repulsion forces.

  • strength (np.ndarray or None) – Repulsion strength parameter for each agent in the target population.

  • max_distance (np.ndarray or None) – Maximum interaction distance for each agent in the target population.

  • p (int) – Power law exponent controlling the decay rate of repulsion. Higher values create steeper decay (stronger short-range repulsion).

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

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

  • parameters (dict) – Parameter configuration for the power-law repulsion:

  • p (int) – Power law exponent for the repulsion force. Common values:

Notes

Force Characteristics:

  • Monotonic Decay: Force decreases monotonically with distance

  • Finite Range: Zero force beyond max_distance

  • Customizable Steepness: Power exponent controls interaction range vs strength

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

  • KeyError – If required interaction parameters are missing in the configuration file.

  • ValueError – If power exponent p is not positive or if parameter shapes are incompatible.

Examples

Soft Repulsion Configuration:

PowerLawRepulsion:
    id: "soft_repulsion"
    p: 2
    parameters:
        mode: "Fixed"
        names: ["strength", "max_distance"]
        values:
            strength: 1.0
            max_distance: 3.0
__init__(target_population, source_population, config_path, name=None)[source]

Initialize the Interaction with target and source populations.

Parameters:
  • target_population (Population) – The population that will be affected by the interaction forces.

  • source_population (Population) – The population that will generate the interaction forces.

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

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

Raises:

FileNotFoundError – If the configuration file cannot be found.

reset()[source]

Reset the interaction parameters to their initial values.

This method reinitializes interaction-specific parameters based on the configuration. It should be called before starting a new simulation.

get_interaction()[source]

Compute power-law repulsion forces between source and target populations.

This method calculates repulsive forces using the power-law formula with a smooth cutoff mechanism. The computation handles distance calculations, applies the power-law kernel, and includes numerical stability measures to prevent instabilities.

Returns:

np.ndarray – Repulsion forces array of shape (N_target, 2) where: - N_target is the number of agents in the target population - Each row represents the total repulsion force on one target agent in 2D space Force vectors point away from source agents (repulsive direction).

Notes

Algorithm Steps:

  1. Distance Computation: Calculate pairwise distances between all source-target pairs

  2. Cutoff Application: Apply smooth cutoff using reference force at max_distance

  3. Kernel Evaluation: Compute power-law repulsion kernel with bounds

  4. Force Assembly: Convert scalar forces to vector forces using relative positions

  5. Force Summation: Sum contributions from all source agents

Mathematical Implementation:

The force kernel is computed as:

\[K(r) = k \cdot \text{clip}\left( \frac{1}{r^p} - \frac{1}{r_{max}^p}, 0, F_{max} \right)\]

where: - \(k\) is the strength parameter - \(r\) is the inter-agent distance (with minimum threshold) - \(p\) is the power law exponent - \(r_{max}\) is the maximum interaction distance - \(F_{max} = 1000\) is the force magnitude cap

Power Law Interaction

Generalized power law interaction that can be attractive or repulsive.

class swarmsim.Interactions.power_law_interaction.PowerLawInteraction(target_population, source_population, config_path, name=None)[source]

Bases: Interaction

Power-law interaction with configurable attraction and repulsion components.

This interaction models a repulsive force that decays according to a power-law function with respect to the distance between agents. The strength of the force is determined by the power exponent p and is active within a defined maximum interaction range.

Parameters:
  • target_population (Population) – The population that receives interaction forces.

  • source_population (Population) – The population that generates interaction forces.

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

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

Variables:
  • target_population (Population) – Population affected by power-law forces.

  • source_population (Population) – Population generating power-law forces.

  • strength_attr (np.ndarray or None) – Attraction strength parameter(s).

  • strength_rep (np.ndarray or None) – Repulsion strength parameter(s).

  • max_distance (np.ndarray or None) – Maximum interaction distance parameter(s).

  • p_attr (int) – Power exponent for attraction term.

  • p_rep (int) – Power exponent for repulsion term.

  • is_attractive (bool) – Whether to allow attractive forces (negative values).

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

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

  • parameters (dict) – Parameter configuration for the power-law interaction:

    • mode : str - Parameter assignment mode

    • names : list - Parameter names [“strength_attr”, “strength_rep”, “max_distance”]

    • limits or values : dict - Parameter ranges or fixed values

  • p_attr (int) – Power exponent for the attraction term (typically 6-8).

  • p_rep (int) – Power exponent for the repulsion term (typically 12-16).

  • is_attractive (bool) – Whether to allow attractive forces. If False, forces are clipped to non-negative values.

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

  • KeyError – If required interaction parameters are missing in the configuration file.

  • ValueError – If parameter shapes are incompatible with population sizes.

Examples

Lennard-Jones-like Configuration:

PowerLawInteraction:
    id: "lj_like_interaction"
    p_attr: 6
    p_rep: 12
    is_attractive: true
    parameters:
        params_mode: "Fixed"
        params_names: ["strength_attr", "strength_rep", "max_distance"]
        params_values:
            strength_attr: 1.0
            strength_rep: 4.0
            max_distance: 5.0

Pure Repulsion Configuration:

PowerLawInteraction:
    id: "repulsion_only"
    p_attr: 6
    p_rep: 3
    is_attractive: false
    parameters:
        params_mode: "Fixed"
        params_names: ["strength_attr", "strength_rep", "max_distance"]
        params_values:
            strength_attr: 0.0
            strength_rep: 2.0
            max_distance: 3.0

Usage in Simulation:

from swarmsim.Interactions import PowerLawInteraction
from swarmsim.Populations import BrownianMotion

# Create populations
agents = BrownianMotion('agent_config.yaml')

# Create power-law self-interaction
interaction = PowerLawInteraction(
    target_population=agents,
    source_population=agents,
    config_path='powerlaw_config.yaml'
)

# Initialize parameters
interaction.reset()

# Compute forces
forces = interaction.get_interaction()

Force Profile Analysis:

import numpy as np
import matplotlib.pyplot as plt

# Plot force vs distance
r = np.linspace(0.5, 5.0, 100)
k_rep, k_attr = 4.0, 1.0
p_rep, p_attr = 12, 6

force = k_rep / r**p_rep - k_attr / r**p_attr

plt.plot(r, force)
plt.axhline(0, color='k', linestyle='--', alpha=0.5)
plt.xlabel('Distance')
plt.ylabel('Force')
plt.title('Power-Law Force Profile')

Equilibrium Distance Calculation:

The equilibrium distance where force is zero occurs when:

\[\frac{k_{rep}}{r_{eq}^{p_{rep}}} = \frac{k_{attr}}{r_{eq}^{p_{attr}}}\]

Solving for \(r_{eq}\):

\[r_{eq} = \left(\frac{k_{rep}}{k_{attr}}\right)^{\frac{1}{p_{rep} - p_{attr}}}\]
__init__(target_population, source_population, config_path, name=None)[source]

Initialize the Interaction with target and source populations.

Parameters:
  • target_population (Population) – The population that will be affected by the interaction forces.

  • source_population (Population) – The population that will generate the interaction forces.

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

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

Raises:

FileNotFoundError – If the configuration file cannot be found.

reset()[source]

Reset the interaction parameters to their initial values.

This method reinitializes interaction-specific parameters based on the configuration. It should be called before starting a new simulation.

get_interaction()[source]

Computes the repulsion force exerted by source_population on target_population using a power-law function.

The repulsion force is computed as:

F_repulsion = strength * (1/distance^p - 1/max_distance^p)

where:
  • distance is the Euclidean distance between agents in target_population and source_population.

  • max_distance defines the interaction cutoff beyond which no force is applied.

  • p controls how rapidly the force decays with distance.

Returns:

np.ndarray – A (N1, D) array representing the repulsion force applied to each agent in target_population, where N1 is the number of agents in target_population and D is the dimensionality of the state space.

Notes

  • The function prevents division by zero by setting a minimum distance (1e-6).

  • The force is capped at 10 to avoid numerical instabilities.

Harmonic Repulsion

Spring-like repulsive interaction following Hooke’s law.

class swarmsim.Interactions.harmonic_repulsion.HarmonicRepulsion(target_population, source_population, config_path, name=None)[source]

Bases: Interaction

Harmonic repulsion interaction with finite interaction range.

This interaction implements a linearly decaying repulsive force between agents from two different populations. The repulsion follows a harmonic potential that provides short-range repulsion up to a finite interaction range.

The repulsion force magnitude follows:

\[ \begin{align}\begin{aligned}F_i = \sum_{j \in population} F_{ij}(r_{ij})\\\begin{split}F_{ij}(r_{ij}) = \begin{cases} -k (r_{max} - r_{ij}) \hat{r}_{ij} & \text{if } r_{ij} < r_{max} \\ 0 & \text{if } r_{ij} \geq r_{max} \end{cases}\end{split}\end{aligned}\end{align} \]

where: - \(F_i\) is the total force on agent i - \(k\) is the strength parameter - \(r_{max}\) is the maximum interaction distance - \(r_{ij}\) is the distance between agents i and j - \(\hat{r}_{ij}\) is the unit vector joining agents i and j

Parameters:
  • target_population (Population) – The population that receives repulsion forces.

  • source_population (Population) – The population that generates repulsion forces.

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

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

Variables:
  • target_population (Population) – Population affected by repulsion forces.

  • source_population (Population) – Population generating repulsion forces.

  • strength (np.ndarray or None) – Repulsion strength parameter(s), shape depends on parameter configuration.

  • distance (np.ndarray or None) – Maximum interaction distance parameter(s), shape depends on parameter configuration.

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

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

  • strength (float or list) – Repulsion strength parameter(s)

  • distance (float or list) – Maximum interaction distance parameter(s)

  • parameters (dict) – Parameter configuration for the harmonic repulsion. Typical structure:

    • mode : str - Parameter assignment mode

Notes

Force Characteristics:

  • Linear Decay: Force decreases linearly with distance until cutoff

  • Finite Range: No interaction beyond maximum distance

  • Pairwise Computation: All source-target agent pairs are evaluated

  • Vectorized: Efficient computation using NumPy broadcasting

Parameter Flexibility:

Parameters can be configured as: - Fixed values: Same for all interactions - Random ranges: Sampled for each agent or interaction - Population-dependent: Different values for different populations

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

  • KeyError – If required interaction parameters are missing in the configuration file.

__init__(target_population, source_population, config_path, name=None)[source]

Initialize the Interaction with target and source populations.

Parameters:
  • target_population (Population) – The population that will be affected by the interaction forces.

  • source_population (Population) – The population that will generate the interaction forces.

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

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

Raises:

FileNotFoundError – If the configuration file cannot be found.

reset()[source]

Reset the interaction parameters to their initial values.

This method reinitializes interaction-specific parameters based on the configuration. It should be called before starting a new simulation.

get_interaction()[source]

Compute harmonic repulsion forces between source and target populations.

This method calculates the repulsive forces that source population agents exert on target population agents using the harmonic repulsion model. Forces decay linearly with distance and have finite interaction range.

Returns:

np.ndarray – Repulsion forces array of shape (N_target, D) where: - N_target is the number of agents in the target population - D is the spatial dimension (typically 2 or 3) Each row represents the total repulsion force on one target agent.

Notes

Algorithm Steps:

  1. Distance Computation: Calculate pairwise distances between all source-target pairs

  2. Range Filtering: Identify agent pairs within interaction range

  3. Force Calculation: Apply harmonic repulsion formula for nearby pairs

  4. Force Summation: Sum contributions from all source agents for each target

Numerical Stability:

  • Minimum distance threshold (1e-6) prevents division by zero

  • Vectorized operations ensure computational efficiency

  • Broadcasting handles different parameter shapes automatically

Best Practices

  1. Start Simple: Begin with well-tested interaction models

  2. Validate Results: Compare with known analytical or experimental results

  3. Performance Testing: Profile interaction computation for large populations

  4. Visualization: Use trajectory plots to verify interaction behaviors

  5. Documentation: Document parameter meanings and typical value ranges