krabmaga 0.6.2

A modern developing art for reliable and efficient Agent-based Model (ABM) simulation with the Rust language.
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
#[cfg(test)]
#[cfg(all(
    feature = "gis",
    not(any(
        feature = "visualization",
        feature = "visualization_wasm",
        feature = "parallel"
    ))
))]
use {
    krabmaga::bevy_a5::prelude::GeoCell,
    krabmaga::engine::fields::field::Field,
    krabmaga::engine::fields::grid_option::GridOption,
    krabmaga::engine::fields::sparse_a5_grid_3d::{A5Cell3D, SparseA5Grid3D},
    std::cell::Cell,
};

#[cfg(all(
    feature = "gis",
    not(any(
        feature = "visualization",
        feature = "visualization_wasm",
        feature = "parallel"
    ))
))]
fn boundaries() -> Vec<f64> {
    vec![0.0, 1_000.0, 10_000.0, 50_000.0]
}

#[cfg(all(
    feature = "gis",
    not(any(
        feature = "visualization",
        feature = "visualization_wasm",
        feature = "parallel"
    ))
))]
fn london_3d_grid() -> (SparseA5Grid3D<u32>, Vec<A5Cell3D>) {
    let london = GeoCell::from_lon_lat(-0.1, 51.5, 1).expect("london resolves");
    let grid: SparseA5Grid3D<u32> = SparseA5Grid3D::new_with_root(london, 4, Some(boundaries()));
    let locs = grid.all_locations().expect("london has res-4 descendants");
    assert!(!locs.is_empty());
    (grid, locs)
}

#[cfg(all(
    feature = "gis",
    not(any(
        feature = "visualization",
        feature = "visualization_wasm",
        feature = "parallel"
    ))
))]
#[test]
fn sparse_a5_grid_3d_layers_and_altitudes() {
    let grid: SparseA5Grid3D<u32> = SparseA5Grid3D::new(2, Some(boundaries()));

    assert_eq!(grid.num_layers(), 3);
    assert_eq!(grid.floor(), Some(0.0));
    assert_eq!(grid.ceiling(), Some(50_000.0));

    // In-range altitudes resolve to consistent layers.
    assert_eq!(grid.layer_for_altitude(0.0), Some(0));
    assert_eq!(grid.layer_for_altitude(500.0), Some(0));
    assert_eq!(grid.layer_for_altitude(1_000.0), Some(1));
    assert_eq!(grid.layer_for_altitude(9_999.99), Some(1));
    assert_eq!(grid.layer_for_altitude(10_000.0), Some(2));
    // Ceiling is inclusive in the top layer.
    assert_eq!(grid.layer_for_altitude(50_000.0), Some(2));

    // Out-of-domain altitudes return None.
    assert_eq!(grid.layer_for_altitude(-1.0), None);
    assert_eq!(grid.layer_for_altitude(50_001.0), None);
}

#[cfg(all(
    feature = "gis",
    not(any(
        feature = "visualization",
        feature = "visualization_wasm",
        feature = "parallel"
    ))
))]
#[test]
fn sparse_a5_grid_3d_unbounded_altitude_is_single_layer() {
    let grid: SparseA5Grid3D<u32> = SparseA5Grid3D::new(2, None);
    assert_eq!(grid.num_layers(), 1);
    assert_eq!(grid.floor(), None);
    assert_eq!(grid.ceiling(), None);
    // Any altitude maps to the single layer.
    assert_eq!(grid.layer_for_altitude(-1e9), Some(0));
    assert_eq!(grid.layer_for_altitude(0.0), Some(0));
    assert_eq!(grid.layer_for_altitude(1e9), Some(0));

    // A single-entry vec normalises to None (single layer).
    let single: SparseA5Grid3D<u32> = SparseA5Grid3D::new(2, Some(vec![100.0]));
    assert_eq!(single.num_layers(), 1);
    assert_eq!(single.floor(), None);
}

#[cfg(all(
    feature = "gis",
    not(any(
        feature = "visualization",
        feature = "visualization_wasm",
        feature = "parallel"
    ))
))]
#[test]
#[should_panic(expected = "layer boundaries must be strictly ascending")]
fn sparse_a5_grid_3d_rejects_non_ascending_boundaries() {
    let _grid: SparseA5Grid3D<u32> = SparseA5Grid3D::new(2, Some(vec![0.0, 100.0, 50.0]));
}

#[cfg(all(
    feature = "gis",
    not(any(
        feature = "visualization",
        feature = "visualization_wasm",
        feature = "parallel"
    ))
))]
#[test]
fn sparse_a5_grid_3d_cell_3d_at_combines_cell_and_layer() {
    let grid: SparseA5Grid3D<u32> = SparseA5Grid3D::new(3, Some(boundaries()));
    let loc = grid
        .cell_3d_at(-0.1, 51.5, 5_000.0)
        .expect("london at 5km resolves");
    assert_eq!(loc.cell.resolution(), 3);
    assert_eq!(loc.layer, 1);
    assert!(grid.contains(&loc));

    // Out-of-domain altitude → None.
    assert!(grid.cell_3d_at(-0.1, 51.5, 1_000_000.0).is_none());
}

#[cfg(all(
    feature = "gis",
    not(any(
        feature = "visualization",
        feature = "visualization_wasm",
        feature = "parallel"
    ))
))]
#[test]
fn sparse_a5_grid_3d_top_layer_lifecycle() {
    // The ceiling altitude is inclusive in the top layer — agents that hit
    // exactly the ceiling must round-trip through the grid like any other.
    let grid: SparseA5Grid3D<u32> = SparseA5Grid3D::new(3, Some(boundaries()));
    let ceiling = grid.ceiling().expect("bounded grid has a ceiling");
    let top = grid
        .cell_3d_at(-0.1, 51.5, ceiling)
        .expect("ceiling altitude resolves");
    assert_eq!(top.layer, grid.num_layers() - 1);
    assert!(grid.contains(&top));

    grid.set_object_location(99, &top);
    let mut grid = grid;
    grid.update();

    assert_eq!(grid.get_location(&99).as_ref(), Some(&top));
    assert_eq!(
        grid.num_objects_at_location(&top),
        1,
        "object inserted at the ceiling layer must be retrievable from it"
    );
    let bag = grid.get_objects(&top).expect("top-layer bag populated");
    assert!(bag.contains(&99));
}

#[cfg(all(
    feature = "gis",
    not(any(
        feature = "visualization",
        feature = "visualization_wasm",
        feature = "parallel"
    ))
))]
#[test]
fn sparse_a5_grid_3d_bags_lifecycle() {
    let (grid, locs) = london_3d_grid();
    let total = locs.len();

    assert_eq!(grid.get_empty_bags().len(), total);
    let pick = grid.get_random_empty_bag().expect("non-empty");
    assert!(grid.contains(&pick));

    grid.set_object_location(7, &pick);
    grid.set_object_location(8, &pick);

    // Pre-update: write buffer holds them, read is empty.
    assert!(grid.get_location_unbuffered(&7).is_some());
    assert!(grid.get_unbuffered(&7).is_some());
    assert!(grid.get_location(&7).is_none());
    assert!(grid.get(&7).is_none());
    assert_eq!(grid.num_objects(), 0);

    let mut grid = grid;
    grid.update();

    // After update(): read buffer has both objects; num_objects counts the
    // read buffer.
    assert_eq!(grid.num_objects(), 2);
    assert_eq!(grid.num_objects_at_location(&pick), 2);
    assert_eq!(grid.get(&7), Some(7));
    assert_eq!(grid.get_location(&7).as_ref(), Some(&pick));
    let bag = grid.get_objects(&pick).expect("bag populated");
    assert!(bag.contains(&7) && bag.contains(&8));
    assert_eq!(grid.get_empty_bags().len(), total - 1);

    // remove_object_location targets the *write* buffer (mirrors the
    // single-threaded `SparseGrid2D` semantics). Stage again, then remove,
    // and verify the write-side view.
    grid.set_object_location(7, &pick);
    grid.set_object_location(8, &pick);
    grid.remove_object_location(7, &pick);
    let write_bag = grid
        .get_objects_unbuffered(&pick)
        .expect("write buffer still has obj 8");
    assert!(!write_bag.contains(&7));
    assert!(write_bag.contains(&8));

    // remove_object walks every cell in the write buffer and drops empties.
    grid.remove_object(&8);
    assert!(
        grid.get_objects_unbuffered(&pick).is_none(),
        "write bag should be removed after remove_object empties it"
    );

    // After lazy_update, the now-empty write buffer is swapped into read.
    grid.lazy_update();
    assert!(grid.get_objects(&pick).is_none());
    assert_eq!(grid.num_objects(), 0);
}

#[cfg(all(
    feature = "gis",
    not(any(
        feature = "visualization",
        feature = "visualization_wasm",
        feature = "parallel"
    ))
))]
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
struct Tagged {
    id: u32,
    flag: bool,
}

#[cfg(all(
    feature = "gis",
    not(any(
        feature = "visualization",
        feature = "visualization_wasm",
        feature = "parallel"
    ))
))]
#[test]
fn sparse_a5_grid_3d_apply_and_iter() {
    let london = GeoCell::from_lon_lat(-0.1, 51.5, 1).expect("london resolves");
    let grid: SparseA5Grid3D<Tagged> = SparseA5Grid3D::new_with_root(london, 4, Some(boundaries()));
    let locs = grid.all_locations().expect("res-4 locs");
    let n = locs.len().min(6);

    for (i, loc) in locs.iter().take(n).enumerate() {
        grid.set_object_location(
            Tagged {
                id: i as u32,
                flag: false,
            },
            loc,
        );
    }

    // iter↔get round-trip on the write buffer.
    let unbuf_count = Cell::new(0usize);
    grid.iter_objects_unbuffered(|loc, t| {
        let bag = grid
            .get_objects_unbuffered(loc)
            .expect("iter handed us a loc that get can't find");
        assert!(bag.iter().any(|x| x.id == t.id));
        unbuf_count.set(unbuf_count.get() + 1);
    });
    assert_eq!(unbuf_count.get(), n);

    grid.apply_to_all_values(
        |_loc, t| {
            Some(Tagged {
                id: t.id,
                flag: true,
            })
        },
        GridOption::WRITE,
    );
    grid.iter_objects_unbuffered(|_loc, t| assert!(t.flag));

    let mut grid = grid;
    grid.lazy_update();

    // iter↔get round-trip on the read buffer.
    let read_count = Cell::new(0usize);
    grid.iter_objects(|loc, t| {
        assert!(t.flag);
        let bag = grid
            .get_objects(loc)
            .expect("iter handed us a loc that get can't find");
        assert!(bag.iter().any(|x| x.id == t.id));
        read_count.set(read_count.get() + 1);
    });
    assert_eq!(read_count.get(), n);

    grid.apply_to_all_values(
        |_loc, t| {
            Some(Tagged {
                id: t.id,
                flag: false,
            })
        },
        GridOption::READ,
    );
    grid.iter_objects(|_loc, t| assert!(!t.flag));

    // Re-stage and exercise READWRITE.
    for (i, loc) in locs.iter().take(n).enumerate() {
        grid.set_object_location(
            Tagged {
                id: i as u32,
                flag: false,
            },
            loc,
        );
    }
    grid.apply_to_all_values(
        |_loc, t| {
            Some(Tagged {
                id: t.id,
                flag: true,
            })
        },
        GridOption::READWRITE,
    );
    grid.lazy_update();
    grid.iter_objects(|_loc, t| assert!(t.flag));
}

#[cfg(all(
    feature = "gis",
    not(any(
        feature = "visualization",
        feature = "visualization_wasm",
        feature = "parallel"
    ))
))]
#[test]
fn sparse_a5_grid_3d_neighbors_stay_in_layer() {
    let (grid, locs) = london_3d_grid();
    // Pick a centre with layer > 0 so a bug where lift_to_layer hard-coded
    // 0 would fail this test.
    let centre = *locs
        .iter()
        .find(|l| l.layer > 0)
        .expect("3D grid has multiple layers");
    assert!(centre.layer > 0);

    let neigh = grid.cell_neighbors(&centre).expect("centre has neighbours");
    assert!(!neigh.is_empty());
    for n in &neigh {
        assert_eq!(
            n.layer, centre.layer,
            "neighbour lifted to wrong layer (expected {}, got {})",
            centre.layer, n.layer
        );
    }

    // Vertex neighbours and disk cells must also stay in the centre's layer.
    if let Some(vneigh) = grid.cell_vertex_neighbors(&centre) {
        for v in &vneigh {
            assert_eq!(v.layer, centre.layer);
        }
    }
    let disk_cells = grid.cell_grid_disk(&centre, 1).expect("disk has cells");
    for d in &disk_cells {
        assert_eq!(d.layer, centre.layer);
    }

    for (i, loc) in neigh.iter().enumerate() {
        grid.set_object_location(100 + i as u32, loc);
    }
    grid.set_object_location(0, &centre);

    let mut grid = grid;
    grid.update();

    let n_objs = grid.get_neighbors(&centre);
    assert_eq!(n_objs.len(), neigh.len());

    let disk = grid.get_objects_within_disk(&centre, 1);
    assert!(disk.contains(&0));
    assert_eq!(disk.len(), neigh.len() + 1);

    let none = grid.get_neighbors_within_distance(&centre, 0.0);
    assert!(none.is_empty());

    let near = grid.get_neighbors_within_distance(&centre, 1_000_000.0);
    assert!(near.contains(&0));
}

#[cfg(all(
    feature = "gis",
    not(any(
        feature = "visualization",
        feature = "visualization_wasm",
        feature = "parallel"
    ))
))]
#[test]
fn sparse_a5_grid_3d_contains_layer_and_subtree() {
    let london = GeoCell::from_lon_lat(-0.1, 51.5, 1).expect("london resolves");
    let grid: SparseA5Grid3D<u32> = SparseA5Grid3D::new_with_root(london, 4, Some(boundaries()));

    let cell = GeoCell::from_lon_lat(-0.1, 51.5, 4).expect("res 4 cell");
    assert!(grid.contains(&A5Cell3D::new(cell, 0)));
    assert!(grid.contains(&A5Cell3D::new(cell, 2)));
    // Out-of-range layer.
    assert!(!grid.contains(&A5Cell3D::new(cell, 3)));
    // Wrong cell resolution.
    let wrong_res = GeoCell::from_lon_lat(-0.1, 51.5, 5).expect("res 5 cell");
    assert!(!grid.contains(&A5Cell3D::new(wrong_res, 0)));
    // Outside the london subtree.
    let antipode = GeoCell::from_lon_lat(180.0, -51.5, 4).expect("antipode");
    assert!(!grid.contains(&A5Cell3D::new(antipode, 0)));

    // World-cell root short-circuits the subtree check, but still rejects
    // wrong resolutions and out-of-range layers.
    let world: SparseA5Grid3D<u32> = SparseA5Grid3D::new(4, Some(boundaries()));
    assert!(world.contains(&A5Cell3D::new(cell, 1)));
    assert!(!world.contains(&A5Cell3D::new(wrong_res, 1)));

    // Root deeper than resolution must be rejected as out-of-bounds.
    let deep_root = GeoCell::from_lon_lat(-0.1, 51.5, 4).expect("deep root");
    let bad_grid: SparseA5Grid3D<u32> =
        SparseA5Grid3D::new_with_root(deep_root, 2, Some(boundaries()));
    let res2 = GeoCell::from_lon_lat(-0.1, 51.5, 2).expect("res 2 cell");
    assert!(!bad_grid.contains(&A5Cell3D::new(res2, 0)));
}