munetauvsim.simulator
Core simulation driver for AUV multi-agent scenarios.
Provides the Simulator class for running autonomous underwater vehicle simulations with support for multiple vehicles, swarm coordination, communication networks, environmental modeling, data collection, and visualization.
Classes
- Simulator
Main simulation orchestrator for AUV scenarios.
Functions
- save(simulation, filename, format)
Save Simulator object to file (pickle format).
- load(filename, format)
Load Simulator object from file.
Notes
Supports direct-access (no network), muNet, and AquaNet communication modes.
Functions
|
Load Simulator object from file. |
|
Save Simulator object to file. |
Classes
|
|
|
|
|
Main simulation coordinator for multi-agent AUV scenarios. |
- class munetauvsim.simulator.Simulator(name='Simulation', sampleTime=0.02, N=60000, ocean=None, vehicles=None, comnet=None, logging='all', commLogging='all', **kwargs)[source]
Bases:
objectMain simulation coordinator for multi-agent AUV scenarios.
Manages the complete simulation workflow including time evolution, vehicle dynamics integration, environmental modeling, inter-vehicle communication, data collection, collision detection, and visualization. Supports multiple communication modes (direct-access, MuNet, AquaNet) and flexible deployment strategies for swarm coordination research.
- Parameters:
name (str, default='Simulation') – Simulation title. Used for output directory and file naming.
sampleTime (float, default=0.02) – Iteration time step in seconds (50 Hz default). Used for discrete-time integration of vehicle dynamics and kinematics.
N (int, default=60000) – Total number of simulation iterations. With default sampleTime, gives 20 minutes of simulated time.
ocean (env.Ocean, optional) – Ocean environment object containing Ocean current and floor depth map. If None, simulation runs without environmental effects.
vehicles (list of Vehicle, optional) – List of vehicle objects to simulate. Can be added after initialization via the vehicles property.
comnet (str, {'muNet', 'AquaNet', None}, optional) – Communication network type. If None, uses direct-access mode where vehicles can directly read each other’s states (no network delays).
logging (str, default='all') – Main logger configuration. Options: ‘all’, ‘none’, ‘noout’, ‘nofile’, ‘quiet’, ‘onlyfile’, ‘onlyconsole’.
commLogging (str, default='all') – Communication logger configuration. Same options as logging parameter.
**kwargs (dict) – Additional attributes to set on simulator instance.
Attributes
Time Management:
- sampleTimefloat
Simulation time step (seconds per iteration).
- Nint
Number of simulation iterations.
- runTimefloat
Total simulation time in seconds. Equal to N * sampleTime. Setting any of these three automatically updates the others.
- simTimendarray, shape (N+1,)
Time vector for plotting. Includes t=0 start point.
- initTimestr
Timestamp when simulator was created (YYMMDD-HHMMSS format).
Environment and Vehicles:
- oceanenv.Ocean
Ocean environment with currents, floor depth, etc.
- vehicleslist of Vehicle
List of all vehicles in simulation.
- nVehint (read-only)
Number of vehicles in simulation.
Communication Networks:
- comnetstr
Communication network type (‘Direct-Access’, ‘muNet’, ‘AquaNet’).
- muNetcomm.MuNet
muNet network instance (if using muNet).
Output and Logging:
- namestr
Simulation name. Can only be set at initialization.
- outDirstr (read-only)
Output directory path: outputs/<script_name>/<name>_<timestamp>/
- saveFilestr (read-only)
Full path for saving simulator object (pickle).
- logFilestr
Path to main log file.
- commFilestr
Path to communication log file.
- gifFilestr
Path to animated GIF output.
- loglogging.Logger
Main simulation logger instance.
- loggingstr
Main logger configuration setting.
- commLoggingstr
Communication logger configuration setting.
Data Collection:
- simDatandarray, shape (nVeh, N+1, 18)
Complete simulation data array containing vehicle states and controls. For each vehicle and timestep: [eta(6), nu(6), u_control(3), u_actual(3)]. Size N+1 to include initial conditions at t=0.
Visualization:
- numDataPointsint, default=200
Number of trajectory points displayed in 3D animation.
- FPSint, default=8
Frames per second for animated GIF output.
Vehicle Proximity Monitoring:
- vehProxMultfloat, default=1.0
Safety multiplier for vehicle contact radius. Contact radius = vehicle_length * vehProxMult.
- vehProxImmobilizebool, default=True
If True, vehicles stop moving on contact detection for the remainder of the simulation.
Internal Group Management (Private):
- _groupsDictdict
Dictionary of non-leader vehicles by groupId.
- _leadersDictdict
Dictionary of leader vehicles by groupId.
- _noneGrouplist
Vehicles without groupId or target assignment.
- _contactCountint
Total number of vehicle collisions detected.
- _contactRadiusndarray
Cached contact threshold distances for all vehicle pairs.
Methods
Simulation Execution:
- run()
Execute complete simulation: loop, collect data, log stats, generate plots.
- simulate()
Run iteration loop and return collected simulation data.
Visualization:
- plot3D(numDataPoints, FPS, gifFile, vehicles, figNo, show*)
Create 3D animated visualization and save as GIF.
Vehicle Deployment:
- deployAtWpt(vehicle, posOnly)
Deploy vehicle at next waypoint position in its database.
- deploySwarmGrid()
Deploy vehicles in grid formation by group, West of leader.
Swarm Coordination:
- linkSwarmGroup()
Populate vehicle.group lists with references or Models for coordination.
Communication Setup:
- loadMuNet(network, episode, txOffset, vehicles, kwargs)
Configure MuNet communication network.
- loadAquaNet(episode, frames, vehicles)
Configure AquaNet TDMA communication.
Monitoring and Logging:
- initVehicleContactMonitor()
Initialize collision detection system.
- logCommStats()
Log network performance statistics.
Internal Simulation Loops (Private):
- _simulateNoComm(nVeh, simData)
Direct-access iteration loop (no network delays).
- _simulateMuNet(nVeh, simData)
muNet communication iteration loop.
- _simulateAquaNet(nVeh, simData)
AquaNet TDMA iteration loop with time synchronization.
- _simSync()
Synchronize simulation time with AquaNet communication timing.
Notes
Time Parameter Interdependence:
The attributes sampleTime, N, and runTime are coupled:
sampleTime can be set directly
N and runTime update automatically when one is set
Setting sampleTime recalculates runTime if N is defined
Example:
>>> sim.sampleTime = 0.01 # 100 Hz >>> sim.N = 10000 # 100 seconds at 100 Hz >>> print(sim.runTime) 100.0
Communication Modes:
Direct-Access (comnet=None):
Vehicles directly read each other’s states
No network delays or packet loss
Ideal for baseline comparisons
muNet (comnet=’muNet’):
Simulated acoustic modem network
Configurable packet loss, jitter, collision detection
Supports FDMA and TDMA access modes
AquaNet (comnet=’AquaNet’):
Real AquaNet stack via Unix sockets
TDMA protocol with leader-follower timing
Requires AquaNet installation and configuration
Output Directory Structure:
outputs/ <script_name>/ <name>_<timestamp>/ <name>_<timestamp>.log # Main log <name>_<timestamp>_comm.log # Communication log <name>_<timestamp>.gif # Animation <name>_<timestamp>.pickle # Saved simulatorVehicle Contact Detection:
The simulator continuously monitors vehicle-vehicle distances during simulation. When distance < contact_radius:
Warning logged with vehicle IDs and positions
Contact counter incremented
Vehicles immobilized (if vehProxImmobilize=True)
Contact radius based on vehicle length and safety multiplier.
Examples
### Basic simulation with path-following leader:
>>> import munetauvsim.simulator as muSim >>> import munetauvsim.environment as env >>> import munetauvsim.vehicles as veh >>> import munetauvsim.guidance as guid >>> import munetauvsim.communication as com >>> >>> # Create vehicles >>> leader = veh.Remus100s(groupId="A", isLeader=True) >>> leader.wpt = guid.Waypoint([0, 500], [0, 500], [0, 15]) >>> leader.loadPathFollowing() >>> leader.loadConstantProp() >>> >>> # Create simulator >>> sim = muSim.Simulator( ... name="LeaderDemo", ... sampleTime=0.02, ... N=30000, # 10 minutes ... ocean=env.Ocean(), ... vehicles=[leader] ... ) >>> >>> # Deploy and run >>> sim.deployAtWpt(leader) >>> sim.run()
### Multi-agent swarm with muNet communication:
>>> # Create swarm >>> leader = veh.Remus100s(groupId="A", isLeader=True) >>> leader.wpt = guid.Waypoint([0, 1000], [0, 0], [0, 40]) >>> leader.loadPathFollowing() >>> leader.loadConstantProp() >>> >>> followers = veh.buildGroup(3, "A", hasLeader=False) >>> for f in followers: ... f.loadTargetTracking(leader, law="APF") >>> >>> # Setup communication >>> network = com.MuNet(PLR=0.05, MAX_JITTER=0.3) >>> >>> # Create simulator >>> sim = muSim.Simulator( ... name="SwarmDemo", ... N=60000, # 20 minutes ... ocean=env.Ocean(spd=0.5, ang=0), ... vehicles=[leader] + followers ... ) >>> >>> # Configure and run >>> sim.loadMuNet(network, episode=5.0, txOffset=0.5) >>> sim.deployAtWpt(leader) >>> sim.deploySwarmGrid() >>> sim.run() >>> muSim.save(sim)
### Load and analyze previous simulation:
>>> sim = muSim.load( ... "/path/to/outputs/SwarmDemo/SwarmDemo_241103-143000.pickle" ... ) >>> print(f"Simulation ran for {sim.runTime} seconds") >>> print(f"Vehicle contacts: {sim._contactCount}") >>> >>> # Re-plot with different settings >>> sim.plot3D(numDataPoints=500, FPS=12, showFloor=False)
See also
- __init__(name='Simulation', sampleTime=0.02, N=60000, ocean=None, vehicles=None, comnet=None, logging='all', commLogging='all', **kwargs)[source]
Initialize Simulator with time parameters, vehicles, and environment.
- Parameters:
name (str) – Simulation title.
sampleTime (float) – Time step per iteration in seconds.
N (int) – Number of simulation iterations.
ocean (env.Ocean, optional) – Ocean environment object.
vehicles (list of Vehicle, optional) – Vehicles to simulate.
comnet (str, optional) – Communication network type.
logging (str) – Main logger configuration.
commLogging (str) – Communication logger configuration.
**kwargs – Additional attributes to set on simulator.
- Return type:
None
Notes
Creates output directory structure: outputs/<script_name>/<simulation_name>_<timestamp>/
Initializes loggers.
Sets up simulation time array.
- __str__()[source]
Return user-friendly string representation of simulator configuration.
- Return type:
- run()[source]
Execute complete simulation workflow: run, collect data, generate plots.
Orchestrates the full simulation process including iteration loop execution, data collection, vehicle contact monitoring, performance logging, and 3D visualization generation.
Notes
Workflow:
Initialize vehicle contact monitoring
Execute simulation loop, calls simulate()
Log performance metrics
Generate 3D plots and animated GIF, calls plot3D()
Display total execution time
- Return type:
None
- simulate()[source]
Execute simulation iteration loop and collect vehicle data.
- Returns:
simData (ndarray, shape (n_vehicles, N+1, 18)) – Simulation data containing vehicle states and controls. Each row: [eta(6), nu(6), u_control(3), u_actual(3)].
- Return type:
Notes
Initializes swarm groups via linkSwarmGroup() before starting iteration loop.
Delegates to appropriate simulation method based on communication network:
_simulateNoComm() for direct-access
_simulateMuNet() for MuNet
_simulateAquaNet() for AquaNet
- plot3D(numDataPoints=None, FPS=None, gifFile=None, vehicles=None, figNo=None, showClock=True, showData=True, showTraj=True, showPos=True, showCur=True, showFloor=True)[source]
Create 3D visualization and animated GIF of simulation.
- Parameters:
numDataPoints (int, optional) – Number of trajectory points to display (default: self.numDataPoints).
FPS (int, optional) – Frames per second for GIF animation (default: self.FPS).
gifFile (str, optional) – Output GIF filename (default: self.gifFile).
vehicles (list of Vehicle, optional) – Vehicles to plot (default: all vehicles).
figNo (int, optional) – Figure number used by Matplotlib for window reference.
showClock (bool) – Display simulation time clock.
showData (bool) – Display vehicle state data panel.
showTraj (bool) – Show vehicle trajectory paths.
showPos (bool) – Show vehicle position markers.
showCur (bool) – Show ocean current vectors.
showFloor (bool) – Show ocean floor surface.
- Return type:
None
Notes
Wrapper for plotTimeSeries.plot3D().
Saves animated GIF to gifFile path.
- deployAtWpt(vehicle, posOnly=False)[source]
Deploy vehicle at next waypoint position in its database.
- Parameters:
- Return type:
None
Notes
Sets vehicle.eta[0:3] from waypoint position.
Sets vehicle.z_d (desired depth) to current depth.
If posOnly=False, calculates and sets heading toward next waypoint.
- deploySwarmGrid()[source]
Deploy vehicles in grid formation by group, West of group leader.
Arranges follower vehicles in a grid formation at specified spacing from the leader. Formation parameters (spacing, columns) are computed from vehicle swarm coordination attributes (r_follow, r_avoid).
Notes
Grid layout: Rows North-South, Columns East-West, starting West of leader.
Spacing factor alpha=1.2 multiplies r_follow and r_avoid.
Default: 3 columns per row.
Assumes one leader per group (uses first found leader).
- Return type:
None
- linkSwarmGroup()[source]
Link swarm group members on each vehicle for coordination.
Populates vehicle.group lists with references (direct-access) or Models (networked communication) of other group members. Sets vehicle.target to leader if applicable.
Notes
Direct-access mode: vehicle.group contains Vehicle references.
Network mode: vehicle.group contains Model objects for state tracking.
Assumes one leader per group.
Called automatically by simulate() before iteration loop.
- Return type:
None
- loadMuNet(network=None, episode=5.0, txOffset=0.5, vehicles=None, **kwargs)[source]
Configure MuNet communication network for simulation vehicles.
- Parameters:
network (comm.MuNet, optional) – MuNet network object. Creates new if None.
episode (float) – Transmission episode duration in seconds (FDMA reporting interval).
txOffset (float) – Time offset between vehicle transmissions.
vehicles (list of Vehicle, optional) – Vehicles to configure (default: all simulation vehicles).
**kwargs – MuNet configuration parameters (PLR, MAX_JITTER, etc.).
- Return type:
None
Notes
Sets self.comnet = “muNet” and assigns network to self.muNet. Calls vehicle.loadMuNetLF() for each Remus100s vehicle.
- loadAquaNet(episode=None, frames=None, vehicles=None)[source]
Configure AquaNet TDMA communication for simulation vehicles.
- Parameters:
episode (float, optional) – Episode cycle duration (default: sum of all frame durations).
frames (float or list of float, optional) – Frame durations in seconds. If list: [BCRQ_duration, RSPN_duration]. Default: 1.0 second per frame.
vehicles (list of Vehicle, optional) – Vehicles to configure (default: all simulation vehicles).
- Return type:
None
Notes
TDMA structure:
Leader broadcasts (BCRQ), then followers respond (RSPN).
Episode = BCRQ_frame + (RSPN_frame * num_followers).
Calls vehicle.loadAquaNetTdmaLF() for each Remus100s vehicle.
- logCommStats()[source]
Log communication network performance statistics.
Writes network performance metrics (message counts, delivery rates, latency statistics) to the simulation log. Only applies when using muNet networked communication (AquaNet not implemented).
Notes
For muNet: Logs statistics for each network instance (supports multiple networks). Calls MuNet.getStatsReport() for formatted output.
For AquaNet: Statistics logging not yet implemented.
For Direct-Access: No operation (no network to report).
Called automatically by run() after simulation completes.
- Return type:
None
- initVehicleContactMonitor()[source]
Initialize vehicle proximity collision detection system.
Sets up data structures for monitoring vehicle-vehicle distances and detecting collisions during simulation. Contact radius for each vehicle pair is cached based on vehicle sizes and safety multiplier.
Notes
Attributes Initialized:
- _contactCountint
Total number of vehicle contact events detected.
- _contactRadiusndarray, shape (nVeh, nVeh)
Pairwise contact threshold distances in meters.
- _activeContactndarray, shape (nVeh, nVeh), bool
Boolean matrix tracking currently active contact pairs.
- _contactPosBufndarray, shape (nVeh, 3)
Position buffer for efficient distance calculation.
- _contactDistBufndarray, shape (nVeh, nVeh)
Distance matrix buffer.
- _contactMaskBufndarray, shape (nVeh, nVeh), bool
Mask buffer for contact detection logic.
Contact radius calculation:
Uniform vehicle sizes: r_contact = vehicle_length*vehProxMult
Mixed vehicle sizes: r_contact = max(length_i, length_j)*vehProxMult
Default vehProxMult = 1.0 (contact at vehicle length).
Called automatically by run() before simulation loop starts.
- Return type:
None
- monitorContact()[source]
Detect vehicle-vehicle collisions using vectorized distance computation.
Computes pairwise distances between all vehicles using NumPy broadcasting and matrix operations. Detects new contact events, logs warnings with position data, and optionally immobilizes colliding vehicles.
Notes
Algorithm:
Uses vectorized pairwise Euclidean distance calculation to avoid creating large intermediate arrays:
dist_ij = sqrt(||x_i||^2 + ||x_j||^2 - 2 * x_i * x_j)
Computed via:
Position buffer: Extract all vehicle positions (nVeh x 3)
Squared norms: Compute ||x||^2 for each vehicle
Gram matrix: Compute x·y^T via matrix multiplication
Distance matrix: Combine terms and take square root
Contact detection: Compare distances to cached contact radii
Contact Tracking:
Maintains _activeContact matrix to track ongoing collisions
Reports only new contacts to prevent spam reporting for same collision
Clears finished contacts when vehicles separate
Side Effects:
Increments self._contactCount for each new collision
Logs warning with vehicle names and positions
Sets vehicle.immobilized = True if vehProxImmobilize is True
Updates self._activeContact tracking matrix
References
[1] Python Like You Mean It: Broadcasting. https://www.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/Broadcasting.html#The-Final-Answer,-At-Last!
See also
initVehicleContactMonitorInitialize contact detection system
- Return type:
None
- _simulateNoComm(simData)[source]
Simulation loop for direct-access mode (no communication network).
- Parameters:
nVeh (int) – Number of vehicles.
simData (ndarray) – Preallocated array to store simulation data.
- Return type:
None
Notes
Vehicles access each other’s states directly (no network delays).
Iteration sequence: update clock, sync environment state, collect sensors, compute guidance, store data, integrate dynamics, propagate attitude.
- _simulateMuNet(simData)[source]
Simulation loop for muNet communication network.
- Parameters:
nVeh (int) – Number of vehicles.
simData (ndarray) – Preallocated array to store simulation data.
- Return type:
None
Notes
Handles message transmission timing and network updates.
Iteration sequence: update clock, sync environment state, transmit messages per schedule, deliver messages, update vehicle states, compute guidance, integrate dynamics.
Supports multiple muNet networks if passed as list.
- _simulateAquaNet(simData)[source]
Simulation loop for AquaNet TDMA communication network.
- Parameters:
nVeh (int) – Number of vehicles.
simData (ndarray) – Preallocated array to store simulation data.
- Return type:
None
Notes
Starts AquaNet stack and message monitoring threads before loop.
Synchronizes simulation time with network communication timing.
Stops network and joins threads after loop completion.
- _simSync()[source]
Synchronize simulation time with AquaNet communication network.
AquaNet operates in separate threads outside the simulation’s discrete time framework. While each simulation iteration represents exactly sampleTime seconds (typically 0.02s), AquaNet message transmission and processing occurs in real-time threads with variable delays.
This creates a temporal mismatch: simulation time advances in fixed increments while the AquaNet network operations are processed in an independent time frame.
This function pauses each simulation iteration for a duration equal to the sampleTime if AquaNet messages are in transit, preventing simulation time from advancing ahead of network communication time. This synchronizes the simulation duration with the actual time taken for AquaNet operations.
Notes
Monitors TDMA Leader-Follower communication schedule states
In BCRQ Frame: waits for all followers to acknowledge broadcast
In RSPN Frame: waits for scheduled follower to transmit report
Sleeps for sampleTime duration when messages are active
Logs total synchronization time when communication completes
- Return type:
None
- _makeSaveDir(dirName)[source]
Create and return output directory path for simulation files.
- Parameters:
dirName (str) – Directory name for this simulation.
- Returns:
outDir (str) – Full path to created output directory.
- Return type:
Notes
Creates directory structure: outputs/<script_name>/<dirName>/
Automatically detects calling script name.
- munetauvsim.simulator.save(simulation, filename=None, format='pickle')[source]
Save Simulator object to file.
- Parameters:
- Return type:
None
Notes
Removes AquaNet socket references before pickling (sockets not serializable). Saves to simulation.outDir if filename has no directory.