Controllers Package

The Controllers package provides control algorithms and strategies for guiding agent behavior in multi-agent simulations. Controllers implement various coordination, shepherding, and guidance strategies that can be applied to populations of agents.

Controllers Module

This module provides interfaces and implementations for controlling agent behavior in multi-agent simulations. Controllers compute control actions that influence agent dynamics based on current states and objectives.

Available Controllers

Controller

Abstract base class defining the interface for all controller types.

ShepherdingLamaController

Shepherding controller that guides one population using another population as herders. Implements the LAMA (Large Area Multi-agent) shepherding algorithm.

GaussianRepulsion

Implements spatially-varying repulsion forces with Gaussian intensity profiles.

LightPattern

Projects spatial light patterns from image files onto the environment for phototaxis control.

Temporal_pulses

Generates temporally-varying pulse signals with periodic on/off patterns.

RectangularFeedback

Provides binary feedback based on agent orientation relative to radial direction.

AngularFeedback

Creates dynamic visual feedback using angular light patterns behind agents.

Key Features

  • Modular Design: Easy to implement custom control strategies

  • Multi-Population Support: Controllers can coordinate multiple populations

  • Spatial Control: Support for spatially-varying control fields

  • Configurable Timing: Controllers can operate at different sampling rates

Examples

Basic controller usage:

from swarmsim.Controllers import ShepherdingLamaController
from swarmsim.Populations import BrownianMotion
from swarmsim.Environments import EmptyEnvironment

# Create populations and environment
herders = BrownianMotion('config.yaml', 'Herders')
targets = BrownianMotion('config.yaml', 'Targets')
environment = EmptyEnvironment('config.yaml')

# Create controller
controller = ShepherdingLamaController(
    population=targets,
    environment=environment,
    config_path='config.yaml',
    other_populations=[herders]
)

# Get control action
control_input = controller.get_action()

Configuration Examples

Shepherding controller:

ShepherdingLamaController:
    dt: 0.1
    gain: 2.0
    target_radius: 5.0

Light pattern controller:

LightPattern:
    pattern_path: ../Configuration/Config_data/BCL.jpeg
    dt: 0.1

This defines a controller that projects the content of BCL.jpeg over the environment and updates the control applied to agents every 0.1 simulation time units.

Modules

  • base_controller: Defines the abstract Controller class interface

  • shepherding_lama_controller: Implements shepherding strategies

  • spatial_inputs: Implements spatially heterogeneous control laws

Package Overview

Controllers in SwarmSim enable sophisticated multi-agent coordination through:

  • Shepherding Algorithms: Guide groups of agents toward specific goals

  • Formation Control: Maintain desired spatial arrangements

  • Coordination Strategies: Implement collective decision-making

  • Adaptive Control: Respond dynamically to changing conditions

  • Hierarchical Control: Multi-level control architectures

All controllers inherit from the base controller interface, ensuring consistent integration with the simulation framework.

Core Modules

Base Controller Interface

The base controller defines the standard interface that all controllers must implement.

class swarmsim.Controllers.base_controller.Controller(population, environment=None, config_path=None, other_populations=None)[source]

Bases: ABC

Abstract base class for implementing control strategies.

This class provides the interface for controllers that compute control actions to influence agent behaviors. Controllers can access population states, environment information, and other populations to make informed control decisions.

Parameters:
  • population (Population) – The target population that this controller will influence.

  • environment (Environment, optional) – The environment where the agents operate. Can be None if environmental information is not needed for control.

  • config_path (str, optional) – Path to the YAML configuration file containing controller parameters.

  • other_populations (list of Population, optional) – List of other populations that may influence the control strategy.

Variables:
  • population (Population) – The target population being controlled.

  • environment (Environment or None) – The environment instance (None if environmental information are not relevant).

  • other_populations (list of Population or None) – List of other populations required to compute the control action.

  • config (dict) – Configuration parameters specific to this controller class.

  • dt (float) – Sampling time interval between two consecutive control actions.

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

  • dt (float) – Sampling time of the controller (time interval between consecutive control actions).

Notes

  • Subclasses must implement the abstract method get_action() to define the control strategy.

  • The get_action_in_space() method can be optionally overridden for spatially non-uniform control actions.

  • Controllers operate at discrete time intervals specified by dt.

Examples

Example YAML configuration for a controller:

MyController:
    dt: 0.1

This configuration sets the controller sampling time to 0.1 seconds.

__init__(population, environment=None, config_path=None, other_populations=None)[source]

Initialize the Controller with the target population and optional components.

Parameters:
  • population (Population) – The population that this controller will influence.

  • environment (Environment, optional) – The environment where agents operate. Default is None.

  • config_path (str, optional) – Path to the YAML configuration file. Default is None.

  • other_populations (list of Population, optional) – Other populations that may influence control decisions. Default is None.

abstractmethod get_action()[source]

Compute the control action for the target population.

This abstract method must be implemented by subclasses to define the specific control strategy. The method should use the current state of the population, environment, and other available information to compute appropriate control inputs.

Returns:

np.ndarray – Control action array of shape (N, input_dim) where N is the number of agents in the target population and input_dim is the dimensionality of the control input.

Notes

This is the core method that defines the controller behavior and must be overridden in subclasses.

get_action_in_space(positions)[source]

Computes spatially varying control actions at specified positions.

This method provides control actions at arbitrary spatial locations. It can be overridden by subclasses that implement spatially varying control strategies.

Parameters:

positions (np.ndarray) – Array of shape (num_positions, state_dim) specifying the positions where control actions should be evaluated.

Returns:

np.ndarray – Control action array of shape (num_positions, input_dim) representing the control field values at the specified positions.

Notes

The default implementation returns None. Subclasses should override this method if they implement spatially varying control fields.

Key Features:

  • Standardized Interface: Consistent API for all controller implementations

  • Flexible Integration: Easy integration with different agent populations

  • State Management: Handle controller state and memory

  • Performance Monitoring: Built-in performance tracking capabilities

Shepherding Controller

Advanced shepherding algorithms for guiding agent groups toward target locations.

class swarmsim.Controllers.shepherding_lama_controller.ShepherdingLamaController(population, targets, environment=None, config_path=None)[source]

Bases: Controller

Implementation of the shepherding controller implemented in Lama (2024).

This controller implements the herding control law from Lama (2024) for shepherding applications. It coordinates herder agents to guide target agents toward a goal region by positioning herders behind the most distant targets and applying repulsive forces to drive the targets toward the goal.

The controller selects the farthest target from the goal within each herder’s sensing radius and positions the herder behind that target at a specified distance. This creates a shepherding behavior where herders push targets toward the goal region.

Parameters:
  • population (Population) – The herder population that will be controlled by this controller.

  • targets (Population) – The target population that needs to be shepherded to the goal.

  • environment (ShepherdingEnvironment, optional) – The shepherding environment containing goal information. Default is None.

  • config_path (str, optional) – Path to the YAML configuration file containing controller parameters. Default is None.

Variables:
  • herders (Population) – Reference to the herder population (same as population).

  • targets (Population) – The target population being shepherded.

  • environment (ShepherdingEnvironment) – The shepherding environment with goal position information.

  • xi (float) – Sensing radius of herder agents for target detection.

  • v_h (float) – Speed of herders when no targets are detected within sensing radius.

  • alpha (float) – Attraction force constant toward the selected target position.

  • lmbda (float) – Lambda parameter (currently not used in implementation).

  • delta (float) – Displacement distance to position herders behind targets.

  • rho_g (float) – Radius of the goal region.

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

  • dt (float) – Sampling time of the controller (time interval between control actions).

  • xi (float, optional) – Sensing radius of herder agents. Default is 15.

  • v_h (float, optional) – Speed of herders when no targets are detected. Default is 12.

  • alpha (float, optional) – Attraction force constant to the selected target. Default is 3.

  • lambda (float, optional) – Lambda parameter (not currently used). Default is 3.

  • delta (float, optional) – Displacement to go behind a target. Default is 1.5.

  • rho_g (float, optional) – Radius of the goal region. Default is 5.

Notes

The controller algorithm works as follows:

  1. Target Selection: Each herder identifies targets within its sensing radius xi

  2. Distance Calculation: Among detected targets, select the one farthest from the goal

  3. Position Calculation: Position herder behind the selected target at distance delta

  4. Control Action: Apply attractive force with strength alpha toward the desired position

  5. No Target Behavior: If no targets detected, move away from goal with speed v_h

The controller assumes a shepherding environment with a defined goal position and requires both herder and target populations to be properly initialized.

Examples

Example YAML configuration:

ShepherdingLamaController:
    dt: 0.1
    xi: 15
    v_h: 12
    alpha: 3
    lambda: 3
    delta: 1.5
    rho_g: 5

This defines a ShepherdingLamaController with xi=15, v_h=12, alpha=3, lambda=3, delta=1.5, rho_g=5. This controller is able to steer a population of targets to the goal region.

References

Lama, Andrea, and Mario di Bernardo. “Shepherding and herdability in complex multiagent systems.” Physical Review Research 6.3 (2024): L032012

__init__(population, targets, environment=None, config_path=None)[source]

Initialize the LAMA shepherding controller.

Parameters:
  • population (Population) – The herder population that will be controlled.

  • targets (Population) – The target population to be shepherded.

  • environment (ShepherdingEnvironment, optional) – The shepherding environment containing goal information. Default is None.

  • config_path (str, optional) – Path to the configuration file. Default is None.

Raises:

TypeError – If environment is not a ShepherdingEnvironment instance.

get_action()[source]

Compute the shepherding control action for herder agents.

This method implements the LAMA shepherding algorithm by: 1. Finding targets within each herder’s sensing radius 2. Selecting the target farthest from the goal for each herder 3. Computing desired herder positions behind selected targets 4. Apply attractive force toward desired herder positions

Returns:

np.ndarray – Control actions of shape (N_herders, 2) representing force vectors for each herder agent in the x and y directions.

Notes

The algorithm follows these steps:

  1. Target Detection: For each herder, find all targets within sensing radius xi

  2. Target Selection: Each herder selects the target farthest from the goal

  3. Position Calculation: Compute desired position behind selected target

  4. Force Calculation: Computes attractive force toward desired position

If no targets are within sensing range: - Herders inside goal region (distance < rho_g) remain stationary - Herders outside goal region move away from origin with speed v_h

If a target is selected: - Apply attractive force: alpha * (desired_position - current_position) - Desired position is behind target: target_pos + delta * target_unit_vector

Key Features:

  • Multi-agent Shepherding: Coordinate multiple shepherd agents

  • Adaptive Strategies: Dynamic adjustment based on group behavior

  • Obstacle Avoidance: Navigate around environmental obstacles

  • Performance Optimization: Efficient algorithms for large-scale groups

Spatial Input Processing

Utilities for processing spatial information and environmental inputs.

class swarmsim.Controllers.spatial_inputs.GaussianRepulsion(population, environment, config_path=None)[source]

Bases: Controller

Implements a spatially-varying radial repulsion force with Gaussian intensity profile.

This controller creates a repulsion field centered at the origin with intensity that follows a 2D Gaussian distribution. Agents experience repulsive forces that push them away from the center, with force magnitude determined by the Gaussian profile and direction determined by their position relative to the origin.

The controller uses spatial interpolation to efficiently compute force values at agent positions from a discretized Gaussian field defined on a regular grid.

Parameters:
  • population (Population) – The population of agents to be controlled by this repulsion field.

  • environment (Environment) – The environment providing spatial boundaries and dimensions.

  • config_path (str, optional) – Path to the YAML configuration file containing controller parameters. Default is None.

Variables:
  • disc_pts (int) – Number of discretization points along each axis for the Gaussian field grid.

  • interpolator (scipy.interpolate.RegularGridInterpolator) – Interpolator object for efficient evaluation of the Gaussian field at arbitrary positions.

Config Requirements:
  • The YAML configuration file should contain the following parameters

  • dt (float) – Sampling time of the controller.

  • disc_pts (int, optional) – Number of points in the discretization grid for the Gaussian input field. Default is 30.

Notes

The repulsion force is computed as:

F(x, y) = G(x, y) * (x, y) / ||x, y||

where: - G(x, y) is the Gaussian intensity at position (x, y) - (x, y) / ||x, y|| is the unit vector pointing away from the origin - The result is a radial repulsion force with Gaussian-modulated strength

The Gaussian field is pre-computed on a regular grid and interpolated for efficiency. The grid spans the environment dimensions with the specified number of discretization points.

Examples

Example YAML configuration:

GaussianRepulsion:
    dt: 0.1
    disc_pts: 50
__init__(population, environment, config_path=None)[source]

Initialize the Gaussian repulsion controller.

Parameters:
  • population (Population) – The population to be controlled by the repulsion field.

  • environment (Environment) – The environment providing spatial dimensions.

  • config_path (str, optional) – Path to the configuration file. Default is None.

get_action()[source]

Compute the Gaussian repulsion forces for all agents.

This method evaluates the Gaussian intensity field at each agent’s position and computes radial repulsion forces pointing away from the origin. The force magnitude is modulated by the Gaussian intensity profile.

Returns:

np.ndarray – Repulsion forces of shape (N, 2) where N is the number of agents. Each row contains the [x, y] force components for the corresponding agent.

Notes

The repulsion force computation involves:

  1. Intensity Evaluation: Sample Gaussian field at agent positions using interpolation

  2. Distance Calculation: Compute distance from each agent to the origin

  3. Direction Calculation: Compute unit vectors pointing away from origin

  4. Force Combination: Multiply intensity by direction to get final forces

Agents at the exact origin (distance = 0) are assigned a small offset to avoid division by zero in the direction calculation.

class swarmsim.Controllers.spatial_inputs.LightPattern(population, environment, config_path=None)[source]

Bases: Controller

Projects a spatial light pattern loaded from an image file onto the environment.

This controller reads an image file and uses it to create a spatial control field that agents can sense. The image is mapped to the environment coordinates, and the blue channel intensity is used as the control signal. This enables complex spatial patterns to be used for agent guidance and control.

The controller is particularly useful for biological agent models where light intensity can influence agent behavior, such as phototaxis or photophobic responses.

Parameters:
  • population (Population) – The population of agents that will sense the light pattern.

  • environment (Environment) – The environment providing spatial boundaries and coordinate mapping.

  • config_path (str, optional) – Path to the YAML configuration file containing controller parameters. Default is None.

Variables:
Config Requirements:
  • The YAML configuration file must contain the following parameters

  • dt (float) – Sampling time of the controller.

  • pattern_path (str) – Path (relative or absolute) to the image file containing the light pattern. Supported formats include JPEG, PNG, and other common image formats.

Notes

The controller implementation:

  1. Image Loading: Reads the specified image file using matplotlib

  2. Coordinate Mapping: Maps image pixels to environment coordinates

  3. Channel Extraction: Uses the blue channel (RGB[2]) as intensity values

  4. Normalization: Normalizes pixel values to [0, 1] range

  5. Interpolation: Creates interpolator for continuous intensity evaluation

Agents outside the environment boundaries are clamped to the boundary values to ensure consistent behavior at the edges.

Examples

Example YAML configuration:

LightPattern:
    dt: 0.1
    pattern_path: ../Configuration/Config_data/BCL.jpeg
__init__(population, environment, config_path=None)[source]

Initialize the light pattern controller.

Parameters:
  • population (Population) – The population that will sense the light pattern.

  • environment (Environment) – The environment providing spatial coordinate mapping.

  • config_path (str, optional) – Path to the configuration file. Default is None.

Raises:
  • FileNotFoundError – If the specified pattern image file cannot be found.

  • KeyError – If the required pattern_path parameter is missing from configuration.

get_action()[source]

Get the light intensity values at the current agent positions.

This method evaluates the light pattern at each agent’s current position, applying boundary clamping to ensure agents outside the environment boundaries receive the edge intensity values.

Returns:

np.ndarray – Light intensity values of shape (N, 1) where N is the number of agents. Values are normalized to the range [0, 1] based on the image data.

Notes

The method performs the following steps:

  1. Boundary Clamping: Clip agent positions to environment boundaries

  2. Interpolation: Evaluate light pattern at clamped positions

  3. Reshaping: Return as column vector for compatibility

Agents outside the defined pattern area receive the boundary values.

get_action_in_space(positions)[source]

Evaluate the light pattern at specified spatial positions.

This method allows querying the light intensity at arbitrary positions in the environment, useful for analysis and visualization.

Parameters:

positions (np.ndarray) – Array of shape (num_positions, 2) containing [x, y] coordinates where light intensity should be evaluated.

Returns:

np.ndarray – Light intensity values of shape (num_positions, 1) at the specified positions. Values are normalized to the range [0, 1] based on the image data.

Notes

This method provides direct access to the interpolated light pattern.

Useful for: - Analyzing light patterns before simulation - Creating visualizations of the control field - Implementing predictive control strategies

class swarmsim.Controllers.spatial_inputs.Temporal_pulses(population, environment, config_path=None)[source]

Bases: Controller

Implements a temporally-varying control signal with periodic on/off pulses.

This controller generates a uniform control signal that alternates between ‘on’ (value = 1) and ‘off’ (value = 0) states with a specified period. The signal is spatially uniform but varies in time, creating synchronized temporal stimulation across all agents.

The controller is useful for studying temporal entrainment, circadian rhythm effects, or synchronized behavioral responses in agent populations.

Parameters:
  • population (Population) – The population of agents to receive the temporal pulse signal.

  • Period (float, optional) – The period of the temporal pulses (time for one complete on/off cycle).

  • config_path (str, optional) – Path to the YAML configuration file containing controller parameters. Default is None.

Variables:
  • T (float) – Period of the temporal pulses (time for one complete on/off cycle).

  • current_time (float) – Current simulation time, updated at each control action.

Config Requirements:
  • The YAML configuration file should contain the following parameters

  • dt (float) – Sampling time of the controller.

  • Period (float, optional) – Period of the temporal pulses in simulation time units. Default is 1.0.

Notes

The pulse pattern follows a square wave: - First half of period (0 ≤ t mod T < T/2): Signal = 1 (ON) - Second half of period (T/2 ≤ t mod T < T): Signal = 0 (OFF)

The controller maintains its own internal time counter that is incremented by dt at each call to get_action().

Examples

Example YAML configuration:

Temporal_pulses:
    dt: 0.01
    Period: 2.0

This creates pulses with 2-second period (1 second ON, 1 second OFF).

__init__(population, environment, config_path=None)[source]

Initialize the temporal pulse controller.

Parameters:
  • population (Population) – The population to receive temporal pulse signals.

  • environment (Environment) – The environment (required for interface compatibility).

  • config_path (str, optional) – Path to the configuration file. Default is None.

get_action()[source]

Generate the current temporal pulse state for all agents.

This method updates the internal time counter and returns the current pulse state (1 for ON, 0 for OFF) based on the temporal position within the pulse period.

Returns:

np.ndarray – Pulse state array of shape (N, 1) where N is the number of agents. All agents receive the same pulse value: 1 during ON phase, 0 during OFF phase.

Notes

The method performs the following:

  1. Time Update: Increment internal time by dt

  2. Phase Calculation: Compute position within current pulse period

  3. State Determination: Return 1 if in first half of period, 0 otherwise

The pulse timing is deterministic and synchronized across all agents, making it suitable for studying collective temporal responses.

get_action_in_space(positions)[source]

Returns the light intensity at the position specified in the positions vector

Parameters:

positions (numpy.Array(num_positions, num_dimensions)) – The positions where you want to retrieve the value of the control action

class swarmsim.Controllers.spatial_inputs.AngularFeedback(population, environment, config_path=None)[source]

Bases: Controller

Implements dynamic visual feedback using angular light patterns behind agents.

This controller creates dynamic light patterns by drawing lines behind each agent based on their current position and a specified angular width. The patterns are updated periodically and projected as visual feedback that agents can sense.

The controller generates wedge-shaped light patterns extending radially outward from each agent’s position, creating a dynamic feedback system that can influence agent behavior through phototaxis or photophobic responses.

Parameters:
  • population (Population) – The population of agents for which light patterns will be generated.

  • environment (Environment) – The environment providing spatial boundaries and coordinate mapping.

  • config_path (str, optional) – Path to the YAML configuration file containing controller parameters. Default is None.

Variables:
  • line_width (int) – Width of the lines drawn in the light pattern (in pixels).

  • angle_width (float) – Angular width of the wedge pattern behind each agent (in radians).

  • agent_distance (float) – Distance behind each agent where the wedge pattern starts.

  • update_time (float) – Time interval between pattern updates (in simulation time units).

  • last_update (float) – Timestamp of the last pattern update.

  • current_time (float) – Current simulation time.

  • x (np.ndarray) – Grid x-coordinates for spatial discretization.

  • y (np.ndarray) – Grid y-coordinates for spatial discretization.

  • interpolator (scipy.interpolate.RegularGridInterpolator) – Interpolator for evaluating light intensity at arbitrary positions.

  • img_count (int) – Counter for saved debug images.

Config Requirements:
  • The YAML configuration file should contain the following parameters

  • dt (float) – Sampling time of the controller.

  • line_width (int, optional) – Width of the drawn lines in pixels. Default is 3.

  • angle_width (float, optional) – Angular width of the wedge pattern in radians. Default is 0.5 * 45 * π/180 (22.5 degrees).

  • agent_distance (float, optional) – Distance behind agents where patterns start. Default is 10.

  • update_time (float, optional) – Time interval between pattern updates. Default is 20 * dt.

Notes

The controller algorithm:

  1. Time Management: Track simulation time and update patterns periodically

  2. Pattern Generation: Create wedge-shaped light patterns behind each agent

  3. Image Creation: Use PIL to draw patterns on a digital canvas

  4. Interpolation Setup: Create interpolator for smooth light evaluation

  5. Light Evaluation: Return light intensity at current agent positions

The patterns are dynamic and respond to agent movement, creating a feedback loop where agent behavior influences the light field they experience.

Examples

Example YAML configuration:

AngularFeedback:
    dt: 0.01
    line_width: 5
    angle_width: 0.785  # π/4 radians (45 degrees)
    agent_distance: 15
    update_time: 0.5

Applications include: - Dynamic visual feedback systems - Agent-responsive light environments - Collective behavior with environmental coupling - Adaptive spatial guidance systems

__init__(population, environment, config_path=None)[source]

Initialize the angular feedback controller.

Parameters:
  • population (Population) – The population for which angular light patterns will be generated.

  • environment (Environment) – The environment providing spatial boundaries.

  • config_path (str, optional) – Path to the configuration file. Default is None.

get_action()[source]

Generate and evaluate the current angular light pattern.

This method updates the dynamic light pattern based on current agent positions and returns the light intensity values experienced by each agent.

Returns:

np.ndarray – Light intensity values of shape (N, 1) where N is the number of agents. Values represent the blue channel intensity (0-1) at each agent’s position.

Notes

The method operates in two phases:

  1. Pattern Update (if update_time has elapsed): - Calculate wedge patterns behind each agent - Draw lines using PIL imaging library - Update the spatial interpolator with new pattern

  2. Light Evaluation (every call): - Clip agent positions to environment boundaries - Evaluate light intensity at current positions - Return intensity values

The wedge patterns are generated by drawing two lines from a point behind each agent to positions that create the specified angular width.

get_action_in_space(positions)[source]

Evaluate the angular light pattern at specified spatial positions.

This method allows querying the current light pattern at arbitrary positions in the environment, useful for analysis and visualization of the dynamic feedback patterns.

Parameters:

positions (np.ndarray) – Array of shape (num_positions, 2) containing [x, y] coordinates where light intensity should be evaluated.

Returns:

np.ndarray – Light intensity values of shape (num_positions, 1) at the specified positions. Values represent the blue channel intensity (0-1) from the current pattern.

Notes

This method evaluates the most recently generated angular pattern at the specified positions. The pattern reflects the agent positions at the time of the last update (controlled by update_time parameter).

Useful for: - Visualizing the dynamic light patterns - Analyzing spatial feedback structures - Creating movies or animations of pattern evolution

Key Features:

  • Spatial Awareness: Process environmental and agent spatial information

  • Sensor Integration: Handle various sensor inputs and data fusion

  • Coordinate Transformations: Convert between different spatial representations

  • Real-time Processing: Efficient real-time spatial data processing

Usage Examples

Basic Controller Setup

from swarmsim.Controllers import BaseController
from swarmsim.Populations import BrownianMotion

# Create population and controller
population = BrownianMotion(n=100, x_dim=2)
controller = BaseController()

# Apply control in simulation loop
for step in range(1000):
    control_input = controller.compute_control(population)
    population.apply_control(control_input)
    population.step()

Shepherding Control

from swarmsim.Controllers import ShepherdingLamaController
from swarmsim.Populations import BrownianMotion
import numpy as np

# Setup target and populations
target_location = np.array([10.0, 10.0])
sheep_population = BrownianMotion(n=50, x_dim=2)
shepherd_population = BrownianMotion(n=3, x_dim=2)

# Initialize shepherding controller
controller = ShepherdingLamaController(
    target_position=target_location,
    shepherding_gain=1.0,
    formation_gain=0.5
)

# Simulation with shepherding
for step in range(2000):
    # Compute shepherding actions
    shepherd_actions = controller.compute_shepherding_action(
        sheep_population.x,
        shepherd_population.x
    )

    # Apply control
    shepherd_population.apply_control(shepherd_actions)

    # Update populations
    sheep_population.step()
    shepherd_population.step()

Advanced Control Strategies

from swarmsim.Controllers import BaseController
from swarmsim.Controllers.spatial_inputs import SpatialInputProcessor
import numpy as np

class CustomFormationController(BaseController):
    def __init__(self, formation_shape='circle', formation_radius=5.0):
        super().__init__()
        self.formation_shape = formation_shape
        self.formation_radius = formation_radius
        self.spatial_processor = SpatialInputProcessor()

    def compute_control(self, population):
        # Get current positions
        positions = population.x
        n_agents = len(positions)

        # Define target formation
        if self.formation_shape == 'circle':
            angles = np.linspace(0, 2*np.pi, n_agents, endpoint=False)
            target_positions = self.formation_radius * np.column_stack([
                np.cos(angles), np.sin(angles)
            ])

        # Compute formation control forces
        position_errors = target_positions - positions
        control_forces = 0.5 * position_errors  # Proportional control

        return control_forces

# Use custom controller
controller = CustomFormationController(formation_shape='circle', formation_radius=8.0)

Control Architecture

The Controllers package supports hierarchical control architectures:

class HierarchicalController:
    def __init__(self):
        self.high_level_controller = StrategicPlanner()
        self.low_level_controllers = [
            LocalController() for _ in range(n_groups)
        ]

    def compute_control(self, populations):
        # High-level strategic decisions
        strategies = self.high_level_controller.plan(populations)

        # Low-level tactical execution
        controls = []
        for i, (population, strategy) in enumerate(zip(populations, strategies)):
            local_control = self.low_level_controllers[i].execute(
                population, strategy
            )
            controls.append(local_control)

        return controls

Performance Considerations

  • Computational Efficiency: Controllers are optimized for real-time performance

  • Scalability: Algorithms designed to handle large populations efficiently

  • Memory Usage: Minimal memory footprint for embedded applications

  • Parallel Processing: Support for parallel control computation

Best Practices

  1. Controller Selection: Choose controllers appropriate for your application

  2. Parameter Tuning: Adjust control gains for stable, responsive behavior

  3. Performance Monitoring: Monitor controller performance and stability

  4. Modular Design: Combine multiple controllers for complex behaviors

  5. Testing: Validate controller behavior across different scenarios