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
422
423
424
425
426
//! Social Force Model (Helbing & Molnar 1995) for pedestrian dynamics.
//!
//! This example demonstrates how to implement the classic Social Force Model
//! using rustsim's `ContinuousSpace2D` and spatial neighbor queries. Pedestrians:
//!
//! - Are driven toward a destination by a **desired force**
//! - Are repelled from other pedestrians by a **social repulsion force**
//! - Are repelled from walls by a **wall repulsion force**
//!
//! ## References
//!
//! - Helbing, D. & Molnar, P. (1995). "Social force model for pedestrian
//!   dynamics." Physical Review E, 51(5), 4282.
//! - Helbing, D., Farkas, I., & Vicsek, T. (2000). "Simulating dynamical
//!   features of escape panic." Nature, 407(6803), 487-490.
//!
//! Run with: `cargo run -p rustsim --example social_force --release`

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

// ---- Simulation parameters ----

const NUM_AGENTS: usize = 200;
const SPACE_X: f64 = 40.0; // meters
const SPACE_Y: f64 = 20.0; // meters
const DT: f64 = 0.1; // time step in seconds
const NUM_STEPS: usize = 2000; // 200 seconds total
const SEARCH_RADIUS: f64 = 5.0; // meters

// Social Force Model parameters (Helbing & Molnar 1995)
const TAU: f64 = 0.5; // relaxation time (seconds)
const DESIRED_SPEED: f64 = 1.3; // desired walking speed (m/s)
const A_SOC: f64 = 2.1; // social force strength (N)
const B_SOC: f64 = 0.3; // social force range (m)
const A_WALL: f64 = 10.0; // wall force strength (N)
const B_WALL: f64 = 0.2; // wall force range (m)
const AGENT_RADIUS: f64 = 0.25; // pedestrian body radius (m)
const MAX_SPEED: f64 = 2.5; // maximum speed (m/s)

// ---- Agent ----

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

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

// ---- Wall definition ----

/// A wall segment defined by two endpoints.
#[derive(Debug, Clone)]
struct Wall {
    x1: f64,
    y1: f64,
    x2: f64,
    y2: f64,
}

impl Wall {
    fn new(x1: f64, y1: f64, x2: f64, y2: f64) -> Self {
        Self { x1, y1, x2, y2 }
    }

    /// Closest point on this wall segment to point (px, py).
    fn closest_point(&self, px: f64, py: f64) -> (f64, f64) {
        let dx = self.x2 - self.x1;
        let dy = self.y2 - self.y1;
        let len_sq = dx * dx + dy * dy;
        if len_sq < 1e-12 {
            return (self.x1, self.y1);
        }
        let t = ((px - self.x1) * dx + (py - self.y1) * dy) / len_sq;
        let t = t.clamp(0.0, 1.0);
        (self.x1 + t * dx, self.y1 + t * dy)
    }
}

// ---- Model properties ----

#[derive(Debug, Clone)]
struct SfmProps {
    walls: Vec<Wall>,
    dt: f64,
    total_arrived: usize,
    density_grid: DensityGrid,
}

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

type SfmModel = StandardModel<
    ContinuousSpace2D,
    Pedestrian,
    HashMapStore<Pedestrian>,
    SfmProps,
    StdRng,
    Fastest,
>;

// ---- Agent step: Social Force Model ----

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

    let dt = ctx.properties().dt;

    // 1. DESIRED FORCE: f_desired = (v_desired * e_i - v_i) / tau
    let dx_dest = agent.dest_x - agent.x;
    let dy_dest = agent.dest_y - agent.y;
    let dist_dest = (dx_dest * dx_dest + dy_dest * dy_dest).sqrt();

    if dist_dest < 0.5 {
        agent.arrived = true;
        agent.vx = 0.0;
        agent.vy = 0.0;
        return;
    }

    let ex = dx_dest / dist_dest;
    let ey = dy_dest / dist_dest;

    let f_desired_x = (agent.desired_speed * ex - agent.vx) / TAU;
    let f_desired_y = (agent.desired_speed * ey - agent.vy) / TAU;

    // 2. SOCIAL REPULSION FORCE from nearby pedestrians
    // Use space's neighbor query for position-based repulsion.
    let nearby = ctx
        .space()
        .nearby_ids_euclidean(&ContinuousPos::new(agent.x, agent.y), SEARCH_RADIUS);

    let mut f_social_x = 0.0;
    let mut f_social_y = 0.0;

    for &nid in &nearby {
        if nid == agent.id {
            continue;
        }
        if let Some(npos) = ctx.space().agent_position(nid) {
            let dx = agent.x - npos.x;
            let dy = agent.y - npos.y;
            let dist = (dx * dx + dy * dy).sqrt();
            let r_sum = agent.radius + AGENT_RADIUS;
            if dist > 0.01 {
                let nx = dx / dist;
                let ny = dy / dist;
                // Exponential repulsion: A * exp(-(d - r_sum) / B)
                let force = A_SOC * (-(dist - r_sum) / B_SOC).exp();
                f_social_x += force * nx;
                f_social_y += force * ny;
            }
        }
    }

    // 3. WALL REPULSION FORCE
    let mut f_wall_x = 0.0;
    let mut f_wall_y = 0.0;

    for wall in &ctx.properties().walls {
        let (cx, cy) = wall.closest_point(agent.x, agent.y);
        let dx = agent.x - cx;
        let dy = agent.y - cy;
        let dist = (dx * dx + dy * dy).sqrt();

        if dist > 0.01 && dist < 3.0 {
            let nx = dx / dist;
            let ny = dy / dist;
            // Exponential wall repulsion
            let force = A_WALL * (-(dist - agent.radius) / B_WALL).exp();
            f_wall_x += force * nx;
            f_wall_y += force * ny;
        }
    }

    // 4. INTEGRATE: Euler integration
    let ax = f_desired_x + f_social_x + f_wall_x;
    let ay = f_desired_y + f_social_y + f_wall_y;

    agent.vx += ax * dt;
    agent.vy += ay * dt;

    // Clamp speed
    let speed = (agent.vx * agent.vx + agent.vy * agent.vy).sqrt();
    if speed > MAX_SPEED {
        let scale = MAX_SPEED / speed;
        agent.vx *= scale;
        agent.vy *= scale;
    }

    agent.x += agent.vx * dt;
    agent.y += agent.vy * dt;

    // Clamp to space bounds
    agent.x = agent.x.clamp(0.01, SPACE_X - 0.01);
    agent.y = agent.y.clamp(0.01, SPACE_Y - 0.01);
}

// ---- Model step: update density grid, remove arrived agents ----

fn model_step(model: &mut SfmModel) {
    // Update density grid
    model.properties_mut().density_grid.clear();
    let positions: Vec<(f64, f64)> = model
        .agents()
        .filter(|a| !a.arrived)
        .map(|a| (a.x, a.y))
        .collect();
    model.properties_mut().density_grid.add_positions(positions);

    // Remove arrived agents and count them
    let to_remove: Vec<AgentId> = model
        .agents()
        .filter(|a| a.arrived)
        .map(|a| a.id())
        .collect();
    let newly_arrived = to_remove.len();
    for id in to_remove {
        model.remove_agent(id);
    }
    model.properties_mut().total_arrived += newly_arrived;

    // Update space positions for remaining agents
    let agent_data: Vec<(AgentId, f64, f64)> = model.agents().map(|a| (a.id(), a.x, a.y)).collect();
    for (id, x, y) in agent_data {
        let _ = model
            .space_mut()
            .move_agent_pos(id, ContinuousPos::new(x, y));
    }
}

// ---- Main ----

fn main() {
    let mut rng = StdRng::seed_from_u64(42);

    // Create continuous space with spatial hashing
    let mut space = ContinuousSpace2D::new(SPACE_X, SPACE_Y, false, SEARCH_RADIUS).unwrap();

    // Define walls: corridor boundaries with a bottleneck in the middle
    let walls = vec![
        // Top boundary
        Wall::new(0.0, SPACE_Y, SPACE_X, SPACE_Y),
        // Bottom boundary
        Wall::new(0.0, 0.0, SPACE_X, 0.0),
        // Bottleneck: upper obstacle
        Wall::new(18.0, SPACE_Y, 18.0, SPACE_Y * 0.65),
        Wall::new(22.0, SPACE_Y, 22.0, SPACE_Y * 0.65),
        // Bottleneck: lower obstacle
        Wall::new(18.0, 0.0, 18.0, SPACE_Y * 0.35),
        Wall::new(22.0, 0.0, 22.0, SPACE_Y * 0.35),
    ];

    // Create agents - two counter-flowing streams
    let mut store = HashMapStore::new();
    for i in 1..=NUM_AGENTS as u64 {
        let going_right = i <= (NUM_AGENTS as u64) / 2;
        let (x, dest_x) = if going_right {
            (rng.gen_range(1.0..8.0), SPACE_X - 1.0)
        } else {
            (rng.gen_range(SPACE_X - 8.0..SPACE_X - 1.0), 1.0)
        };
        let y = rng.gen_range(SPACE_Y * 0.4..SPACE_Y * 0.6);

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

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

        store.insert(ped);
    }

    let props = SfmProps {
        walls,
        dt: DT,
        total_arrived: 0,
        density_grid: DensityGrid::new(SPACE_X, SPACE_Y, 2.0).unwrap(),
    };

    let mut model = SfmModel::new(
        store,
        space,
        Fastest::new(),
        props,
        StdRng::seed_from_u64(42),
        Some(Box::new(sfm_step)),
        Some(model_step),
        true, // agents step first, then model step updates space
    );

    // LoS criteria for pedestrian walkway analysis
    let walkway_los = PedestrianWalkway;

    // ---- Run simulation ----

    println!();
    println!("=== Social Force Model (Helbing & Molnar 1995) ===");
    println!(
        "Pedestrians: {} ({} per direction)",
        NUM_AGENTS,
        NUM_AGENTS / 2
    );
    println!(
        "Space:       {:.0} x {:.0} m with bottleneck at x=18-22",
        SPACE_X, SPACE_Y
    );
    println!("Time step:   {DT} s");
    println!(
        "Duration:    {} s ({NUM_STEPS} steps)",
        NUM_STEPS as f64 * DT
    );
    println!("Model:       desired force + social repulsion + wall repulsion");
    println!(
        "LoS:         {} ({})",
        walkway_los.name(),
        walkway_los.unit()
    );
    println!();

    println!(
        "{:>6}  {:>6}  {:>10}  {:>10}  {:>6}  {:>6}",
        "Time", "Active", "Max rho", "Mean rho", "LoS", "Done"
    );
    println!("{}", "-".repeat(58));

    let t0 = std::time::Instant::now();

    for step in 0..NUM_STEPS {
        model.step();

        if step % 50 == 0 || step == NUM_STEPS - 1 {
            let time = (step + 1) as f64 * DT;
            let active = model.agents_len();
            let stats = model.properties().density_grid.statistics(&walkway_los);
            let arrived = model.properties().total_arrived;

            println!(
                "{:5.1}s  {:>6}  {:>7.2}/m2  {:>7.2}/m2  {:>5}  {:>6}",
                time, active, stats.max_density, stats.mean_density, stats.worst_los, arrived,
            );
        }
    }

    let elapsed = t0.elapsed();
    let total_arrived = model.properties().total_arrived;

    println!();
    println!("=== Results ===");
    println!("Pedestrians arrived: {total_arrived}/{NUM_AGENTS}");
    println!("Still walking:       {}", model.agents_len());

    let stats = model.properties().density_grid.statistics(&walkway_los);
    println!("Final max density:   {:.2} pax/m2", stats.max_density);
    println!("Final worst LoS:     {}", stats.worst_los);
    println!(
        "LoS distribution:    A={} B={} C={} D={} E={} F={}",
        stats.los_distribution[0],
        stats.los_distribution[1],
        stats.los_distribution[2],
        stats.los_distribution[3],
        stats.los_distribution[4],
        stats.los_distribution[5],
    );
    println!("Wall time:           {:.1} ms", elapsed.as_millis());
    println!(
        "Steps/s:             {:.0}",
        NUM_STEPS as f64 / elapsed.as_secs_f64()
    );
}

/// Helper wrapper for initial space registration.
/// (We need a PositionedAgent to register with ContinuousSpace2D.)
#[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;
    }
}