-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontroller.rs
187 lines (165 loc) · 5.34 KB
/
controller.rs
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
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic_in_result_fn)]
use clap::Parser;
use log::error;
use mosaik_api::tcp::ConnectionDirection;
use mosaik_api::types::{
Attr, CreateResult, EntityId, InputData, Meta, ModelDescription, OutputData, OutputRequest,
SimId, SimulatorType, Time,
};
use mosaik_api::{run_simulation, MosaikApi};
use serde_json::{json, Map, Value};
use std::collections::HashMap;
use std::sync::LazyLock;
static META: LazyLock<Meta> = LazyLock::new(|| {
Meta::new(
SimulatorType::EventBased,
HashMap::from([(
"Agent".to_string(),
ModelDescription {
public: true,
params: &[],
attrs: &["val_in", "delta"],
trigger: None,
any_inputs: None,
persistent: None,
},
)]),
None,
)
});
// A simple demo controller. Inspired by the python tutorial
#[derive(Default)]
pub struct Controller {
agents: Vec<String>,
data: HashMap<EntityId, HashMap<Attr, Value>>,
time: Time,
}
impl MosaikApi for Controller {
fn init(
&mut self,
_sid: SimId,
_time_resolution: f64,
_sim_params: Map<String, Value>,
) -> Result<&'static Meta, String> {
Ok(&META)
}
fn create(
&mut self,
num: usize,
model_name: String,
_model_params: Map<String, Value>,
) -> Result<Vec<CreateResult>, String> {
let n_agents = self.agents.len();
let mut entities: Vec<CreateResult> = vec![];
for i in n_agents..(n_agents + num) {
let eid = format!("Agent_{i}");
self.agents.push(eid.clone());
entities.push(CreateResult {
eid,
model_type: model_name.clone(),
rel: None,
children: None,
extra_info: None,
});
}
Ok(entities)
}
fn setup_done(&self) -> Result<(), String> {
Ok(())
}
fn stop(&self) {}
fn step(
&mut self,
time: Time,
inputs: InputData,
_max_advance: Time,
) -> Result<Option<Time>, String> {
self.time = time;
let mut data = HashMap::new();
for (agent_eid, attrs) in inputs {
if let Some(delta_dict) = attrs.get("delta") {
if !delta_dict.is_empty() {
data.insert(
agent_eid.clone(),
HashMap::from([(
"delta".to_string(),
delta_dict.values().next().unwrap().clone(),
)]),
);
continue;
}
}
if let Some(values_dict) = attrs.get("val_in") {
assert!(
values_dict.len() == 1,
"Only one ingoing connection allowed per agent, but \"{}\" has {}.",
agent_eid,
values_dict.len()
);
let value = values_dict.values().next().unwrap();
let delta = if value.as_f64().unwrap() >= 3.0 {
-1
} else if value.as_f64().unwrap() <= -3.0 {
1
} else {
continue;
};
data.insert(
agent_eid.clone(),
HashMap::from([("delta".to_string(), json!(delta))]),
);
}
}
self.data = data;
Ok(None)
}
fn get_data(&self, outputs: OutputRequest) -> Result<OutputData, String> {
let mut data: HashMap<String, HashMap<String, Value>> = HashMap::new();
for (agent_eid, attrs) in outputs {
for attr in attrs {
if attr != "delta" {
return Err(format!("Unknown output attribute \"{attr}\""));
}
if let Some(agent_data) = self.data.get(&agent_eid) {
data.entry("time".to_string())
.or_default()
.insert("time".to_string(), json!(self.time));
data.entry(agent_eid.clone()).or_default().insert(
attr.clone(),
agent_data.get(&attr).unwrap_or(&json!(0.0)).clone(),
);
}
}
}
Ok(OutputData {
requests: data,
time: Some(self.time),
})
}
}
#[derive(Parser, Debug)]
struct Args {
/// The local addres mosaik connects to, or none if we connect to them
#[clap(short, long)]
addr: Option<String>,
}
pub fn main() {
//get the address if there is one
let args = Args::parse();
env_logger::init();
let address = match args.addr {
//case if we connect us to mosaik
Some(addr) => {
ConnectionDirection::ConnectToAddress(addr.parse().expect("Address is not parseable."))
}
//case if mosaik connects to us
None => {
let addr = "127.0.0.1:5678";
ConnectionDirection::ListenOnAddress(addr.parse().expect("Address is not parseable."))
}
};
let controller = Controller::default();
if let Err(e) = run_simulation(address, controller) {
error!("Error running controller: {:?}", e);
}
}