diff --git a/HAWK_DOVE.md b/HAWK_DOVE.md new file mode 100644 index 0000000..3086a63 --- /dev/null +++ b/HAWK_DOVE.md @@ -0,0 +1,84 @@ +# Hawk–Dove phase transition for the "normal ball" weapon + +## The problem + +The experiment in `simulator/conf.toml` pits an aggressive team (**red**, the +hawk) against a pacifist team (**blue**, the dove). Both carry the same weapon +but only red ever fires it. With the *ball* weapon (a blast centred on the +shooter) red essentially always wins: firing is free, so any blue it kills is +pure profit. The dove never inherits a benefit from the weapon. + +We want a phase diagram where **having a weapon goes from favouring the hawk to +favouring the dove** — i.e. a region where the armed aggressor wins and a region +where the unarmed pacifist wins, with a real boundary between them. + +## Game theory: escalation with a collateral cost + +This is the classic **Hawk–Dove** game. A hawk's payoff for escalating is the +value `V` of what it wins; the cost is `C`, the damage the fight does to the +hawk itself. Escalation is favoured while `V > C` and stops paying once +`C > V`. + +The ball weapon gives a natural, tunable `C`: the blast is centred on the +*shooter*, so it also hits + +* **kin** (friendly fire), and +* **food** (the blast's `peers` include food, which is killed on contact). + +Both scale with the blast area, i.e. with `radius²`, while the benefit (killing +doves) saturates. Make the hawks stand close enough together and a big blast +turns the hunter into its own worst enemy — the weapon now *favours the dove*. + +## Scenarios considered + +| # | Idea | Outcome | +|---|------|---------| +| 1 | Keep original columns, ball weapon only | Red wins almost everywhere (the "never favours the dove" baseline). | +| 2 | Blues clustered, reds spread | Red wipes the cluster; hawk wins even harder. | +| 3 | Reds clustered, blues spread | Dove wins everywhere: hawks nuke their own pack on the first shot. | +| 4 | Clustered hawks + `kills_user = true` | Dove wins unless the blast is huge; no hawk window. | +| 5 | **Clustered hawks (moderate), scattered doves, dense food** | Red wins with a small blast, loses once friendly fire + food destruction dominate — the desired hawk→dove transition. | + +Scenario 5 is the one kept. The key geometry change is the **hawk nest**: reds +start in a compact box in the middle of the food field, while doves are +scattered over the whole field. + +## The chosen configuration (`ball.toml`) + +* `type = "ball"`, `kills_user = false` — firing is not immediately suicidal; + the cost is purely collateral. +* `red_spawn` = 400×400 box in the field centre (the hawk nest). +* `blu_spawn` = the whole food field (doves dispersed). +* `food_spawn` = the whole food field, `food_amount = 250`. + +Sweeping `(view_dist, radius)` gives: + +* **low radius / enough view_dist → weapon favours the hawk.** A small blast + lets the packed hawks finish off nearby doves without hurting the nest. +* **high radius → weapon favours the dove.** The blast catches kin and + vaporises the nest's food; the scattered doves out-forage the survivors. +* insufficient `view_dist` alone also hurts red (the nest cannot range out to + food), which bends the boundary upwards as `view_dist` grows. + +The boundary is robust: it barely moves when red's `kin`/`nonkin`/`none` +policies are perturbed (see the scan in the commit history / scratch work). + +## Reproducing + +```bash +bash run.sh +# view_dist 100:350:12.5 × radius 0:250:12.5, sigma 3, refine 1 +# -> sweep_out/results.jsonl, sweep_out/results.csv, sweep_out/phase.png +``` + +Final run: 600 points, ~354k seeds, **red 312 / blue 214 / tie 74**. The +boundary (`mean_diff = 0`) climbs from radius ≈ 105 at `view_dist = 100` to +≈ 175 by `view_dist ≈ 200` and then flattens — a single, smooth, weapon-driven +hawk→dove frontier with a thin undecided band. + +## Simulator change + +Spawns were hard-coded columns. `SimConfig` now accepts three optional regions +(`blu_spawn`, `red_spawn`, `food_spawn`, each `x0/x1/y0/y1`), sampled uniformly +per seed. Omitting them reproduces the original fixed columns bit-for-bit, so +all pre-existing tests and configs still pass. diff --git a/ball.toml b/ball.toml new file mode 100644 index 0000000..dbda1e7 --- /dev/null +++ b/ball.toml @@ -0,0 +1,66 @@ +# Hawk–Dove phase experiment for the "normal ball" weapon. +# +# Red is the hawk (aggressive, fires the ball on sight of a non-kin); +# Blue is the dove (pacifist, never fires). Both teams carry the same weapon. +# +# The ball weapon is centred on the shooter, so escalating is a *costly* +# signal: its blast also catches kin and food. To turn that cost into a phase +# transition we change the spawn geometry: +# +# * Red (hawks) start packed together in a nest in the middle of the food +# field. Packed hawks are efficient at finishing off nearby doves with a +# small blast, but a large blast kills the pack itself (friendly fire) and +# vaporises the nest's food. +# * Blue (doves) start scattered across the whole field, so they forage +# widely and are poor targets for any single blast. +# +# Sweeping (view_dist, weapon radius) then separates two regimes: +# * low radius / enough view_dist -> the weapon favours the hawk; +# * high radius -> the weapon favours the dove. +# This is the classic Hawk–Dove result: escalation pays while C < V and stops +# paying once the blast's collateral cost dominates. + +food_amount = 250 +view_dist = 200 +red_count = 10 +blu_count = 10 + +[weapon] +kills_user = false +type = "ball" +radius = 90 + +# Hawks: a tight nest near the middle of the field (400x400 box). +[red_spawn] +x0 = 450 +x1 = 850 +y0 = 350 +y1 = 750 + +# Doves: scattered over the entire food field. +[blu_spawn] +x0 = 200 +x1 = 1100 +y0 = 200 +y1 = 900 + +# Food: scattered over the entire field. +[food_spawn] +x0 = 200 +x1 = 1100 +y0 = 200 +y1 = 900 + +[red_policy] +aggressive = true +food = [1,0] +kin = [-0.3,0.02] +nonkin = [0.3,0.02] +none= [0.3, 0.01] + +[blu_policy] +aggressive = false +food = [1,0] +kin = [-0.3,0.02] +nonkin = [-0.3,-0.02] +none= [0.3, 0.01] diff --git a/run.sh b/run.sh new file mode 100644 index 0000000..012774e --- /dev/null +++ b/run.sh @@ -0,0 +1,8 @@ +#!/bin/bash + +source env/bin/activate + +python3 tools/sweep.py --base ball.toml --view-dist 100:350:12.5 --radius 0:250:12.5 \ + --sigma 3 --max-samples 2000 --refine 1 --refine-max-samples 2500 \ + --seed-budget 3000000 --workers 16 --rayon-threads 1 +python3 tools/plot_phase.py sweep_out/results.jsonl -o sweep_out/phase.png diff --git a/simulator/src/main.rs b/simulator/src/main.rs index e08ded1..7548048 100644 --- a/simulator/src/main.rs +++ b/simulator/src/main.rs @@ -407,6 +407,28 @@ struct Weapon { model: WeaponType, } +/// An axis-aligned spawn region. When a team (or the food) is given one, its +/// members are scattered uniformly inside it instead of the legacy fixed +/// columns. This is the lever that lets an experiment control who starts next +/// to whom, which in turn controls how much of the weapon's blast is spent on +/// opponents versus on kin and food. +#[derive(Deserialize, Clone, Copy)] +struct SpawnRect { + x0: f32, + x1: f32, + y0: f32, + y1: f32, +} + +impl SpawnRect { + fn sample(&self, rng: &mut SmallRng) -> Vec2 { + Vec2 { + x: rng.random_range(self.x0..self.x1), + y: rng.random_range(self.y0..self.y1), + } + } +} + #[derive(Deserialize)] struct SimConfig { food_amount: usize, @@ -416,6 +438,14 @@ struct SimConfig { blu_count: usize, blu_policy: Policy, weapon: Weapon, + /// Optional spawn regions. Omitted fields reproduce the original fixed + /// columns (`blu` at x=100, `red` at x=1200, both on a vertical grid). + #[serde(default)] + blu_spawn: Option, + #[serde(default)] + red_spawn: Option, + #[serde(default)] + food_spawn: Option, } struct Simulation { @@ -448,22 +478,35 @@ impl Simulation { // blue robots for i in 0..config.blu_count { let rand_angle = angle.sample(&mut rng); - let pose:Pose = Pose::from_parts(Vec2 { x: 100.0, y: i as f32*50.0 + 250.0}, Rot2::from_angle(rand_angle)); + let pos = match config.blu_spawn { + Some(r) => r.sample(&mut rng), + None => Vec2 { x: 100.0, y: i as f32 * 50.0 + 250.0 }, + }; + let pose: Pose = Pose::from_parts(pos, Rot2::from_angle(rand_angle)); robots.push(Robot::new(pose, BLUE, config.blu_policy.clone(), config.weapon.clone(), config.view_dist)); } //red robots for i in 0..config.red_count { let rand_angle = angle.sample(&mut rng); - let pose:Pose = Pose::from_parts(Vec2 { x: 1200.0, y: i as f32*50.0 + 250.0}, Rot2::from_angle(rand_angle)); + let pos = match config.red_spawn { + Some(r) => r.sample(&mut rng), + None => Vec2 { x: 1200.0, y: i as f32 * 50.0 + 250.0 }, + }; + let pose: Pose = Pose::from_parts(pos, Rot2::from_angle(rand_angle)); robots.push(Robot::new(pose, RED, config.red_policy.clone(), config.weapon.clone(), config.view_dist)); } let mut food = Vec::new(); for _ in 0..config.food_amount { - let x = rng.random_range(200.0 .. 1100.0); - let y = rng.random_range(200.0 .. 900.0); + let (x, y) = match config.food_spawn { + Some(r) => { + let p = r.sample(&mut rng); + (p.x, p.y) + } + None => (rng.random_range(200.0 .. 1100.0), rng.random_range(200.0 .. 900.0)), + }; food.push(Food::new(Vec2 { x, y })); } let cell = grid_cell(config.view_dist); @@ -984,6 +1027,74 @@ mod tests { toml::from_str(include_str!("../equal.toml")).unwrap() } + /// Spawn regions are honoured: every robot/food lands inside its declared + /// rectangle, and omitting the regions keeps the legacy fixed columns. + #[test] + fn spawn_rects_are_respected() { + let text = r#" +food_amount = 5 +view_dist = 200 +red_count = 3 +blu_count = 4 +[weapon] +kills_user = false +type = "ball" +radius = 10 +[red_spawn] +x0 = 500 +x1 = 600 +y0 = 400 +y1 = 450 +[blu_spawn] +x0 = 100 +x1 = 200 +y0 = 300 +y1 = 350 +[food_spawn] +x0 = 700 +x1 = 800 +y0 = 600 +y1 = 650 +[red_policy] +aggressive = true +food = [1,0] +kin = [-0.3,0.02] +nonkin = [0.3,0.02] +none = [0.3,0.01] +[blu_policy] +aggressive = false +food = [1,0] +kin = [-0.3,0.02] +nonkin = [-0.3,-0.02] +none = [0.3,0.01] +"#; + let config: SimConfig = toml::from_str(text).unwrap(); + let sim = Simulation::new(7, &config); + + let in_rect = |p: Vec2, r: SpawnRect| { + p.x >= r.x0 && p.x <= r.x1 && p.y >= r.y0 && p.y <= r.y1 + }; + let red = config.red_spawn.unwrap(); + let blu = config.blu_spawn.unwrap(); + let food = config.food_spawn.unwrap(); + + for r in sim.robots.iter().filter(|r| r.team == RED) { + assert!(in_rect(r.pose.translation, red), "red out of region: {:?}", r.pose.translation); + } + for r in sim.robots.iter().filter(|r| r.team == BLUE) { + assert!(in_rect(r.pose.translation, blu), "blue out of region: {:?}", r.pose.translation); + } + for f in sim.food.iter() { + assert!(in_rect(f.pose.translation, food), "food out of region: {:?}", f.pose.translation); + } + + // Without spawn regions the legacy columns are still used. + let legacy: SimConfig = toml::from_str(include_str!("../conf.toml")).unwrap(); + let sim = Simulation::new(0, &legacy); + assert!(sim.robots.iter().filter(|r| r.team == BLUE).all(|r| r.pose.translation.x == 100.0)); + assert!(sim.robots.iter().filter(|r| r.team == RED).all(|r| r.pose.translation.x == 1200.0)); + } + /// The analytic replacements must agree with parry bit-for-bit, both on /// whether a contact exists and on the reported `point1.distance(origin)`. /// This is the load-bearing test behind the whole speedup: the hot path no diff --git a/tools/README.md b/tools/README.md index e95c873..9534ba8 100644 --- a/tools/README.md +++ b/tools/README.md @@ -136,6 +136,25 @@ sweep over the same grid would have been ~1.4M seeds). - The boundary band (`tie` points) is where `|mean_diff| / SE < 3` even after the sample cap. +## Spawn geometry + +The base config may declare optional spawn regions: + +```toml +[red_spawn] +x0 = 450 +x1 = 850 +y0 = 350 +y1 = 750 +``` + +`red_spawn`, `blu_spawn` and `food_spawn` each take `x0/x1/y0/y1`; members are +scattered uniformly inside the rectangle per seed. Omitting a region keeps the +original fixed columns (`blu` at `x = 100`, `red` at `x = 1200`, food in +`[200,1100] × [200,900]`). `ball.toml` uses this to build the Hawk–Dove +experiment in `HAWK_DOVE.md` (hawks nested in the field centre, doves +scattered); see that document for the game-theoretic rationale. + ## Extending - **Other axes:** point `--view-dist`/`--radius` at any numeric field, or add a