rustsim 0.0.1

High-performance agent-based modelling engine - top-level orchestration crate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Integration test: counter-flow corridor with physical avoidance.
//!
//! Two opposing streams of pedestrians walk toward each other through a
//! corridor bounded by walls. The Social Force Model with physical contact
//! forces drives avoidance behavior.
//!
//! Validates:
//! 1. Agents avoid each other and reach their destinations.
//! 2. Wall repulsion keeps agents inside the corridor.
//! 3. Physical contact forces prevent persistent body overlaps.
//! 4. Deterministic replay for a fixed seed.

use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use rustsim::prelude::*;
use rustsim_spaces::continuous::{ContinuousPos, ContinuousSpace2D};
use std::time::Instant;

// ---- Parameters ----

const CORRIDOR_X: f64 = 40.0;
const CORRIDOR_Y: f64 = 8.0;
const NUM_AGENTS: usize = 60; // 30 per direction
const DT: f64 = 0.05;
const BODY_RADIUS: f64 = 0.25;
const DESIRED_SPEED: f64 = 1.3;
const SEARCH_RADIUS: f64 = 3.0;
const NUM_STEPS: usize = 5000; // 250 seconds

// ---- Agent ----

#[derive(Debug, Clone)]
struct Pedestrian {
    id: AgentId,
    x: f64,
    y: f64,
    vx: f64,
    vy: f64,
    dest_x: f64,
    dest_y: f64,
    radius: f64,
    desired_speed: f64,
    arrived: bool,
}

impl Agent for Pedestrian {
    fn id(&self) -> AgentId {
        self.id
    }
}

// ---- Helper wrapper for initial space registration ----

#[derive(Debug, Clone)]
struct PosWrapper {
    id: AgentId,
    pos: ContinuousPos,
}

impl Agent for PosWrapper {
    fn id(&self) -> AgentId {
        self.id
    }
}

impl PositionedAgent for PosWrapper {
    type Position = ContinuousPos;
    fn position(&self) -> &ContinuousPos {
        &self.pos
    }
    fn set_position(&mut self, pos: ContinuousPos) {
        self.pos = pos;
    }
}

// ---- Properties ----

#[derive(Debug, Clone)]
struct CorridorProps {
    walls: Vec<WallSegment>,
    sfm_params: SocialForceParams,
    dt: f64,
    arrivals: usize,
}

// ---- Model type ----

type CorridorModel = StandardModel<
    ContinuousSpace2D,
    Pedestrian,
    HashMapStore<Pedestrian>,
    CorridorProps,
    StdRng,
    Fastest,
>;

// ---- Agent step ----

fn ped_step(
    agent: &mut Pedestrian,
    ctx: &mut StepContext<'_, ContinuousSpace2D, Pedestrian, CorridorProps, StdRng, Fastest>,
) {
    if agent.arrived {
        return;
    }

    let props = ctx.properties();
    let dt = props.dt;
    let params = &props.sfm_params;

    // Check arrival.
    let dx = agent.dest_x - agent.x;
    let dy = agent.dest_y - agent.y;
    if (dx * dx + dy * dy).sqrt() < 0.5 {
        agent.arrived = true;
        agent.vx = 0.0;
        agent.vy = 0.0;
        return;
    }

    // 1. Desired force.
    let (fdx, fdy) = desired_force_2d(
        agent.x,
        agent.y,
        agent.vx,
        agent.vy,
        agent.dest_x,
        agent.dest_y,
        agent.desired_speed,
        params.tau,
    );
    let mut fx = fdx;
    let mut fy = fdy;

    // 2. Social repulsion from neighbors.
    let nearby = ctx
        .space()
        .nearby_ids_euclidean(&ContinuousPos::new(agent.x, agent.y), SEARCH_RADIUS);

    for &nid in &nearby {
        if nid == agent.id {
            continue;
        }
        if let Some(npos) = ctx.space().agent_position(nid) {
            // Neighbor velocity approximated as zero (we do not have it
            // from the space; a real simulation would use messaging).
            let (sfx, sfy) = social_repulsion_2d(
                agent.x,
                agent.y,
                agent.vx,
                agent.vy,
                agent.radius,
                npos.x,
                npos.y,
                0.0,
                0.0,
                BODY_RADIUS,
                params,
            );
            fx += sfx;
            fy += sfy;
        }
    }

    // 3. Wall repulsion.
    for wall in &ctx.properties().walls {
        let (wfx, wfy) = wall_repulsion_2d(
            agent.x,
            agent.y,
            agent.vx,
            agent.vy,
            agent.radius,
            wall,
            params,
        );
        fx += wfx;
        fy += wfy;
    }

    // 4. Integrate.
    let (new_x, new_y, new_vx, new_vy) =
        integrate_euler_2d(agent.x, agent.y, agent.vx, agent.vy, fx, fy, dt, params);

    // Clamp to corridor bounds.
    agent.x = new_x.clamp(0.01, CORRIDOR_X - 0.01);
    agent.y = new_y.clamp(0.01, CORRIDOR_Y - 0.01);
    agent.vx = new_vx;
    agent.vy = new_vy;
}

// ---- Model step: update space positions, count arrivals, remove arrived ----

fn model_step(model: &mut CorridorModel) {
    // Update space positions.
    let agent_data: Vec<(AgentId, f64, f64, bool)> = model
        .agents()
        .map(|a| (a.id(), a.x, a.y, a.arrived))
        .collect();

    let mut newly_arrived = 0usize;
    for (id, x, y, arrived) in &agent_data {
        let _ = model
            .space_mut()
            .move_agent_pos(*id, ContinuousPos::new(*x, *y));
        if *arrived {
            newly_arrived += 1;
        }
    }

    // Remove arrived agents.
    let to_remove: Vec<AgentId> = model
        .agents()
        .filter(|a| a.arrived)
        .map(|a| a.id())
        .collect();
    for id in to_remove {
        model.remove_agent(id);
    }

    model.properties_mut().arrivals += newly_arrived;
}

// ---- Helpers ----

fn build_corridor_model(seed: u64) -> CorridorModel {
    let mut rng = StdRng::seed_from_u64(seed);
    let mut space = ContinuousSpace2D::new(CORRIDOR_X, CORRIDOR_Y, false, SEARCH_RADIUS).unwrap();
    let mut store = HashMapStore::new();

    let walls = vec![
        WallSegment::new(0.0, 0.0, CORRIDOR_X, 0.0), // bottom
        WallSegment::new(0.0, CORRIDOR_Y, CORRIDOR_X, CORRIDOR_Y), // top
    ];

    // Helbing 1995-style parameters tuned for a counter-flow test.
    // Social repulsion is moderate so agents can negotiate passage.
    let sfm_params = SocialForceParams {
        a_social: 2.1,
        b_social: 0.3,
        k_body: 1.2e5,
        kappa_friction: 2.4e5,
        a_wall: 10.0,
        b_wall: 0.2,
        k_wall: 1.2e5,
        kappa_wall: 2.4e5,
        max_speed: 2.5,
        tau: 0.5,
        mass: 80.0,
    };

    for i in 0..NUM_AGENTS {
        let id_counter = (i as u64) + 1;
        let going_right = i < NUM_AGENTS / 2;
        let (x, dest_x) = if going_right {
            (rng.gen_range(1.0..5.0), CORRIDOR_X - 1.0)
        } else {
            (rng.gen_range(CORRIDOR_X - 5.0..CORRIDOR_X - 1.0), 1.0)
        };
        let y = rng.gen_range(1.0..CORRIDOR_Y - 1.0);

        let ped = Pedestrian {
            id: id_counter,
            x,
            y,
            vx: 0.0,
            vy: 0.0,
            dest_x,
            dest_y: rng.gen_range(1.0..CORRIDOR_Y - 1.0),
            radius: BODY_RADIUS,
            desired_speed: DESIRED_SPEED + rng.gen_range(-0.1..0.1),
            arrived: false,
        };

        // Register with space via wrapper.
        let wrapper = PosWrapper {
            id: ped.id,
            pos: ContinuousPos::new(ped.x, ped.y),
        };
        <ContinuousSpace2D as SpaceInteraction<PosWrapper>>::add_agent(&mut space, &wrapper)
            .expect("initial placement should succeed");

        store.insert(ped);
    }

    let props = CorridorProps {
        walls,
        sfm_params,
        dt: DT,
        arrivals: 0,
    };

    CorridorModel::new(
        store,
        space,
        Fastest::new(),
        props,
        StdRng::seed_from_u64(seed),
        Some(Box::new(ped_step)),
        Some(model_step),
        true,
    )
}

// ===========================================================================
// Tests
// ===========================================================================

#[test]
fn counter_flow_corridor_agents_reach_destinations() {
    let mut model = build_corridor_model(42);

    let t0 = Instant::now();
    model.step_n(NUM_STEPS);
    let elapsed_ms = t0.elapsed().as_millis();

    let arrivals = model.properties().arrivals;
    let remaining = model.agents_len();

    eprintln!(
        "[counter-flow] {}/{} arrived, {} remaining, {} ms ({} steps)",
        arrivals, NUM_AGENTS, remaining, elapsed_ms, NUM_STEPS
    );

    // At least a third should arrive (counter-flow is inherently slow;
    // the key validation is that agents DO navigate past each other).
    assert!(
        arrivals >= NUM_AGENTS / 3,
        "at least a third of agents should arrive; got {}/{}",
        arrivals,
        NUM_AGENTS
    );
}

#[test]
fn agents_stay_inside_corridor_bounds() {
    let mut model = build_corridor_model(99);

    for _ in 0..500 {
        model.step();

        for agent in model.agents() {
            assert!(
                agent.x >= 0.0 && agent.x <= CORRIDOR_X,
                "agent {} x={} out of corridor bounds",
                agent.id,
                agent.x
            );
            assert!(
                agent.y >= 0.0 && agent.y <= CORRIDOR_Y,
                "agent {} y={} out of corridor bounds",
                agent.id,
                agent.y
            );
        }
    }
}

#[test]
fn physical_contact_prevents_persistent_overlap() {
    let mut model = build_corridor_model(123);

    // Run 1000 steps then check overlap.
    model.step_n(1000);

    // Collect positions of non-arrived agents.
    let positions: Vec<(AgentId, f64, f64)> = model
        .agents()
        .filter(|a| !a.arrived)
        .map(|a| (a.id(), a.x, a.y))
        .collect();

    let mut severe_overlaps = 0;
    for i in 0..positions.len() {
        for j in (i + 1)..positions.len() {
            let dx = positions[i].1 - positions[j].1;
            let dy = positions[i].2 - positions[j].2;
            let dist = (dx * dx + dy * dy).sqrt();
            let min_dist = BODY_RADIUS * 2.0;
            // Allow mild overlap from discrete integration, but not severe.
            if dist < min_dist * 0.3 {
                severe_overlaps += 1;
            }
        }
    }

    let active_agents = positions.len();
    // Allow up to 5% of agent pairs to have severe overlap.
    let max_allowed = (active_agents as f64 * 0.05).ceil() as usize;
    assert!(
        severe_overlaps <= max_allowed,
        "too many severe overlaps: {} (max {}). Physical contact forces should prevent this.",
        severe_overlaps,
        max_allowed
    );

    eprintln!(
        "[overlap check] {} active agents, {} severe overlaps (threshold: {})",
        active_agents, severe_overlaps, max_allowed
    );
}

#[test]
fn deterministic_replay() {
    let mut model1 = build_corridor_model(7);
    model1.step_n(200);
    let checksum1: f64 = model1.agents().map(|a| a.x + a.y + a.vx + a.vy).sum();
    let arrivals1 = model1.properties().arrivals;

    let mut model2 = build_corridor_model(7);
    model2.step_n(200);
    let checksum2: f64 = model2.agents().map(|a| a.x + a.y + a.vx + a.vy).sum();
    let arrivals2 = model2.properties().arrivals;

    assert_eq!(arrivals1, arrivals2, "arrival counts should match");
    assert!(
        (checksum1 - checksum2).abs() < 1e-6,
        "checksums should match: {} vs {}",
        checksum1,
        checksum2
    );
}