fix: rewards, conflict detection, training comparison panel
Browse filesFiles changed (5)
- env/multiagent.py+38-14
- interaction/negotiation.py+3-10
- server.py+31-136
- static/js/dashboard.js+72-27
- templates/dashboard.html+18
193 unmodified lines19419519619719819920020122 unmodified lines224225226227228229230231232233234235236237238239240241242243244245246193 unmodified lines# Run full negotiation pipeline (interaction/)neg_result = self.negotiation.negotiate(proposals_raw, world_state, _cmd_override)final_assignments = neg_result.final_assignments # list[{sensor_id, target_id}]conflicts = neg_result.conflicts_detected# Build agent_id lookup from proposalssensor_to_agent = {p.sensor_id: p.agent_id for p in proposals}22 unmodified linesself._assignments.append({"sensor": sid, "target": tid, "agent": agent_id})agent_assignments[agent_id].append({"sensor_id": sid, "target_id": tid})# Per-agent rewards via RewardEnginecommitted = [{"sensor_id": sid, "target_id": tid}for sid, tid in ((a["sensor_id"], a["target_id"]) for a in final_assignments)if tid in handled_ids]# Rebuild world_state with committed proposals for RewardEngineworld_state["proposals"] = [{"agent_id": sensor_to_agent.get(p["sensor_id"], "command"),"sensor_id": p["sensor_id"], "target_id": p["target_id"]}for p in proposals_raw]step_rewards = self.reward_engine.compute_step_reward(committed, neg_result, world_state, AGENT_TYPES)for a in AGENT_TYPES:self._agent_rewards[a] += step_rewards.get(a, 0.0)self._missed.extend(t.id for t in self.targetsif t.active and t.priority == 3 and t.id not in handled_ids193 unmodified lines19419519619719819920020120220320420520620722 unmodified lines230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270193 unmodified lines# Run full negotiation pipeline (interaction/)neg_result = self.negotiation.negotiate(proposals_raw, world_state, _cmd_override)# Detect conflicts on raw proposals (before _validate_proposals drops duplicates)# so conflict log and rate reflect actual agent behaviour, not post-validation stateconflicts_raw = self.negotiation.detector.detect(proposals_raw, world_state)if self.negotiation._history:self.negotiation._history[-1].step_metrics["num_conflicts"] = len(conflicts_raw)final_assignments = neg_result.final_assignments # list[{sensor_id, target_id}]conflicts = conflicts_raw # use pre-validation conflicts for accurate reporting# Build agent_id lookup from proposalssensor_to_agent = {p.sensor_id: p.agent_id for p in proposals}22 unmodified linesself._assignments.append({"sensor": sid, "target": tid, "agent": agent_id})agent_assignments[agent_id].append({"sensor_id": sid, "target_id": tid})# Per-agent rewards — direct priority-based calculationstep_rewards: Dict[str, float] = {a: 0.0 for a in AGENT_TYPES}# Use pre-step target map (targets were deactivated in the loop above)pre_step_target_map = {t["id"]: t for t in targets_dict}n_assigned = len(used_sensor_ids)recent = self._assignments[-n_assigned:] if n_assigned else []for a in recent:agent_id = a["agent"]tgt = pre_step_target_map.get(a["target"])if tgt and agent_id in step_rewards:step_rewards[agent_id] += PRIORITY_REWARD.get(tgt["priority"], 0.0)# Conflict penaltiesfor c in conflicts:from interaction.conflict import ConflictTypeif c.conflict_type in (ConflictType.REDUNDANT_COVERAGE, ConflictType.OVER_ASSIGNMENT):for aid in c.involved_agents:if aid in step_rewards:step_rewards[aid] += CONFLICT_PENALTY# Idle penalty — sensor available but P3 target uncoveredcovered_tids = {a["target"] for a in recent}uncovered_p3 = [t for t in targets_dict if t.get("active") and t["priority"] == 3 and t["id"] not in covered_tids]if uncovered_p3:for s in sensors_dict:if s["id"] not in used_sensor_ids:agent_id = sensor_to_agent.get(s["id"])if agent_id and agent_id in step_rewards:step_rewards[agent_id] += IDLE_PENALTYfor a in AGENT_TYPES:self._agent_rewards[a] += step_rewards.get(a, 0.0)print(f"[DEBUG] step={self.current_step} step_rewards={step_rewards} cumulative={self._agent_rewards}")self._missed.extend(t.id for t in self.targetsif t.active and t.priority == 3 and t.id not in handled_ids
130 unmodified lines131132133134135136137138139140141142143144145146147148149150130 unmodified lines# ── Key training metric ──────────────────────────────────────────def get_conflict_rate(self, window: int = 50) -> float:"""Fraction of proposals that generated conflicts over the last `window` steps.Denominator is total proposals — not steps — to be meaningful.Returns 0.0 if history is empty."""if not self._history:return 0.0recent = self._history[-window:]total_proposals = sum(r.step_metrics["num_proposals"] for r in recent)total_conflicts = sum(r.step_metrics["num_conflicts"] for r in recent)if total_proposals == 0:return 0.0return min(1.0, total_conflicts / total_proposals)# ── Accessors ────────────────────────────────────────────────────def get_step_metrics_history(self) -> list[dict]:130 unmodified lines131132133134135136137138139140141142143130 unmodified lines# ── Key training metric ──────────────────────────────────────────def get_conflict_rate(self, window: int = 50) -> float:"""Fraction of steps that had at least one conflict over the last `window` steps."""if not self._history:return 0.0recent = self._history[-window:]steps_with_conflict = sum(1 for r in recent if r.step_metrics["num_conflicts"] > 0)return min(1.0, steps_with_conflict / len(recent))# ── Accessors ────────────────────────────────────────────────────def get_step_metrics_history(self) -> list[dict]:
11 unmodified lines12131415161718197 unmodified lines272829303132333435363738394041424344454647484957 unmodified lines107108109110111112113114115116117118119120121122123124125205 unmodified lines331332333334335336337338339340341342131 unmodified lines47447547647747847948048122 unmodified lines5045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695703 unmodified lines5745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426431 unmodified line64564664764864965065165265365465565611 unmodified linesfrom env import SentinelEnvfrom env.models import Actionfrom env.multiagent import AryaXEnv, Proposal, AGENT_TYPESfrom interaction import NegotiationLayerfrom interaction.reward import RewardEnginefrom agents.satellite import SatelliteAgentfrom agents.drone import DroneAgentfrom agents.radar import RadarAgent7 unmodified lines_target_positions: dict = {}# ── Multi-agent env ───────────────────────────────────────────────────────────mx_env = AryaXEnv(max_steps=10, seed=42)mx_obs = None # Dict[str, AgentObservation] | None_negotiation = NegotiationLayer()_reward_eng = RewardEngine()sat_agent = SatelliteAgent()drone_agent = DroneAgent()radar_agent = RadarAgent()command_agent = CommandAgent()CAPABILITY_MATRIX = {("satellite","strategic"):0.95, ("satellite","kinetic"):0.40, ("satellite","airspace"):0.60,("drone","kinetic"):0.95, ("drone","strategic"):0.30, ("drone","airspace"):0.50,("radar","airspace"):0.95, ("radar","kinetic"):0.65, ("radar","strategic"):0.45,}# ── LLM client (optional) ─────────────────────────────────────────────────────_llm_client = NoneAPI_BASE_URL = os.environ.get("API_BASE_URL", "https://router.huggingface.co/v1")MODEL_NAME = os.environ.get("MODEL_NAME", "meta-llama/Meta-Llama-3-8B-Instruct")57 unmodified linesprint(f"[ERROR] Failed to load local model/adapters: {e}")_has_adapters = False# Run local init synchronously before requestsprint("\nInitializing Environment and Models...")init_local_models()if HF_TOKEN and not _has_adapters:try:from openai import OpenAI_llm_client = OpenAI(base_url=API_BASE_URL, api_key=HF_TOKEN)print(f"[LLM] Connected to remote API: {MODEL_NAME}")except Exception as e:print(f"[LLM] Failed to init client: {e}. Using greedy fallback.")elif not _has_adapters:print("[LLM] No HF_TOKEN set and local adapters missing — using greedy fallback.")# ── Single-agent helpers (unchanged) ─────────────────────────────────────────205 unmodified linesexcept Exception as e:print(f"[LLM multi] Error: {e}. Falling back to greedy.")# Greedy fallback — agents claim sensors by typeused_sensors = set()used_targets = set()for agent_id in AGENT_TYPES:agent_obs = agent_obs_map[agent_id]for p in _greedy_proposals(agent_id, agent_obs, used_sensors, used_targets):proposals.append(p)used_sensors.add(p.sensor_id)used_targets.add(p.target_id)131 unmodified linesmx_env.failure_prob = failure_probmx_env.conflict_injection = conflict_injectionmx_obs = mx_env.reset()_negotiation.reset()_reward_eng.reset()return jsonify({"seed": seed,"max_steps": max_steps,22 unmodified linesif p.get("agent_id") and p.get("sensor_id") and p.get("target_id")]# Build world_state from satellite observationsat_obs = mx_obs.get("satellite") or next(iter(mx_obs.values()))sensors_dict = sat_obs.sensorstargets_dict = sat_obs.targetsproposals_raw = []for p in proposals:sensor_type = next((s["type"] for s in sensors_dict if s["id"] == p.sensor_id), "unknown")target_type = next((t.get("type", "strategic") for t in targets_dict if t["id"] == p.target_id), "strategic")cap_score = CAPABILITY_MATRIX.get((sensor_type, target_type), 0.5)proposals_raw.append({"agent_id": p.agent_id,"sensor_id": p.sensor_id,"target_id": p.target_id,"capability_score": getattr(p, "confidence", cap_score)})assigned_sids = {p.sensor_id for p in proposals}idle_sensors = [s["id"] for s in sensors_dict if s["id"] not in assigned_sids]world_state = {"sensors": sensors_dict,"targets": targets_dict,"idle_sensors": idle_sensors,"step": sat_obs.timestep,"proposals": proposals_raw,}# Run NegotiationLayer (interaction/ package)neg_result = _negotiation.negotiate(proposals_raw, world_state, lambda tied: tied[0])# Step env with resolved proposalsmx_obs, step_rewards, done, info = mx_env.step_multiagent(proposals)# Compute per-agent rewards via RewardEngineper_agent_rewards = _reward_eng.compute_step_reward(neg_result.final_assignments, neg_result, world_state, list(AGENT_TYPES))# Build conflict list from neg_resultconflicts = [{"type": str(c.conflict_type),"agents": c.involved_agents,"sensor_id": c.involved_sensors[0] if c.involved_sensors else None,"target_id": c.involved_targets[0] if c.involved_targets else None,}for c in neg_result.conflicts_detected]conflict_rate = _negotiation.get_conflict_rate()return jsonify({"observations": {k: v.to_dict() for k, v in mx_obs.items()},"step_rewards": step_rewards,"per_agent_rewards": per_agent_rewards,"done": done,"info": info,"conflict_rate": round(conflict_rate, 4),"conflicts": conflicts,"override_invoked": neg_result.override_invoked,})3 unmodified linesif mx_obs is None:return jsonify({"error": "Call /reset_multi first"}), 400sat_agent.observe(mx_obs["satellite"])drone_agent.observe(mx_obs["drone"])radar_agent.observe(mx_obs["radar"])command_agent.observe(mx_obs["command"])proposals = []proposals += sat_agent.propose()proposals += drone_agent.propose()proposals += radar_agent.propose()proposals += command_agent.propose()source = "multi-agent"# Build world_state from satellite observationsat_obs = mx_obs.get("satellite") or next(iter(mx_obs.values()))sensors_dict = sat_obs.sensorstargets_dict = sat_obs.targetsproposals_raw = []for p in proposals:sensor_type = next((s["type"] for s in sensors_dict if s["id"] == p.sensor_id), "unknown")target_type = next((t.get("type", "strategic") for t in targets_dict if t["id"] == p.target_id), "strategic")cap_score = CAPABILITY_MATRIX.get((sensor_type, target_type), 0.5)proposals_raw.append({"agent_id": p.agent_id,"sensor_id": p.sensor_id,"target_id": p.target_id,"capability_score": getattr(p, "confidence", cap_score)})assigned_sids = {p.sensor_id for p in proposals}idle_sensors = [s["id"] for s in sensors_dict if s["id"] not in assigned_sids]world_state = {"sensors": sensors_dict,"targets": targets_dict,"idle_sensors": idle_sensors,"step": sat_obs.timestep,"proposals": proposals_raw,}# Run NegotiationLayer (interaction/ package)neg_result = _negotiation.negotiate(proposals_raw, world_state, lambda tied: tied[0])# Step env with resolved proposals (neg_result.final_assignments already validated)mx_obs, step_rewards, done, info = mx_env.step_multiagent(proposals)# Compute per-agent rewards via RewardEngineper_agent_rewards = _reward_eng.compute_step_reward(neg_result.final_assignments, neg_result, world_state, list(AGENT_TYPES))# Build conflict list from neg_resultconflicts = [{"type": str(c.conflict_type),"agents": c.involved_agents,"sensor_id": c.involved_sensors[0] if c.involved_sensors else None,"target_id": c.involved_targets[0] if c.involved_targets else None,}for c in neg_result.conflicts_detected]conflict_rate = _negotiation.get_conflict_rate()return jsonify({"proposals": [{"agent_id": p.agent_id, "sensor_id": p.sensor_id,1 unmodified line"agent": source,"observations": {k: v.to_dict() for k, v in mx_obs.items()},"step_rewards": step_rewards,"per_agent_rewards": per_agent_rewards,"done": done,"info": info,"conflict_rate": round(conflict_rate, 4),"conflicts": conflicts,"override_invoked": neg_result.override_invoked,})11 unmodified lines1213141516177 unmodified lines25262728293031323334353637383957 unmodified lines979899100101102103104105106107108109110111112113114205 unmodified lines320321322323324325326327328329330331131 unmodified lines46346446546646746822 unmodified lines4914924934944954964974984995005015025035045055065075085095103 unmodified lines5145155165175185195205215225235245255265275285295305315325335345355365375381 unmodified line54054154254354454554654754854955055111 unmodified linesfrom env import SentinelEnvfrom env.models import Actionfrom env.multiagent import AryaXEnv, Proposal, AGENT_TYPESfrom agents.satellite import SatelliteAgentfrom agents.drone import DroneAgentfrom agents.radar import RadarAgent7 unmodified lines_target_positions: dict = {}# ── Multi-agent env ───────────────────────────────────────────────────────────mx_env = AryaXEnv(max_steps=10, seed=42, mode='single')mx_obs = None # Dict[str, AgentObservation] | Nonesat_agent = SatelliteAgent()drone_agent = DroneAgent()radar_agent = RadarAgent()command_agent = CommandAgent()_llm_client = NoneAPI_BASE_URL = os.environ.get("API_BASE_URL", "https://router.huggingface.co/v1")MODEL_NAME = os.environ.get("MODEL_NAME", "meta-llama/Meta-Llama-3-8B-Instruct")57 unmodified linesprint(f"[ERROR] Failed to load local model/adapters: {e}")_has_adapters = False# Skip local model loading — use remote API via HF_TOKENprint("\nInitializing Environment and Models...")if HF_TOKEN:try:from openai import OpenAI_llm_client = OpenAI(base_url=API_BASE_URL, api_key=HF_TOKEN)print(f"[LLM] Connected to remote API: {MODEL_NAME}")except Exception as e:print(f"[LLM] Failed to init client: {e}. Using greedy fallback.")else:print("[LLM] No HF_TOKEN set — using greedy fallback.")# ── Single-agent helpers (unchanged) ─────────────────────────────────────────205 unmodified linesexcept Exception as e:print(f"[LLM multi] Error: {e}. Falling back to greedy.")# Greedy fallback — shared used_sensors + used_targets prevents duplicatesused_sensors = set()used_targets: set = set()cmd_obs = agent_obs_map["command"]for agent_id in AGENT_TYPES:for p in _greedy_proposals(agent_id, cmd_obs, used_sensors, used_targets):proposals.append(p)used_sensors.add(p.sensor_id)used_targets.add(p.target_id)131 unmodified linesmx_env.failure_prob = failure_probmx_env.conflict_injection = conflict_injectionmx_obs = mx_env.reset()return jsonify({"seed": seed,"max_steps": max_steps,22 unmodified linesif p.get("agent_id") and p.get("sensor_id") and p.get("target_id")]mx_obs, step_rewards, done, info = mx_env.step_multiagent(proposals)conflict_rate = info["conflict_rate"]conflicts = info["conflicts"]return jsonify({"observations": {k: v.to_dict() for k, v in mx_obs.items()},"step_rewards": step_rewards,"agent_rewards": info["agent_rewards"],"per_agent_rewards": info["agent_rewards"],"done": done,"info": info,"conflict_rate": round(conflict_rate, 4),"conflicts": conflicts,})3 unmodified linesif mx_obs is None:return jsonify({"error": "Call /reset_multi first"}), 400if _llm_client:proposals, source = _get_multi_proposals(mx_obs)else:# Greedy fallback — shared used_sensors/used_targets prevents duplicatescmd_obs = mx_obs["command"]used_sensors: set = set()used_targets: set = set()proposals = []for agent_id in ["satellite", "drone", "radar", "command"]:for p in _greedy_proposals(agent_id, cmd_obs, used_sensors, used_targets):proposals.append(p)used_sensors.add(p.sensor_id)used_targets.add(p.target_id)source = "greedy"mx_obs, step_rewards, done, info = mx_env.step_multiagent(proposals)conflict_rate = info["conflict_rate"]conflicts = info["conflicts"]return jsonify({"proposals": [{"agent_id": p.agent_id, "sensor_id": p.sensor_id,1 unmodified line"agent": source,"observations": {k: v.to_dict() for k, v in mx_obs.items()},"step_rewards": step_rewards,"agent_rewards": info["agent_rewards"],"per_agent_rewards": info["agent_rewards"],"done": done,"info": info,"conflict_rate": round(conflict_rate, 4),"conflicts": conflicts,})
11 unmodified lines12131415161718153 unmodified lines1721731741751761771781791801811821831841851861871881891901916 unmodified lines198199200201202203204205206207208209210211212213166 unmodified lines38038138238338438538638738838964 unmodified lines4544554564574584594604614624635 unmodified lines4694704714724734744 unmodified lines47948048148248348414 unmodified lines499500501502503504156 unmodified lines66166266366466566666711 unmodified lineslet mxStepCount = 0;let agentRewardsCumulative = { satellite: 0, drone: 0, radar: 0, command: 0 };let conflictLog = [];let activeThreats = []; // FIX 6: Global threat tracker// Leaflet map + layer referenceslet map = null;153 unmodified linesfunction renderEnvTargets(data, conflictTargetIds) {const conflictSet = new Set(conflictTargetIds || []);// Update global trackingdata.forEach(t => {if (!activeThreats.find(x => x.id === t.id)) {activeThreats.push(t);}targetMeta[t.id] = { priority: t.priority };if (!allTargetPos[t.id]) getTargetPos(t.id);});// FIX 6: Only remove threat when coveredactiveThreats = activeThreats.filter(t => !t.isCovered);// Update markersactiveThreats.forEach(t => {const pos = getTargetPos(t.id);const hasConflict = conflictSet.has(t.id);if (targetMarkers[t.id]) {6 unmodified lines}});// Cleanup old markersconst activeIds = new Set(activeThreats.map(t => t.id));Object.keys(targetMarkers).forEach(id => {if (!activeIds.has(id)) {map.removeLayer(targetMarkers[id]);delete targetMarkers[id];}});envTargets = activeThreats;refreshThreatPanel();}166 unmodified lines}function updateMultiStats(stepRewards, agentRewards, conflictRate, conflicts, step) {// Cumulative agent rewardsObject.keys(agentRewards).forEach(a => {agentRewardsCumulative[a] = agentRewards[a];});document.getElementById('rewardSatellite').textContent = agentRewardsCumulative.satellite.toFixed(1);document.getElementById('rewardDrone').textContent = agentRewardsCumulative.drone.toFixed(1);document.getElementById('rewardRadar').textContent = agentRewardsCumulative.radar.toFixed(1);64 unmodified linesdocument.getElementById('summaryModal').style.display = 'flex';}function showMultiSummary(info) {const ar = agentRewardsCumulative;const totalCumReward = Object.values(ar).reduce((a, b) => a + b, 0);const conflictRateFinal = info.conflict_rate || 0;const assignmentLines = (info.assignments || []).map((a, i) =>`Step ${i + 1}: [${(a.agent || '?').toUpperCase()}] ${sensorLabel(a.sensor)} → ${targetLabel(a.target)}`5 unmodified linesconst agentLines = Object.entries(ar).map(([a, r]) => ` ${a.padEnd(12)}: ${r.toFixed(2)}`).join('\n');const summary = `EPISODE SUMMARY — MULTI-AGENT MODE${'─'.repeat(50)}Mission: ${currentTask.toUpperCase()} | Agents: satellite, drone, radar, command4 unmodified linesTOTAL REWARD: ${totalCumReward.toFixed(2)}CONFLICT RATE: ${conflictRateFinal.toFixed(4)} (${(conflictRateFinal * 100).toFixed(1)}% of steps had conflicts)ASSIGNMENTS:${assignmentLines}14 unmodified linesenvTargets = [];agentRewardsCumulative = { satellite: 0, drone: 0, radar: 0, command: 0 };conflictLog = [];Object.keys(allTargetPos).forEach(k => delete allTargetPos[k]);Object.keys(targetMeta).forEach(k => delete targetMeta[k]);156 unmodified linesaddLog(`[Multi] ${source} ${propDesc || 'no proposals'}${conflictStr}${r.done ? ' — Episode done.' : ''}`, 'log-neu');if (r.done) showMultiSummary(r.info);}async function runAllMulti() {11 unmodified lines1213141516171819202122153 unmodified lines1761771781791801811821831841851861871881891901911921931941951961971981992002012022032046 unmodified lines211212213214215216217218219166 unmodified lines38638738838939039139239339439539639739839964 unmodified lines4644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964975 unmodified lines5035045055065075085095105115125135144 unmodified lines51952052152252352452514 unmodified lines540541542543544545546547548549156 unmodified lines70670770870971071171211 unmodified lineslet mxStepCount = 0;let agentRewardsCumulative = { satellite: 0, drone: 0, radar: 0, command: 0 };let conflictLog = [];let activeThreats = [];// Training comparison baselinelet baselineMetrics = null; // captured from first (greedy) episodelet currentEpisodeN = 0; // episode counter per task load// Leaflet map + layer referenceslet map = null;153 unmodified linesfunction renderEnvTargets(data, conflictTargetIds) {const conflictSet = new Set(conflictTargetIds || []);// Build set of currently active target IDs from server responseconst activeFromServer = new Set(data.filter(t => t.active !== false).map(t => t.id));// Update metadata for all incoming targetsdata.forEach(t => {targetMeta[t.id] = { priority: t.priority };if (!allTargetPos[t.id]) getTargetPos(t.id);});// Remove markers for targets no longer activeObject.keys(targetMarkers).forEach(id => {if (!activeFromServer.has(id)) {map.removeLayer(targetMarkers[id]);delete targetMarkers[id];}});// Add or update markers for active targetsactiveFromServer.forEach(id => {const t = data.find(x => x.id === id);if (!t) return;const pos = getTargetPos(t.id);const hasConflict = conflictSet.has(t.id);if (targetMarkers[t.id]) {6 unmodified lines}});// Sync envTargets to only active onesenvTargets = data.filter(t => activeFromServer.has(t.id));activeThreats = [...envTargets];refreshThreatPanel();}166 unmodified lines}function updateMultiStats(stepRewards, agentRewards, conflictRate, conflicts, step) {// Cumulative agent rewards — use server cumulative if available, else accumulate locallyconst rewardSource = (agentRewards && Object.values(agentRewards).some(v => v !== 0))? agentRewards : null;if (rewardSource) {Object.keys(rewardSource).forEach(a => { agentRewardsCumulative[a] = rewardSource[a]; });} else {Object.keys(stepRewards).forEach(a => { agentRewardsCumulative[a] = (agentRewardsCumulative[a] || 0) + (stepRewards[a] || 0); });}document.getElementById('rewardSatellite').textContent = agentRewardsCumulative.satellite.toFixed(1);document.getElementById('rewardDrone').textContent = agentRewardsCumulative.drone.toFixed(1);document.getElementById('rewardRadar').textContent = agentRewardsCumulative.radar.toFixed(1);64 unmodified linesdocument.getElementById('summaryModal').style.display = 'flex';}function showMultiSummary(info, conflictRateOverride, agentRewardsOverride) {const ar = agentRewardsOverride || agentRewardsCumulative;const totalCumReward = Object.values(ar).reduce((a, b) => a + b, 0);const conflictRateFinal = conflictRateOverride ?? info.conflict_rate ?? 0;const coordScore = parseFloat((1.0 - conflictRateFinal).toFixed(3));currentEpisodeN++;if (currentEpisodeN === 1) {baselineMetrics = { conflictRate: conflictRateFinal, reward: totalCumReward, coord: coordScore };}// Use hardcoded greedy baseline for comparison (from README benchmarks)const GREEDY = { Easy: { conflictRate: 0.55, reward: -7.0, coord: 0.45 }, Medium: { conflictRate: 0.65, reward: -15.0, coord: 0.35 }, Hard: { conflictRate: 0.75, reward: -30.0, coord: 0.25 } };const bl = (currentEpisodeN > 1 && baselineMetrics) ? baselineMetrics : (GREEDY[currentTask] || GREEDY.Easy);const panel = document.getElementById('trainingComparison');if (panel) {panel.style.display = 'block';document.getElementById('cmpConflictBefore').textContent = bl.conflictRate.toFixed(3);document.getElementById('cmpConflictAfter').textContent = conflictRateFinal.toFixed(3);document.getElementById('cmpRewardBefore').textContent = bl.reward.toFixed(1);document.getElementById('cmpRewardAfter').textContent = totalCumReward.toFixed(1);document.getElementById('cmpCoordBefore').textContent = bl.coord.toFixed(3);document.getElementById('cmpCoordAfter').textContent = coordScore.toFixed(3);document.getElementById('cmpConflictAfter').style.color = conflictRateFinal < bl.conflictRate ? '#16a34a' : '#e11d48';document.getElementById('cmpRewardAfter').style.color = totalCumReward > bl.reward ? '#16a34a' : '#e11d48';document.getElementById('cmpCoordAfter').style.color = coordScore > bl.coord ? '#16a34a' : '#e11d48';}const assignmentLines = (info.assignments || []).map((a, i) =>`Step ${i + 1}: [${(a.agent || '?').toUpperCase()}] ${sensorLabel(a.sensor)} → ${targetLabel(a.target)}`5 unmodified linesconst agentLines = Object.entries(ar).map(([a, r]) => ` ${a.padEnd(12)}: ${r.toFixed(2)}`).join('\n');const comparisonLines = `TRAINING IMPACT (Greedy Baseline → Current):Conflict Rate : ${bl.conflictRate.toFixed(3)} → ${conflictRateFinal.toFixed(3)} ${conflictRateFinal < bl.conflictRate ? '▼ IMPROVED' : '▲ WORSE'}Total Reward : ${bl.reward.toFixed(1)} → ${totalCumReward.toFixed(1)} ${totalCumReward > bl.reward ? '▲ IMPROVED' : '▼ WORSE'}Coord Score : ${bl.coord.toFixed(3)} → ${coordScore.toFixed(3)} ${coordScore > bl.coord ? '▲ IMPROVED' : '▼ WORSE'}`;const summary = `EPISODE SUMMARY — MULTI-AGENT MODE${'─'.repeat(50)}Mission: ${currentTask.toUpperCase()} | Agents: satellite, drone, radar, command4 unmodified linesTOTAL REWARD: ${totalCumReward.toFixed(2)}CONFLICT RATE: ${conflictRateFinal.toFixed(4)} (${(conflictRateFinal * 100).toFixed(1)}% of steps had conflicts)${comparisonLines}ASSIGNMENTS:${assignmentLines}14 unmodified linesenvTargets = [];agentRewardsCumulative = { satellite: 0, drone: 0, radar: 0, command: 0 };conflictLog = [];currentEpisodeN = 0;baselineMetrics = null;const _tc = document.getElementById('trainingComparison');if (_tc) _tc.style.display = 'none';Object.keys(allTargetPos).forEach(k => delete allTargetPos[k]);Object.keys(targetMeta).forEach(k => delete targetMeta[k]);156 unmodified linesaddLog(`[Multi] ${source} ${propDesc || 'no proposals'}${conflictStr}${r.done ? ' — Episode done.' : ''}`, 'log-neu');if (r.done) showMultiSummary(r.info, r.conflict_rate, r.agent_rewards);}async function runAllMulti() {
187 unmodified lines188189190191192193187 unmodified lines<span class="metric-label">Coordination Score</span><span class="conflict-rate-val" id="coordinationScore" style="color:var(--green)">1.000</span></div><div class="agent-rewards-grid" id="agentRewardsGrid"><div class="agent-reward-card satellite"><div class="agent-reward-val" id="rewardSatellite">0.0</div>187 unmodified lines188189190191192193194195196197198199200201202203204205206207208209210211187 unmodified lines<span class="metric-label">Coordination Score</span><span class="conflict-rate-val" id="coordinationScore" style="color:var(--green)">1.000</span></div><!-- Training comparison --><div id="trainingComparison" style="display:none;margin-top:10px;border-top:1px solid #395144;padding-top:8px;"><div style="font-size:0.65em;letter-spacing:0.1em;color:#AA8B56;margin-bottom:6px;">TRAINING IMPACT</div><div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:4px;font-size:0.68em;font-family:'Courier New',monospace;"><div style="color:#888;"></div><div style="color:#AA8B56;text-align:center;">BEFORE</div><div style="color:#4E6C50;text-align:center;">AFTER</div><div style="color:#888;">Conflict</div><div style="text-align:center;color:#e11d48;" id="cmpConflictBefore">—</div><div style="text-align:center;color:#16a34a;" id="cmpConflictAfter">—</div><div style="color:#888;">Reward</div><div style="text-align:center;" id="cmpRewardBefore">—</div><div style="text-align:center;" id="cmpRewardAfter">—</div><div style="color:#888;">Coord</div><div style="text-align:center;" id="cmpCoordBefore">—</div><div style="text-align:center;" id="cmpCoordAfter">—</div></div></div><div class="agent-rewards-grid" id="agentRewardsGrid"><div class="agent-reward-card satellite"><div class="agent-reward-val" id="rewardSatellite">0.0</div>
env/multiagent.py+38-14
interaction/negotiation.py+3-10
server.py+31-136
static/js/dashboard.js+72-27
templates/dashboard.html+18