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
//! Space interaction API - add, remove, move, and query agents in space.
//!
//! This module provides the ergonomic helper functions that mirror Julia
//! Agents.jl's `model_accessing_API.jl` and `space_interaction_API.jl`:
//!
//! - [`add_agent`], [`add_agent_random`] - insert an agent into both the store and the space.
//! - [`remove_agent`] - remove an agent from both the store and the space.
//! - [`move_agent`] - change an agent's position in the space.
//! - [`nearby_ids`], [`nearby_ids_except`] - query agents near a position.
//! - [`nearby_agents`], [`nearby_agents_except`] - query agent references near a position.
//! - [`random_agent`], [`random_id`] - pick a random agent.
//! - [`all_ids`] - list all agent IDs.
//!
//! These functions operate on [`StandardModel`] and require the agent type to
//! implement [`PositionedAgent`] and the space to implement [`SpaceInteraction`].
//!
//! [`StandardModel`]: crate::standard::StandardModel

use crate::{
    agent::Agent, scheduler::Scheduler, space::Space, standard::StandardModel, store::AgentStore,
    types::AgentId,
};
use rand::seq::SliceRandom;
use thiserror::Error;

/// Errors that can occur during space interaction operations.
#[derive(Debug, Error)]
pub enum InteractionError<E: std::fmt::Debug + std::fmt::Display> {
    /// An agent with this ID already exists in the store.
    #[error("duplicate agent id {0}")]
    DuplicateId(AgentId),
    /// No agent with this ID was found.
    #[error("agent not found: {0}")]
    AgentNotFound(AgentId),
    /// The agent store and spatial index disagree about this agent.
    #[error("agent {0} is missing from the spatial index at its stored position")]
    SpaceIndexMissing(AgentId),
    /// The agent appears more than once in the spatial index at its stored position.
    #[error("agent {0} appears more than once in the spatial index at its stored position")]
    SpaceIndexDuplicate(AgentId),
    /// The underlying space reported an error (e.g. out of bounds).
    #[error("space error: {0}")]
    Space(E),
    /// A rollback failed after a space mutation error, leaving the model in an unknown state.
    #[error("space rollback failed during {operation}: original error: {source}; rollback error: {rollback}")]
    RollbackFailed {
        /// Operation that was being rolled back.
        operation: &'static str,
        /// Original operation error.
        source: E,
        /// Rollback error.
        rollback: E,
    },
}

/// Extension trait for agents that have a spatial position.
///
/// Implement this for agent types used with spatial models (grids, continuous
/// spaces, graphs, etc.). The position type is determined by the space.
pub trait PositionedAgent: Agent {
    /// The position type (e.g. `(usize, usize)` for grids, `ContinuousPos` for continuous space).
    type Position: Clone;

    /// Current position of the agent.
    fn position(&self) -> &Self::Position;

    /// Update the agent's position.
    fn set_position(&mut self, position: Self::Position);
}

/// Trait that spaces implement to support agent lifecycle and neighbor queries.
///
/// Each space type defines its own `Error` type and provides methods to
/// add/remove agents, generate random positions, and find nearby agent IDs.
pub trait SpaceInteraction<A: PositionedAgent>: Space {
    /// Error type for space operations.
    type Error: std::fmt::Debug + std::fmt::Display;

    /// Generate a random valid position within this space.
    fn random_position<R: rand::RngCore>(&self, rng: &mut R) -> A::Position;

    /// Register an agent with the space at its current position.
    fn add_agent(&mut self, agent: &A) -> Result<(), Self::Error>;

    /// Deregister an agent from the space.
    fn remove_agent(&mut self, agent: &A) -> Result<(), Self::Error>;

    /// Return all agent IDs within `radius` of `position`.
    ///
    /// The meaning of `radius` depends on the space: grid cells (Chebyshev),
    /// Euclidean distance (continuous), or graph hops (graph).
    fn nearby_ids(&self, position: &A::Position, radius: usize) -> Vec<AgentId>;
}

/// Add a positioned agent to both the store and the space.
///
/// Returns [`InteractionError::DuplicateId`] if an agent with the same ID
/// already exists, or [`InteractionError::Space`] if the space rejects the position.
pub fn add_agent<S, A, Store, Props, R, Sch>(
    model: &mut StandardModel<S, A, Store, Props, R, Sch>,
    agent: A,
) -> Result<(), InteractionError<S::Error>>
where
    A: PositionedAgent,
    S: SpaceInteraction<A>,
    Store: AgentStore<A>,
    R: rand::RngCore,
    Sch: Scheduler<StandardModel<S, A, Store, Props, R, Sch>>,
{
    let id = agent.id();
    if model.agents.contains(id) {
        return Err(InteractionError::DuplicateId(id));
    }

    // Register with the space before committing the store insert. If the
    // space rejects the position, the model remains unchanged.
    model
        .space
        .add_agent(&agent)
        .map_err(InteractionError::Space)?;

    model.agents.insert(agent);

    // Update max_id
    if id > model.max_id {
        model.max_id = id;
    }

    Ok(())
}

/// Validate that every positioned agent in the store is present exactly once
/// in the spatial index at its stored position.
pub fn validate_space_index<S, A, Store, Props, R, Sch>(
    model: &StandardModel<S, A, Store, Props, R, Sch>,
) -> Result<(), InteractionError<S::Error>>
where
    A: PositionedAgent,
    S: SpaceInteraction<A>,
    Store: AgentStore<A>,
    R: rand::RngCore,
    Sch: Scheduler<StandardModel<S, A, Store, Props, R, Sch>>,
{
    for id in model.agents.iter_ids() {
        let Some(agent) = model.agents.get(id) else {
            continue;
        };
        let matches = model
            .space
            .nearby_ids(agent.position(), 0)
            .into_iter()
            .filter(|candidate| *candidate == id)
            .count();
        match matches {
            0 => return Err(InteractionError::SpaceIndexMissing(id)),
            1 => {}
            _ => return Err(InteractionError::SpaceIndexDuplicate(id)),
        }
    }
    Ok(())
}

/// Remove a positioned agent from both the store and the space.
///
/// Returns `Ok(None)` if no agent with this ID was found.
pub fn remove_agent<S, A, Store, Props, R, Sch>(
    model: &mut StandardModel<S, A, Store, Props, R, Sch>,
    id: AgentId,
) -> Result<Option<A>, InteractionError<S::Error>>
where
    A: PositionedAgent,
    S: SpaceInteraction<A>,
    Store: AgentStore<A>,
    R: rand::RngCore,
    Sch: Scheduler<StandardModel<S, A, Store, Props, R, Sch>>,
{
    // Need to access agent to remove from space
    if let Some(agent_ref) = model.agents.get(id) {
        model
            .space
            .remove_agent(&*agent_ref)
            .map_err(InteractionError::Space)?;
    } else {
        return Ok(None);
    }

    Ok(model.agents.remove(id))
}

/// Move an agent to a new position in the space.
///
/// Returns [`InteractionError::AgentNotFound`] if no agent with this ID was found,
/// or [`InteractionError::Space`] if the space rejects the new position.
pub fn move_agent<S, A, Store, Props, R, Sch>(
    model: &mut StandardModel<S, A, Store, Props, R, Sch>,
    id: AgentId,
    new_position: A::Position,
) -> Result<(), InteractionError<S::Error>>
where
    A: PositionedAgent,
    S: SpaceInteraction<A>,
    Store: AgentStore<A>,
    R: rand::RngCore,
    Sch: Scheduler<StandardModel<S, A, Store, Props, R, Sch>>,
{
    let mut agent_ref = model
        .agents
        .get_mut(id)
        .ok_or(InteractionError::AgentNotFound(id))?;

    let old_position = agent_ref.position().clone();

    model
        .space
        .remove_agent(&*agent_ref)
        .map_err(InteractionError::Space)?;

    agent_ref.set_position(new_position);

    if let Err(source) = model.space.add_agent(&*agent_ref) {
        agent_ref.set_position(old_position);
        if let Err(rollback) = model.space.add_agent(&*agent_ref) {
            return Err(InteractionError::RollbackFailed {
                operation: "move_agent",
                source,
                rollback,
            });
        }
        return Err(InteractionError::Space(source));
    }

    Ok(())
}

/// Pick a random agent ID from the model.
///
/// Returns `None` if the agent store is empty.
pub fn random_id<S, A, Store, Props, R, Sch>(
    model: &mut StandardModel<S, A, Store, Props, R, Sch>,
) -> Option<AgentId>
where
    A: Agent,
    S: Space,
    Store: AgentStore<A>,
    R: rand::RngCore,
    Sch: Scheduler<StandardModel<S, A, Store, Props, R, Sch>>,
{
    let ids: Vec<AgentId> = model.agents.iter_ids();
    if ids.is_empty() {
        return None;
    }

    let mut rng = model.rng_mut();
    ids.choose(&mut *rng).copied()
}

/// Get a vector of all agent IDs in the model.
pub fn all_ids<S, A, Store, Props, R, Sch>(
    model: &StandardModel<S, A, Store, Props, R, Sch>,
) -> Vec<AgentId>
where
    A: Agent,
    S: Space,
    Store: AgentStore<A>,
    R: rand::RngCore,
    Sch: Scheduler<StandardModel<S, A, Store, Props, R, Sch>>,
{
    model.agents.iter_ids()
}

/// Query agent IDs near a position, using the space's distance metric.
///
/// The meaning of `radius` depends on the space: grid cells (Chebyshev),
/// Euclidean distance (continuous), or graph hops (graph).
pub fn nearby_ids<S, A, Store, Props, R, Sch>(
    model: &StandardModel<S, A, Store, Props, R, Sch>,
    position: &A::Position,
    radius: usize,
) -> Vec<AgentId>
where
    A: PositionedAgent,
    S: SpaceInteraction<A>,
    Store: AgentStore<A>,
    R: rand::RngCore,
    Sch: Scheduler<StandardModel<S, A, Store, Props, R, Sch>>,
{
    model.space.nearby_ids(position, radius)
}

/// Query agent references near a position, using the space's distance metric.
///
/// The meaning of `radius` depends on the space: grid cells (Chebyshev),
/// Euclidean distance (continuous), or graph hops (graph).
pub fn nearby_agents<'a, S, A, Store, Props, R, Sch>(
    model: &'a StandardModel<S, A, Store, Props, R, Sch>,
    position: &A::Position,
    radius: usize,
) -> Vec<std::cell::Ref<'a, A>>
where
    A: PositionedAgent,
    S: SpaceInteraction<A>,
    Store: AgentStore<A>,
    R: rand::RngCore,
    Sch: Scheduler<StandardModel<S, A, Store, Props, R, Sch>>,
{
    model
        .space
        .nearby_ids(position, radius)
        .into_iter()
        .filter_map(|id| model.agents.get(id))
        .collect()
}

/// Query agent IDs near a position, excluding a specific agent.
///
/// The meaning of `radius` depends on the space: grid cells (Chebyshev),
/// Euclidean distance (continuous), or graph hops (graph).
pub fn nearby_ids_except<S, A, Store, Props, R, Sch>(
    model: &StandardModel<S, A, Store, Props, R, Sch>,
    position: &A::Position,
    radius: usize,
    exclude_id: AgentId,
) -> Vec<AgentId>
where
    A: PositionedAgent,
    S: SpaceInteraction<A>,
    Store: AgentStore<A>,
    R: rand::RngCore,
    Sch: Scheduler<StandardModel<S, A, Store, Props, R, Sch>>,
{
    model
        .space
        .nearby_ids(position, radius)
        .into_iter()
        .filter(|&id| id != exclude_id)
        .collect()
}

/// Query agent references near a position, excluding a specific agent.
///
/// The meaning of `radius` depends on the space: grid cells (Chebyshev),
/// Euclidean distance (continuous), or graph hops (graph).
pub fn nearby_agents_except<'a, S, A, Store, Props, R, Sch>(
    model: &'a StandardModel<S, A, Store, Props, R, Sch>,
    position: &A::Position,
    radius: usize,
    exclude_id: AgentId,
) -> Vec<std::cell::Ref<'a, A>>
where
    A: PositionedAgent,
    S: SpaceInteraction<A>,
    Store: AgentStore<A>,
    R: rand::RngCore,
    Sch: Scheduler<StandardModel<S, A, Store, Props, R, Sch>>,
{
    model
        .space
        .nearby_ids(position, radius)
        .into_iter()
        .filter(|&id| id != exclude_id)
        .filter_map(|id| model.agents.get(id))
        .collect()
}

/// Pick a random agent reference from the model.
///
/// Returns `None` if the agent store is empty.
pub fn random_agent<'a, S, A, Store, Props, R, Sch>(
    model: &'a mut StandardModel<S, A, Store, Props, R, Sch>,
) -> Option<std::cell::Ref<'a, A>>
where
    A: Agent,
    S: Space,
    Store: AgentStore<A>,
    R: rand::RngCore,
    Sch: Scheduler<StandardModel<S, A, Store, Props, R, Sch>>,
{
    let ids = model.agents.iter_ids();
    if ids.is_empty() {
        return None;
    }

    let mut rng = model.rng_mut();
    let id = *ids.choose(&mut *rng)?;
    drop(rng);

    model.agents.get(id)
}

/// Add an agent to the model at a random position in the space.
///
/// The agent must not already exist in the store. If the space rejects the
/// position, returns [`InteractionError::Space`].
pub fn add_agent_random<S, A, Store, Props, R, Sch>(
    model: &mut StandardModel<S, A, Store, Props, R, Sch>,
    mut agent: A,
) -> Result<(), InteractionError<S::Error>>
where
    A: PositionedAgent,
    S: SpaceInteraction<A>,
    Store: AgentStore<A>,
    R: rand::RngCore,
    Sch: Scheduler<StandardModel<S, A, Store, Props, R, Sch>>,
{
    let mut rng = model.rng_mut();
    let position = model.space.random_position(&mut *rng);
    drop(rng);

    agent.set_position(position);
    add_agent(model, agent)
}