rustsim-core 0.0.1

Core ABM engine: agents, models, stores, schedulers, stepping, data collection
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
#![allow(clippy::type_complexity)]

// Tests that verify behavioral parity between Rustsim and Julia Agents.jl.
// Each test mirrors a specific Julia behavior documented in the Agents.jl source.

use rand::rngs::StdRng;
use rand::SeedableRng;
use rustsim_core::{
    collect::collect_step,
    interaction::{self, PositionedAgent},
    prelude::*,
};
mod support;
use support::{Grid2D, GridPos2, NothingSpace};

// --- Agent definitions ---

#[derive(Debug, Clone)]
struct Counter {
    id: AgentId,
    count: u64,
}
impl Agent for Counter {
    fn id(&self) -> AgentId {
        self.id
    }
}

#[derive(Debug, Clone)]
struct GridBot {
    id: AgentId,
    pos: GridPos2,
    #[allow(dead_code)]
    energy: i32,
}
impl Agent for GridBot {
    fn id(&self) -> AgentId {
        self.id
    }
}
impl PositionedAgent for GridBot {
    type Position = GridPos2;
    fn position(&self) -> &GridPos2 {
        &self.pos
    }
    fn set_position(&mut self, p: GridPos2) {
        self.pos = p;
    }
}

// --- Model type aliases ---

type CounterModel =
    StandardModel<NothingSpace, Counter, HashMapStore<Counter>, (), StdRng, Fastest>;
type GridModel = StandardModel<Grid2D, GridBot, HashMapStore<GridBot>, (), StdRng, Fastest>;

// ====================================================================
// Parity: step! time semantics
// Julia: time starts at 0, incremented by 1 after each step
// ====================================================================

fn counting_step(
    agent: &mut Counter,
    _ctx: &mut StepContext<'_, NothingSpace, Counter, (), StdRng, Fastest>,
) {
    agent.count += 1;
}

#[test]
fn time_starts_at_zero_and_increments_each_step() {
    let mut store = HashMapStore::new();
    store.insert(Counter { id: 1, count: 0 });

    let mut model = CounterModel::new(
        store,
        NothingSpace,
        Fastest::new(),
        (),
        StdRng::seed_from_u64(0),
        Some(Box::new(counting_step)),
        None,
        true,
    );

    assert_eq!(
        model.time(),
        rustsim_core::types::Time::Discrete(0),
        "Julia: abmtime(model) == 0 initially"
    );
    model.step();
    assert_eq!(
        model.time(),
        rustsim_core::types::Time::Discrete(1),
        "Julia: step! increments time by 1"
    );
    model.step_n(4);
    assert_eq!(
        model.time(),
        rustsim_core::types::Time::Discrete(5),
        "Julia: after 5 steps, time == 5"
    );
}

// ====================================================================
// Parity: agents_first ordering
// Julia: agents_first=true -> agent_step! runs before model_step!
//        agents_first=false -> model_step! runs before agent_step!
// ====================================================================

// We test ordering by encoding the call sequence into the agent count field:
// agent_step sets bit 0, model_step sets bit 1. The final value tells us the order.

#[test]
fn agents_first_true_runs_agents_before_model() {
    // Track ordering via a shared vec inside model properties
    type OrderModel = StandardModel<
        NothingSpace,
        Counter,
        HashMapStore<Counter>,
        Vec<&'static str>,
        StdRng,
        Fastest,
    >;

    fn agent_step_af(
        agent: &mut Counter,
        ctx: &mut StepContext<'_, NothingSpace, Counter, Vec<&'static str>, StdRng, Fastest>,
    ) {
        ctx.properties_mut().push("agent");
        agent.count += 1;
    }

    fn model_step_af(model: &mut OrderModel) {
        model.properties_mut().push("model");
    }

    let mut store = HashMapStore::new();
    store.insert(Counter { id: 1, count: 0 });

    let mut model = OrderModel::new(
        store,
        NothingSpace,
        Fastest::new(),
        Vec::new(),
        StdRng::seed_from_u64(0),
        Some(Box::new(agent_step_af)),
        Some(model_step_af),
        true,
    );

    model.step();

    assert_eq!(
        model.properties().as_slice(),
        &["agent", "model"],
        "Julia: agents_first=true -> agent step then model step"
    );
}

#[test]
fn agents_first_false_runs_model_before_agents() {
    type OrderModel = StandardModel<
        NothingSpace,
        Counter,
        HashMapStore<Counter>,
        Vec<&'static str>,
        StdRng,
        Fastest,
    >;

    fn agent_step_mf(
        agent: &mut Counter,
        ctx: &mut StepContext<'_, NothingSpace, Counter, Vec<&'static str>, StdRng, Fastest>,
    ) {
        ctx.properties_mut().push("agent");
        agent.count += 1;
    }

    fn model_step_mf(model: &mut OrderModel) {
        model.properties_mut().push("model");
    }

    let mut store = HashMapStore::new();
    store.insert(Counter { id: 1, count: 0 });

    let mut model = OrderModel::new(
        store,
        NothingSpace,
        Fastest::new(),
        Vec::new(),
        StdRng::seed_from_u64(0),
        Some(Box::new(agent_step_mf)),
        Some(model_step_mf),
        false,
    );

    model.step();

    assert_eq!(
        model.properties().as_slice(),
        &["model", "agent"],
        "Julia: agents_first=false -> model step then agent step"
    );
}

// ====================================================================
// Parity: removed agents are skipped during stepping
// Julia: agent_not_removed(id, model) check in step_ahead!
// ====================================================================

type RemovableModel = StandardModel<NothingSpace, Counter, HashMapStore<Counter>, (), StdRng, ById>;

fn remove_self_if_even(
    agent: &mut Counter,
    ctx: &mut StepContext<'_, NothingSpace, Counter, (), StdRng, ById>,
) {
    if agent.id.is_multiple_of(2) {
        ctx.defer_remove_agent(agent.id());
    } else {
        agent.count += 1;
    }
}

#[test]
fn removed_agents_skipped_during_step() {
    let mut store = HashMapStore::new();
    for i in 1..=4 {
        store.insert(Counter { id: i, count: 0 });
    }

    let mut model = RemovableModel::new(
        store,
        NothingSpace,
        ById::new(),
        (),
        StdRng::seed_from_u64(0),
        Some(Box::new(remove_self_if_even)),
        None,
        true,
    );

    model.step();

    assert!(model.agent(2).is_none(), "agent 2 removed itself");
    assert!(model.agent(4).is_none(), "agent 4 removed itself");
    assert_eq!(model.agent(1).unwrap().count, 1);
    assert_eq!(model.agent(3).unwrap().count, 1);
}

// ====================================================================
// Parity: nearby_ids(agent, model, r) excludes the agent's own ID
// Julia: nearby_ids(agent, model, r) filters out agent.id
// ====================================================================

#[test]
fn nearby_ids_except_excludes_self() {
    let store = HashMapStore::new();
    let grid = Grid2D::new(5, 5, false);

    let mut model = GridModel::new(
        store,
        grid,
        Fastest::new(),
        (),
        StdRng::seed_from_u64(0),
        None,
        None,
        true,
    );

    let a1 = GridBot {
        id: model.next_id(),
        pos: (2, 2),
        energy: 10,
    };
    let a2 = GridBot {
        id: model.next_id(),
        pos: (2, 3),
        energy: 5,
    };
    interaction::add_agent(&mut model, a1).unwrap();
    interaction::add_agent(&mut model, a2).unwrap();

    // Position-based: includes self (like Julia nearby_ids(pos, model, r))
    let all = interaction::nearby_ids(&model, &(2, 2), 1);
    assert!(
        all.contains(&1),
        "position-based includes agent at that position"
    );
    assert!(all.contains(&2));

    // Agent-based: excludes self (like Julia nearby_ids(agent, model, r))
    let without_self = interaction::nearby_ids_except(&model, &(2, 2), 1, 1);
    assert!(
        !without_self.contains(&1),
        "Julia: nearby_ids(agent, model, r) excludes agent.id"
    );
    assert!(without_self.contains(&2));
}

// ====================================================================
// Parity: model-only stepping (dummystep agent)
// Julia: step_ahead! with dummystep agent skips scheduler entirely
// ====================================================================

fn model_only_step(model: &mut CounterModel) {
    let ids: Vec<AgentId> = model.agents().map(|a| a.id()).collect();
    for id in ids {
        if let Some(mut a) = model.agent_mut(id) {
            a.count += 10;
        }
    }
}

#[test]
fn model_only_step_works_without_agent_step() {
    let mut store = HashMapStore::new();
    store.insert(Counter { id: 1, count: 0 });
    store.insert(Counter { id: 2, count: 0 });

    let mut model = CounterModel::new(
        store,
        NothingSpace,
        Fastest::new(),
        (),
        StdRng::seed_from_u64(0),
        None,
        Some(model_only_step),
        true,
    );

    model.step_n(3);
    assert_eq!(model.time(), rustsim_core::types::Time::Discrete(3));
    assert_eq!(model.agent(1).unwrap().count, 30);
    assert_eq!(model.agent(2).unwrap().count, 30);
}

// ====================================================================
// Parity: deterministic RNG
// Julia: seeded RNG produces identical results across runs
// ====================================================================

type RandomCounterModel =
    StandardModel<NothingSpace, Counter, HashMapStore<Counter>, (), StdRng, Randomly>;

fn counting_step_random(
    agent: &mut Counter,
    _ctx: &mut StepContext<'_, NothingSpace, Counter, (), StdRng, Randomly>,
) {
    agent.count += 1;
}

#[test]
fn deterministic_rng_same_seed_same_result() {
    fn run_sim(seed: u64) -> Vec<u64> {
        let mut store = HashMapStore::new();
        for i in 1..=5 {
            store.insert(Counter { id: i, count: 0 });
        }

        let mut model = RandomCounterModel::new(
            store,
            NothingSpace,
            Randomly::new(),
            (),
            StdRng::seed_from_u64(seed),
            Some(Box::new(counting_step_random)),
            None,
            true,
        );

        model.step_n(10);

        let mut results: Vec<(AgentId, u64)> = model.agents().map(|a| (a.id, a.count)).collect();
        results.sort_by_key(|r| r.0);
        results.iter().map(|r| r.1).collect()
    }

    let run1 = run_sim(42);
    let run2 = run_sim(42);

    assert_eq!(run1, run2, "Julia: same seed produces identical results");
}

// ====================================================================
// Parity: add_agent! with auto-generated ID
// Julia: nextid(model) auto-increments maxid
// ====================================================================

#[test]
fn next_id_auto_increments() {
    let store: HashMapStore<Counter> = HashMapStore::new();
    let mut model = CounterModel::new(
        store,
        NothingSpace,
        Fastest::new(),
        (),
        StdRng::seed_from_u64(0),
        None,
        None,
        true,
    );

    let id1 = model.next_id();
    let id2 = model.next_id();
    let id3 = model.next_id();

    assert_eq!(id1, 1, "Julia: nextid starts at 1");
    assert_eq!(id2, 2);
    assert_eq!(id3, 3);
}

// ====================================================================
// Parity: collect data at each step
// Julia: run!(model, n; adata=[...], mdata=[...])
// ====================================================================

#[test]
fn data_collection_mirrors_julia_run() {
    let mut store = HashMapStore::new();
    for i in 1..=3 {
        store.insert(Counter { id: i, count: 0 });
    }

    let mut model = CounterModel::new(
        store,
        NothingSpace,
        Fastest::new(),
        (),
        StdRng::seed_from_u64(0),
        Some(Box::new(counting_step)),
        None,
        true,
    );

    let mut agent_data: Vec<(rustsim_core::types::Time, u64, u64)> = Vec::new();
    let mut model_data: Vec<(rustsim_core::types::Time, usize)> = Vec::new();

    // Collect initial state (Julia: init=true)
    let ids: Vec<AgentId> = model.agents().map(|a| a.id()).collect();
    collect_step(
        &model,
        &ids,
        Some(&|a: &Counter, m: &CounterModel| (m.time(), a.id, a.count)),
        Some(&|m: &CounterModel| (m.time(), m.agents().count())),
        &mut agent_data,
        &mut model_data,
    );

    // Step and collect (Julia: when=1, collecting every step)
    for _ in 0..3 {
        model.step();
        let ids: Vec<AgentId> = model.agents().map(|a| a.id()).collect();
        collect_step(
            &model,
            &ids,
            Some(&|a: &Counter, m: &CounterModel| (m.time(), a.id, a.count)),
            Some(&|m: &CounterModel| (m.time(), m.agents().count())),
            &mut agent_data,
            &mut model_data,
        );
    }

    // 4 collection points (init + 3 steps) times 3 agents = 12 agent rows
    assert_eq!(agent_data.len(), 12);
    // 4 model rows
    assert_eq!(model_data.len(), 4);

    // At time 0, all counts are 0
    let t0: Vec<_> = agent_data
        .iter()
        .filter(|r| r.0 == rustsim_core::types::Time::Discrete(0))
        .collect();
    assert!(t0.iter().all(|r| r.2 == 0));

    // At time 3, all counts are 3
    let t3: Vec<_> = agent_data
        .iter()
        .filter(|r| r.0 == rustsim_core::types::Time::Discrete(3))
        .collect();
    assert!(t3.iter().all(|r| r.2 == 3));
}

// ====================================================================
// Parity: ByProperty scheduler sorts greatest first
// Julia: ByProperty(property) -- greater property ordered first
// ====================================================================

#[test]
fn by_property_scheduler_orders_greatest_first() {
    let mut store = HashMapStore::new();
    store.insert(Counter { id: 1, count: 10 });
    store.insert(Counter { id: 2, count: 30 });
    store.insert(Counter { id: 3, count: 20 });

    let model = StandardModel::<
        NothingSpace,
        Counter,
        HashMapStore<Counter>,
        (),
        StdRng,
        ByProperty<_>,
    >::new(
        store,
        NothingSpace,
        ByProperty::new(|a: &Counter| a.count),
        (),
        StdRng::seed_from_u64(0),
        None,
        None,
        true,
    );

    let mut sched = ByProperty::new(|a: &Counter| a.count);
    let mut buf = Vec::new();
    sched.schedule_into(&model, &mut buf);

    assert_eq!(
        buf,
        vec![2, 3, 1],
        "Julia: ByProperty orders agents with greatest property first"
    );
}

// ====================================================================
// Parity: ById scheduler sorts by integer ID
// Julia: Schedulers.ByID() sorts agents by their integer ID
// ====================================================================

#[test]
fn by_id_scheduler_sorts_ascending() {
    let mut store = HashMapStore::new();
    store.insert(Counter { id: 5, count: 0 });
    store.insert(Counter { id: 1, count: 0 });
    store.insert(Counter { id: 3, count: 0 });

    let model =
        StandardModel::<NothingSpace, Counter, HashMapStore<Counter>, (), StdRng, ById>::new(
            store,
            NothingSpace,
            ById::new(),
            (),
            StdRng::seed_from_u64(0),
            None,
            None,
            true,
        );

    let mut sched = ById::new();
    let mut buf = Vec::new();
    sched.schedule_into(&model, &mut buf);

    assert_eq!(
        buf,
        vec![1, 3, 5],
        "Julia: ByID() returns IDs sorted ascending"
    );
}

// ====================================================================
// Parity: EventQueueABM processes events in time order
// Julia: events processed by time, ties broken deterministically
// ====================================================================

use rustsim_core::event_queue::{EventContext, EventQueueModel};

type EQModel = EventQueueModel<NothingSpace, Counter, HashMapStore<Counter>, (), StdRng>;

fn eq_action(agent: &mut Counter, _ctx: &mut EventContext<'_, NothingSpace, Counter, (), StdRng>) {
    agent.count += 1;
}

#[test]
fn event_queue_processes_chronologically() {
    let mut store = HashMapStore::new();
    store.insert(Counter { id: 1, count: 0 });

    let actions: Vec<fn(&mut Counter, &mut EventContext<'_, NothingSpace, Counter, (), StdRng>)> =
        vec![eq_action];
    let mut model = EQModel::new(store, NothingSpace, (), StdRng::seed_from_u64(0), actions);

    model.add_event(1, 0, 3.0);
    model.add_event(1, 0, 1.0);
    model.add_event(1, 0, 2.0);

    model.step_event();
    assert!(
        (model.time_f64() - 1.0).abs() < 1e-10,
        "Julia: earliest event processed first"
    );

    model.step_event();
    assert!((model.time_f64() - 2.0).abs() < 1e-10);

    model.step_event();
    assert!((model.time_f64() - 3.0).abs() < 1e-10);

    assert_eq!(model.agent(1).unwrap().count, 3);
}

#[test]
fn event_queue_step_until_respects_boundary() {
    let mut store = HashMapStore::new();
    store.insert(Counter { id: 1, count: 0 });

    let actions: Vec<fn(&mut Counter, &mut EventContext<'_, NothingSpace, Counter, (), StdRng>)> =
        vec![eq_action];
    let mut model = EQModel::new(store, NothingSpace, (), StdRng::seed_from_u64(0), actions);

    model.add_event(1, 0, 1.0);
    model.add_event(1, 0, 2.0);
    model.add_event(1, 0, 5.0);

    model.step_until(3.0);

    assert_eq!(
        model.agent(1).unwrap().count,
        2,
        "Julia: only events with time <= stop_time fire"
    );
    assert!(
        (model.time_f64() - 3.0).abs() < 1e-10,
        "Julia: model time advances to stop_time"
    );
    assert_eq!(model.queue_len(), 1, "one event remains at t=5");
}

// ====================================================================
// Parity: EventQueueABM skips removed agents
// Julia: !agent_not_removed(id, model) && return in process_event!
// ====================================================================

#[test]
fn event_queue_skips_removed_agents() {
    let mut store = HashMapStore::new();
    store.insert(Counter { id: 1, count: 0 });
    store.insert(Counter { id: 2, count: 0 });

    let actions: Vec<fn(&mut Counter, &mut EventContext<'_, NothingSpace, Counter, (), StdRng>)> =
        vec![eq_action];
    let mut model = EQModel::new(store, NothingSpace, (), StdRng::seed_from_u64(0), actions);

    model.add_event(1, 0, 1.0);
    model.add_event(2, 0, 2.0);

    model.remove_agent(1);

    model.step_event();
    assert!((model.time_f64() - 1.0).abs() < 1e-10);

    model.step_event();
    assert_eq!(model.agent(2).unwrap().count, 1);
}