# Start Here: System Mental Model & 30-Minute Reading Order

> Core mental model for the decentralized multi-robot car search system, team subsystem boundaries between Swarm and SLAM, essential glossary terminology, and the recommended code-reading order.

- Repository: ivaziz/swarm_car_search
- GitHub: https://github.com/ivaziz/swarm_car_search
- Human wiki: https://grok-wiki.com/public/wiki/ivaziz-swarm-car-search-66a3d00cb601
- Complete Markdown: https://grok-wiki.com/public/wiki/ivaziz-swarm-car-search-66a3d00cb601/llms-full.txt

## Source Files

- `README.md`
- `scripts/main.py`
- `docs/GLOSSARY.md`
- `configs/default_config.yaml`
- `swarm/core/swarm_coordinator.py`

---

<details>
<summary>Relevant source files</summary>
The following files were used as context for generating this wiki page:
- [README.md](README.md)
- [scripts/main.py](scripts/main.py)
- [docs/GLOSSARY.md](docs/GLOSSARY.md)
- [configs/default_config.yaml](configs/default_config.yaml)
- [configs/aco_params.yaml](configs/aco_params.yaml)
- [interfaces/slam_interface.py](interfaces/slam_interface.py)
- [docs/slam_integration_guide.md](docs/slam_integration_guide.md)
- [docs/architecture.md](docs/architecture.md)
- [swarm/core/swarm_coordinator.py](swarm/core/swarm_coordinator.py)
- [swarm/core/robot_agent.py](swarm/core/robot_agent.py)
- [swarm/states/robot_states.py](swarm/states/robot_states.py)
- [swarm/aco/task_scorer.py](swarm/aco/task_scorer.py)
- [swarm/aco/aco_engine.py](swarm/aco/aco_engine.py)
- [swarm/task_allocation/allocation_strategy.py](swarm/task_allocation/allocation_strategy.py)
- [swarm/failure_handling/recovery_manager.py](swarm/failure_handling/recovery_manager.py)
- [perception/matching_engine.py](perception/matching_engine.py)
</details>

# Start Here: System Mental Model & 30-Minute Reading Order

The **SwarmX** codebase (`ivaziz/swarm_car_search`) implements an autonomous multi-robot coordination architecture designed for locating missing and stolen vehicles in complex outdoor urban environments. Built as a robotics graduation project, the system unites bio-inspired Ant Colony Optimization (ACO), indirect spatial memory (stigmergy), Bayesian target belief modeling, and multi-stage computer vision to coordinate a decentralized fleet of ground robots under noisy real-world communication and hardware constraints.

This guide provides the foundational mental model for navigating the repository. It details the strict engineering boundary separating the Swarm and SLAM subsystems, standardizes core robotics and swarm intelligence terminology, and charts an efficient 30-minute code reading path for onboarding engineers, reviewers, and evaluators.

---

## 1. System Mental Model

The core architecture operates as a **decentralized feedback loop**: mobile robots explore an unknown urban street network, ingest sensor data, infer geometric frontiers, share environmental cues stigmergically, and probabilistically allocate search tasks without requiring a single point of failure.

```mermaid
graph TB
    subgraph SensingAndSLAM["1. Sensing & State Estimation Tier (ISLAMProvider)"]
        Sensors["Sensors: 2D LiDAR / IMU / Encoders / Camera"] --> SLAMImpl["SLAM Provider (MockSLAMProvider / Gazebo Bridge)"]
        SLAMImpl --> SLAMSnapshot["SLAMState\n- Pose2D (x, y, theta)\n- OccupancyGrid2D (free / occupied / -1 unknown)\n- FrontierCluster List"]
    end

    subgraph SwarmCore["2. Swarm Coordination & Stigmergy Tier"]
        SLAMSnapshot --> SwarmCoord["SwarmCoordinator\n(Orchestration Engine)"]
        SwarmCoord --> StigmergyMap["Tri-Layer Pheromone Map\n- Exploration Field (tau_e, rho=0.01)\n- Recruitment Field (tau_s, rho=0.05)\n- Avoidance Field (tau_a, rho=0.30)"]
        SwarmCoord --> TaskPool["TaskManager\n(Frontier Ingestion & Deduplication)"]
        SwarmCoord --> BayesMap["TargetProbabilityMap\n(Bayesian Prior & Spatial Memory)"]
    end

    subgraph DecisionAndAlloc["3. Bio-Inspired Task Allocation Tier"]
        TaskPool --> Scorer["TaskScorer\nMulti-Objective Objective Function\n(Info Gain, Target Prior, Distance, Congestion)"]
        StigmergyMap --> Scorer
        BayesMap --> Scorer
        Scorer --> Boltzmann["ACOEngine\nScale-Invariant Boltzmann Softmax Allocator\nP(task_i | robot_j)"]
        Boltzmann --> Dispatch["Task Assignment Dispatch"]
    end

    subgraph RobotAgentExec["4. Onboard Robot Agent & Kinematics Tier"]
        Dispatch --> Agent["RobotAgent\n- RobotStateMachine (FSM: IDLE, NAVIGATING, ...)\n- Differential Drive Kinematics (v, omega)\n- Collision Avoidance Halting"]
    end

    subgraph PerceptionTier["5. Perception & Verification Tier"]
        Agent --> RaycastFOV["SimulatedVehicleDetector\n(Raycast Line-of-Sight & 90 deg FoV)"]
        RaycastFOV --> OCRMatcher["MatchingEngine\n- Fuzzy OCR (Levenshtein Distance)\n- Vehicle Appearance Verifier\n- Multi-Frame Temporal Voting (k >= 3)"]
        OCRMatcher -->|MatchEvent: Confirmed| TargetAlert["Mission Event: TARGET_FOUND\nDeposit tau_s Recruitment Pheromones"]
        TargetAlert --> SwarmCoord
    end

    subgraph FaultToleranceTier["6. Dynamic Fault Tolerance Tier"]
        Agent --> HealthMon["FailureDetector\n(Heartbeat Timeouts, Low Battery, Motion Stall)"]
        HealthMon --> RecMgr["RecoveryManager\n- Release Orphaned Tasks\n- Deposit Avoidance at Crash Site\n- Reassign Tasks to Peers"]
        RecMgr --> SwarmCoord
    end
```

### The Six Foundational Architectural Concepts

1. **Frontier-Based Exploration via Decoupled SLAM**:
   Robots discover candidate exploration regions by finding frontiers—the borders where known free navigable space meets unmapped unknown space. The Swarm system never calculates maps directly; it receives extracted `FrontierCluster` centroids from an `ISLAMProvider`.
2. **Tri-Layer Stigmergic Pheromones ($\tau_e, \tau_s, \tau_a$)**:
   Instead of flooding the wireless network with centralized path broadcasts, robots communicate indirectly via 2D spatial scalar fields:
   - **Exploration Layer ($\tau_e$)**: Slow evaporation rate ($\rho_e = 0.01$) acts as long-term memory of covered street corridors.
   - **Recruitment Layer ($\tau_s$)**: Medium evaporation rate ($\rho_s = 0.05$) attracts neighboring robots toward candidate target sightings.
   - **Avoidance Layer ($\tau_a$)**: Fast evaporation rate ($\rho_a = 0.30$) temporarily repels robots from areas occupied by peers or disabled wreckage to prevent search overlap and traffic jams.
3. **Multi-Objective Task Scoring**:
   Candidate tasks are evaluated from each robot’s unique spatial position using a scale-invariant objective function balancing positive incentives (information gain, Bayesian priors, urgency, exploration pheromone) against negative costs (Euclidean distance, peer congestion, collision risk, and redundant visits).
4. **Boltzmann Softmax Action Selection**:
   To prevent all robots from greedily collapsing onto the single highest-scoring frontier, tasks are sampled probabilistically using temperature-parameterized Boltzmann Softmax selection. Logits are normalized against the maximum candidate score to guarantee numerical stability.
5. **Multi-Stage Computer Vision Verification**:
   Target identification uses a 5-stage pipeline: field-of-view raycasting, plate cropping, fuzzy Levenshtein OCR matching against an optical confusion map ($8 \leftrightarrow B, 0 \leftrightarrow O$), vehicle appearance verification, and multi-frame temporal voting requiring $k \ge 3$ consistent frames before triggering a mission alarm.
6. **Dynamic Fault Recovery**:
   Robots monitor peer heartbeats, motion stalling, and battery drainage. When a robot fails, its assigned tasks are immediately returned to the unassigned pool, a high avoidance pheromone ($\tau_a$) is stamped at the failure coordinate, and surviving peers reallocate the task dynamically.

Sources: [README.md:28-76](), [docs/architecture.md:5-70]()

---

## 2. Team Subsystem Boundaries: Swarm vs. SLAM

To ensure clean engineering separation across the project team, responsibilities are strictly split between the Swarm team and the SLAM team.

```
+---------------------------------------------------------------------------------------+
|                            SUBSYSTEM RESPONSIBILITY MATRIX                            |
+---------------------------------------------------------------------------------------+
|  SLAM Subsystem (Saqr & Mahmoud)              |  Swarm Subsystem (Mohammed & Ibrahim) |
+-----------------------------------------------+---------------------------------------+
|  - Sensor Driver Integration (2D LiDAR, IMU)  |  - ACO Task Scorer & Boltzmann Engine |
|  - EKF / Odometry Fusion (Wheel Encoders)     |  - Tri-Layer Stigmergic Pheromone Map |
|  - 2D Occupancy Grid Generation (data: -1/0/100)|  - Task Lifecycle & Deduplication   |
|  - Obstacle Inflation & Raycasting            |  - Dynamic Failure Detection & Recovery|
|  - Frontier Extraction & Clustering           |  - Robot State Machine (FSM) & Kinematics|
|  - ISLAMProvider Concrete Implementation      |  - 5-Stage Vision & Plate OCR Matching|
+---------------------------------------------------------------------------------------+
```

### The Architectural Invariant

> **Architectural Invariant**: The Swarm coordination subsystem **never** implements SLAM internally, never fuses raw wheel encoder or IMU data, and never accesses raw sensor buffers directly. All spatial understanding flows through the standardized [`ISLAMProvider`](interfaces/slam_interface.py) abstract interface.

### The Contract: `interfaces/slam_interface.py`

The SLAM subsystem communicates with the Swarm coordinator by providing a `SLAMState` snapshot containing standardized dataclasses:

```python
# interfaces/slam_interface.py:12-100
@dataclass(frozen=True)
class Pose2D:
    x: float
    y: float
    theta: float  # Heading in radians [-pi, pi]

@dataclass
class OccupancyGrid2D:
    width: int
    height: int
    resolution: float  # Meters per cell edge
    origin: Pose2D
    data: List[int]    # -1: Unknown, 0: Free space, 100: Occupied obstacle

@dataclass(frozen=True)
class FrontierCluster:
    cluster_id: str
    centroid_x: float
    centroid_y: float
    size: int
    bounding_box: Tuple[float, float, float, float]

@dataclass
class SLAMState:
    robot_id: str
    timestamp: float
    pose: Pose2D
    linear_velocity: float
    angular_velocity: float
    occupancy_grid: OccupancyGrid2D
    frontiers: List[FrontierCluster]
    exploration_ratio: float
    navigation_cost_map: Optional[List[float]] = None

class ISLAMProvider(ABC):
    @abstractmethod
    def get_latest_state(self, robot_id: str) -> SLAMState: ...
    @abstractmethod
    def is_healthy(self, robot_id: str) -> bool: ...
```

In headless Python tests and benchmarks, this contract is fulfilled by `MockSLAMProvider`, which simulates raycasting and frontier clustering over an `UrbanEnvironment`. In 3D Gazebo Fortress simulations, it is fulfilled by `GazeboSLAMBridge` subscribing to ROS 2 topics.

Sources: [interfaces/slam_interface.py:1-100](), [docs/slam_integration_guide.md:10-33](), [docs/architecture.md:15-28]()

---

## 3. Essential Glossary & Key Terminology

The table below summarizes the core terminology used across code modules, configuration files, and thesis documentation.

| Term | Domain | Code Reference | Definition & System Role |
| :--- | :--- | :--- | :--- |
| **Ant Colony Optimization (ACO)** | Swarm Intelligence | `swarm/aco/aco_engine.py` | Bio-inspired metaheuristic where artificial ants (robots) sample candidate search frontiers based on heuristic attractiveness and pheromone trails. |
| **Stigmergy** | Swarm Intelligence | `swarm/pheromone/` | Indirect coordination via continuous 2D scalar fields ($\tau_e, \tau_s, \tau_a$), eliminating the need for centralized trajectory negotiation. |
| **Multi-Robot Task Allocation (MRTA)** | Robotics / AI | `swarm/task_allocation/` | Computational problem of assigning frontier clusters and target verification goals to distributed robots to maximize global coverage. |
| **Boltzmann / Softmax Selection** | Metaheuristics | `swarm/aco/aco_engine.py` | Temperature-scaled probability distribution $P(t_i) \propto \exp(Q_i / T)$ preventing greedy clustering onto identical search sectors. |
| **Frontier-Based Exploration** | SLAM / Mapping | `interfaces/slam_interface.py` | Exploration strategy navigating toward frontier boundaries between known free space (`0`) and unknown territory (`-1`). |
| **2D Occupancy Grid** | Mapping | `interfaces/slam_interface.py` | Discretized spatial grid where cells indicate unknown (`-1`), free (`0`), or obstacle (`100`) status. |
| **Differential Drive Kinematics** | Motion Control | `simulation/sim_robot.py` | Non-holonomic two-wheel motion model constrained by linear forward velocity $v$ and yaw angular velocity $\omega$. |
| **Pose2D** | Geometry / SLAM | `interfaces/slam_interface.py` | 3-DOF coordinate tuple $(x, y, \theta)$ expressing position and orientation in the global frame. |
| **Levenshtein Distance** | Computer Vision | `perception/matching_engine.py` | Minimum single-character edit operations between OCR string and target watchlist plate, normalized to $[0.0, 1.0]$. |
| **Multi-Frame Temporal Consensus** | Computer Vision | `perception/temporal_tracker.py` | Aggregates successive sightings of stationary vehicles, requiring $k \ge 3$ frames and character voting to eliminate transient OCR glitches. |
| **Dynamic Urgency Escalation** | Swarm Intelligence | `swarm/aco/task_scorer.py` | Multiplier ($2.2\times$ to $3.5\times$) boosting task priority when candidate visual cues indicate a likely stolen vehicle match. |
| **ROS 2 & Gazebo Fortress** | Infrastructure | `ros2_ws/`, `run_gazebo_gui.sh` | Middleware (ROS 2 Humble) and 3D rigid-body dynamic simulator providing realistic sensor streams and physics. |

Sources: [docs/GLOSSARY.md:7-92](), [README.md:55-76]()

---

## 4. The 30-Minute Code Reading Order

To understand how high-level swarm decisions translate into physical robot motion, follow this sequence. It starts with system interfaces, traces the top-level coordination tick, inspects the ACO allocation mathematics, examines the onboard agent state machine, and concludes with computer vision and failure handling.

```
+-------------------------------------------------------------------------------------------+
|                              30-MINUTE CODE READING ROADMAP                               |
+-------------------------------------------------------------------------------------------+
| Stage | Target Files                                     | Focus Area              | Time |
+-------+--------------------------------------------------+-------------------------+------+
| 1     | README.md, scripts/main.py, slam_interface.py    | Architecture & Contract | 5m   |
| 2     | swarm/core/swarm_coordinator.py                  | Central Coordination    | 7m   |
| 3     | swarm/aco/task_scorer.py & aco_engine.py         | Multi-Objective Scoring | 6m   |
| 4     | swarm/core/robot_agent.py & robot_states.py      | FSM & Robot Execution   | 6m   |
| 5     | perception/matching_engine.py & recovery_mgr.py  | Vision & Fault Recovery | 6m   |
+-------------------------------------------------------------------------------------------+
```

### Stage 1 (0–5 min): System Entry Point & Global Contracts
* **Files**: [`README.md`](README.md), [`scripts/main.py`](scripts/main.py:1-127), [`interfaces/slam_interface.py`](interfaces/slam_interface.py:1-100)
* **What to inspect**:
  1. `scripts/main.py`: The single CLI launcher supporting `sim`, `eval`, `test`, and `info`.
  2. `interfaces/slam_interface.py`: The dataclasses `Pose2D`, `OccupancyGrid2D`, `FrontierCluster`, `SLAMState`, and the abstract class `ISLAMProvider`.
* **Key takeaway**: Any subsystem component can be mocked or swapped as long as it adheres to `ISLAMProvider`.

### Stage 2 (5–12 min): The Swarm Coordination Loop
* **File**: [`swarm/core/swarm_coordinator.py`](swarm/core/swarm_coordinator.py:174-467)
* **What to inspect**:
  1. Inspect `SwarmCoordinator.step_coordination(timestamp, dt)`:
     - Step 1: Advance physics, SLAM, and spatial search memory.
     - Step 2: Ingest peer heartbeats and trigger failure detection.
     - Step 3: Ingest frontier clusters from active robots' SLAM states into `TaskManager`.
     - Step 4: Allocate pending tasks to idle or preemptible robots via `ACOAllocationStrategy`.
     - Step 5: Evaluate multi-stage perception and check for target confirmation.
     - Step 6: Deposit exploration and avoidance pheromones, followed by discrete evaporation.
* **Key takeaway**: The coordinator synchronizes the swarm tick while delegating local decisions to individual agents.

### Stage 3 (12–18 min): Bio-Inspired Task Allocation & Stigmergy
* **Files**: [`swarm/aco/task_scorer.py`](swarm/aco/task_scorer.py:37-148), [`swarm/aco/aco_engine.py`](swarm/aco/aco_engine.py:103-176), [`configs/aco_params.yaml`](configs/aco_params.yaml:1-36)
* **What to inspect**:
  1. `task_scorer.py`: Inspect `explain_score(...)`. Notice the 8 normalized components:
     $$\text{Score} = \text{NetUtility} \cdot \left(\frac{\tau^{\alpha \cdot 0.5} \cdot G^{\delta}}{C^{\varepsilon \cdot 0.5}}\right) \cdot \text{BatteryFactor}$$
     where $\tau$ is recruitment pheromone, $G$ is urgency, and $C$ is distance cost.
  2. `aco_engine.py`: Inspect `select_task(...)`. Look at how relative logits prevent numeric overflow during Boltzmann sampling:
     ```python
     # swarm/aco/aco_engine.py:157-159
     weights = [math.exp(((s / max_score) - 1.0) / temp) for s in scores]
     ```
* **Key takeaway**: The scoring function blends empirical robotics costs (distance, battery) with natural ant foraging dynamics.

### Stage 4 (18–24 min): Robot Agent, FSM, and Kinematics
* **Files**: [`swarm/core/robot_agent.py`](swarm/core/robot_agent.py:116-150), [`swarm/states/robot_states.py`](swarm/states/robot_states.py:9-60), [`swarm/states/state_machine.py`](swarm/states/state_machine.py)
* **What to inspect**:
  1. `robot_states.py`: Review `RobotState` values (`IDLE`, `NAVIGATING`, `SEARCHING`, `VEHICLE_DETECTED`, `VERIFYING`, `REPORTING`, `FAILED`).
  2. `robot_agent.py`: Trace `assign_task(...)` and notice how incoming `TARGET_CONFIRMATION` tasks preempt generic exploration tasks.
* **Key takeaway**: Each physical robot maintains an autonomous onboard finite state machine, allowing it to navigate and sense independently even during communication blackouts.

```mermaid
stateDiagram-v2
    [*] --> IDLE
    IDLE --> NAVIGATING: Task Assigned
    NAVIGATING --> SEARCHING: Arrived at Centroid
    SEARCHING --> NAVIGATING: Reassigned New Frontier
    SEARCHING --> VEHICLE_DETECTED: Camera FoV Trigger
    NAVIGATING --> VEHICLE_DETECTED: Sighting in Transit
    VEHICLE_DETECTED --> VERIFYING: Run OCR & Appearance Matcher
    VERIFYING --> REPORTING: Watchlist Match Confirmed
    VERIFYING --> SEARCHING: Non-Target Decoy
    REPORTING --> COMPLETED: Mission Finalized
    NAVIGATING --> FAILED: Stall / Heartbeat / Battery Depleted
    SEARCHING --> FAILED: Critical Failure
    FAILED --> [*]
```

### Stage 5 (24–30 min): Perception Pipeline & Dynamic Fault Recovery
* **Files**: [`perception/matching_engine.py`](perception/matching_engine.py:95-215), [`swarm/failure_handling/recovery_manager.py`](swarm/failure_handling/recovery_manager.py:63-120)
* **What to inspect**:
  1. `matching_engine.py`: Look at `evaluate_multi_stage_match(...)`, which fuses vehicle classification ($C_{\text{veh}}$), plate localization ($C_{\text{plate}}$), Levenshtein OCR ($C_{\text{ocr}} \times S_{\text{plate}}$), RGB appearance ($C_{\text{app}}$), and temporal consensus ($C_{\text{temp}}$).
  2. `recovery_manager.py`: Trace `handle_failure(...)`. See how orphaned tasks are marked `PENDING`, high avoidance pheromone ($\tau_a = 12.0$) is deposited over the disabled vehicle, and the task is immediately evaluated for dynamic reassignment to healthy peers.
* **Key takeaway**: The swarm is resilient to physical attrition and sensor noise, recovering mission progress in $< 0.2\,\text{s}$ without operator intervention.

Sources: [swarm/core/swarm_coordinator.py:174-467](), [swarm/aco/task_scorer.py:37-148](), [swarm/aco/aco_engine.py:103-176](), [swarm/core/robot_agent.py:116-150](), [swarm/states/robot_states.py:9-60](), [swarm/failure_handling/recovery_manager.py:63-120]()

---

## 5. System Configuration & Runtime Execution

The system supports two execution paradigms:
1. **Zero-Dependency Headless Python**: Fast Monte Carlo simulation and unit tests using Python's standard library.
2. **Containerized ROS 2 & Gazebo Fortress**: High-fidelity 3D physics with LiDAR and camera rendering accessible via noVNC web browser.

### Key Configuration Parameters

```yaml
# configs/default_config.yaml:11-32
swarm:
  num_robots: 3
  heartbeat_interval_sec: 1.0
  failure_timeout_sec: 5.0
  reassignment_cooldown_sec: 2.0

navigation:
  max_linear_velocity: 1.5   # m/s
  max_angular_velocity: 1.0  # rad/s
  waypoint_tolerance: 0.5    # meters

perception:
  detection_confidence_threshold: 0.70
  ocr_confidence_threshold: 0.80
  evidence_capture_enabled: true
```

```yaml
# configs/aco_params.yaml:5-36
objective_function_weights:
  alpha: 1.2       # Positive recruitment pheromone
  beta: 1.5        # Information gain / frontier size
  gamma: 1.8       # Target vehicle prior probability
  delta: 1.0       # Mission urgency multiplier
  epsilon: 1.3     # Travel distance penalty
  zeta: 2.0        # Robot congestion penalty
  theta: 1.5       # Avoidance / recent visit penalty

pheromone_dynamics:
  evaporation_rates:
    exploration: 0.01  # Long-term memory
    success: 0.05      # Recruitment decay
    avoidance: 0.30    # Rapid congestion release

stochastic_selection:
  temperature: 1.0
  epsilon_greedy: 0.05
```

### Common CLI Invocations

All repository capabilities are launched through [`scripts/main.py`](scripts/main.py):

```bash
# Display system banner and architecture overview
python3 scripts/main.py info

# Run all unit and integration tests (96+ passing)
python3 scripts/main.py test

# Launch autonomous simulation with 4 robots for 100 steps
python3 scripts/main.py sim --robots 4 --steps 100 --output-dir output/simulation_run

# Execute comparative Monte Carlo benchmark against Greedy & Random Walk baselines
python3 scripts/main.py eval --trials 5 --steps 60 --robots 4 --output-dir output/benchmark_run
```

Sources: [configs/default_config.yaml:5-32](), [configs/aco_params.yaml:5-36](), [scripts/main.py:85-124]()

---

## 6. Summary

The `ivaziz/swarm_car_search` architecture decouples high-level bio-inspired swarm intelligence from low-level robotics mapping. By maintaining a clean boundary through `ISLAMProvider`, Mohammed & Ibrahim's decentralized ACO task allocation and stigmergic pheromone maps operate seamlessly alongside Saqr & Mahmoud's SLAM state estimators. Following the 30-minute reading order will give any developer or evaluator an end-to-end understanding of how frontier ingestion, multi-objective scoring, Boltzmann selection, and dynamic fault recovery collaborate to find targets in challenging urban environments.
