Utilities Package
The Utils package provides essential utility functions and helper modules for SwarmSim operations. These utilities cover common tasks such as parameter management, data logging, control algorithms, visualization, and simulation setup.
swarmsim.Utils
This module provides essential utility functions for multi-agent simulation setup, execution, and analysis.
The Utils module contains a comprehensive collection of utility functions that support all aspects of multi-agent simulation development, from initialization and parameter management to data logging and visualization. These utilities streamline simulation setup and provide robust tools for analysis and debugging.
Module Contents
Core Utilities:
load_config : YAML configuration file loading and validation
set_global_seed : Reproducible random number generation across frameworks
get_states : Agent initialization from files or random distributions
get_parameters : Parameter loading and generation for populations
Control and Interaction Utilities:
compute_distances : Efficient pairwise distance computation
gaussian_input : 2D Gaussian function evaluation for spatial fields
Logging and Data Management:
add_entry, append_entry : Structured data logging utilities
get_positions : Population state extraction for logging
print_log : Console output formatting
append_txt, append_csv : File output utilities
save_npz, save_mat : Binary data serialization
Shepherding Analysis:
get_target_distance : Distance computation to goal regions
xi_shepherding : Shepherding success metric calculation
get_done_shepherding : Termination condition evaluation
Visualization Utilities:
get_snapshot : Pygame surface screenshot capture
Key Features
Configuration Management:
YAML-based configuration loading with validation
Nested configuration structure support
Error handling for missing files and malformed configs
Initialization Flexibility:
Multiple initialization modes (random, file-based)
Support for box and circular spatial distributions
Parameter generation with various statistical distributions
File format support (CSV, NPZ) with validation
Performance Optimization:
Vectorized distance computations for large populations
Efficient memory management for parameter generation
Optimized data structures for logging operations
Data Analysis Tools:
Shepherding metrics and success criteria
Statistical analysis utilities
Flexible data export formats
Notes
All utilities support numpy arrays and standard Python data types
Configuration validation prevents common setup errors
Reproducible random number generation across multiple frameworks
Flexible data serialization supports various analysis workflows
Package Overview
The Utils package is organized into specialized modules:
Parameter Management: Loading and generating agent parameters from files or distributions
Data Logging: Comprehensive data collection and export in multiple formats
Control Utilities: Mathematical functions for control system implementation
Initialization: Helper functions for setting up simulations and populations
Visualization: Plotting utilities for data analysis and visualization
Shepherding: Specialized utilities for shepherding behavior analysis
Simulation: General simulation management and utility functions
Core Modules
Parameter Utilities
The parameter utilities module provides flexible parameter loading and generation capabilities.
- swarmsim.Utils.params_utils.get_parameters(params_config, params_shapes, num_samples)[source]
Load or generate parameters for population initialization with flexible configuration.
This function serves as the main entry point for parameter generation in the swarmsim framework. It supports both file-based parameter loading and procedural parameter generation using statistical distributions, enabling flexible population initialization for multi-agent simulations.
- Parameters:
params_config (dict) – Configuration dictionary specifying parameter loading/generation method. Must contain ‘mode’ key with value ‘file’ or ‘generate’, plus corresponding configuration section.
params_shapes (dict[str, tuple]) – Dictionary mapping parameter names to their expected shapes per agent. Used for validation and reshaping operations.
num_samples (int) – Number of agents/samples to generate parameters for.
- Returns:
dict[str, np.ndarray] – Dictionary mapping parameter names to NumPy arrays of shape (num_samples, *shape) where shape corresponds to the parameter’s expected dimensions.
Configuration Structure
———————-
File Mode –
mode: "file" file: file_path: "path/to/parameters.csv" # or .npz
Generate Mode –
mode: "generate" generate: parameter_name: sampler: "normal" # Distribution type args: loc: 0.0 # Distribution parameters scale: 1.0 shape: [3] # Parameter shape per agent homogeneous: false # Same value for all agents
Error Handling
FileNotFoundError: Raised when specified parameter file doesn’t exist
KeyError: Raised when expected parameters are missing from loaded data
ValueError: Raised for invalid parameter shapes or configurations
RuntimeError: Raised for invalid mode specifications
Applications
Population Initialization: Set agent properties for simulation start
Parameter Studies: Generate parameter sets for sensitivity analysis
Multi-species Systems: Handle heterogeneous agent populations
Reproducible Research: Load exact parameter sets from files
See also
_load_parametersFile-based parameter loading implementation
_generate_parametersStatistical parameter generation implementation
_reshape_parameterParameter reshaping utilities
Key Features:
File-based Loading: Load parameters from CSV or NPZ files
Statistical Generation: Generate parameters using 30+ probability distributions
Population Matching: Automatically adjust parameter count to match population size
Shape Broadcasting: Intelligent parameter reshaping for multi-dimensional properties
Validation: Parameter validation and statistical analysis
Example Usage:
from swarmsim.Utils import get_parameters
# Load from file
config = {
'mode': 'file',
'file': {'file_path': 'agent_params.csv'}
}
# Or generate with distributions
config = {
'mode': 'generate',
'generate': {
'mass': {'sampler': 'normal', 'args': {'loc': 1.0, 'scale': 0.1}},
'position': {'sampler': 'uniform', 'args': {'low': -5, 'high': 5}, 'shape': [3]}
}
}
params = get_parameters(config, shapes={'mass': (), 'position': (3,)}, num_samples=100)
Logger Utilities
The logger utilities module handles comprehensive data collection and export functionality.
Logging utility functions for structured data collection and export.
This module provides a comprehensive suite of utilities for logging simulation data in multiple formats, supporting real-time monitoring, data persistence, and post-simulation analysis. The utilities support flexible data collection with configurable output formats.
- swarmsim.Utils.logger_utils.add_entry(current_info, save_mode=[], **kwargs)[source]
Add single-value entries to the logging data structure.
This function adds individual data entries to a structured logging dictionary, associating each entry with specific save modes that determine how the data will be output (print, file, etc.).
- Parameters:
current_info (dict) – The logging data structure to modify.
save_mode (list, optional) – List of output modes for the entries. Options: [‘print’, ‘txt’, ‘csv’, ‘npz’, ‘mat’].
**kwargs (key-value pairs) – Data entries to add, where keys become field names and values are the data.
Structure (Data)
--------------
format (Each entry in current_info follows the)
code-block: (..) –
python: {
- ’field_name’: {
‘value’: data_value, ‘save_mode’: [‘print’, ‘npz’, …]
}
}
Notes
Overwrites existing entries with the same key
For time series data, use append_entry instead
Save modes determine which output functions will process the data
Values can be scalars, arrays, or complex data structures
- swarmsim.Utils.logger_utils.append_entry(info, save_mode=[], **kwargs)[source]
Append time-series data to existing logging entries.
This function appends new data to existing entries in the logging structure, automatically handling the creation of new entries or stacking data for existing ones. It’s ideal for collecting time series data during simulation.
- Parameters:
info (dict) – The logging data structure to modify.
save_mode (list, optional) – List of output modes for the entries. Options: [‘print’, ‘txt’, ‘csv’, ‘npz’, ‘mat’].
**kwargs (key-value pairs) – Data to append, where keys are field names and values are the new data.
Handling (Data)
-------------
Entries (- Existing)
Entries
Consistency (- Shape)
Applications
Trajectory Logging: Recording agent paths over time
Performance Monitoring: Collecting metrics throughout simulation
Real-time Analysis: Building datasets for online analysis
Performance Notes
Uses np.vstack for efficient array concatenation
Memory usage grows linearly with simulation length
Consider periodic saving for very long simulations
Shape consistency is automatically maintained
Notes
Automatically handles first entry creation vs. subsequent appends
Maintains data type consistency within each field
Compatible with all numpy array types and scalars
Ideal for building time series datasets
- swarmsim.Utils.logger_utils.get_positions(info, populations, save_mode)[source]
Extract and log population positions with systematic naming.
This function extracts position data from multiple populations and appends them to the logging structure with automatically generated field names that include population ID and spatial dimension information.
- Parameters:
info (dict) – The logging data structure to modify.
populations (list of Population) – List of population objects with ‘x’ position arrays and ‘id’ attributes.
save_mode (list) – Output modes for the position data.
Convention (Naming)
-----------------
pattern (Field names follow the)
Examples ('sheep_state0', 'sheep_state1', 'herders_state0', 'herders_state1')
Applications
Trajectory Analysis: Building complete movement histories
Visualization: Creating animated trajectory plots
Notes
Requires populations to have ‘x’ attribute (position array)
Requires populations to have ‘id’ attribute (string identifier)
Position data shape: (num_agents, state_dim)
Creates separate field for each spatial dimension
- swarmsim.Utils.logger_utils.print_log(current_info)[source]
Display logging information to console with filtered output.
This function prints selected logging entries to the console, filtering by save mode to show only data marked for console output. It provides real-time monitoring capabilities during simulation execution.
- Parameters:
current_info (dict) – Logging data structure containing entries with save modes.
Format (Output)
-------------
format (Entries are printed in the)
Applications
Real-time Monitoring: Live simulation progress tracking
Debug Output: Immediate feedback during development
Event Notification: Alerts for significant simulation events
Performance Tracking: Regular metric updates during training
Status Updates: Periodic progress reports
Notes
Automatically adds newline after all entries
Handles all data types that can be converted to string
Non-blocking operation suitable for real-time monitoring
Filters entries based on save_mode to avoid console spam
- swarmsim.Utils.logger_utils.append_txt(log_name, current_info)[source]
Append logging entries to a text file with structured formatting.
This function writes selected logging entries to a text file, filtering by save mode and providing human-readable output suitable for logs, reports, and debugging traces.
- Parameters:
Applications
Debugging Logs: Detailed execution traces for troubleshooting
Experiment Records: Human-readable experiment documentation
Event Logs: Chronological record of simulation events
Status Reports: Periodic progress summaries
Configuration Logs: Parameter and setting documentation
Notes
Only processes entries with ‘txt’ in their save_mode
Creates parent directories if they don’t exist
Adds blank line separator between logging calls
- swarmsim.Utils.logger_utils.append_csv(log_name, current_info)[source]
Append logging entries to a CSV file with automatic header management.
This function writes selected logging entries to a CSV file, filtering by save mode and handling automatic header creation for new files. It provides structured tabular output suitable for data analysis and spreadsheet import.
- Parameters:
Applications
Performance Monitoring: Real-time metric collection
Statistical Analysis: Data suitable for statistical software
Report Generation: Tabular data for presentations and papers
Notes
Only processes entries with ‘csv’ in their save_mode
Automatically handles header creation and management
Creates parent directories if needed
Compatible with pandas for post-processing analysis
- swarmsim.Utils.logger_utils.save_npz(log_name, data)[source]
Save logging data to compressed NumPy archive (.npz) format.
This function exports selected logging entries to a compressed NumPy archive, providing efficient binary storage for large datasets with fast loading capabilities. It’s ideal for numerical data that will be processed with NumPy-based analysis tools.
- Parameters:
Examples
Basic NPZ logging:
from swarmsim.Utils import add_entry, append_entry, save_npz log_data = {} # Log time series data for step in range(100): append_entry(log_data, save_mode=['npz'], positions=population.x, velocities=population.v, timestep=step) # Save to NPZ file save_npz("simulation_data.npz", log_data)
Applications
Large Datasets: Efficient storage of simulation trajectories
Scientific Analysis: Compatible with NumPy/SciPy ecosystem
Notes
Only saves entries with ‘npz’ in their save_mode
Automatically compresses data for smaller file sizes
Preserves exact numerical precision
Files can be opened with np.load() for analysis
Remember to close loaded files to free memory
Ideal for numerical simulation data storage and analysis
- swarmsim.Utils.logger_utils.save_mat(log_name, data)[source]
Save logging data to MATLAB .mat format for cross-platform analysis.
This function exports selected logging entries to MATLAB-compatible format, enabling seamless integration with MATLAB analysis workflows and providing interoperability between Python simulations and MATLAB post-processing tools.
- Parameters:
Examples
Basic MAT file logging:
from swarmsim.Utils import add_entry, append_entry, save_mat log_data = {} # Log simulation parameters add_entry(log_data, save_mode=['mat'], n_agents=100, dt=0.01, max_speed=2.0) # Log time series data for step in range(1000): append_entry(log_data, save_mode=['mat'], positions=population.x, velocities=population.v, energies=population.energy) # Save for MATLAB analysis save_mat("simulation_results.mat", log_data)
Applications
MATLAB Integration: Seamless data exchange with MATLAB analysis tools
Signal Processing: Compatible with MATLAB Signal Processing Toolbox
Visualization: Use MATLAB’s advanced plotting capabilities
Notes
Only saves entries with ‘mat’ in their save_mode
Requires scipy.io.savemat for the actual file writing
Variable names must be valid MATLAB identifiers
Large arrays are stored efficiently in MAT format
Ideal for teams using both Python and MATLAB workflows
Key Features:
Multi-format Export: Support for CSV, NPZ, MAT, and text formats
Time Series Logging: Efficient time series data collection
Real-time Monitoring: Live data streaming and console output
Memory Management: Optimized for large-scale simulations
Flexible Save Modes: Configure output formats per logging entry
Example Usage:
from swarmsim.Utils import add_entry, append_entry, save_npz
log_data = {}
# Log single values
add_entry(log_data, save_mode=['csv', 'npz'],
simulation_time=100.0, total_agents=200)
# Log time series
for step in range(1000):
append_entry(log_data, save_mode=['npz'],
positions=population.x, velocities=population.v)
# Export data
save_npz("simulation_results.npz", log_data)
Control Utilities
Mathematical functions and utilities for implementing control algorithms.
Control and interaction utility functions for multi-agent systems.
This module provides efficient computational utilities for control systems and agent interactions, including distance calculations and spatial field generation.
- swarmsim.Utils.control_utils.compute_distances(positions_1, positions_2)[source]
Compute pairwise Euclidean distances between two sets of agent positions.
This function efficiently calculates all pairwise distances between agents in two different populations using vectorized operations. It’s optimized for large-scale multi-agent systems where distance-based interactions are common.
- Parameters:
positions_1 (np.ndarray) – Positions of first agent population. Shape: (N, spatial_dim) or (spatial_dim,) for single agent.
positions_2 (np.ndarray) – Positions of second agent population. Shape: (M, spatial_dim) or (spatial_dim,) for single agent.
- Returns:
distances (np.ndarray) – Pairwise Euclidean distances. Shape: (N, M).
relative_positions (np.ndarray) – Relative position vectors from positions_2 to positions_1. Shape: (N, M, spatial_dim).
Algorithm Details
—————–
The function uses numpy broadcasting to efficiently compute all pairwise distances
1. **Shape Expansion** (Input arrays are expanded to enable broadcasting)
2. **Relative Positions** (Computed as positions_1 - positions_2)
3. **Distance Calculation** (Euclidean norm along spatial dimension)
Mathematical formulation
.. math:: – d_{ij} = |mathbf{p}_i^{(1)} - mathbf{p}_j^{(2)}|_2
Where \(\mathbf{p}_i^{(1)}\) and \(\mathbf{p}_j^{(2)}\) are position vectors.
Applications
Interaction Forces: Repulsion, attraction, alignment calculations
Neighbor Detection: Finding agents within sensing or communication range
Collision Avoidance: Distance-based safety constraints
Notes
Input arrays are automatically expanded to support broadcasting
Handles both single agents and populations seamlessly
Relative positions point from positions_2 to positions_1
Optimized for repeated calls in simulation loops
Compatible with 2D, 3D, or higher-dimensional spaces
- swarmsim.Utils.control_utils.gaussian_input(x, y, A=5.0, mu_x=0.0, mu_y=0.0, sigma_x=1.0, sigma_y=1.0)[source]
Evaluate a 2D Gaussian distribution at specified points with diagonal covariance.
This function computes the value of a 2D Gaussian distribution at given coordinates, assuming a diagonal covariance matrix. It’s commonly used for generating spatial fields, attraction/repulsion landscapes, and bio-inspired navigation signals.
- Parameters:
x (float or np.ndarray) – X-coordinates where to evaluate the Gaussian.
y (float or np.ndarray) – Y-coordinates where to evaluate the Gaussian.
A (float, optional) – Maximum amplitude (peak value) of the Gaussian. Default is 5.0.
mu_x (float, optional) – Mean (center) of the Gaussian in the x-direction. Default is 0.0.
mu_y (float, optional) – Mean (center) of the Gaussian in the y-direction. Default is 0.0.
sigma_x (float, optional) – Standard deviation in the x-direction. Default is 1.0.
sigma_y (float, optional) – Standard deviation in the y-direction. Default is 1.0.
- Returns:
np.ndarray or float – Gaussian function values at the specified coordinates. Same shape as input arrays.
Mathematical Formulation
————————
The 2D Gaussian with diagonal covariance is defined as
.. math:: – f(x, y) = A expleft(-frac{(x - mu_x)^2}{2sigma_x^2} - frac{(y - mu_y)^2}{2sigma_y^2}right)
Where
\(A\) is the amplitude (maximum value)
\((\mu_x, \mu_y)\) is the center point
\((\sigma_x, \sigma_y)\) are the standard deviations
Applications
Spatial Control Fields: Creating attraction/repulsion landscapes
Potential Field Methods: Path planning and obstacle avoidance
Performance Notes
Vectorized operations support efficient grid evaluations
Computational complexity: O(N) where N is number of evaluation points
Memory efficient for large spatial grids
Compatible with numpy broadcasting
Notes
Assumes diagonal covariance matrix (no correlation between x and y)
Peak value occurs at (mu_x, mu_y) with value A
Key Features:
Geometric Calculations: Distance, angle, and spatial relationship functions
Control Algorithms: PID controllers, feedback systems, and stability analysis
Coordinate Transformations: Conversion between coordinate systems
Signal Processing: Filtering and noise reduction utilities
Initialization Utilities
Helper functions for setting up simulations, populations, and environments.
Agent initialization utilities for multi-agent simulations.
This module provides flexible and robust utilities for initializing agent states in multi-agent simulations. It supports both random initialization with various spatial distributions and deterministic initialization from data files.
- swarmsim.Utils.init_utils.get_states(init_config, num_samples, dim_samples)[source]
Generate or load initial states for agents in multi-agent simulations.
This function provides flexible initialization of agent states, supporting both random generation with configurable spatial distributions and deterministic loading from data files. It’s designed to handle various initialization scenarios for different types of multi-agent systems.
- Parameters:
- Returns:
np.ndarray – Initial states array with shape (num_samples, dim_samples).
Configuration Structure
———————–
The init_config dictionary supports two main modes
**Random Mode**
.. code-block:: yaml – mode: “random” random:
shape: “box” # or “circle” box:
lower_bounds: [-10, -10, 0, 0] upper_bounds: [10, 10, 0, 0]
# OR circle:
min_radius: 0 max_radius: 5 lower_bounds_other_states: [0, 0] upper_bounds_other_states: [0, 0]
**File Mode**
.. code-block:: yaml – mode: “file” file:
file_path: “initial_conditions.csv” # or .npz
Initialization Modes
——————–
**Box Distribution** (Uniform random initialization within hyperrectangular bounds)
**Circle Distribution** (Uniform distribution within circular region (first 2D), uniform for other dimensions)
**File Loading** (Direct loading from CSV or NPZ files with validation)
Examples
Box initialization for 2D agents with velocities:
from swarmsim.Utils import get_states box_config = { 'mode': 'random', 'random': { 'shape': 'box', 'box': { 'lower_bounds': [-50, -50, -2, -2], # [x_min, y_min, vx_min, vy_min] 'upper_bounds': [50, 50, 2, 2] # [x_max, y_max, vx_max, vy_max] } } } states = get_states(box_config, num_samples=100, dim_samples=4) print(f"Initialized {states.shape[0]} agents with {states.shape[1]}D states")
Circular initialization for spatial clustering:
circle_config = { 'mode': 'random', 'random': { 'shape': 'circle', 'circle': { 'min_radius': 2.0, 'max_radius': 10.0, 'lower_bounds_other_states': [-1, -1], # For velocity components 'upper_bounds_other_states': [1, 1] } } } states = get_states(circle_config, num_samples=50, dim_samples=4)
File-based initialization from CSV:
file_config = { 'mode': 'file', 'file': { 'file_path': 'predefined_formation.csv' } } states = get_states(file_config, num_samples=20, dim_samples=6)
Error Handling
The function provides comprehensive error checking:
File Validation: Checks file existence and format compatibility
Dimension Validation: Ensures state dimensions match expectations
Agent Count Validation: Verifies number of agents in file data
Configuration Validation: Validates all required parameters
Notes
Box initialization supports arbitrary dimensionality
Circle initialization applies to first 2 dimensions only
File formats must match expected agent count and state dimensions
Random number generation uses numpy’s global random state
All bounds are inclusive for uniform distributions
Key Features:
Population Setup: Initialize agent populations with diverse properties
Environment Configuration: Set up simulation environments and boundaries
Parameter Loading: Load configuration files and simulation parameters
Validation: Check configuration consistency and parameter validity
Supporting Modules
Plot Utilities
Visualization and plotting utilities for data analysis and presentation.
Visualization utility functions for multi-agent simulation analysis.
This module provides utilities for capturing and saving visual output from simulation renderers, supporting post-simulation analysis and documentation.
- swarmsim.Utils.plot_utils.get_snapshot(snapshot, name='')[source]
Save a pygame surface as an image file for documentation or analysis.
This utility function captures a pygame surface (typically from a renderer) and saves it as an image file. It’s useful for creating documentation, generating datasets, or performing post-simulation visual analysis.
- Parameters:
snapshot (pygame.Surface) – Pygame surface containing the image to save.
name (str, optional) – Output filename with extension. If empty, uses default naming.
Formats (Supported)
-----------------
extension (The function supports various image formats based on file)
.png (-)
.jpg/.jpeg (-)
.bmp (-)
.tga (-)
Applications
Documentation: Creating figures for papers and reports
Dataset Generation: Building visual datasets for machine learning
Progress Tracking: Capturing simulation progress over time
Comparative Analysis: Visualizing results from different algorithms
Debugging: Saving problematic states for later analysis
Video Creation: Individual frames for animation generation
Notes
Requires pygame to be initialized before use
File extension determines output format
Creates parent directories if they don’t exist (depending on pygame version)
Compatible with all pygame surface objects
Thread-safe for single-threaded pygame applications
Key Features:
Trajectory Visualization: Plot agent paths and movement patterns
Statistical Plots: Distribution analysis and statistical summaries
Animation Support: Create animated visualizations of simulation data
Export Options: Save plots in various formats (PNG, PDF, SVG)
Shepherding Utilities
Specialized utilities for analyzing shepherding behaviors and multi-agent coordination.
Specialized utility functions for shepherding task analysis and evaluation.
This module provides analysis tools specifically designed for shepherding simulations, including success metrics, termination conditions, and performance evaluation utilities.
- swarmsim.Utils.shepherding_utils.get_target_distance(targets, environment)[source]
Compute distances from target agents to the goal region center.
This function calculates the Euclidean distance from each target agent to the center of the goal region, providing essential information for shepherding analysis and termination conditions.
- Parameters:
targets (Population) – Target population (typically sheep) with position attribute ‘x’.
environment (Environment) – Environment instance containing goal position (‘goal_pos’) and dimensions.
- Returns:
np.ndarray – Array of distances from each target to goal center. Shape: (n_targets,).
Mathematical Details
——————–
Distance calculation
.. math:: – d_i = |mathbf{p}_i - mathbf{g}|_2
Where \(\mathbf{p}_i\) is the position of target i and \(\mathbf{g}\) is the goal center.
Notes
Uses only spatial dimensions from target positions
Compatible with arbitrary environment dimensions
Optimized for repeated calls during simulation
- swarmsim.Utils.shepherding_utils.xi_shepherding(targets, environment)[source]
Compute the shepherding success metric (fraction of targets in goal region).
This function calculates the key performance metric for shepherding tasks: the fraction of target agents that are currently within the goal region. This metric is commonly denoted as ξ (xi) in shepherding literature.
- Parameters:
targets (Population) – Target population with position attribute ‘x’.
environment (Environment) – Environment with ‘goal_pos’ and ‘goal_radius’ attributes.
- Returns:
float – Fraction of targets within goal region, range [0, 1].
Mathematical Definition
———————–
The shepherding metric is defined as
.. math:: – xi = frac{1}{N} sum_{i=1}^{N} mathbf{1}[d_i < r_{goal}]
Where
\(N\) is the total number of targets
\(d_i\) is the distance from target i to goal center
\(r_{goal}\) is the goal region radius
\(\mathbf{1}[\cdot]\) is the indicator function
Applications
Performance Evaluation: Primary metric for shepherding success
Termination Conditions: End episodes when ξ reaches threshold
Real-time Monitoring: Track progress during simulation
Notes
Returns value in range [0, 1] where 1 indicates perfect shepherding
Commonly used threshold values: 0.8-0.95 for task completion
Efficient computation suitable for real-time evaluation
Compatible with arbitrary goal region shapes (uses distance to center)
- swarmsim.Utils.shepherding_utils.get_done_shepherding(populations, environment, xi=None, threshold=1)[source]
Determine if shepherding task has reached completion criteria.
This function evaluates whether a shepherding task should be considered complete based on the fraction of targets within the goal region. It provides flexible termination logic for both simulation and reinforcement learning applications.
- Parameters:
populations (list or Population) – Target population(s) to evaluate. If list, uses first element.
environment (Environment) – Environment containing goal region specifications.
xi (float, optional) – Pre-computed shepherding success metric. If None, computes from populations.
threshold (float, optional) – Success threshold for task completion. Default is 1.0 (100% success).
- Returns:
bool – True if shepherding task is complete, False otherwise.
Threshold Guidelines
——————–
Common threshold values and their applications
- **threshold = 1.0** (Perfect shepherding (all targets in goal))
- **threshold = 0.95** (Near-perfect (95% success, practical for noisy environments))
- **threshold = 0.9** (High success (90% success, commonly used benchmark))
- **threshold = 0.8** (Moderate success (80% success, for challenging scenarios))
Applications
Episode Termination: End RL episodes when task is complete
Simulation Control: Stop simulations at successful completion
Performance Benchmarking: Define success criteria for algorithm comparison
Notes
Returns immediately if xi is provided, avoiding recomputation
Threshold of 1.0 requires perfect shepherding (may be too strict for noisy systems)
Compatible with both single populations and population lists
Commonly used in conjunction with xi_shepherding function
Key Features:
Herding Metrics: Calculate shepherding effectiveness and performance
Group Analysis: Analyze group cohesion and formation patterns
Control Strategies: Implement shepherding control algorithms
Behavioral Assessment: Evaluate shepherding behavior quality
Simulation Utilities
General simulation management and utility functions.
Core simulation utilities for configuration management and reproducibility.
This module provides fundamental utilities for simulation setup, including configuration file loading, random seed management, and reproducible simulation execution across different frameworks.
- swarmsim.Utils.sim_utils.set_global_seed(seed)[source]
Set reproducible random seeds across all major frameworks and libraries.
This function ensures reproducible results by setting seeds for Python’s built-in random module, NumPy, and PyTorch (both CPU and GPU). This is essential for scientific reproducibility and debugging simulations.
- Parameters:
seed (int) – Random seed value to use across all frameworks.
Applications
Scientific Reproducibility: Ensure consistent results across runs
Debugging: Reproduce exact problematic scenarios
Benchmarking: Fair comparison between algorithms
Notes
Should be called before any random operations
PyTorch CUDA seeding affects all available GPU devices
Does not affect system-level randomness (e.g., thread scheduling)
- swarmsim.Utils.sim_utils.load_config(config_path)[source]
Load and validate YAML configuration files for simulation setup.
This function provides robust loading of YAML configuration files with proper error handling and validation. It’s the standard method for loading simulation parameters, component configurations, and experimental settings.
- Parameters:
config_path (str) – Path to the YAML configuration file to load.
- Returns:
dict – Parsed configuration dictionary with nested structure preserved.
- Raises:
FileNotFoundError – If the specified configuration file does not exist.
yaml.YAMLError – If the file contains invalid YAML syntax.
Notes
Uses PyYAML’s safe_load for security
Preserves nested dictionary structure
Supports all standard YAML data types
Path can be absolute or relative to working directory
Configuration files should use .yaml or .yml extension
Key Features:
Simulation Management: Start, stop, and monitor simulation execution
Performance Monitoring: Track simulation performance and resource usage
Configuration Handling: Load and validate simulation configurations
Error Handling: Robust error management and recovery