munetauvsim.communication
Communication network simulation for multi-vehicle acoustic messaging.
This module implements the Communication components for simulating underwater acoustic vehicle-to-vehicle networks. It provides a discrete-event network simulator (MuNet) that models physical layer characteristics of acoustic communication including propagation delay, packet loss, bit errors, and collision dynamics.
The module supports multiple Medium Access Control (MAC) protocols for channel allocation and provides configurable error models for realistic network behavior under varying environmental conditions and communication ranges.
Classes
- Network Infrastructure
- MuNet
Underwater acoustic network simulator with configurable MAC protocols, error models, and channel management. Main simulation engine for message transmission, reception, and delivery.
- MuNode
Network node representing vehicle connection to acoustic network with TX/RX channel assignments and collision detection state.
- Data Structures
- MuNetQEntry
Queue entry dataclass for tracking message transmission and reception with metadata (times, addresses, channel info, distance) and payload.
- MuChannel
Network channel specification with frequency, bandwidth, ID, and broadcast flag.
Functions
- Network Management
- getMsgStruct(msgType)Return construct library binary structure for
message type (‘RPRT’, ‘LRPT’, ‘BCRQ’).
- recvMsg(vehicle)Spawn daemon receiver thread for vehicle network
listening.
- recvMsgCallback(bytesMsg, vehicle)Message dispatcher routing received
messages to appropriate handler by type flag.
- REPORT Message Operations (Vehicle State Broadcast)
- writeReport(vehicle, msgType=’REPORT’)Serialize vehicle position,
velocity, timestamp into 37-byte RPRT message.
- sendReport(vehicle, msgType=’REPORT’, address=None)Serialize and
transmit REPORT message over network.
- recvReport(vehicle, bytesMsg)Parse REPORT message, validate fields,
update group member state.
- LEADER-REPORT Message Operations (Leader→Follower)
- writeLeaderReport(vehicle)Serialize leader current state and predicted
next waypoint into 57-byte LRPT message.
- sendLeaderReport(vehicle)Transmit leader state to followers on
broadcast channel.
- recvLeaderReport(vehicle, bytesMsg)Parse leader report, validate
fields, update target tracking state.
- BROADCAST/REQUEST Message Operations (TDMA_LF Swarm Coordination)
- writeBroadcastReq(vehicle)Serialize complete swarm state (leader +
all followers) with response schedule into variable-length BCRQ message (65 + 32*N bytes).
- sendBroadcastReq(vehicle)Transmit swarm broadcast from leader,
reset follower response flags.
- recvBroadcastReq(vehicle, bytesMsg)Parse swarm broadcast, validate
multi-field structure, update target and group member states, compute response timing.
- Message Transmission Scheduling
- schedulerTdmaLF(vehicle)Compute and apply TDMA leader-follower
transmission and response slots for group-synchronized messaging in TDMA_LF protocol.
- schedulerFdmaLF(vehicle)Compute response and coordination timing for
frequency-division (FDMA) leader-follower messaging.
- Position/Velocity Logging Utilities
- writeEtaVelLogs(vehicle)Append current position/velocity/timestamp
to vehicle log.
- resizeLog(logArray, logSize, newCap)Truncate or expand a position /
velocity log to a target capacity, maintaining chronological order.
- readLastEtaLogs(model, n)Retrieve the last n records of position/attitude
(eta) history from a vehicle or model’s log.
- readLastVelLogs(model, n)Retrieve the last n records of velocity history
from a vehicle or model’s log.
- Data Validation and Recovery
- dataIsCorrupted(data, field, kwargs)Validate message field using
type checks, range validation, and structural verification specific to field type.
- restoreCorrupt(vehicle, field, data, kwargs)Attempt recovery of
corrupted field using fallback strategies (logs, predictions, vehicle state, defaults).
- recoverPredict(vehicle, field, data)Recover corrupted field using known
data to compute estimates.
- recoverPrevious(vehicle, field, data)Recover corrupted field using the
last known valid value for that attribute.
- recoverNeutral(vehicle, field, data)Recover corrupted field by replacing
with a neutral / benign default.
- recoverSentinel(vehicle, field, data)Replace corrupted field with a clear
outlier or sentinel value to flag for further handling.
- recoverSkipField(vehicle, field, data)Skip data recovery attempt for
corrupted field, proceeding with rest of message.
- recoverSkip(vehicle, field, data)Skip data recovery, rejecting entire
message.
Notes
Communications Role in Simulation Architecture:
The Communication block operates alongside Guidance, Navigation, and Control blocks in the vehicle autonomy stack:
Guidance Block -> Computes desired trajectories and generates state change commands for formation control, path following, or target tracking.
Navigation Block -> Estimates vehicle state (position, attitude, velocity) from sensors and integrates kinematics for dead reckoning.
Control Block -> Generates actuator commands (rudder, stern plane, propeller) to track guidance references while maintaining stability.
Communication Block -> Enables information sharing between vehicles for cooperative behaviors (formation flying, swarm intelligence, distributed sensing) and coordination with command stations.
Network Simulation Scope:
Application layer functionality (message serialization) is provided by functions in the Communication module, while the MAC layer is simulated by a combination of functions and MuNet methods, and the physical layer (propagation, errors, collisions) is simulated by MuNet alone:
Application Layer: (module functions) Message serialization and parsing. Three message types carry vehicle state and coordination data with binary serialization via Python construct library.
MAC Layer: (split implementation)
Scheduler functions: Message transmissing timing control.
MuNet class: Channel allocation, node assignment, and access protocol infrastructure.
Four access protocols manage channel allocation and scheduling: shared (single broadcast), TDMA (time division), TDMA_LF (leader-follower two-channel), FDMA (frequency division with dedicated channels).
Physical Layer: Acoustic propagation modeled with distance-dependent travel time (speed of sound in water), packet jitter (environmental variability), packet loss (range and frequency dependent), bit errors (SNR or distance based), and collision effects (packet drop or XOR corruption).
Message Types and Structure:
Three binary message formats defined via construct library:
REPORT (RPRT) - 37 bytes:
Standard vehicle state broadcast for group awareness.
Field Type Bytes Description
----- ---- ----- -----------
type bytes(4) 4 Message flag: b'RPRT' or b'RSPN'
group_id bytes(1) 1 Group identifier (ASCII char)
reporter_id uint32 4 Sender vehicle ID
reporter_pos float32[3] 12 Position [x, y, z] meters
reporter_vel float32[3] 12 Velocity [vx, vy, vz] m/s
time_stamp float32 4 Transmission time (seconds)
LEADER-REPORT (LRPT) - 57 bytes:
Leader state with predictive waypoint for follower coordination.
Field Type Bytes Description
----- ---- ----- -----------
type bytes(4) 4 Message flag: b'LRPT'
group_id bytes(1) 1 Group identifier
leader_pos float32[3] 12 Current position
leader_vel float32[3] 12 Current velocity
leader_next_pos float32[3] 12 Next waypoint position
leader_next_vel float32[3] 12 Next waypoint velocity
time_stamp float32 4 Transmission time
BROADCAST/REQUEST (BCRQ) - Variable:
Complete swarm state with response scheduling for TDMA_LF.
Field Type Bytes Description
----- ---- ----- -----------
type bytes(4) 4 Message flag: b'BCRQ'
group_id bytes(1) 1 Group identifier
leader_pos float32[3] 12 Leader current position
leader_vel float32[3] 12 Leader current velocity
leader_next_pos float32[3] 12 Leader next position
leader_next_vel float32[3] 12 Leader next velocity
num_followers uint32 4 Array size N
followers_pos float32[3*N] 12*N Follower positions
followers_vel float32[3*N] 12*N Follower velocities
followers_rspn float32[N] 4*N Last message times
rspn_sched uint32[N] 4*N Response order (IDs)
rspn_start float32 4 Schedule start time
time_stamp float32 4 Transmission time
Total Size: 65 + 32*N bytes
Example (9 followers): 65 + 288 = 353 bytes
MAC Protocols and Channel Architecture:
Shared (‘shared’):
Single broadcast channel at BASE_FREQ
All nodes TX and RX on same channel
Simplest protocol, highest collision risk
TDMA (‘tdma’):
Single channel using full BANDWIDTH
Time-domain multiplexing via protocol schedulers
Nodes transmit in assigned time slots
Eliminates collisions via time separation
Requires precise clock synchronization
TDMA Leader-Follower (‘tdma_lf’):
Two-channel architecture optimized for hierarchical swarms
Broadcast channel (BCAST_ADDR): Leader -> All Followers
Response channel (next available): All Followers -> Leader
Leader sends BCRQ with response schedule
Followers respond in assigned time slots
Efficient for centralized coordination (1 leader + N followers)
FDMA (‘fdma’):
Frequency-division with dedicated TX channel per node
Each node: TX on unique channel, RX on all others
- Maximum capacity:
CHAN_MAXN = (BANDWIDTH - 2*GUARD_BW)/(CHAN_MINBW + GUARD_BW)
Eliminates collisions via frequency separation
Scalability to larger swarms is limited by bandwidth
Channel allocation strategies: center_out (symmetric from BASE_FREQ) or edge_in (sequential from lowest frequency)
Physical Layer Error Models:
Jitter (Packet Delay Variability):
Uniform: Random delay [0, MAX_JITTER] seconds
Models environmental propagation variability
Affects message ordering at receiver
Packet Loss Rate (PLR):
Uniform: Constant drop probability PLR
Exponential: Distance-based PLR = PLR * exp((d - d_nom)/d_char) * f_factor
Sonar Simple: PLR = PLR * (d/d_nom)^1.5 * exp((d - d_nom)/d_char) * f_factor
Frequency correction: +1% loss per kHz above BASE_FREQ
Bit Error Rate (BER):
Poisson: Constant BER, error count ~ Poisson(totalBits * BER)
Exponential: Distance-based BER = BER * exp((d - d_nom)/d_char)
SNR: SNR = SNR_0 - 15*log10(d/d_nom), BER = BER * 10^(slope*(SNR_0 - SNR))
Random bit positions flipped via XOR
Collision Handling:
Drop: All overlapping packets removed from queue
Corrupt: XOR of overlapping byte regions (additive interference model)
Collision detection via per-node active RX dictionary tracking ongoing receptions by channel
Queue Architecture and Message Flow:
TX Queue (Transmission):
Min-heap priority queue sorted by delivery start/end time
Entries created during transmit() for each receiver
Metadata: start_time, end_time, src_addr, dest_addr, cid, freq, bw, distance, message
Sorting:
Collision disabled: heap sorted by end_time (delivery completion)
Collision enabled: heap sorted by start_time (delivery initiation)
RX Queue (Active Reception):
Min-heap sorted by end_time (delivery completion)
Used only when collision detection enabled
Messages move TX->RX when reaching start_time
Active RX dictionary (rxd) tracks overlapping receptions per channel
Delivery Flow:
Application: vehicle.CommNetwork.send(message, address)
Network.transmit(): Compute times, distances -> enqueue to TXQ
Simulation loop: Network.deliver(time) called each timestep
deliver() dispatcher:
Collision disabled: _rxNoColl
Pop from TXQ when time ≥ end_time
Apply PLR -> Apply BER -> Deliver to node.recv()
Collision enabled: _rxWithColl
Pop from TXQ when time ≥ start_time -> push to RXQ
Track in rxd (active RX dictionary)
Pop from RXQ when time ≥ end_time
Check collisions via rxd -> Apply PLR -> Apply BER -> Deliver
node.recv(): Call recvMsgCallback() dispatcher
recvMsgCallback(): Route by type flag to handler
Handler (recvReport, recvLeaderReport, recvBroadcastReq):
Parse message via getMsgStruct()
Validate all fields via dataIsCorrupted()
Attempt recovery via restoreCorrupt() if corruption detected
Update vehicle state (group, target, logs)
Data Validation and Corruption Recovery:
Underwater acoustic network settings allow simulating high error rates (BER, packet collision corruption) requiring validation and recovery:
Validation Strategy:
Type-specific checks for each message field
Range validation (positions within 10E6 m, velocities within 100 m/s)
Structural verification (array lengths, element types, finite values)
Recovery Strategies:
Configurable per vehicle and per message field
Uses a sequential fallback to allow multiple recovery attempts using a preference heirarchy
Strategies include:
Predict: use available known data to estimate corrupted data
Previous: use previous known data to replace corrupted data
Neutral: use harmless neutral data to replace corrupted data
Sentinel: use obvious bad value to replace corrupted data
Skip Field: skip only corrupted message field
Skip: skip entire message
Design Philosophy:
The module uses strategy pattern for dynamic assignment of:
Protocol handlers (channel builders, node assigners)
Channel allocation generators (center-out, edge-in)
Error models (PLR, BER, collision, jitter)
See also
vehicles.VehicleVehicle state and dynamics
vehicles.ModelData model for vehicle state
guidance.pyFormation control and path following
navigation.pyState estimation and sensor fusion
control.pyActuator command generation
Functions
|
Validate message field data for corruption using field-specific rules. |
|
Returns the same class as was passed in, with dunder methods added based on the fields defined in the class. |
|
Return binary message structure for serialization/parsing. |
|
Least-recently-used cache decorator. |
|
Retrieve last n records from vehicle data model position (eta) log. |
|
Retrieve last n records from vehicle data model velocity log. |
|
Handle corrupted field by replacing with zero or neutral value. |
|
Recover corrupted field using predictive estimation from available data. |
|
Recover corrupted field using last known valid value. |
|
Handle corrupted field by replacing with a sentinel value. |
|
Handle corrupt data by skipping the entire message. |
|
Skip recovery for corrupted field but continue processing rest of message. |
|
Parse BROADCAST/REQUEST message and update follower's target and group member states. |
|
Parse and process LEADER-REPORT message from leader vehicle. |
|
Spawn a new receiver thread for vehicle message listening. |
|
Dispatch incoming network message to appropriate handler by type flag. |
|
Parse and process received REPORT message from group member. |
|
Expand position and velocity logs of data model to new capacity. |
|
Attempt corrupted message field recovery by defined strategy with fallback. |
|
Compute response and coordination timing for FDMA leader-follower messaging. |
|
Compute and apply TDMA leader-follower transmission scheduling. |
|
Serialize and send BROADCAST/REQUEST message from leader to all followers on broadcast channel. |
|
Serialize and send leader state LEADER-REPORT message to followers. |
|
Serialize and send vehicle state REPORT message over network. |
|
Sends a scheduled RESPONSE message from follower to leader. |
|
Serialize leader and all follower states into BROADCAST/REQUEST message. |
|
Appends reported position and velocity in vehicle model data logs. |
|
Serialize leader state into LRPT message. |
|
Serialize vehicle state into REPORT message. |
Classes
|
|
|
Network channel for acoustic transmission. |
|
Underwater acoustic network simulator with discrete-event message delivery. |
|
Message entry for transmission/reception queue in network simulation. |
|
Network node representing vehicle connection to acoustic network. |
|
|
|
|
|
A class that represents a thread of control. |
- class munetauvsim.communication.MuNetQEntry(start_time, end_time, src_addr, dest_addr, cid, freq, bw, distance, message)[source]
Bases:
objectMessage entry for transmission/reception queue in network simulation.
Container dataclass holding network metadata and message payload for tracking acoustic transmissions through TX/RX queues. Metadata used for network simulation and error model calculations; only payload transmitted as acoustic data.
Attributes
- start_timefloat
Time when message transmission begins reaching receiver.
- end_timefloat
Time when message transmission ends at receiver.
- src_addrint
Source node address.
- dest_addrint
Destination node address.
- cidint
Channel ID carrying transmission.
- freqfloat
Channel center frequency in kHz.
- bwfloat
Channel bandwidth in kHz.
- distancefloat
Distance from source to destination in meters (computed at creation).
- messagebytearray
Message payload (this is the only part carried as acoustic data).
Notes
Heap queue ordering maintained by tuple (sort_time, qid):
TX queue with collision disabled: sorts by end_time
TX queue with collision enabled: sorts by start_time
RX queue: sorts by end_time
Dataclass uses __slots__ for memory efficiency in large message volumes.
- Parameters:
- class munetauvsim.communication.MuChannel(cid, freq, bw, isBcst)[source]
Bases:
objectNetwork channel for acoustic transmission.
Attributes
- cidint
Unique channel identifier.
- freqfloat
Center frequency in kHz.
- bwfloat
Channel bandwidth in kHz.
- isBcstbool
True if broadcast channel (all nodes RX).
- class munetauvsim.communication.MuNode(address, vehicle, network)[source]
Bases:
objectNetwork node representing vehicle connection to acoustic network.
Abstracts vehicle communication interface with TX/RX channel assignments, active reception tracking for collision detection, and message send/receive methods.
Attributes
- addressint
Unique node address on network.
- vehicleVehicle
Vehicle object associated with this node.
- networkMuNet
Reference to MuNet network instance.
- rxddict
Active reception dictionary tracking overlapping transmissions by channel for collision detection. Maps channel_id -> [queue_entries].
- tx_channelsset
Channel IDs available for transmission.
- rx_channelsset
Channel IDs tuned for reception.
Methods
- send(message, cid)
Transmit message on specified channel.
- recv(message, cid)
Receive message from specified channel.
Notes
The rxd (receive dictionary) tracks active message receptions by channel. When message completes reception, it is removed from rxd. If two messages overlap in time and channel, collision detection occurs. This design supports multi-channel collision detection without global search.
- __init__(address, vehicle, network)[source]
Initialize network node for vehicle communication interface.
- Parameters:
- Return type:
None
Notes
Initializes empty rxd (active reception dictionary) and empty TX/RX channel sets. Channels assigned later via network._assignNodes().
- send(message, cid)[source]
Transmit message from node on specified channel.
Forwards message to network transmission queue via network.transmit(). Logs transmission event with channel details.
- Parameters:
- Return type:
None
Notes
Acoustic Network Limitation:
Acoustic network does not include physical layer for automatic sender identification. Senders must package source identity in message payload if receiver needs to identify sender.
Logging:
Logs transmission at INFO level with format:
{sender_addr:channel_id} (cid|freq) message_bytes
Example: {003:__1} (1|24.50) b’RPRT…’
- recv(message, cid)[source]
Receive message at node and route to vehicle message handler.
Logs reception event and invokes recvMsgCallback() dispatcher to route message to appropriate handler based on message type flag.
- Parameters:
- Return type:
None
Notes
Acoustic Network Limitation:
Receiver does not automatically know sender address unless packaged in message payload, or if sender is on dedicated channel (as in FDMA where channel ID implies sender).
Message Routing:
Calls recvMsgCallback(message, self.vehicle) which: 1. Extracts 4-byte type flag from message header 2. Validates type flag for corruption 3. Routes to handler: recvReport, recvLeaderReport, or recvBroadcastReq
Logging:
Logs reception at INFO level with format:
{channel_id:receiver_addr} (cid|freq) message_bytes
Example: {__1:003} (1|24.50) b’RPRT…’
Error Handling:
Exceptions during message handling caught and logged by recvMsgCallback().
- class munetauvsim.communication.MuNet(**kwargs)[source]
Bases:
objectUnderwater acoustic network simulator with discrete-event message delivery.
Simulates vehicle-to-vehicle acoustic communication including Medium Access Control (MAC) protocols, physical layer transmission characteristics, such as jitter, and error models, such as packet loss, bit errors, and collisions. Provides infrastructure for cooperative vehicle behaviors requiring information exchange in underwater swarm robotics.
The simulator uses a priority queue-based message scheduling, dynamic strategy assignment for protocol and error model selection, and per-node channel management for frequency-division and time-division multiple access.
Attributes
Physical Layer Parameters:
- C_WATERfloat, default=1500.0
Speed of sound in water (m/s). Determines acoustic propagation delay between vehicles. Constant approximation valid for shallow depths (<100m). For depth-dependent modeling, incorporate Mackenzie equation.
- BASE_FREQfloat, default=24.0
Network base (center) acoustic frequency (kHz). Symmetric frequency allocation strategies (center_out) place first channel here. Typical underwater acoustic modems operate 10-30 kHz for medium-range communication.
- BANDWIDTHfloat, default=10.0
Total available bandwidth for all channels (kHz). Determines maximum number of frequency-division channels. Higher bandwidth supports more simultaneous channels but may increase interference.
- GUARD_BWfloat, default=0.25
Guard bandwidth between adjacent channels and at band edges (kHz). Prevents inter-channel interference from frequency drift and imperfect filtering. Larger guards reduce usable bandwidth but improve isolation.
CHAN_MAXN : see Properties.
- CHAN_MINBWfloat, default=1.0
Minimum channel bandwidth for data transmission (kHz). With guard bands, determines channel spacing. Narrower channels support more frequency division but may limit data rate.
- BCAST_ADDRint, default=255
Reserved address for broadcast channel in shared and TDMA protocols. Messages sent to this address received by all nodes listening on broadcast channel.
- DATA_RATEint, default=1000
Channel data transmission rate (bits per second). Determines message transmission time: t_data = (message_bytes * 8) / DATA_RATE. Typical acoustic modems: 100-5000 bps depending on range and quality.
- MAX_JITTERfloat, default=0.2
Maximum random packet delay added to transmission (seconds). Simulates environmental propagation variability from temperature gradients, salinity variations, surface reflections. Uniform distribution [0, MAX_JITTER].
- NOM_DISTfloat, default=1000.0
Nominal reference distance for distance-based error models (meters). At this range, computed PLR/BER equals base value. Shorter distances see improved performance; longer distances see degradation.
- PLRfloat, default=0.02
Base Packet Loss Ratio in range [0.0, 1.0]. Fraction of packets randomly dropped before delivery. Default 2% represents moderate acoustic channel. Actual loss may be distance-dependent based on plrType strategy.
- PLR_CHARDISTfloat, default=2000.0
Characteristic distance for exponential PLR attenuation (meters). Controls rate of PLR increase beyond nominal distance in distance-based models. Smaller values -> faster degradation with range.
- BERfloat, default=1e-3
Base Bit Error Rate (errors per bit). Probability of random bit flip in message payload. Typical ranges: Poor 1e-1 to 1e-2, Moderate 1e-3 to 1e-4, Good 1e-5 to 1e-6. Generated via Poisson distribution.
- BER_CHARDISTfloat, default=3000.0
Characteristic distance for exponential BER attenuation (meters). Controls rate of BER increase beyond nominal distance. Smaller values -> faster bit error degradation with range.
- SNR_NOMINALfloat, default=30.0
Nominal Signal-to-Noise Ratio for SNR-based BER models (decibels). Reference SNR where BER equals base value. Path loss reduces SNR with distance using simplified spreading model.
- SNR_SLOPEfloat, default=0.1
Slope factor for SNR-based BER models (dimensionless). Controls BER sensitivity to SNR variations. Higher slope -> faster BER increase as SNR degrades.
MAC Protocol Configuration:
- accessMode{‘shared’, ‘tdma’, ‘tdma_lf’, ‘fdma’}, default=’fdma’
Medium Access Control protocol for channel allocation and node assignment. Determines how vehicles share acoustic bandwidth:
‘shared’: Single broadcast channel, all nodes TX/RX simultaneously. Simplest but highest collision risk.
‘tdma’: Time-Division Multiple Access. Single channel using full bandwidth. Nodes transmit in assigned time slots. Eliminates collisions via temporal separation. Requires clock synchronization and scheduling coordination.
‘tdma_lf’: TDMA Leader-Follower variant. Two-channel architecture: broadcast for leader->followers, dedicated response for followers-> leader. Optimized for hierarchical swarms (1 leader + N followers). Efficient coordinated communication with response scheduling.
‘fdma’: Frequency-Division Multiple Access. Dedicated TX channel per node, RX on all others. Eliminates collisions via frequency separation. Scalable to larger swarms limited by bandwidth capacity.
- orderMode{‘center_out’, ‘edge_in’}, default=’center_out’
Channel frequency allocation strategy in available bandwidth:
‘center_out’: Symmetric allocation from BASE_FREQ. First channel at center, then alternates ±offset pairs expanding outward. Balances frequency distribution, minimizes worst-case interference.
‘edge_in’: Sequential allocation from lowest frequency. Fills from band edge upward by lane increments. Simplifies allocation but may create uneven frequency usage.
Error Model Configuration:
- jitterType{‘uniform’, ‘off’}, default=’uniform’
Packet delay variability strategy:
‘uniform’: Random delay [0, MAX_JITTER] from uniform distribution. Models propagation variability from environmental effects.
‘off’: Zero jitter. Packets arrive at deterministic propagation time. For idealized testing.
- collType{‘drop’, ‘corrupt’, ‘off’}, default=’drop’
Collision handling strategy when messages overlap in time/channel:
‘drop’: All colliding packets removed from queue. Conservative approach simulating complete signal destruction from interference.
‘corrupt’: XOR overlapping byte regions bidirectionally. Models additive interference destroying signals in overlap window. Packets delivered but corrupted.
‘off’: No collision detection. Messages delivered independently even if overlapping. For capacity testing without interference.
- plrType{‘uniform’, ‘exp_simple’, ‘sonar_simple’, ‘off’}, default=’sonar_simple’
Packet Loss Rate strategy:
‘uniform’: Constant PLR independent of distance. Simple baseline.
‘exp_simple’: Distance-based exponential attenuation: PLR_d = PLR * exp((d - d_nom)/d_char) * (1 + (f - f_0)*0.01) Includes frequency correction (+1% per kHz above BASE_FREQ).
‘sonar_simple’: Sonar equation approximation with geometric spreading and absorption: PLR_d = PLR * (d/d_nom)^1.5 * exp((d - d_nom)/d_char) * freq_factor Uses practical spreading exponent (1.5) between spherical (2) and cylindrical (1). More realistic for underwater acoustics.
‘off’: No packet loss. All messages delivered (subject to collisions).
- berType{‘poisson’, ‘exp_simple’, ‘snr’, ‘off’}, default=’poisson’
Bit Error Rate strategy:
‘poisson’: Constant BER. Error count sampled from Poisson(total_bits * BER). Random bit positions flipped via XOR. Distance-independent baseline.
‘exp_simple’: Distance-based exponential BER: BER_d = BER * exp((d - d_nom)/d_char) Error count from Poisson(total_bits * BER_d).
‘snr’: SNR-based BER using path loss model: SNR = SNR_0 - 15*log10(d/d_nom) BER_SNR = BER * 10^(slope*(SNR_0 - SNR)) More realistic signal quality degradation with distance.
‘off’: No bit errors. Messages delivered uncorrupted (subject to packet loss and collisions).
- seedint, optional
Random seed for NumPy RNG. Enables reproducible simulations with deterministic error patterns. If None, uses system entropy for non-reproducible runs.
Data Structures:
- channelsdict
Network channel registry. Key: channel ID (int), Value: MuChannel dataclass with (cid, freq, bw, isBcst). Populated during channel building phase based on accessMode.
- nodesdict
Registered network nodes. Key: node address (int), Value: MuNode object with vehicle reference, TX/RX channel sets, active reception dictionary. Populated during vehicle registration.
- txqlist
Transmission queue (min-heap). Entries: (sort_time, qid, MuNetQEntry). Sorted by start_time (collision enabled) or end_time (collision disabled). Messages moved to txq during transmit(), popped during deliver().
- rxqlist
Active reception queue (min-heap). Used only when collision detection enabled. Entries: (end_time, qid, MuNetQEntry). Messages moved from txq when reaching start_time, tracked in node.rxd for collision detection.
- rngnumpy.random.Generator
NumPy random number generator instance. Initialized with seed parameter. Used for all stochastic operations (jitter, PLR, BER, bit positions).
Statistics Tracking:
- statsdict
Network performance counters updated during message flow:
- packetSentint
Total packets enqueued to txq during transmit() calls.
- packetDeliveredint
Packets successfully delivered to node.recv() after all error models.
- packetDropPLRint
Packets dropped by Packet Loss Rate strategy.
- packetDropCollint
Packets dropped by collision strategy (collType=’drop’ only).
- packetFailedDelint
Packets that triggered exceptions during node.recv() callback.
- inTransitTXint
Messages currently in txq (updated by calcStats()).
- inTransitRXint
Messages currently in rxq (updated by calcStats()).
- plrActualfloat
Actual PLR: packetDropPLR / packetSent (computed by calcStats()).
- plrDeliveryRatefloat
Delivery rate: packetDelivered / packetSent (computed by calcStats()).
- collDropRatefloat
Collision drop rate: packetDropColl / packetSent (computed by calcStats(), collType=’drop’ only).
- inTransitRatefloat
In-transit ratio: (inTransitTX + inTransitRX) / packetSent (computed by calcStats()).
- collisionsint
Collision events detected (overlapping messages on same channel).
- packetCorruptCollint
Packets corrupted by collision XOR (collType=’corrupt’ only).
- packetBERint
Packets modified by bit error injection.
- bitErrorsint
Total individual bit flips applied across all messages.
Dynamically Assigned Methods:
The following methods are assigned during __init__ based on configuration, implementing strategy pattern for protocol and error model selection:
- _buildChannelscallable
Channel builder for accessMode: _buildChannelsShared, _buildChannelsTDMA, _buildChannelsTDMALF, or _buildChannelsFDMA.
- _assignNodescallable
Node channel assigner for accessMode: _assignNodesShared, _assignNodesTDMA, _assignNodesTDMALF, or _assignNodesFDMA.
- _genChannelcallable
Channel generator for orderMode: _genChannelCenterOut or _genChannelEdgeIn.
- _channelGenGenerator
Active channel generator instance created from _genChannel.
- _generateJittercallable
Jitter generator for jitterType: _jitterUniform or _jitterDisabled.
- _applyCollcallable
Collision handler for collType: _collDrop, _collCorrupt, or pass-through.
- _txEnqueuecallable
TX queue enqueuer for collType: _txWithColl or _txNoColl.
- delivercallable
Message delivery dispatcher for collType: _rxWithColl or _rxNoColl.
- _applyPLRcallable
PLR strategy for plrType: _plrUniform, _plrExpSimple, _plrSonarSimple, or _plrDisabled.
- _applyBERcallable
BER strategy for berType: _berPoisson, _berExpSimple, _berSNR, or _berDisabled.
Methods
Public Interface:
- register(vehicle)MuNode
Create network node for vehicle with channel assignment. Returns MuNode with TX/RX channels configured per accessMode.
- transmit(message, cid, srcAddr)None
Queue message for transmission to all receivers on channel. Computes propagation times and enqueues to txq.
- deliver(time)None
Process message queues at simulation time. Dynamically assigned to _rxNoColl or _rxWithColl based on collision configuration.
- calcStats()None
Compute network performance statistics from raw counters. Updates derived metrics (delivery rate, PLR, collision rate).
- getStatsReport()str
Return formatted multi-line statistics report. Calls calcStats() first.
Queue Management:
- _txEnqueue(rxTime, dataTime, srcAddr, rNode, channel, distances, message)None
Enqueue messages to txq. Dynamically assigned to _txNoColl or _txWithColl.
- _txNoColl(…)None
Enqueue without collision tracking. Sorts by end_time.
- _txWithColl(…)None
Enqueue with collision tracking. Sorts by start_time.
- _rxNoColl(time)None
Deliver messages without collision detection. Pop from txq, apply PLR/BER, deliver to node.
- _rxWithColl(time)None
Deliver with collision detection. Two-phase: txq->rxq (populate node.rxd), rxq->deliver (check collisions, apply PLR/BER).
- _nextQid()int
Return next sequential queue message ID for heap tie-breaking.
- _getChannelRXNodes(cid)list[MuNode]
Return nodes registered to receive on channel ID.
Error Models:
- _generateJitter(size)ndarray
Generate jitter delays. Assigned to _jitterUniform or _jitterDisabled.
- _jitterUniform(size)ndarray
Uniform random delays [0, MAX_JITTER].
- _jitterDisabled(size)ndarray
Zero delays (array of zeros).
- _applyColl(entry, rNode)bool
Check/handle collisions. Assigned to _collDrop, _collCorrupt, or pass-through.
- _collDrop(entry, rNode)bool
Drop all colliding packets from rxq.
- _collCorrupt(entry, rNode)bool
XOR overlapping byte regions of colliding packets.
- _applyPLR(entry)bool
Test for packet loss. Assigned to _plrUniform, _plrExpSimple, _plrSonarSimple, or _plrDisabled.
- _plrUniform(entry)bool
Constant PLR test (random < PLR).
- _plrExpSimple(entry)bool
Distance-based exponential PLR.
- _plrSonarSimple(entry)bool
Sonar equation PLR with spreading and absorption.
- _plrDisabled(entry)bool
No packet loss (always False).
- _applyBER(entry)None
Inject bit errors. Assigned to _berPoisson, _berExpSimple, _berSNR, or _berDisabled.
- _berPoisson(entry)None
Constant BER with Poisson error count.
- _berExpSimple(entry)None
Distance-based exponential BER.
- _berSNR(entry)None
SNR-based BER with path loss model.
- _berDisabled(entry)None
No bit errors (pass-through).
- _flipBits(msg, bitPos)None
Flip specified bit positions in bytearray via XOR.
Channel Management:
- _genChannel(cid, freq, bw, isBcst)Generator[MuChannel]
Generate channels per allocation strategy. Assigned to _genChannelCenterOut or _genChannelEdgeIn.
- _genChannelCenterOut(…)Generator[MuChannel]
Center-outward allocation from BASE_FREQ.
- _genChannelEdgeIn(…)Generator[MuChannel]
Edge-inward allocation from lowest frequency.
- _getChannelCenterLimits()tuple
Compute frequency bounds for channel centers. Returns (center, fmin, fmax, lane, chan_bw).
- _makeBroadcastChannel(cid, freq, bw)MuChannel
Create broadcast channel with optional parameter overrides.
- _buildChannels()None
Build channel registry. Assigned to _buildChannelsShared, _buildChannelsTDMA, _buildChannelsTDMALF, or _buildChannelsFDMA.
- _buildChannelsShared()None
Single broadcast channel for all nodes.
- _buildChannelsTDMA()None
Single TDMA channel using full bandwidth.
- _buildChannelsTDMALF()None
Two channels for leader-follower TDMA.
- _buildChannelsFDMA()None
Multiple channels for frequency division.
- _assignNodes(node)str
Assign TX/RX channels to node. Assigned to _assignNodesShared, _assignNodesTDMA, _assignNodesTDMALF, or _assignNodesFDMA.
- _assignNodesShared(node)str
Assign to broadcast channel.
- _assignNodesTDMA(node)str
Assign to TDMA channel.
- _assignNodesTDMALF(node)str
Assign based on leader/follower role.
- _assignNodesFDMA(node)str
Assign dedicated TX channel, RX on all others.
- _updateNodeRXFDMA()None
Update all nodes’ RX channels when new TX channel added in FDMA.
Properties
- CHAN_MAXNint
Maximum channels in available bandwidth (read-only). Formula: (BANDWIDTH - 2*GUARD_BW) // (CHAN_MINBW + GUARD_BW). Determines FDMA capacity limit.
Notes
Discrete-Event Simulation Architecture:
MuNet operates as a discrete-event simulator with two priority queues:
Transmitting Queue (txq): Messages pending transmission delivery
Min-heap sorted by start_time (collision enabled) or end_time (collision disabled)
Entries: (sort_time, qid, MuNetQEntry)
Populated during transmit()
Drained during deliver()
Receiving Queue (rxq): Active message receptions (collision mode only)
Min-heap sorted by end_time
Entries: (end_time, qid, MuNetQEntry)
Populated from txq when time ≥ start_time
Drained when time ≥ end_time
Enables collision detection via node.rxd dictionary
Message Flow:
Application -> vehicle.CommNetwork.send(message, address)
Network.transmit() -> Compute times/distances -> Enqueue to txq
Simulation loop -> Network.deliver(time) each timestep
deliver() dispatcher:
Collision disabled (_rxNoColl):
txq -> Apply PLR -> Apply BER -> Deliver
Collision enabled (_rxWithColl):
Phase 1: txq -> rxq (populate node.rxd)
Phase 2: rxq -> Check collisions -> Apply PLR -> Apply BER -> Deliver
node.recv() -> recvMsgCallback() -> Message handler
Message handler -> Parse -> Validate -> Update vehicle state
Strategy Pattern Design:
Dynamic method assignment during __init__ enables protocol and error model selection without conditional branching during message flow:
MAC protocol strategies (4 variants)
Channel allocation strategies (2 variants)
Error model strategies (2 jitter * 3 collision * 4 PLR * 4 BER = 96 combinations)
Total configuration space: 768 unique network configurations.
Network Capacity Limits:
Shared/TDMA: Unlimited nodes (single channel)
TDMA_LF: 1 leader + unlimited followers (two channels)
FDMA: Max nodes = CHAN_MAXN (typically 8-20 for 10 kHz bandwidth)
See also
MuNodeNetwork node representing vehicle communication interface
MuNetQEntryQueue entry dataclass for message tracking
MuChannelChannel specification dataclass
vehicles.VehicleVehicle state and dynamics
Examples
>>> # Network creation >>> network = MuNet( ... accessMode='fdma', ... plrType='sonar_simple', ... berType='snr', ... collType='corrupt', ... seed=42 ... )
>>> # Vehicle registration >>> vehicle.CommNetwork = network >>> vehicle.commNode = network.register(vehicle)
>>> # Periodic transmission (in vehicle update loop) >>> if vehicle.clock % vehicle.reportInterval == 0: ... sendReport(vehicle)
>>> # Network delivery (in main simulation loop) >>> for timestep in simulation: >>> # ... vehicle dynamics, guidance, control ... ... network.deliver(time) # Process queued messages >>> # ... update visualizations ...
>>> # Statistics >>> network.calcStats() >>> print(network.getStatsReport())
- __init__(**kwargs)[source]
Initialize acoustic network with physical parameters, protocols, and error models.
Configures all network simulation parameters, assigns strategy methods for MAC protocols and error models, initializes data structures, and logs network configuration. All parameters customizable via kwargs for rapid prototyping.
- Parameters:
**kwargs (dict) – Optional keyword arguments override default parameter values. Supported keys correspond to instance attributes documented in class docstring.
- Return type:
None
Notes
Parameter Categories:
Physical Constants (7 parameters):
C_WATER, BASE_FREQ, BANDWIDTH, GUARD_BW, CHAN_MINBW, BCAST_ADDR, DATA_RATE
Define acoustic propagation, frequency allocation, addressing
Error Model Parameters (8 parameters):
MAX_JITTER, NOM_DIST, PLR, PLR_CHARDIST, BER, BER_CHARDIST, SNR_NOMINAL, SNR_SLOPE
Control packet loss, bit errors, propagation variability
Protocol Configuration (6 parameters):
accessMode, orderMode, jitterType, collType, plrType, berType
Select MAC protocol and error model strategies
Reproducibility (1 parameter):
seed
Enables deterministic simulation runs
Initialization Sequence:
1. Set Default Parameters Physical layer constants, error model parameters, protocol configuration.
2. Apply Keyword Overrides Custom parameters from kwargs update defaults via __dict__.update().
3. Initialize Data Structures Empty channel/node dictionaries, TX/RX queues, statistics counters.
4. Create RNG Instance NumPy random generator with seed for reproducibility.
5. Assign Protocol Strategies Dynamic method binding for MAC protocols (channel builders, node assigners).
6. Create Channel Generator Instantiate generator from _genChannel strategy.
7. Assign Error Model Strategies Dynamic method binding for jitter, collisions, PLR, BER.
8. Log Configuration Write network parameters and strategy selections to log.
Strategy Pattern Implementation:
Instead of conditional logic during message flow, __init__ assigns concrete implementations to abstract method names based on configuration keywords:
accessMode: Assigns channel builder and node assigner method pairs
orderMode: Assigns frequency allocation generator method
jitterType: Assigns packet delay generator method
- collType: Assigns collision handler, queue enqueuer, and message
delivery methods
plrType: Assigns packet loss rate strategy method
berType: Assigns bit error rate strategy method
This enables runtime polymorphism without performance overhead of conditional branching during network operation.
Statistics Initialization:
All statistics counters reset to zero:
‘packetSent’, ‘packetDelivered’, ‘packetDropPLR’, ‘packetDropColl’, ‘packetFailedDel’, ‘inTransitTX’, ‘inTransitRX’, ‘plrActual’, ‘plrDeliveryRate’, ‘collDropRate’, ‘inTransitRate’, ‘collisions’, ‘packetCorruptColl’, ‘packetBER’, ‘bitErrors’
Statistics updated during message processing. Call calcStats() to compute derived metrics before reading rates.
Channel Generator Initialization:
After strategy assignment, instantiates a channel generator. Generator yields MuChannel objects on demand during channel building. Removes need to pre-allocate channel list, supports lazy allocation in FDMA as nodes register.
Error Model Interaction:
Multiple error models applied sequentially during message delivery:
Collision detection (if enabled): Check rxd for overlaps
If collType=’drop’: Remove all colliding packets
If collType=’corrupt’: XOR overlapping byte regions
Packet Loss: Test with _applyPLR()
If dropped: Increment stats, skip delivery
Bit Errors: Apply with _applyBER()
Flip random bit positions in message payload
Delivery: Call node.recv() with possibly corrupted message
Order matters: PLR prevents BER computation on dropped packets, saving cycles.
Examples
### Default network (FDMA, sonar PLR, poisson BER):
>>> import munetauvsim.communication as comm >>> network = comm.MuNet()
### Custom configuration:
>>> network = comm.MuNet( ... accessMode='tdma_lf', ... plrType='exp_simple', ... PLR=0.05, ... PLR_CHARDIST=1500, ... berType='snr', ... BER=1e-3, ... SNR_NOMINAL=25, ... collType='corrupt', ... seed=42 ... )
### Ideal network (no errors):
>>> network = comm.MuNet( ... jitterType='off', ... collType='off', ... plrType='off', ... berType='off' ... )
### High-error scenario:
>>> network = comm.MuNet( ... PLR=0.20, ... BER=1E-2, ... MAX_JITTER=1.0, ... collType='corrupt' ... )
- rng
Some stats not accurate until calcStats() is called.
- __getstate__()[source]
Customize pickle serialization by removing non-serializable generator.
- Returns:
dict – Network state with channel generator removed for safe pickling.
- Return type:
Notes
Generator objects cannot be pickled. This method removes _channelGen during serialization.
- __setstate__(state)[source]
Restore network state and recreate channel generator after unpickling.
- Parameters:
state (dict) – Network state dictionary from __getstate__.
- Return type:
None
Notes
Recreates channel generator according to current orderMode strategy. Generator does not restore to pre-pickle state (generates from start).
- register(vehicle)[source]
Create and register vehicle node on network with channel assignment.
- Parameters:
vehicle (Vehicle) –
Vehicle object with nodeAddr and callSign attributes.
nodeAddr : int, node network address
callSign : str, custom unique vehicle identifier
- Returns:
MuNode – New network node for vehicle with assigned TX/RX channels.
- Return type:
Notes
Automatically builds channels if not yet created.
Assigns channels according to accessMode protocol.
Logs status string ‘CONFIRMED’ if successful or ‘DENIED’ if channel capacity exceeded.
- transmit(message, cid, srcAddr)[source]
Queue message for transmission to all receivers on channel.
Computes transmission times (data rate, travel time, jitter) and enqueues message copies to TX queue for each receiver on channel (except sender).
- Parameters:
- Return type:
None
Notes
Enqueues one message for each node registered as receiver on channel. For each message, computes:
Data transmission time: (message_bytes * 8) / DATA_RATE
Travel time: distance / C_WATER
Jitter: random delay via _generateJitter strategy
- Message delivery times computed as:
rxTime_start = srcTime+ travelTime + jitterTime rxTime_end = rxTime_start + dataTime
- deliver(time)[source]
Dequeue messages from TX queue and deliver to RX nodes.
- Parameters:
time (float) – Current simulation time.
- Return type:
None
Notes
Main entry point for message delivery. Dynamically assigned during initialization based on configuration specified by collType:
If collisions enabled, uses: _rxWithColl
If collisions disabled, uses: _rxNoColl
- calcStats()[source]
Compute network performance statistics from current state.
Calculates derived metrics (delivery rate, collision rate, in-transit ratio) from raw statistics counters updated during message processing.
Notes
Statistics valid only after calling calcStats(). Some stats (in-transit counts) updated continuously; others (delivery rate) computed here.
- Return type:
None
- getStatsReport()[source]
Return formatted network performance statistics report.
- Returns:
str – Multi-line formatted report of network traffic, quality, and performance metrics.
- Return type:
- _txEnqueue(rxTime, dataTime, srcAddr, rNode, channel, distances, message)[source]
Enqueue transmitted messages to network TX queue.
- Parameters:
- Return type:
None
Notes
Dynamically assigned during initialization based on configuration specified by collType:
If collisions enabled, uses: _txWithColl
If collisions disabled, uses: _txNoColl
- _txNoColl(rxTime, dataTime, srcAddr, rNode, channel, distances, message)[source]
Enqueue messages to network TX queue without collision handling.
- Parameters:
- Return type:
None
Notes
Used when collType=’off’.
Each receiver gets separate queue entry with computed arrival time.
Packages each message as MuNetQEntry dataclass with transmission metadata:
‘start_time’ : message delivery start time
‘end_time’ : message delivery end time
‘src_addr’ : source address
‘dest_addr’ : destination address
‘cid’ : channel id
‘freq’ : channel frequency
‘bw’ : channel bandwidth
‘distance’ : distance from src to dest
‘message’ : message
Heap sorting is done on: ‘end_time’.
- _rxNoColl(time)[source]
Dequeue TX messages and deliver without collision detection.
Simple queue processing without active reception tracking or collision checking.
- Parameters:
time (float) – Current simulation time.
- Return type:
None
Notes
Processes TX queue sequentially: apply PLR, apply BER, then deliver to receiver node via recv() callback.
Used when collType=’off’.
TX queue entries are MuNetQEntry dataclass with transmission metadata:
‘start_time’ : message delivery start time
‘end_time’ : message delivery end time
‘src_addr’ : source address
‘dest_addr’ : destination address
‘cid’ : channel id
‘freq’ : channel frequency
‘bw’ : channel bandwidth
‘distance’ : distance from src to dest
‘message’ : message
Heap sorting is done on: ‘end_time’
- _txWithColl(rxTime, dataTime, srcAddr, rNode, channel, distances, message)[source]
Enqueue messages to TX queue with collision detection preparation.
- Parameters:
- Return type:
None
Notes
Used when collType in {‘drop’, ‘corrupt’}.
Each receiver gets separate queue entry with computed arrival time.
Packages each message as MuNetQEntry dataclass with transmission metadata:
‘start_time’ : message delivery start time
‘end_time’ : message delivery end time
‘src_addr’ : source address
‘dest_addr’ : destination address
‘cid’ : channel id
‘freq’ : channel frequency
‘bw’ : channel bandwidth
‘distance’ : distance from src to dest
‘message’ : message
Heap sorting is done on ‘start_time’. Enables populating receiver rxd (active RX dict) and monitoring for collisions until ‘end_time’.
- _rxWithColl(time)[source]
Dequeue TX messages and deliver with collision detection.
- Parameters:
time (float) – Current simulation time.
- Return type:
None
Notes
Two-phase processing:
TX -> RX: Move messages from TX queue to RX queue and active RX dict
RX -> Deliver: Check for collisions, apply PLR/BER, deliver
Used when collType in {‘drop’, ‘corrupt’}.
Queue entries are are MuNetQEntry dataclass with transmission metadata:
‘start_time’ : message delivery start time
‘end_time’ : message delivery end time
‘src_addr’ : source address
‘dest_addr’ : destination address
‘cid’ : channel id
‘freq’ : channel frequency
‘bw’ : channel bandwidth
‘distance’ : distance from src to dest
‘message’ : message
TXQ heap sorting is done on: ‘start_time’
RXQ heap sorting is done on: ‘end_time’
- Maintains rxd (active RX dictionary) per receiver per channel:
{Key = source channel id, Value = [RX queue entry]}.
Colliding packets handled by _applyColl strategy (drop or corrupt).
- _nextQid()[source]
Return next sequential TX/RX queue message ID number.
- Returns:
int – Unique message identifier for heap sort tie-breaking.
- Return type:
Notes
Increments class-level counter __qid. Used to maintain sort order when messages have identical timestamps in priority queue.
- _getChannelRXNodes(cid)[source]
Return nodes registered to receive on channel.
- Parameters:
cid (int) – Channel ID.
- Returns:
nodes (list of MuNode) – Nodes with cid in their rx_channels set.
- Return type:
Notes
Linear search over all nodes. For large networks (1000+ nodes), consider caching receiver lists by channel.
- _generateJitter(size)[source]
Generate jitter values for network transmission delays.
- Parameters:
size (int) – Number of jitter values to generate.
- Returns:
jitter (ndarray) – Array of jitter delays in seconds.
- Return type:
Notes
Dynamically assigned during initialization based on jitter configuration:
If jitterType=’uniform’, uses: _jitterUniform
If jitterType=’off’, uses: _jitterDisabled
- _jitterUniform(size)[source]
Generate random jitter values for network transmission delays.
Applies random uniform delays to simulate network propagation variability on packet transmission timing. Values are drawn from a uniform distribution in the range [0, MAX_JITTER].
- _applyColl(entry, rNode)[source]
Apply packet collision strategy to overlapping transmissions.
- Parameters:
entry (MuNetQEntry) – Message entry from RX queue.
rNode (MuNode) – Receiving node.
- Returns:
bool – True if packet was dropped due to collision.
- Return type:
Notes
Dynamically assigned during initialization based on collision configuration:
If collType=’drop’, uses: _collDrop
If collType=’corrupt’, uses: _collCorrupt
If collType=’off’, returns: False (no collision)
- _collDrop(entry, rNode)[source]
Apply network collision by dropping all overlapping packets.
Checks receiver’s active RX dictionary for collisions on entry’s channel. If multiple messages active, removes all from RX queue and statistics.
- Parameters:
entry (MuNetQEntry) – Message entry from RX queue.
rNode (MuNode) – Receiving node with rxd (active RX dict).
- Returns:
bool – True (packet dropped) if collision detected, False otherwise.
- Return type:
Notes
Used if collType=’drop’
Updates stats: collisions counter, packetDropColl counter.
- _collCorrupt(entry, rNode)[source]
Apply collision by corrupting overlapping packet regions via XOR.
Models additive interference. For each colliding message, XORs overlapping byte regions to simulate mutual signal destruction.
- Parameters:
entry (MuNetQEntry) – Message entry from RX queue.
rNode (MuNode) – Receiving node with rxd (active RX dict).
- Returns:
bool – False (packet not dropped) - packets corrupted in-place but delivered.
- Return type:
Notes
Used if collType=’corrupt’
Updates stats: collisions counter, packetCorruptColl counter.
Overlap calculation: Determines byte indices for overlap window at data rate, then XORs corrupted regions bidirectionally.
- _applyPLR(entry)[source]
Apply packet loss strategy to determine if message should be dropped.
- Parameters:
entry (MuNetQEntry) – Message entry from TX queue.
- Returns:
bool – True if packet should be dropped.
- Return type:
Notes
Dynamically assigned during initialization based on PLR configuration:
If plrType=’uniform’, uses: _plrUniform
If plrType=’exp_simple’, uses: _plrExpSimple
If plrType=’sonar_simple’, uses: _plrSonarSimple
If plrType=’off’, uses: _plrDisabled
- _plrUniform(entry)[source]
Apply uniform random packet loss.
Compares value drawn from random uniform distribution [0,1] to PLR parameter. If random < PLR, drop packet.
- Parameters:
entry (MuNetQEntry) – Message entry.
- Returns:
bool – True if packet dropped.
- Return type:
- _plrExpSimple(entry)[source]
Apply distance-based exponential packet loss.
PLR increases exponentially with distance beyond nominal range. Includes frequency correction (+1% per kHz above BASE_FREQ).
- Parameters:
entry (MuNetQEntry) – Message entry with distance field.
- Returns:
bool – True if packet dropped.
- Return type:
Notes
PLR reaches base rate at nominal distance and increases exponentially beyond the nominal range, with the rate modulated by the characteristic distance:
distance_factor = exp((dist - NOM_DIST) / PLR_CHARDIST)
A smaller characteristic distance produces a faster exponential increase. An additional frequency correction is included, adding 1% additional loss per kHz above base frequency:
frequency_factor = 1 + (freq - BASE_FREQ) * 0.01
Maximum PLR is capped at 100%.
PLR_d = min(PLR * distance_factor * frequency_factor, 1.0)
A value is drawn from a random uniform distribution [0,1]. If random < PLR_d, the packet is dropped.
- _plrSonarSimple(entry)[source]
Apply distance-based PLR using simplified sonar equation approximation.
Combines geometric spreading (distance^1.5, practical compromise between spherical and cylindrical) with exponential absorption.
- Parameters:
entry (MuNetQEntry) – Message entry with distance field.
- Returns:
bool – True if packet dropped.
- Return type:
Notes
This model stays in linear space and approximates a simplified sonar equation by considering sound intensity degradation as dominated by two components: geometric spreading and absorption. The geometric spreading describes how the signal weakens with distance as the waves expand, while the use of nominal and characteristic distance in an exponential can approximate the contributions of noise and attenuation. A small frequency-dependent loss is also included.
The geometric power-law spreading uses the practical spreading compromise between spherical (^2) and cylindrical (^1):
geo_spread = (dist / NOM_DIST)^1.5,
The spreading is combined with exponential absorption:
exp_abs = exp((dist - NOM_DIST) / PLR_CHARDIST),
which is equal to 1 at the nominal distance, and increases exponentially beyond that at a rate modulated by the characteristic distance. An additional frequency correction is included, adding 1% additional loss per kHz above base frequency:
freq_factor = 1 + (freq - BASE_FREQ) * 0.01
Maximum PLR is capped at 100%.
PLR_d = min(PLR * geo_spread * exp_abs * freq_factor, 1.0)
A value is drawn from a random uniform distribution in [0,1] and compared to PLR_d. If random < PLR_d, the packet is dropped.
References
[1] bioSNR: The Sound Stops with the Passive Sonar Equation. CRAN bioSNR vignette. https://cran.r-project.org/web/packages/bioSNR/vignettes/sonar.html
[2] Discovery of Sound in the Sea. Sonar Equation: Passive sonar example. https://dosits.org/science/advanced-topics/sonar-equation/sonar-equation-example-passive-sonar/
- _plrDisabled(entry)[source]
No packet loss applied (PLR disabled).
- Parameters:
entry (MuNetQEntry) – Message entry from TX queue.
- Returns:
bool – Always False (packet not dropped).
- Return type:
- _applyBER(entry)[source]
Apply bit error strategy to corrupt message payload.
- Parameters:
entry (MuNetQEntry) – Message entry with metadata and message payload to corrupt in-place.
- Return type:
None
Notes
Dynamically assigned during initialization based on BER configuration:
If berType=’poisson’, uses: _berPoisson
If berType=’exp_simple’, uses: _berExpSimple
If berType=’snr’, uses: _berSNR
If berType=’off’, uses: _berDisabled
- _berPoisson(entry)[source]
Apply constant BER via Poisson-distributed bit flips.
Samples number of bit errors from Poisson(totalBits * BER), then flips random bit positions.
- Parameters:
entry (MuNetQEntry) – Message entry with metadata and message payload to corrupt.
- Return type:
None
Notes
Updates stats: packetBER counter, bitErrors counter.
- _berExpSimple(entry)[source]
Apply distance-based exponential BER.
Bit error rate increases exponentially with distance. Samples bit error count from Poisson(totalBits * ber_d).
- Parameters:
entry (MuNetQEntry) – Message entry with metadata and message payload to corrupt.
- Return type:
None
Notes
BER reaches base rate at nominal distance and increases exponentially with distance beyond the nominal range, with the rate modulated by the characteristic distance:
distance_factor = exp((dist - NOM_DIST) / BER_CHARDIST)
A smaller characteristic distance produces a faster exponential increase. Maximum BER is capped at 100%.
ber_d = min(BER * distance_factor, 1.0)
The number of corrupted bits is selected with a Poisson distribution from the total length of the message payload, and bit positions are selected by random sample from the payload array. Finally, the bits are flipped in-place by XOR with a bit mask.
- _berSNR(entry)[source]
Apply SNR-based BER model using path loss.
Estimates SNR from distance via path loss model. BER scales with SNR deviation from nominal.
- Parameters:
entry (MuNetQEntry) – Message entry with metadata and message payload to corrupt.
- Return type:
None
Notes
This model operates in decible (log) space, estimating SNR based on distance using simplified path loss model with practical spreading (15*log(dist), compromise between spherical (20) and cylindrical (10)):
distance_factor = 15 * log10(distance / NOM_DIST).
The signal is improved inside the nominal distance, has no affect at the nominal distance, and degrades beyond the nominal distance:
SNR = SNR_NOMINAL - distance_factor.
BER varies with SNR and the maximum is capped at 100%:
BER_SNR = min(BER * 10^(SNR_SLOPE * distance_factor), 1.0).
Where the SNR_SLOPE captures the sensitiviy of BER to signal quality changes: with a larger slope, the BER increases (signal degrades) faster.
The number of corrupted bits is selected with a Poisson distribution from the total length of the message payload, and bit positions are selected by random sample from the payload array. Finally, the bits are flipped in-place by XOR with a bit mask.
References
[1] Salim Wireless. “Relationship Between BER and SNR.” https://www.salimwireless.com/2022/05/relationship-between-ber-and-snr.html
[2] Northeastern University/Neu (Department of Electrical and Computer Engineering). “Handbook Chapter 5.” https://millitsa.coe.neu.edu/publications/book/handbook-chap5.pdf
- _berDisabled(entry)[source]
No bit error rate applied (BER disabled).
- Parameters:
entry (MuNetQEntry) – Message entry from TX/RX queue.
- Return type:
None
Notes
Pass-through method that performs no operations on message.
- _flipBits(msg, bitPos)[source]
Flip specified bit positions in bytearray via XOR.
In-place modification of message buffer.
- _genChannel(cid=0, freq=None, bw=None, isBcst=False)[source]
Generator yielding network channels per allocation strategy.
- Parameters:
cid (int, default=0) – Override starting channel id. Otherwise starts from the default value and increments by 1 on each yield.
freq (float, optional) – Override starting frequency. Otherwise, starts from the value in the ordering strategy and increments according to channel order configuration on each yield.
bw (float, optional) – Override channel bandwidth. Otherwise, uses the bandwidth determined by the channel order configuration on each yield.
isBcst (bool, default=False) – Broadcast flag. All channels generated by the returned generator object will carry the same flag.
- Returns:
MuChannel Generator – Yields channels generated according to channel order sequence set in configuration settings. Channel ids and frequencies are incremented on each iteration, bandwidth is static unless strategy determines otherwise, and broadcast flag is static.
- Return type:
Notes
Dynamically assigned during initialization based on channel order mode configuration:
If orderMode=’center_out’: uses _genChannelCenterOut
If orderMode=’edge_in’: uses _genChannelEdgeIn
- _genChannelCenterOut(cid=0, freq=None, bw=None, isBcst=False)[source]
Generates new network channels using a center-outward strategy.
First channel is at BASE_FREQ, then alternates above and below until the bandwidth is full.
- Parameters:
cid (int, default=0) – Override starting channel id.
freq (float, optional) – Override starting frequency. Otherwise, starts from BASE_FREQ.
bw (float, optional) – Override channel bandwidth. Otherwise, uses CHAN_MINBW
isBcst (bool, default=False) – Broadcast flag. All channels generated will carry the same flag.
- Returns:
MuChannel Generator – Yields channels with incrementing ID and frequencies alternating out from center. Bandwidth and broadcast flag are static.
- Return type:
- _genChannelEdgeIn(cid=0, freq=None, bw=None, isBcst=False)[source]
Generates new network channels using an edge-inward strategy.
First channel borders the lowest frequency in the network bandwidth, then increments by channel bandwidth plus guard bandwidth until the bandwidth is full.
- Parameters:
cid (int, default=0) – Override starting channel id.
freq (float, optional) – Override starting frequency. Otherwise, starts from lowest available channel slot in network bandwith.
bw (float, optional) – Override channel bandwidth. Otherwise, uses CHAN_MINBW
isBcst (bool, default=False) – Broadcast flag. All channels generated will carry the same flag.
- Returns:
MuChannel Generator – Yields channels with incrementing ID and frequencies. Bandwidth and broadcast flag are static.
- Return type:
- _getChannelCenterLimits()[source]
Compute bounds for channel center frequencies from network bandwidth.
- Returns:
center (float) – Network base (center) frequency (self.BASE_FREQ).
fmin_center (float) – Minimum frequency allowed for a channel center frequency (kHz).
fmax_center (float) – Maximum frequency allowed for a channel center frequency (kHz).
lane (float) – Bandwidth size of a channel with guard.
chan_bw (float) – Network channel minimum bandwidth (self.CHAN_MIN).
- Return type:
Notes
Determines upper and lower bound symmetrically around central network band defined in BASE_FREQ:
freq_min = center - half_bandwidth + guard_bw + channel_bw/2 freq_max = center + half_bandwidth - guard_bw - channel_bw/2
Uses guard bandwidth as inter-channel spacing.
- _makeBroadcastChannel(cid=None, freq=None, bw=None)[source]
Create a broadcast channel with optional overrides.
- _buildChannels()[source]
Build a network registry of network channels.
Notes
Dynamically assigned during initialization based on access mode configurations.
accessMode=’shared’, assigns: _buildChannelsShared
accessMode=’tdma’, assigns: _buildChannelsTDMA
accessMode=’tdma_lf’, assigns: _buildChannelsTDMALF
accessMode=’fdma’, assigns: _buildChannelsFDMA
- Return type:
None
Build a single operational network channel shared by all nodes.
Notes
Creates one channel at BASE_FREQ with id=BCAST_ADDR, isBcst=True. All nodes TX and RX on this channel. Clears existing channels first.
- Return type:
None
- _buildChannelsTDMA()[source]
Build a single operational channel for TDMA using full bandwidth.
Notes
Similar to shared mode but uses entire BANDWIDTH instead of CHAN_MINBW. Channel id=BCAST_ADDR, isBcst=True. Time-domain multiplexing handled by protocol schedulers.
- Return type:
None
- _buildChannelsTDMALF()[source]
Build two-channel TDMA network for leader-follower coordination.
Creates a dual-channel architecture optimized for leader-follower swarm communication where the leader broadcasts to all followers, and followers respond on a dedicated shared channel.
Notes
Channel Architecture:
Channel 1 - Broadcast (BCAST_ADDR):
Purpose: Leader -> All Followers (one-to-many)
CID: BCAST_ADDR (typically 255)
Frequency: BASE_FREQ
Bandwidth: CHAN_MINBW
Flag: isBcst=True
Channel 2 - Response (computed CID):
Purpose: All Followers -> Leader (many-to-one)
CID: Next available from channel generator (typically 1)
Frequency: BASE_FREQ + lane offset
Bandwidth: CHAN_MINBW
Flag: isBcst=False
Implementation Steps:
Clear existing channel registry
Create new channel generator
Generate broadcast channel
Generate response channel
Register both channels registry
Time-Domain Multiplexing:
Leader sends messages on broadcast channel during episode window. Followers respond on response channel in assigned time slots. This prevents collisions while using only two frequency channels.
Integration:
Used with _assignNodesTDMALF() which assigns:
Leader: TX on broadcast, RX on response
Followers: TX on response, RX on broadcast
- Return type:
None
- _buildChannelsFDMA()[source]
Build multiple channels for FDMA frequency-division network.
Generates one unique transmission channel per node currently registered in self.nodes. Each node gets exclusive TX frequency to prevent collisions without time-domain multiplexing.
Notes
Channel Allocation Strategy:
One channel per node
Channel IDs match node addresses where possible
Avoids BCAST_ADDR (typically 255) as channel ID
Uses channel generator to assign frequencies
Rebuild Behavior:
This method performs a complete rebuild on each call:
Clears all existing channels
Creates new channel generator
Generates channels for all current nodes
Not incremental - regenerates entire channel set. This design ensures consistent frequency allocation but means calling during runtime rebuilds the full network.
Channel ID Assignment:
Assigns channel ID equal to node ID if node ID is not BCAST_ADDR and is not already assigned. Otherwise increments until those conditions are met.
Capacity Limit:
Maximum channels limited by CHAN_MAXN property. If capacity exceeded, logs warning and stops channel generation. Nodes without channels cannot transmit.
Frequency Assignment:
Channels generated in order by order mode strategy (center_out or edge_in). First registered node gets first generated frequency, second node gets second frequency, etc.
Integration:
Works with _assignNodesFDMA() which assigns:
TX: Single dedicated channel per node
RX: All channels except own TX channel
- Return type:
None
- _assignNodes(node)[source]
Assign TX/RX channels to node according to network access mode.
- Parameters:
node (MuNode) – Network node requesting channel assignment. Must have node.address and node.vehicle attributes.
- Returns:
status (str) – Assignment result: ‘CONFIRMED’ if successful, ‘DENIED’ if capacity exceeded or assignment failed.
- Return type:
Notes
Dynamically assigned during initialization based on access mode configuration:
accessMode=’shared’, assigns: _assignNodesShared
accessMode=’tdma’, assigns: _assignNodesTDMA
accessMode=’tdma_lf’, assigns: _assignNodesTDMALF
accessMode=’fdma’, assigns: _assignNodesFDMA
Channel Sets:
Method modifies two node attributes:
node.tx_channels: set of channel IDs for transmission
node.rx_channels: set of channel IDs tuned for reception
Status Codes:
‘CONFIRMED’: Assignment successful, node ready for communication
‘DENIED’: Assignment failed (typically FDMA capacity exceeded)
Side Effects:
May trigger channel building if channels not yet created. May update other nodes’ RX channels (FDMA multi-node updates).
Assign node to single shared broadcast channel (TX and RX).
Assigns all nodes to the single operational channel designated by the _buildChannelsShared channel planner.
- Parameters:
node (MuNode) – Node requesting assignment.
- Returns:
str – ‘CONFIRMED’ (always successful).
- Return type:
Notes
Builds channel if none exists.
- _assignNodesTDMA(node)[source]
Assign node to TDMA channel (TX and RX on same channel).
Assigns all nodes to the operational channel designated by the _buildChannelsTDMA channel planner.
- Parameters:
node (MuNode) – Node requesting assignment.
- Returns:
str – ‘CONFIRMED’ (always successful).
- Return type:
Notes
Builds TDMA channel if none exists.
- _assignNodesTDMALF(node)[source]
Assign channels for leader-follower TDMA protocol.
Assigns node to appropriate TX/RX channels based on vehicle role (leader or follower). Leader and followers use complementary channel assignments to enable bidirectional communication on two channels.
- Parameters:
node (MuNode) – Network node requesting assignment. Requires node.vehicle.isLeader attribute for role determination.
- Returns:
status (str) – Always returns ‘CONFIRMED’ (no capacity limits in TDMA_LF).
- Return type:
Notes
Channel Verification:
Checks that exactly 2 channels exist with proper broadcast configuration. Rebuilds channels via _buildChannelsTDMALF() if:
Channel count does not equal 2
BCAST_ADDR not in channels
No non-broadcast channel exists
Leader Assignment:
TX: Broadcast channel (eg 255) # Transmit on broadcast
RX: Response channel (eg 1) # Receive on dedicated
Leader broadcasts messages to all followers simultaneously and listens for responses on a separate channel.
Follower Assignment:
TX: Response channel (eg 1) # Transmit direct to leader
RX: Broadcast channel (eg 255) # Receive on broadcast
Followers listen for leader broadcasts and respond on dedicated channel.
Role Detection:
Uses node.vehicle.isLeader boolean:
True: Vehicle is formation leader (assigns leader channels)
False: Vehicle is follower (assigns follower channels)
This attribute must be set on vehicle before registration.
- _assignNodesFDMA(node)[source]
Assign exclusive TX channel and multi-RX for FDMA frequency division.
Each node receives one dedicated TX channel (no other node transmits on that frequency) and listens on all channels except its own. This eliminates collisions via frequency separation rather than time-domain multiplexing.
- Parameters:
node (MuNode) – Network node requesting channel assignment. Uses node.address as preferred TX channel ID.
- Returns:
status (str) – ‘CONFIRMED’ if assignment successful, ‘DENIED’ if bandwidth capacity exceeded.
- Return type:
Notes
Capacity Check:
If the number of channels exceeds the maximum capable by the network bandwidth (computed in CHAN_MAXN), the node is denied channel assignment.
Maximum channels = (BANDWIDTH - 2*GUARD_BW) // (CHAN_MINBW + GUARD_BW).
Default policy is to deny further assignment if FDMA overflow occurs. No alternatives are in development, but possibilities to consider are an RX-only fallback with no TX, or fallback to TX on a broadcast channel.
Channel ID Selection:
Prefers node.address as channel ID but adjusts if that ID is already taken or if is equal to BCAST_ADDR. If there is a conflict, then channel ID is incremented until first success.
Channel Generation:
Uses channel generator to get next frequency in sequence determined by order mode configuration (e.g. center-out or edge-in), and the channel ID is assigned. If the generator is exhausted (StopIteration), logs warning and returns ‘DENIED’.
TX and RX Assignment:
node.tx_channels = {cid} # Single dedicated channel
node.rx_channels = set(channels) - {cid} # All except own TX
Multi-Node Update:
Updates all existing nodes when new channel is assigned, ensuring all nodes can receive from newly registered nodes.
Generator State:
Verifies channel generator exists before use and creates one if not found. The generator may be None after unpickling.
Error Handling:
Logs detailed error with bandwidth parameters if capacity exceeded:
Current BANDWIDTH setting
CHAN_MINBW requirement
GUARD_BW overhead
- munetauvsim.communication.getMsgStruct(msgType)[source]
Return binary message structure for serialization/parsing.
Uses Python construct library to define structured binary formats for three message types: REPORT, LEADER-REPORT, and BROADCAST/REQUEST. Structures specify field names, types, and byte layout for network transmission.
- Parameters:
msgType ({'RPRT', 'LRPT', 'BCRQ', 'REPORT', 'RESPONSE', 'LEADER-REPORT', 'BROADCAST/REQUEST'}) – Message type identifier. Case-insensitive. Multiple aliases supported.
- Returns:
cst.Struct – Construct library Struct object defining message format. Use .build(dict) to serialize and .parse(bytes) to deserialize.
- Return type:
Struct
Notes
Message Structures:
RPRT (REPORT / RESPONSE) - 37 bytes: { 'type': b'RPRT' or b'RSPN', # 4 bytes - Message type flag 'group_id': bytes, # 1 byte - Group identifier 'reporter_id': int, # 4 bytes - Sender vehicle ID 'reporter_pos': [x, y, z], # 12 bytes - Position (3x float32) 'reporter_vel': [vx, vy, vz], # 12 bytes - Velocity (3x float32) 'time_stamp': float, # 4 bytes - Transmission time } LRPT (LEADER-REPORT) - 57 bytes: { 'type': b'LRPT', # 4 bytes - Const type flag 'group_id': bytes, # 1 byte - Group identifier 'leader_pos': [x, y, z], # 12 bytes - Current position 'leader_vel': [vx, vy, vz], # 12 bytes - Current velocity 'leader_next_pos': [x, y, z], # 12 bytes - Next waypoint 'leader_next_vel': [vx, vy, vz], # 12 bytes - Next velocity 'time_stamp': float, # 4 bytes - Transmission time } BCRQ (BROADCAST/REQUEST) - Variable (353 bytes with 9 followers): { 'type': b'BCRQ', # 4 bytes - Const type flag 'group_id': bytes, # 1 byte 'leader_pos': [x, y, z], # 12 bytes 'leader_vel': [vx, vy, vz], # 12 bytes 'leader_next_pos': [x, y, z], # 12 bytes 'leader_next_vel': [vx, vy, vz], # 12 bytes 'num_followers': int, # 4 bytes - Array size = N 'followers_pos': [[x,y,z], ...], # 12*N bytes - Position arrays 'followers_vel': [[vx,vy,vz], ...], # 12*N bytes - Velocity arrays 'followers_rspn': [t1, t2, ...], # 4*N bytes - Response times 'rspn_sched': [id1, id2, ...], # 4*N bytes - Response order 'rspn_start': float, # 4 bytes - Schedule start time 'time_stamp': float, # 4 bytes } Total: 65 + 32xN bytesField Types:
Float32l: Little-endian single-precision float (4 bytes)
Int32ul: Unsigned little-endian integer (4 bytes)
Bytes(n): Raw byte sequence of fixed length
Array[type]: Dynamic-length array based on num_followers field
Type Flag:
First 4 bytes identify message type for recvMsgCallback() dispatcher. RPRT/LRPT use Const() to enforce correct flag during build. REPORT allows variable flag (b’RPRT’ or b’RSPN’) for flexibility.
Transmission:
Only values are packed in serialization build, not keys. Keys are implicit in structure definition. Receiver must know message type to parse correctly.
LRU Caching:
Uses Least Recently Used (LRU) caching to store compiled structures in memory. Construct compilation has overhead; caching avoids recompilation on repeated calls. Maxsize=5 sufficient for 3 message types plus aliases.
References
[1] construct library: https://construct.readthedocs.io/
Examples
### Serialization:
>>> msg_struct = getMsgStruct('REPORT') >>> bytes_msg = msg_struct.build({ ... 'type': b'RPRT', ... 'group_id': b'A', ... 'reporter_id': 1, ... 'reporter_pos': [100.0, 200.0, 25.0], ... 'reporter_vel': [1.5, 0.5, 0.0], ... 'time_stamp': 123.45, ... })
### Deserialization:
>>> msg_dict = msg_struct.parse(bytes_msg) >>> pos_1 = msg_dict['reporter_pos'] # [100.0, 200.0, 25.0]
- munetauvsim.communication.recvMsg(vehicle)[source]
Spawn a new receiver thread for vehicle message listening.
- Parameters:
vehicle (Vehicle) – Vehicle with CommNetwork attribute.
- Returns:
Thread – Started daemon thread running network receiver loop.
- Return type:
None
Notes
Only used by AquaNet communication network
Thread calls vehicle.CommNetwork.recv() with recvMsgCallback as handler.
Daemon thread terminates when main program exits.
- munetauvsim.communication.recvMsgCallback(bytesMsg, vehicle)[source]
Dispatch incoming network message to appropriate handler by type flag.
Extracts 4-byte message type identifier from header and routes message to corresponding parser (recvReport, recvLeaderReport, or recvBroadcastReq). Validates type flag for corruption before routing.
- Parameters:
- Return type:
None
Notes
Message Routing Table:
Type Flag -> Handler Function:
b’RPRT’ -> recvReport(vehicle, bytesMsg)
b’RSPN’ -> recvReport(vehicle, bytesMsg)
b’LRPT’ -> recvLeaderReport(vehicle, bytesMsg)
b’BCRQ’ -> recvBroadcastReq(vehicle, bytesMsg)
Type Flag Extraction:
>>> msgType = bytesMsg[:4] # First 4 bytes
Type flags use fixed 4-byte ASCII encoding (e.g., b’RPRT’, b’LRPT’).
Validation Flow:
Extract type flag from message header
Check flag against dataIsCorrupted(‘type’) validator
If corrupted: Attempt recovery via restoreCorrupt()
If recovery fails: Log error and discard message
If valid: Route to appropriate handler function
Error Handling:
Catches and logs multiple exception types:
UnicodeDecodeError: Corrupted type flag cannot decode to ASCII
IndexError: Message too short (< 4 bytes)
KeyError: Unknown message type flag
General Exception: Unexpected parsing errors
All errors logged with vehicle callSign for debugging. Messages with unrecoverable errors are silently dropped (no delivery to handler).
Handler Responsibilities:
This callback performs only routing. Individual handlers are responsible for:
Full message parsing via getMsgStruct()
Group membership verification
Field-level data validation
State updates to vehicle/target/group objects
- munetauvsim.communication.writeReport(vehicle, msgType='REPORT')[source]
Serialize vehicle state into REPORT message.
- Parameters:
vehicle (Vehicle) –
Vehicle with eta, velocity, clock, groupId, id attributes.
eta: vehicle position / attitude vector
velocity: vehicle velocity vector (END frame)
clock: simulation time
groupId: swarm group id
id: unique vehicle id
msgType ({'REPORT', 'RESPONSE'}, default='REPORT') – Message type determines flag: REPORT -> b’RPRT’, RESPONSE -> b’RSPN’.
- Returns:
bytes – Serialized RPRT message ready for transmission.
- Return type:
Notes
REPORT vs RESPONSE:
Functionally identical message formats with different type flags:
REPORT (b’RPRT’): Standard vehicle state broadcast
RESPONSE (b’RSPN’): Reply in TDMA_LF scheduled response slot
Type flag enables receivers to distinguish message context but both parsed identically by recvReport().
Message Payload (37 bytes):
Uses getMsgStruct(‘RPRT’) for message format. Contains:
{ 'type': b'RPRT' or b'RSPN', # 4 bytes 'group_id': bytes, # 1 byte 'reporter_id': int, # 4 bytes 'reporter_pos': [x,y,z], # 12 bytes (3x float32) 'reporter_vel': [vx,vy,vz], # 12 bytes (3x float32) 'time_stamp': float, # 4 bytes }
- munetauvsim.communication.sendReport(vehicle, msgType='REPORT', address=None)[source]
Serialize and send vehicle state REPORT message over network.
Packages current vehicle position, velocity, and timestamp into binary message format and transmits on assigned TX channel.
- Parameters:
vehicle (Vehicle) –
Vehicle sending report. Requires eta, velocity, clock, nodeAddr, groupId, callSign, CommNetwork, and txAddr attributes.
eta: vehicle position / attitude vector
velocity: vehicle velocity vector (END frame)
clock: simulation time
nodeAddr: unique address of network node
groupId: swarm group id
callSign: unique vehicle identification string
CommNetwork: a communication network manager instance
txAddr: transmission channel id
msgType ({'REPORT', 'RESPONSE'}, default='REPORT') – Message type flag written to header. ‘REPORT’ -> b’RPRT’, ‘RESPONSE’ -> b’RSPN’. Both use same message structure.
address (int, optional) – Override transmission address. If None, uses vehicle.txAddr. Determines which TX channel to send on.
- Return type:
None
Notes
Message Construction Flow:
Call writeReport to serialize state
Determine transmission address
Call vehicle.CommNetwork.send(message, address)
REPORT vs RESPONSE:
Functionally identical message formats with different type flags:
REPORT (b’RPRT’): Standard vehicle state broadcast
RESPONSE (b’RSPN’): Reply in TDMA_LF scheduled response slot
Type flag enables receivers to distinguish message context but both parsed identically by recvReport().
Message Payload (37 bytes):
{ 'type': b'RPRT' or b'RSPN', # 4 bytes 'group_id': bytes, # 1 byte 'reporter_id': int, # 4 bytes 'reporter_pos': [x,y,z], # 12 bytes (3x float32) 'reporter_vel': [vx,vy,vz], # 12 bytes (3x float32) 'time_stamp': float, # 4 bytes }
- munetauvsim.communication.recvReport(vehicle, bytesMsg)[source]
Parse and process received REPORT message from group member.
Deserializes REPORT/RESPONSE message, validates all fields for corruption, attempts recovery where possible, and updates receiving vehicle’s group member state with reporter position, velocity, and timestamp.
- Parameters:
- Return type:
None
Notes
Group Member Update:
If reporter is found in vehicle.group and all message fields valid, an internal data model of the reporter is updated with:
- reporter_pos # Reporter Position - reporter_vel # Reporter Velocity - time_stamp # Last message time - rprtRecv = True # Flag: report received from this cycle - writeEtaVelLogs(reporter) # Append to position/velocity log
Field Validation Sequence:
Each individual message field is checked for data corruption via dataIsCorrupted(). If corruption is detected, then data recovery is attempted via restoreCorrupt(). Data recovery strategies for each field can be defined in the vehicle.dataRepair dictionary.
Group Membership Verification:
Rejects messages from vehicles not in same group. Also rejects if reporter_id not found in vehicle.group list (may be former group member or incorrectly addressed message).
Message Parsing Flow:
Parse binary message via getMsgStruct(‘RPRT’)
Extract and validate reporter_id
Extract and validate group_id
Verify vehicle in same group (compare group IDs)
Locate reporter in vehicle.group list by ID
Validate reporter_pos, reporter_vel, time_stamp
Update internal data model of group member if all validations pass
- munetauvsim.communication.writeLeaderReport(vehicle)[source]
Serialize leader state into LRPT message.
- Parameters:
vehicle (Vehicle) –
Leader vehicle with eta, velocity, clock, groupId attributes.
eta: vehicle position / attitude vector
velocity: vehicle velocity vector (END frame)
clock: simulation time
groupId: swarm group id
- Returns:
bytes – Serialized LRPT message ready for transmission.
- Return type:
Notes
Message Payload (57 bytes):
Uses getMsgStruct(‘LRPT’) for format. Contains:
{ 'type': b'LRPT', # 4 bytes - Constant 'group_id': bytes, # 1 byte 'leader_pos': [x,y,z], # 12 bytes 'leader_vel': [vx,vy,vz], # 12 bytes 'leader_next_pos': [x,y,z], # 12 bytes 'leader_next_vel': [vx,vy,vz], # 12 bytes 'time_stamp': float, # 4 bytes }Next Waypoint Prediction:
Uses guidance.predictNextEtaVel() to estimate leader’s next position. Prediction based on current path following state, typically looking ahead to next waypoint in vehicle.waypoints queue.
- munetauvsim.communication.sendLeaderReport(vehicle)[source]
Serialize and send leader state LEADER-REPORT message to followers.
Packages leader position, velocity, next waypoint position, and next velocity into binary message and transmits on leader’s TX channel.
- Parameters:
vehicle (Vehicle) –
Leader vehicle sending report. Requires eta, velocity, clock, nodeAddr, groupId, callSign, CommNetwork, txAddr, and navigation attributes for waypoint prediction.
eta: leader position / attitude vector
velocity: leader velocity vector (END frame)
clock: simulation time
nodeAddr: unique address of network node
groupId: swarm group id
callSign: unique vehicle identification string
CommNetwork: a communication network manager instance
txAddr: transmission channel id
- Return type:
None
Notes
Message Construction Flow:
Predict next waypoint: guid.predictNextEtaVel(vehicle)
Call writeLeaderReport(vehicle) to serialize complete leader state
Transmit via vehicle.CommNetwork.send() on vehicle.txAddr
Message Payload (57 bytes):
{ 'type': b'LRPT', # 4 bytes - Constant 'group_id': bytes, # 1 byte 'leader_pos': [x,y,z], # 12 bytes 'leader_vel': [vx,vy,vz], # 12 bytes 'leader_next_pos': [x,y,z], # 12 bytes 'leader_next_vel': [vx,vy,vz], # 12 bytes 'time_stamp': float, # 4 bytes }Next Waypoint Prediction:
Uses guidance.predictNextEtaVel() to estimate leader’s next position. Prediction based on current path following state, typically looking ahead to next waypoint in vehicle.waypoints queue.
- munetauvsim.communication.recvLeaderReport(vehicle, bytesMsg)[source]
Parse and process LEADER-REPORT message from leader vehicle.
Deserializes leader report, validates all fields, and updates follower’s target tracking state with leader position, velocity, next waypoint, and message metadata.
- Parameters:
vehicle (Vehicle) –
Follower vehicle receiving message. Requires groupId, target, clock, and callSign attributes.
groupId: swarm group id
target: swarm group leader data model
clock: simulation time
callSign: unique vehicle identification string
bytesMsg (bytes) – Complete serialized LRPT message (57 bytes).
- Return type:
None
Notes
Target Object Updates:
If all message fields are valid, an internal data model of the target is updated with:
- leader_pos # Leader position - leader_vel # Leader velocity - leader_next_pos # Next waypoint - leader_next_vel # Next leader velocity - time_stamp # Message timestamp - clock - timestamp # Age of message - writeEtaVelLogs(target) # Append to position/velocity log
Field Validation:
Each individual message field is checked for data corruption via dataIsCorrupted(). If corruption is detected, then data recovery is attempted via restoreCorrupt(). Data recovery strategies for each field can be defined in the vehicle.dataRepair dictionary.
Message Parsing Flow:
Parse message via getMsgStruct(‘LRPT’)
Validate group_id and verify membership
Validate leader_pos, leader_vel (current state)
Validate leader_next_pos, leader_next_vel (predicted state)
Validate time_stamp
Update vehicle.target with all fields if valid
Compute message delay: vehicle.clock - time_stamp
- munetauvsim.communication.writeBroadcastReq(vehicle)[source]
Serialize leader and all follower states into BROADCAST/REQUEST message.
Packages complete swarm state (leader + all followers) into single broadcast message with response schedule. Used in protocols for coordinated leader-to-followers communication with scheduled response slots.
- Parameters:
vehicle (Vehicle) –
Leader vehicle sending broadcast. Requires eta, velocity, clock, groupId, group, rspnSched, nextEta, nextVel attributes.
eta: leader position / attitude vector
velocity: leader velocity vector (END frame)
clock: simulation time
groupId: swarm group id
group: list of swarm group follower data models
rspnSched: list of follower ids in scheduled response order
nextEta: leader next position
nextVel: leader next velocity
- Returns:
bytes – Serialized BCRQ message ready for network transmission.
- Return type:
Notes
Message Structure (Variable Size):
Base size: 65 bytes (leader data + metadata) Per-follower: 32 bytes (position + velocity + response time + ID) Total: 65 + (32 * num_followers) bytes
Example with 9 followers: 65 + (32 * 9) = 353 bytes
Message Fields:
{ 'type': b'BCRQ', # 4 bytes - Constant 'group_id': bytes, # 1 byte 'leader_pos': [x,y,z], # 12 bytes - Current position 'leader_vel': [vx,vy,vz], # 12 bytes - Current velocity 'leader_next_pos': [x,y,z], # 12 bytes - Next waypoint 'leader_next_vel': [vx,vy,vz], # 12 bytes - Next velocity 'num_followers': int, # 4 bytes - Array size 'followers_pos': [[x,y,z], ...], # 12*N bytes - Follower positions 'followers_vel': [[vx,vy,vz], ...], # 12*N bytes - Follower velocities 'followers_rspn': [t1, t2, ...], # 4*N bytes - Response times 'rspn_sched': [id1, id2, ...], # 4*N bytes - Response order 'rspn_start': float, # 4 bytes - Schedule start time 'time_stamp': float, # 4 bytes - Transmission time }Next Waypoint Prediction:
Computes leader’s next position for follower path prediction. Uses guidance system to estimate next waypoint based on current path following state. Enables followers to anticipate leader maneuvers for more stable following.
Follower Data Packaging:
When followers send REPORT messages to leader, leader stores follower states on internal data models in the group list. For each BCRQ message, leader iterates the group list to extract and repeat this information to all listeners:
- follower.eta # Follower position - follower.velocity # Follower velocity - follower.timeLastMsg # Time of follower report - follower.id # Follower id
Response Schedule:
Two components define response timing:
rspn_sched: Ordered list of follower IDs defining response sequence
rspn_start: Absolute time when first response should occur
Each follower calculates its response time:
my_index = rspn_sched.index(my_id) my_response_time = rspn_start + (my_index * rspnDur)
where rspnDur is stored on vehicle.
- munetauvsim.communication.sendBroadcastReq(vehicle)[source]
Serialize and send BROADCAST/REQUEST message from leader to all followers on broadcast channel.
Constructs complete swarm state broadcast, resets follower response flags, and transmits on leader’s TX channel (broadcast). Triggers follower response cycle in TDMA_LF protocol.
- Parameters:
vehicle (Vehicle) –
Leader vehicle. Requires all attributes for writeBroadcastReq() plus txAddr, CommNetwork, and callSign attributes.
txAddr: transmission channel id
CommNetwork: a communication network manager instance
callSign: unique vehicle identification string
- Return type:
None
Notes
Message Contents Summary:
Leader current and predicted state (position, velocity, next waypoint)
All follower positions and velocities (from last received reports)
Response schedule defining follower reply timing
Timestamp for message age calculation
Transmission Sequence:
Serialize complete swarm state via writeBroadcastReq()
Reset all follower response flags: m.rprtRecv = False
Transmit on broadcast channel via vehicle.CommNetwork.send()
Response Flag Reset:
Before transmission, clears rprtRecv flag for all followers. Leader uses these flags to track which followers have responded in current cycle. Flags set to True when follower responses received.
Message Cycle:
Typical TDMA_LF communication pattern:
Leader sends BCRQ at t = m*epsdDur
Follower 1 responds at t = rspn_start (e.g., t=1.0)
Follower 2 responds at t = rspn_start + slot (e.g., t=1.5)
…
Follower N responds at t = rspn_start + (N-1)*slot
Leader sends next BCRQ at t = (m+1)*epsdDur
Repeat cycle
Broadcast Channel:
Transmitted on vehicle.txAddr which for leader in TDMA_LF is BCAST_ADDR. All followers tuned to receive on this channel.
- munetauvsim.communication.recvBroadcastReq(vehicle, bytesMsg)[source]
Parse BROADCAST/REQUEST message and update follower’s target and group member states.
Deserializes BCRQ message from leader, validates all fields with corruption checking, updates target (leader) tracking, updates all group member states, and computes response timing from schedule. Receiving this message triggers a RESPONSE message at the scheduled response time slot.
- Parameters:
vehicle (Vehicle) –
Follower vehicle receiving message. Requires groupId, target, group (list), id, clock, rspnDuration, and callSign attributes.
groupId: swarm group id
target: swarm group leader data model
group: list of group neighbor data models
id: unique vehicle id
clock: simulation time
rspnDur: duration of response time slot
callSign: unique vehicle identification string
bytesMsg (bytes) – Complete serialized BCRQ message (variable size: 65 + 32*N bytes), where N is number of swarm followers.
- Return type:
None
Notes
Target Updates (Leader Tracking):
If all message fields are valid, an internal data model of the target is updated with:
- leader_pos # Leader position - leader_vel # Leader velocity - leader_next_pos # Next waypoint - leader_next_vel # Next leader velocity - time_stamp # Message timestamp - clock - timestamp # Age of message - writeEtaVelLogs(target) # Append to position/velocity log
Group Member Updates:
For each follower found in vehicle.group and all message fields valid, an internal data model of the follower is updated with:
- reporter_pos # Reporter Position - reporter_vel # Reporter Velocity - time_stamp # Last message time - writeEtaVelLogs(reporter) # Append to position/velocity log
Field Validation:
Each individual message field is checked for data corruption via dataIsCorrupted(). If corruption is detected, then data recovery is attempted via restoreCorrupt(). Data recovery strategies for each field can be defined in the vehicle.dataRepair dictionary.
Response Time Calculation:
Follower determines when to send response based on schedule position:
my_index = rspn_sched.index(my_id) my_response_time = rspn_start + (my_index * rspnDuration)
where rspnDuration is stored on vehicle. If vehicle.id not in schedule, logs warning (not expected to respond).
Performance Note:
Most computationally expensive message handler due to:
Variable-length arrays requiring iteration
Multiple validation passes
Group member lookups by ID
Log append operations for each member
For large swarms (20+ followers), consider caching ID->index mappings.
- munetauvsim.communication.sendResponse(vehicle)[source]
Sends a scheduled RESPONSE message from follower to leader.
Wrapper function calling sendReport with RSPN message type. Used in TDMA Leader-Follower configuration during follower response window.
- Parameters:
vehicle (Vehicle) –
Follower vehicle sending report. Requires eta, velocity, clock, nodeAddr, groupId, callSign, CommNetwork, and txAddr attributes.
eta: vehicle position / attitude vector
velocity: vehicle velocity vector (END frame)
clock: simulation time
nodeAddr: unique address of network node
groupId: swarm group id
callSign: unique vehicle identification string
CommNetwork: a communication network manager instance
txAddr: transmission channel id
- Return type:
None
Notes
REPORT vs RESPONSE:
Functionally identical message formats with different type flags:
REPORT (b’RPRT’): Standard vehicle state broadcast
RESPONSE (b’RSPN’): Reply in TDMA_LF scheduled response slot
Type flag enables receivers to distinguish message context but both parsed identically by recvReport().
Message Payload (37 bytes):
{ 'type': b'RSPN', # 4 bytes 'group_id': bytes, # 1 byte 'follower_id': int, # 4 bytes 'follower_pos': [x,y,z], # 12 bytes (3x float32) 'follower_vel': [vx,vy,vz], # 12 bytes (3x float32) 'time_stamp': float, # 4 bytes }
- munetauvsim.communication.schedulerTdmaLF(vehicle)[source]
Compute and apply TDMA leader-follower transmission scheduling.
Manages bidirectional group-synchronized messaging for TDMA_LF protocol. Leader broadcasts BCRQ messages at fixed intervals. Followers respond in assigned time slots determined by rspnSlot and rspnDur.
- Parameters:
vehicle (Vehicle) –
Leader or follower vehicle. Requires clock, epsdDur, rspnSlot, rspnDur, isLeader, and rspnRqst (follower) attributes.
clock: Simulation time
epsdDur: Duration of complete message frame cycle
rspnSlot: Start time of vehicles scheduled response time slot
rspnDur: Duration of response time slot
isLeader: Boolean flag if vehicle is swarm leader
rspnRqst: Boolean flag is RESPONSE message request is true
- Return type:
None
Notes
Leader Behavior:
Broadcasts BCRQ message every epsdDur seconds. BCRQ contains complete swarm state (leader + all followers) with response schedule (rspn_sched, rspn_start).
Follower Behavior:
Receipt of BCRQ by followers triggers a RSPN transmission. Waits until simulation time is between assigned start and end time of scheduled response slot, then sends RESPONSE message.
Response Timing:
Follower response time computed in recvBroadcastReq():
>>> my_index = rspnSched.index(vehicle.id) >>> rspnSlot = rspn_start + (my_index * rspnDur)
Typical Timeline (3 followers, epsdDur=10s, rspnDur=1s):
t=0.0: Leader sends BCRQ
t=1.0: Follower 0 responds
t=2.0: Follower 1 responds
t=3.0: Follower 2 responds
t=10.0: Leader sends next BCRQ (cycle repeats)
Coordination Requirements:
Leader must send BCRQ before followers respond
Followers must receive and parse BCRQ to learn assignedResponseTime
Clock synchronization required
Response schedule prevents packet collisions via time-domain separation
See also
sendBroadcastReqLeader transmission function
recvBroadcastReqFollower handler computing response timing
sendReportFollower response transmission
- munetauvsim.communication.schedulerFdmaLF(vehicle)[source]
Compute response and coordination timing for FDMA leader-follower messaging.
Manages periodic state broadcasts for leader-follower formations using frequency-division channels. Leader sends LRPT messages at fixed intervals. Followers send RPRT messages at same intervals on dedicated channels.
- Parameters:
vehicle (Vehicle) –
Leader or follower vehicle. Requires clock, rspnSlot, epsdDur, sampleTime, and isLeader attributes.
clock: Simulation time
rspnSlot: Start time of vehicles scheduled response time slot
epsdDur: Duration of complete message frame cycle
sampleTime: Simulation iteration time step
isLeader: Boolean flag if vehicle is swarm leader
- Return type:
None
Notes
Leader Behavior:
Sends Leader Report every epsdDur seconds. LRPT message contains leader current state and predicted next waypoint. Transmitted on leader’s dedicated FDMA channel.
Follower Behavior:
Sends standard Report every epsdDur seconds. RPRT message contains follower position, velocity, timestamp. Transmitted on follower’s dedicated FDMA channel. Vehicle transmit times typically initialized with offset from each other.
FDMA Channel Architecture:
Each vehicle: TX on dedicated channel, RX on all other channels
No collision risk because each vehicle has unique TX frequency. No response scheduling needed.
Typical Message Flow (txOffset=0.5s):
t=0.0: Leader -> LRPT on channel 0 -> All members receive leader
t=0.5: Follower1 -> RPRT on channel 1 -> All members receive follower1
t=1.0: Follower2 -> RPRT on channel 2 -> All members receive follower2
…
See also
sendLeaderReportLeader transmission function
recvLeaderReportFollower handler for leader state
sendReportFollower transmission function
recvReportLeader handler for follower state
- munetauvsim.communication.writeEtaVelLogs(model)[source]
Appends reported position and velocity in vehicle model data logs.
- Parameters:
model (Model) – Data model of vehicle that is getting data record updated.
- Return type:
None
Notes
Model eta and velocity logs are dynamically resized with resizeLog() if they are full.
- munetauvsim.communication.resizeLog(logArray, logSize, newCap)[source]
Expand position and velocity logs of data model to new capacity.
Maintains chronological order while resizing log array. Pads with zero. Used by writeEtaVelLogs() to dynamically increase size of etaLog and velLog attributes of vehicle data models.
- Parameters:
- Returns:
ndarray – Resized log array with capacity=newCap, preserving most recent records.
- Return type:
- munetauvsim.communication.readLastEtaLogs(model, n=1)[source]
Retrieve last n records from vehicle data model position (eta) log.
- munetauvsim.communication.readLastVelLogs(model, n=1)[source]
Retrieve last n records from vehicle data model velocity log.
- munetauvsim.communication.dataIsCorrupted(data, expType, **kwargs)[source]
Validate message field data for corruption using field-specific rules.
Performs type checking, range validation, and structural verification on message fields. Designed for acoustic network error detection where bit errors and collisions corrupt data in unpredictable ways.
- Parameters:
data (Any) – Data value to validate. Type depends on field parameter.
expType (str, {'type', 'group_id', 'reporter_id', 'num_followers', 'int', 'rspn_sched', 'float', 'position', 'velocity', 'float_array', 'timestamp'}) – Field type identifier determining validation rules.
**kwargs (dict) –
Optional context for validation:
- uidint
Receiving vehicle ID for self-check (reporter_id validation)
- isLeaderbool
True if validating leader data (affects recovery strategy)
- idint
Specific vehicle ID being validated (for targeted recovery)
- Returns:
bool – True if data appears corrupted, False if valid.
- Return type:
Notes
Design Philosophy:
More comprehensive data validation is possible here. This framework provides basic validation, which can be extended for more robust or sophisticated requirements.
Validations employ range and threshold checks to reject unreasonable values, but these may not apply to your mission parameters. Check and adjust if needed.
Validation designed for underwater acoustic channel characteristics:
High bit error rates
Collision-induced corruption (XOR of overlapping signals)
Conservative validation prevents:
Physically impossible states (positions, velocities)
Type confusion (int as float, bytes as int)
Array structure damage (wrong size, wrong types)
Logic errors (negative time, self-reporting)
Limitations:
Cannot detect:
Semantically valid but factually wrong data
Corrupted data that remains within valid ranges
Multi-field corruption
Validation Rules by Field:
type (4-byte message flag):
Must be exactly 4 bytes in length
Must be one of the valid message types: RPRT, RSPN, LRPT, or BCRQ
Must decode properly as UTF-8 text
group_id (1-byte group identifier):
Must be exactly 1 byte in length
Must decode as valid UTF-8 character
Must be printable and alphanumeric ASCII character
reporter_id (4-byte unsigned integer):
Must be a valid positive integer type
Must be within reasonable ID range of own ID (+/-1000)
position (3-element float array):
Must be a list or array type with exactly 3 elements
All elements must be finite numbers (no NaN or infinity)
Position values must be within reasonable geographic bounds (100 km)
velocity (3-element float array):
Must be a list or array type with exactly 3 elements
All elements must be finite numbers (no NaN or infinity)
Velocity values must be within realistic AUV limits (100 m/s)
timestamp (4-byte float):
Must be a valid positive numeric type
Must be finite (no NaN or infinity) and less that 1,000,000
num_followers (4-byte unsigned integer):
Must be a valid integer type
Must be positive and within reasonable swarm size limits (1-1000)
rspn_sched (array of vehicle IDs):
Must be a list or array type
All elements must be valid positive integers
Must be within reasonable ID range of own ID (+/-1000)
rspn_start (4-byte float):
Must be a valid numeric type
Must be finite (no NaN or infinity)
Should represent a future time for response scheduling
Data Recovery
Calls restoreCorrupt() for recovery when corruption detected.
Data recovery strategies stored in dictionary at vehicle.dataRepair
- munetauvsim.communication.restoreCorrupt(vehicle, field, badData, **kwargs)[source]
Attempt corrupted message field recovery by defined strategy with fallback.
Applies field-specific recovery methods when dataIsCorrupted() detects corruption. Recovery strategies use historical data, vehicle state, or reasonable defaults depending on field type and available context. Strategies are defined per field in vehicle.dataRepair dictionary.
- Parameters:
vehicle (Vehicle) –
Vehicle receiving corrupted message. Requires groupId, group, target, and clock attributes.
groupId: swarm group id
group: list of swarm group neighbor data models
target: swarm group leader data model
clock: simulation time
field (str) – Field type identifier matching dataIsCorrupted() field types.
badData (Any) – Corrupted data.
**kwargs (dict) –
Optional context for targeted recovery:
- idint
Vehicle ID for targeted log retrieval
- isLeaderbool
True if recovering leader data (uses vehicle.target logs)
- Returns:
goodData (Any) – Recovered data value. Type matches expected type for field.
isGood (bool) – True if recovery successful, False if unrecoverable.
- Return type:
Tuple[Any, bool]
Notes
Fallback:
Attempts data recovery strategy for each strategy listed by field in vehicle.dataRepair dictionary. When multiple strategies are listed, recovery is attempted in sequence until success or end of list. If no strategy is defined for field, falls back to default (skip entire message).
Strategies:
predict:
Estimate field value using kinematic prediction, message history, or bitwise comparison for optimal matching.
previous:
Use last known valid value from vehicle logs, group member data, or target tracking state.
neutral:
Replace with safe default values (zero positions/velocities, current time for timestamps, origin values) for continued operation with reduced disruption.
sentinel:
Replace with obviously invalid marker values (-1, -999, 0xFF) for downstream handler.
skip_field:
Accept corrupted field as-is and continue processing remaining message fields.
skip:
Reject entire message.
Logging:
Recovery attempts logged at WARNING level. Failed recoveries logged at ERROR level.
- munetauvsim.communication.recoverPredict(vehicle, field, badData, **kwargs)[source]
Recover corrupted field using predictive estimation from available data.
Computes estimates for corrupted message fields using vehicle state, known data from same message, and guidance prediction algorithms. Provides a forward-looking data recovery strategy.
- Parameters:
vehicle (Vehicle) – Vehicle receiving corrupted message.
field (str) – Message field identifier of corrupted data. (eg. ‘reporter_pos’)
badData (Any) – Corrupted data.
**kwargs (dict) –
Additional parameters passed in for specific strategies.
id : int, Message source ID for group member fields
isLeader : bool, True if message is from leader
- Returns:
goodData (Any) – Predicted field value.
isSuccess (bool) – True if data recovery was successful.
- Return type:
Tuple[Any, bool]
Notes
Prediction Strategies by Field:
type:
Use bitwise comparison with valid flag types and select best match. Accept match if less than half of the bits are different (16bits).
group_id:
Use the vehicles own group id.
reporter_id:
Select the id from vehicle group list that has the longest time since receiving the last message.
num_followers:
Use the number of vehicles in own group list (+1 if is not leader). Uses kwarg ‘isLeader’.
rspn_start:
Calculate from own last response frame start time and the episode duration.
rspn_sched:
Compare corrupted array to last stored response schedule. Uses bitwise comparison on unmatched reference ids to select the best match. Secondary criteria is index proximity. Accepts if less than half of the elements were predicted.
time_stamp, followers_rspn:
If source ID or isLeader is provided as keyword argument, adds average of time between eta log timestamps to the last timestamp entry. Otherwise subtracts one half episode duration from current time. Uses ‘isLeader’ or ‘id’ kwargs.
reporter_pos, followers_pos, leader_pos:
Use last logged position, velocity, and time stored on model to predict position using constant velocity approximation. Uses ‘id’ or ‘isLeader’ kwargs.
reporter_vel, followers_vel, leader_vel:
Use last logged velocities to predict position using constant acceleration approximation. Uses ‘id’ or ‘isLeader’ kwargs.
leader_next_pos, leader_next_vel:
Not compatible with ‘predict’ strategy, would collapse to same recovery used in ‘previous’ strategy.
- munetauvsim.communication.recoverPrevious(vehicle, field, badData, **kwargs)[source]
Recover corrupted field using last known valid value.
Retrieves most recent stored value, if available, for corrupted message field. Assumes recent values approximate current state.
- Parameters:
vehicle (Vehicle) – Vehicle receiving corrupted message.
field (str) – Message field identifier of corrupted data. (eg. ‘reporter_pos’)
badData (Any) – Corrupted data.
**kwargs (dict) –
Additional parameters passed in for specific strategies.
id : int, Message source ID for group member fields
isLeader : bool, True if message is from leader
- Returns:
goodData (Any) – Last stored value for field.
isSuccess (bool) – True if data recovery was successful.
- Return type:
Tuple[Any, bool]
Notes
Recovery Strategies by Field:
type:
Not compatible with ‘previous’ strategy. No message type data stored. Try ‘predict’ strategy.
group_id:
With id keyword, finds model from group list and retrieves model.groupId. If no id keyword, attempts to retrieve target.groupId.
reporter_id:
Not compatible with ‘previous’ strategy. No reliable method to identify which previous reporter id. Try ‘predict’ strategy.
num_followers:
Not compatible with ‘previous’ strategy. No data stored on number of followers. Try ‘predict’ or ‘skip’ strategy.
rspn_start:
Use value stored in rspnFrame.
rspn_sched:
Use value stored in rspnSched.
time_stamp:
With id keyword, finds model from group list and retrieves model.timeLastMsg. If no id keyword, attempts to retrieve target.timeLastMsg.
followers_rspn:
With id keyword, finds model from group list and retrieves model.timeLastMsg.
reporter_pos, followers_pos:
With id keyword, finds model from group list and retrieves model.eta.
reporter_vel, followers_vel:
With id keyword, finds model from group list and retrieves model.velocity.
leader_pos:
Use value stored in target.eta.
leader_vel:
Use value stored in target.velocity.
leader_next_pos:
Use value stored in target.nextEta.
leader_next_vel:
Use value stored in target.nextVel.
- munetauvsim.communication.recoverNeutral(vehicle, field, badData, **kwargs)[source]
Handle corrupted field by replacing with zero or neutral value.
Neutral values are chosen to be safe (mostly harmless) for continued operation.
- Parameters:
vehicle (Vehicle) – Vehicle receiving corrupted message.
field (str) – Message field identifier of corrupted data. (eg. ‘reporter_pos’).
badData (Any) – Corrupted data.
**kwargs –
Additional parameters passed in for specific strategies
neutral: Custom neutral value to use instead of defaults (scalar)
- Returns:
goodData (Any) – Neutral default value for field type.
isSuccess (bool) – True if the strategy was successful. In theory, always True as neutral value always available.
- Return type:
Tuple[Any, bool]
Notes
Typical neutral values:
Arrays: filled with appropriate scalar value
Scalars:
bytes: b’0’
integers: 0 or 1
times: current clock time
positions: zero (origin)
velocities: zero (stationary)
- munetauvsim.communication.recoverSentinel(vehicle, field, badData, **kwargs)[source]
Handle corrupted field by replacing with a sentinel value.
Sentinel values are chosen to be obviously bad. Requires downstream handler to identify and prevent data consumption.
- Parameters:
vehicle (Vehicle) – Vehicle receiving corrupted message.
field (str) – Message field identifier of corrupted data. (eg. ‘reporter_pos’).
badData (Any) – Corrupted data.
**kwargs –
Additional parameters passed in for specific strategies
sentinel: Custom sentinel value to use instead of default (scalar)
- Returns:
goodData (Any) – Sentinel value for field type.
isSuccess (bool) – True if the strategy was successful. In theory, always True as sentinel value always available.
- Return type:
Tuple[Any, bool]
Notes
Typical sentinel values:
Arrays: filled with appropriate scalar sentinel
Scalars:
bytes: ‘ÿ’
integers: -1
times: -1.0
positions: -999999.0
velocities: -999.0
- munetauvsim.communication.recoverSkipField(vehicle, field, badData, **kwargs)[source]
Skip recovery for corrupted field but continue processing rest of message.
Allows continued message processing despite corrupted field by always returning isSuccess=True. Original corrupted data is returned.
- Parameters:
- Returns:
badData (Any) – Original corrupted data.
isSuccess (bool) – True if the strategy was successful. True for all cases.
- Return type:
Tuple[Any, bool]
- munetauvsim.communication.recoverSkip(vehicle, field, badData, **kwargs)[source]
Handle corrupt data by skipping the entire message.
Prevents continued message processing by always returning isSuccess=False. Original corrupted data is returned.
- Parameters:
- Returns:
badData (Any) – Original corrupted data.
isSuccess (bool) – True if the strategy was successful. False for all cases.
- Return type:
Tuple[Any, bool]