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
use crate::{
    simulation::{environment::ObservableEnvironment, SimulationEnvironment},
    types::{NodeId, RailwayObjectId},
};
use std::any::Any;

use super::{DecisionAgent, RailMovableAction};

use std::time::Duration;

/// The `ForwardUntilTargetAgent` struct represents a decision agent that moves
/// a railway object forward until it reaches its next target node.
///
/// # Type parameters
///
/// * `T`: A type implementing the `RailwayObject`, `Movable`, and `NextTarget` traits.
#[derive(Debug, Default)]
pub struct ForwardUntilTargetAgent {
    object_id: RailwayObjectId,
    position: Option<NodeId>,
    target: Option<NodeId>,
}

impl ForwardUntilTargetAgent {
    /// Constructs a new `ForwardUntilTargetAgent` with the given railway object and `RailwayGraph`.
    ///
    /// # Arguments
    ///
    /// * `object`: The railway object that the agent controls.
    pub fn new(object_id: RailwayObjectId) -> Self {
        Self {
            object_id,
            ..Default::default()
        }
    }

    /// Checks if the railway object has reached its next target node.
    ///
    /// # Returns
    ///
    /// `true` if the railway object's position matches its next target node, `false` otherwise.
    fn target_reached(&self) -> bool {
        self.position == self.target
    }
}

impl DecisionAgent for ForwardUntilTargetAgent {
    type A = RailMovableAction;

    fn next_action(&self, _delta_time: Option<Duration>) -> Self::A {
        if self.target_reached() {
            RailMovableAction::Stop
        } else {
            RailMovableAction::AccelerateForward { acceleration: 20 }
        }
    }

    fn observe(&mut self, environment: &SimulationEnvironment) {
        if let Some(object) = environment
            .get_objects()
            .iter()
            .find(|o| o.id() == self.object_id)
        {
            self.position = object.position();
            self.target = object.next_target();
        }
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

#[cfg(test)]
mod tests {
    use geo::coord;
    use std::collections::VecDeque;

    use super::*;
    use crate::railway_objects::{RailwayObject, Train};

    #[test]
    fn test_decision_agent() {
        let mut train = Train {
            id: 1,
            position: Some(3),
            geo_location: Some(coord! { x:0.0, y: 0.0}),
            next_target: Some(5),
            targets: VecDeque::from(vec![5, 10, 15]),
            ..Default::default()
        };

        // Create agent
        let mut agent = ForwardUntilTargetAgent::new(train.id());

        agent.position = Some(0);
        agent.target = Some(5);
        // Check if the agent suggests the correct action when the target is not reached
        assert_eq!(
            agent.next_action(None),
            RailMovableAction::AccelerateForward { acceleration: 20 }
        );

        // Update agent's object
        train.position = Some(5);
        let agent = ForwardUntilTargetAgent::new(train.id());

        // Check if the agent suggests the correct action when the target is reached
        assert_eq!(agent.next_action(None), RailMovableAction::Stop);
    }
}