Visualization & Rendering
The renderers package provides sophisticated visualization capabilities for multi-agent simulations, supporting both real-time interactive displays and high-quality static outputs. These renderers enable comprehensive visual analysis of swarm dynamics, behavioral patterns, and emergent phenomena.
Overview
SwarmSim’s rendering framework offers flexible visualization solutions that scale from simple trajectory plotting to complex multi-population animations with environmental interactions. The modular design supports multiple rendering backends while maintaining consistent interfaces for different visualization needs.
Key Features
Multiple Backends: Matplotlib for publication-quality plots, Pygame for interactive real-time visualization
Multi-Population Support: Simultaneous rendering of multiple agent populations with distinct visual properties
Environmental Integration: Visualization of obstacles, boundaries, force fields, and environmental gradients
Animation Capabilities: Smooth real-time animations with configurable frame rates and export options
Interactive Controls: Zoom, pan, pause, and parameter adjustment during simulation
Publication Ready: High-resolution outputs with customizable styling for research publications
Module Reference
swarmsim.Renderers
This module provides rendering utilities for visualizing multi-agent environments.
- It includes:
A base renderer (BaseRenderer) supporting both Matplotlib and Pygame.
A specialized renderer (ShepherdingRenderer) for shepherding simulations, which includes a goal region visualization.
An abstract interface (Renderer) to define custom rendering implementations.
Module Contents
Renderer : Abstract base class defining the rendering interface.
BaseRenderer : General-purpose renderer supporting Matplotlib and Pygame.
ShepherdingRenderer : Specialized renderer with goal visualization.
Examples
Example usage:
from swarmsim.Renderers import BaseRenderer
renderer = BaseRenderer(populations, environment, config_path="config.yaml")
renderer.render()
Notes
If render_mode=”matplotlib”, the renderer creates a static figure with a pause interval.
If render_mode=”pygame”, a Pygame window is created for interactive rendering.
The ShepherdingRenderer adds a visualized goal region for shepherding tasks.
Base Renderer Interface
The abstract foundation for all rendering implementations, defining the core visualization interface.
- class swarmsim.Renderers.renderer.Renderer(populations, environment, config_path)[source]
Bases:
ABCAbstract base class for real-time visualization of multi-agent simulations.
This class provides the interface for rendering environments and agent populations during simulation execution. Renderers can use different visualization backends (Matplotlib, Pygame, etc.) to provide real-time feedback on simulation state.
- Parameters:
populations (list of Population) – List of agent populations to visualize.
environment (Environment) – The environment instance containing spatial and visual information.
config_path (str) – Path to the YAML configuration file containing rendering parameters.
- Variables:
populations (list of Population) – List of populations being rendered.
environment (Environment) – The simulation environment.
config (dict) – Configuration parameters for rendering settings.
render_dt (float) – Time delay between rendering frames in seconds.
activate (bool) – Flag to enable/disable rendering.
- Config Requirements:
The YAML configuration file should contain a renderer section with
render_dt (float, optional) – Time delay between frames in seconds. Default is
0.05.activate (bool, optional) – Whether to enable rendering. Default is
True.Additional renderer-specific parameters depend on the implementation.
Notes
Subclasses must implement the abstract methods render() and close().
The renderer is called at each simulation timestep if activated.
Common visualization elements include:
Agent positions and orientations
Environment boundaries and obstacles
Interaction forces or fields
Trajectories and paths
Performance metrics
- abstractmethod __init__(populations, environment, config_path)[source]
Initialize the renderer with simulation components and configuration.
- Parameters:
populations (list of Population) – List of agent populations to visualize.
environment (Environment) – The simulation environment instance.
config_path (str) – Path to the YAML configuration file containing rendering parameters.
Notes
Subclasses should call this constructor to initialize common attributes and then set up their specific visualization backend (windows, graphics contexts, etc.).
- abstractmethod render()[source]
Render the current state of the simulation with suitable visualization.
This method should update the visual representation to show the current positions and states of all agents, environment features, and any additional visualization elements (forces, trajectories, metrics, etc.).
Implementation Requirements
Subclasses may implement the following rendering pipeline:
Environment Rendering: Draw boundaries, obstacles, and spatial features
Agent Visualization: Render all populations with appropriate styling
Interaction Visualization: Show forces, connections, or influences (optional)
Overlay Elements: Add goal regions, trajectories, or analysis data (optional)
Frame Management: Handle timing and display updates
Notes
Called at each simulation timestep when rendering is active
Should respect the
self.activateflag to enable/disable renderingPerformance critical method - optimize for real-time execution
- abstractmethod close()[source]
Clean up rendering resources and shut down visualization.
This method should properly shut down the visualization backend and release any allocated resources such as graphics contexts, windows, memory buffers, GPU resources, or file handles. It ensures clean termination of the rendering system and prevents resource leaks.
Cleanup Tasks
Graphics Resources:
Close rendering windows and graphics contexts
Release GPU memory and buffers
Shut down graphics libraries (pygame, OpenGL, etc.)
Clear cached surfaces and textures
Notes
Called when simulation ends or renderer is explicitly shut down
Critical for preventing resource leaks in long-running simulations
Standard Base Renderer
The primary renderer implementation providing comprehensive visualization capabilities for general simulations.
- class swarmsim.Renderers.base_renderer.BaseRenderer(populations, environment, config_path)[source]
Bases:
RendererA base renderer class responsible for rendering agents in an environment using either Matplotlib or Pygame.
This class provides a flexible rendering system for visualizing populations within a simulation environment. It supports both Matplotlib (for static plots) and Pygame (for interactive rendering).
- Parameters:
- Variables:
populations (list) – List of population objects to be rendered.
environment (object) – The environment in which agents operate.
config (dict) – Dictionary containing rendering configuration parameters.
agent_colors (str or list) – Color(s) used to render the agents.
agent_shapes (str or list) – Shape(s) used to represent agents (e.g., “circle”, “diamond”).
agent_sizes (float or list) – Size of the agents in the rendering.
background_color (str) – Background color of the rendering window.
render_mode (str) – Rendering mode, either “matplotlib” or “pygame”.
render_dt (float) – Time delay between frames in seconds.
ax (fig,) – Matplotlib figure and axis (if using Matplotlib mode).
window (pygame.Surface) – Pygame window surface (if using Pygame mode).
clock (pygame.time.Clock) – Pygame clock for controlling frame rate.
screen_size (tuple) – Size of the Pygame window.
arena_size (tuple) – Size of the simulation arena in the Pygame window.
- Config requirements:
The YAML configuration file must contain a `renderer` section with the following parameters
agent_colors (str or list, optional) – Default color(s) for the agents (default is “blue”).
agent_shapes (str or list, optional) – Shape(s) used to render agents (“circle” or “diamond”, default is “circle”).
agent_sizes (float or list, optional) – Size of the agents (default is 1).
background_color (str, optional) – Background color of the rendering (default is “white”).
render_mode (str, optional) – Rendering mode (“matplotlib” or “pygame”, default is “matplotlib”).
render_dt (float, optional) – Time delay between frames in seconds (default is 0.05).
Notes
The rendering mode must be either “matplotlib” (for static plots) or “pygame” (for interactive rendering).
If using Matplotlib, a new figure is created at initialization.
If using Pygame, a window is created, and agents are rendered as circles or diamonds.
Examples
Example YAML configuration:
renderer: agent_colors: ["red", "green"] agent_shapes: ["circle", "diamond"] agent_size: 5 background_color: "black" render_mode: "pygame" render_dt: 0.1
This configuration will render agents using Pygame, with red and green agents appearing as circles and diamonds, on a black background.
- __init__(populations, environment, config_path)[source]
Initializes the renderer with the selected visualization mode.
- render()[source]
Render the agents and environment using the selected renderer mode.
- Raises:
ValueError – If an unsupported rendering mode is specified.
- render_matplotlib()[source]
Render the simulation using Matplotlib with efficient scatter plot updates.
This method provides high-performance rendering by updating existing scatter plot data rather than recreating plots at each frame. It supports real-time visualization of agent positions with customizable colors, shapes, and sizes.
Implementation Details
Dynamic Axis Updates: Adjusts plot limits based on environment dimensions
Pre-render Hook: Calls custom pre-rendering logic for environment features
Efficient Updates: Updates scatter plot offsets without recreation
Post-render Hook: Adds custom visualization elements after agent rendering
Frame Control: Uses
plt.pause()for animation timing
Performance Notes
Only updates position data, preserving color/shape/size settings
Suitable for real-time visualization with hundreds of agents
Memory efficient for long simulation runs
Notes
Background color and axis limits are updated each frame for dynamic environments
Legend is created once during initialization to avoid redrawing overhead
Grid and labels remain static for better visual stability
- render_pygame()[source]
Renders agents and the environment using Pygame.
This method initializes a Pygame window (if not already created) and renders the agent populations using circles or diamond shapes.
Notes
The function first fills the screen with the background color.
Calls pre_render_hook_pygame() before rendering agents.
Calls post_render_hook_pygame() after rendering.
Uses pygame.display.flip() to update the screen.
Uses self.clock.tick(1 / self.render_dt) to control rendering speed.
- Returns:
np.ndarray or pygame.Surface –
If render_mode == “rgb_array”, returns a NumPy array representing the rendered frame.
Otherwise, returns the Pygame window.
- pre_render_hook_matplotlib()[source]
Customizable pre-rendering hook for Matplotlib visualization extensions.
This method is called before agent rendering, providing a hook for subclasses to add custom visualization elements such as environment features, force fields, trajectories, or background images.
Common Use Cases
Environment boundary visualization
Obstacle and barrier rendering
Force field or potential visualization
Background image overlay
Dynamic environment feature updates
Performance Considerations
Cache expensive computations outside this method when possible
Use matplotlib’s artist system for efficient updates
Notes
Called after axis setup but before agent scatter plot updates
Has access to
self.axmatplotlib axes objectShould not modify agent scatter plots directly
- post_render_hook_matplotlib()[source]
Customizable post-rendering hook for Matplotlib visualization.
This method is called after agent rendering, providing a hook for subclasses to add overlay elements such as annotations, measurements, goal regions, or real-time analysis visualizations.
Common Use Cases
Goal region visualization
Performance metric overlays
Agent trajectory trails
Inter-agent connection lines
Real-time analysis annotations
Success/failure indicators
Measurement and scaling references
Notes
Called after agent positions are updated but before frame display
Has full access to population states and environment information
Should preserve existing plot elements unless intentionally modifying them
- pre_render_hook_pygame()[source]
Customizable pre-rendering hook for Pygame visualization extensions.
This method is called after screen clearing but before agent rendering, providing a hook for subclasses to add background elements, environment features, or spatial information visualization.
Common Use Cases
Environment boundary visualization
Obstacle and terrain rendering
Spatial field visualization (heat maps, gradients)
Background texture or pattern overlay
Grid system or coordinate references
Dynamic environment state visualization
Notes
Called after
self.window.fill()but before agent renderingHas access to
self.windowpygame surfaceCoordinate system uses pygame screen coordinates (origin top-left)
Can access
self.scale_factorfor simulation-to-screen conversion
- post_render_hook_pygame()[source]
Customizable post-rendering hook for Pygame visualization extensions.
This method is called after agent rendering but before display update, providing a hook for subclasses to add overlay elements, UI components, or analysis visualizations on top of the agent layer.
Common Use Cases
Goal region and target visualization
Agent connection networks
Performance metric displays
UI elements and controls
Trajectory trails and paths
Analysis overlay graphics
Semi-transparent information layers
Notes
Overlays appear on top of agent visualization
Can access real-time simulation state for dynamic visualizations
Should handle coordinate system conversion from simulation to screen space
Biological Systems Renderer
Specialized renderer for biological and ecological simulations with organism-specific visualization features.
- class swarmsim.Renderers.bio_renderer.BioRenderer(populations, environment, config_path, controller)[source]
Bases:
BaseRendererSpecialized renderer for bio-inspired simulations with spatial field visualization.
This renderer extends the base renderer to visualize spatial control fields and environmental gradients that influence bio-inspired agent behavior. It creates real-time spatial intensity maps showing how controllers respond to different spatial locations, providing insight into bio-inspired navigation and decision-making.
The renderer generates a continuous spatial field visualization by:
Grid Sampling: Creates a dense grid across the environment
Controller Evaluation: Queries the controller at each grid point
Color Mapping: Maps controller responses to visual intensity
Real-time Update: Updates the spatial field each frame
- Parameters:
populations (list of Population) – List of agent populations to visualize.
environment (Environment) – The simulation environment instance.
config_path (str) – Path to YAML configuration file with rendering parameters.
controller (Controller) – Controller instance used to generate spatial field visualization.
- Variables:
controller (Controller) – The controller providing spatial field information.
screen_size (tuple) – Pygame window dimensions (width, height). Default: (1366, 768).
arena_size (tuple) – Arena rendering dimensions. Default: (1366, 768).
spatial_input (pygame.Surface) – Cached surface containing the spatial field visualization.
Details (Implementation)
----------------------
by (The spatial field is computed)
dimensions (1. Creating a uniform grid spanning the environment)
point (2. Evaluating controller.get_action_in_space() at each grid)
values (3. Mapping controller responses to RGB color)
blitting (4. Generating a pygame surface for efficient)
Mapping (Color)
-------------
Response (- Low)
Response
Interpolation (-)
Examples
Basic bio-renderer setup:
from swarmsim.Renderers import BioRenderer from swarmsim.Controllers import LightSensitiveController controller = LightSensitiveController(config_path="bio_config.yaml") renderer = BioRenderer(populations, environment, "render_config.yaml", controller) # Render with spatial field background renderer.render()
Configuration example:
BioRenderer: render_mode: "pygame" render_dt: 0.05 agent_colors: ["blue", "green"] agent_sizes: [2, 3] background_color: "black"
Notes
Requires pygame rendering mode for spatial field visualization
Controller must implement
get_action_in_space(positions)methodSpatial field is recomputed each frame if controller state changes
Best suited for visualizing spatially-varying control policies
- __init__(populations, environment, config_path, controller)[source]
Initialize the bio-renderer with spatial field visualization capabilities.
- Parameters:
populations (list of Population) – List of agent populations to visualize.
environment (Environment) – The simulation environment instance.
config_path (str) – Path to YAML configuration file containing rendering parameters.
controller (Controller) – Controller instance for generating spatial field visualization. Must implement
get_action_in_space(positions)method.
Notes
Initializes spatial field surface during construction
Controller is used immediately to generate initial spatial visualization
- pre_render_hook_pygame()[source]
Render the spatial field background before drawing agents.
This method applies the cached spatial field surface as a background, providing visual context for bio-inspired agent behavior. The spatial field shows the controller’s response across the entire environment.
Implementation
Blits the pre-computed spatial field surface to the pygame display
Called automatically before agent rendering in each frame
Uses cached surface for optimal performance
Notes
Spatial field surface is generated by
create_spatial_input()Background visualization updates when controller state changes
Provides continuous spatial context for discrete agent positions
- create_spatial_input()[source]
Generate spatial field visualization surface from controller responses.
This method creates a high-resolution spatial field by evaluating the controller at every pixel location and mapping the responses to colors. The resulting surface provides a continuous visualization of how the controller responds across the entire environment space.
Algorithm
Grid Generation: Create uniform grid spanning environment dimensions
Coordinate Mapping: Map screen pixels to simulation coordinates
Controller Evaluation: Query controller response at each position
Color Interpolation: Blend red (high) and white (low) based on response
Surface Creation: Generate pygame surface for efficient rendering
Mathematical Details
Coordinate transformation:
\[ \begin{align}\begin{aligned}x_{sim} = x_{inf} + \frac{i}{w} (x_{sup} - x_{inf})\\y_{sim} = y_{inf} + \frac{j}{h} (y_{sup} - y_{inf})\end{aligned}\end{align} \]Where \((i,j)\) are pixel coordinates and \((w,h)\) are screen dimensions.
Color blending:
\[RGB(i,j) = \text{intensity}(i,j) \cdot [255,0,0] + (1-\text{intensity}(i,j)) \cdot [255,255,255]\]Notes
Called during initialization and when controller state changes
Handles controllers returning None by creating default visualization
Uses pygame’s surface array interface for efficient pixel manipulation
Assumes controller output is normalized to [0,1] range
Shepherding Renderer
Domain-specific renderer for shepherding simulations with predator-prey visualization capabilities.
- class swarmsim.Renderers.shepherding_renderer.ShepherdingRenderer(populations, environment, config_path)[source]
Bases:
BaseRendererSpecialized renderer for shepherding tasks with goal region and sensing area visualization.
This renderer extends the
BaseRendererto provide visualization features specifically designed for shepherding simulations where autonomous agents (herders) guide target agents (sheep) toward specific goal regions. It adds visual elements that are crucial for understanding shepherding dynamics and performance.Key Features
Goal Region Visualization: Semi-transparent circular regions showing target areas
Sensing Area Display: Optional visualization of herder sensing radii
Multi-modal Support: Consistent visualization across Matplotlib and Pygame
Dynamic Updates: Real-time updates of goal position and radius
Transparency Control: Configurable opacity for visual clarity
Visual Elements
Goal Region:
Matplotlib: Semi-transparent green circle with configurable alpha
Pygame: Layered semi-transparent surface with color blending
Dynamic: Position and radius update automatically each frame
Sensing Areas (Optional):
Pygame Only: Blue semi-transparent circles around herder agents
Configurable: Controlled by
sensing_radiusparameterMulti-agent: Individual sensing area for each herder
- param populations:
List of agent populations (typically [sheep, herders]).
- type populations:
list of Population
- param environment:
Shepherding environment with goal_pos and goal_radius attributes.
- type environment:
Environment
- param config_path:
Path to YAML configuration file containing rendering parameters.
- type config_path:
str
- ivar sensing_radius:
Radius of herder sensing areas. Set to
float('inf')to disable.- vartype sensing_radius:
float
- ivar goal_circle:
Cached matplotlib circle object for efficient goal region updates.
- vartype goal_circle:
matplotlib.patches.Circle or None
Examples
Basic shepherding renderer setup:
from swarmsim.Renderers import ShepherdingRenderer from swarmsim.Environments import ShepherdingEnvironment # Create shepherding environment with goal env = ShepherdingEnvironment(config_path="shepherding_config.yaml") env.goal_pos = np.array([10.0, 5.0]) env.goal_radius = 3.0 # Initialize populations sheep = BrownianMotion(config_path="sheep_config.yaml") herders = SimpleIntegrators(config_path="herder_config.yaml") # Create specialized renderer renderer = ShepherdingRenderer([sheep, herders], env, "render_config.yaml") renderer.render()
Notes
Requires environment with
goal_posandgoal_radiusattributesAssumes populations[1] contains herder agents for sensing visualization
Goal region automatically updates if environment goal changes
Sensing areas only rendered in pygame mode
Semi-transparent overlays preserve agent visibility
- __init__(populations, environment, config_path)[source]
Initializes the renderer with the selected visualization mode.
- post_render_hook_matplotlib()[source]
Adds the goal region rendering in Matplotlib.
This function draws a semi-transparent green circle at the goal position, visually indicating where the target agents should be herded.
Notes
Uses plt.Circle to draw the goal region.
The alpha value makes the goal semi-transparent.
The circle automatically updates if the goal moves.
Examples
The goal region is added after agents are plotted:
goal_circle = plt.Circle(self.environment.goal_pos, self.environment.goal_radius, color='green', alpha=0.3, label='Goal Region') self.ax.add_artist(goal_circle)
- post_render_hook_pygame()[source]
Adds the goal region rendering in Pygame.
This function draws a semi-transparent shaded circle at the goal position, visually indicating where the target agents should be herded.
Notes
Uses pygame.Surface to create a shaded overlay.
The goal region is semi-transparent, allowing agents to remain visible.
The shading is dynamically adjusted based on the arena size and goal radius.
Examples
The goal region is added after agents are plotted:
shading_surface = pygame.Surface((self.screen_size[0], self.screen_size[1]), pygame.SRCALPHA) shading_color = (0, 255, 0, 100) # Green color with alpha = 100 (semi-transparent) pygame.draw.circle(shading_surface, shading_color, (goal_x, goal_y), goal_radius) self.window.blit(shading_surface, (0, 0))
See Also
Populations Package - Agent population data structures
Environments Package - Environmental visualization
Simulators Package - Simulation control for rendering
examples.visualization - Comprehensive visualization examples