-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtypes.rs
401 lines (350 loc) · 13.1 KB
/
types.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
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
//! Mosaik types as defined in the [Mosaik API](https://gitlab.com/mosaik/api/mosaik-api-python/-/blob/3.0.9/mosaik_api_v3/types.py?ref_type=tags)
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::collections::HashMap;
///Time is represented as the number of simulation steps since the
///simulation started. One step represents `time_resolution` seconds.
/// All time-based or hybrid simulators start at time=0.
pub type Time = u64;
///An attribute name
pub type Attr = String;
///The name of a model.
pub type ModelName = String;
///A simulator ID
pub type SimId = String;
///An entity ID
pub type EntityId = String;
///A full ID of the form "`sim_id.entity_id`"
pub type FullId = String;
///The format of input data for simulator's step methods.
pub type InputData = HashMap<EntityId, HashMap<Attr, Map<FullId, Value>>>;
///The requested outputs for `get_data`. For each entity where data is
///needed, the required attributes are listed.
pub type OutputRequest = HashMap<EntityId, Vec<Attr>>;
///The compatible Mosaik version with this edition of the API
pub const API_VERSION: &str = "3.0";
///The format of output data as return by ``get_data``
#[derive(Debug, Serialize, Deserialize)]
pub struct OutputData {
#[serde(flatten)]
pub requests: HashMap<EntityId, HashMap<Attr, Value>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub time: Option<Time>,
}
/// Description of a single model in `Meta`
///
/// ## Example implementation
/// ```rust
/// use mosaik_api::types::ModelDescription;
///
/// const foo: ModelDescription = ModelDescription {
/// public: true,
/// params: &["init_val"],
/// attrs: &["delta", "val"],
/// trigger: Some(&["delta"]),
/// any_inputs: None,
/// persistent: None,
/// };
/// ```
#[derive(Debug, Serialize, PartialEq, Clone, Default)]
pub struct ModelDescription {
/// Whether the model can be created directly.
pub public: bool,
/// The parameters given during creating of this model.
pub params: &'static [&'static str],
/// The input and output attributes of this model.
pub attrs: &'static [&'static str],
/// Whether this model accepts inputs other than those specified in `attrs`.
#[serde(skip_serializing_if = "Option::is_none")]
pub any_inputs: Option<bool>,
/// The input attributes that trigger a step of the associated simulator.
/// (Non-trigger attributes are collected and supplied to the simulator when it
/// steps next.)
#[serde(skip_serializing_if = "Option::is_none")]
pub trigger: Option<&'static [&'static str]>,
/// The output attributes that are persistent.
#[serde(skip_serializing_if = "Option::is_none")]
pub persistent: Option<&'static [&'static str]>,
}
impl ModelDescription {
/// Creates a new `ModelDescription` with fields `any_inputs`, `trigger` and `persistent` set to `None`.
#[must_use]
pub fn new(
public: bool,
params: &'static [&'static str],
attrs: &'static [&'static str],
) -> Self {
Self {
public,
params,
attrs,
any_inputs: None,
trigger: None,
persistent: None,
}
}
}
/// The meta-data for a simulator.
#[derive(Debug, Serialize, PartialEq, Clone)]
pub struct Meta {
/// The API version that this simulator supports in the format "major.minor".
api_version: &'static str,
/// The simulator's stepping type.
#[serde(rename = "type")]
pub simulator_type: SimulatorType,
/// The descriptions of this simulator's models.
pub models: HashMap<ModelName, ModelDescription>,
/// The names of the extra methods this simulator supports.
///
/// # Note
/// > These methods can be called while the scenario is being created and can be used
/// > for operations that don’t really belong into init() or create().
#[serde(skip_serializing_if = "Option::is_none")]
pub extra_methods: Option<Vec<String>>,
}
impl Meta {
#[must_use]
pub fn new(
simulator_type: SimulatorType,
models: HashMap<ModelName, ModelDescription>,
extra_methods: Option<Vec<String>>,
) -> Self {
Self {
api_version: API_VERSION,
simulator_type,
models,
extra_methods,
}
}
#[must_use]
pub fn version(&self) -> &str {
self.api_version
}
}
impl Default for Meta {
#[must_use]
fn default() -> Self {
Self {
api_version: API_VERSION,
simulator_type: SimulatorType::default(),
models: HashMap::new(),
extra_methods: None,
}
}
}
/// The three types of simulators. With `Hybrid` being the default.
/// - `TimeBased`: start at time 0, return the next step time after each step, and produce data valid for \([t_{now}, t_{next})\).
/// - `EventBased`: start whenever their first event is scheduled, step at event times, can schedule their own events, and produce output valid at specific times.
/// - `Hybrid`: a mix of the two. Also starts at time 0.
#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone)]
#[serde(rename_all = "kebab-case")]
pub enum SimulatorType {
TimeBased,
EventBased,
#[default]
Hybrid,
}
/// The type for elements of the list returned by `create` calls in the mosaik API.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct CreateResult {
/// The entity ID of this entity.
pub eid: EntityId,
/// The model name (as given in the simulator's meta) of this entity.
#[serde(rename = "type")]
pub model_type: ModelName,
/// The entity IDs of the entities of this simulator that are related to this entity.
#[serde(skip_serializing_if = "Option::is_none")]
pub rel: Option<Vec<EntityId>>,
/// The child entities of this entity.
#[serde(skip_serializing_if = "Option::is_none")]
pub children: Option<Vec<CreateResult>>,
/// Any additional information about the entity that the simulator wants to pass back to the scenario.
#[serde(skip_serializing_if = "Option::is_none")]
pub extra_info: Option<HashMap<String, String>>,
}
impl CreateResult {
#[must_use]
pub fn new(eid: EntityId, model_type: ModelName) -> Self {
Self {
eid,
model_type,
rel: None,
children: None,
extra_info: None,
}
}
}
/*
// The below types are copied from the python implementation.
// pub type CreateResultChild = CreateResult;
class EntitySpec(TypedDict):
type: ModelName
class EntityGraph(TypedDict):
nodes: Dict[FullId, EntitySpec]
edges: List[Tuple[FullId, FullId, Dict]]
*/
// tests for Meta
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn test_output_data() {
// Example JSON data
let json_data = r#"{
"eid_1": {"attr_1": "val_1"},
"time": 64
}
"#
.replace(['\n', ' '], "");
// Deserialize JSON to OutputData struct
let data: OutputData = serde_json::from_str(&json_data).unwrap();
assert_ne!(data.requests, HashMap::new());
assert_eq!(data.time, Some(64));
// Serialize EventData struct to JSON
let serialized_json = serde_json::to_string(&data).unwrap();
assert!(!serialized_json.contains("requests"));
assert!(serialized_json.contains("time"));
assert_eq!(serialized_json, json_data);
}
#[test]
fn test_model_description_without_optionals() {
let mut model = ModelDescription::default();
assert!(!model.public);
assert_eq!(model.params.len(), 0);
assert_eq!(model.attrs.len(), 0);
assert_eq!(model.any_inputs, None);
assert_eq!(model.trigger, None);
assert_eq!(model.persistent, None);
let model_json = serde_json::to_string(&model).unwrap();
assert_eq!(r#"{"public":false,"params":[],"attrs":[]}"#, model_json);
model.public = true;
model.params = &["init_reading"];
model.attrs = &["trades", "total"];
assert!(model.public);
assert_eq!(model.params.len(), 1);
assert_eq!(model.attrs.len(), 2);
let model_json = serde_json::to_string(&model).unwrap();
assert_eq!(
r#"{"public":true,"params":["init_reading"],"attrs":["trades","total"]}"#,
model_json
);
}
#[test]
fn test_model_description_with_optionals() {
let mut model = ModelDescription::new(true, &["init_reading"], &["p_mw_pv", "p_mw_load"]);
model.any_inputs = Some(true);
model.trigger = Some(&["trigger1"]);
model.persistent = Some(&["trades"]);
let model_json = serde_json::to_string(&model).unwrap();
assert_eq!(
r#"{"public":true,"params":["init_reading"],"attrs":["p_mw_pv","p_mw_load"],"any_inputs":true,"trigger":["trigger1"],"persistent":["trades"]}"#,
model_json
);
model.trigger = Some(&["trigger1"]);
model.any_inputs = None;
model.persistent = None;
let model_json = serde_json::to_string(&model).unwrap();
assert_eq!(
r#"{"public":true,"params":["init_reading"],"attrs":["p_mw_pv","p_mw_load"],"trigger":["trigger1"]}"#,
model_json
);
}
#[test]
fn test_meta_empty() {
let meta = Meta::new(SimulatorType::default(), HashMap::new(), None);
assert_eq!(
meta.api_version, API_VERSION,
"API version should match the global variable."
);
assert_eq!(
meta.version(),
API_VERSION,
"version should return the API version."
);
assert_eq!(
meta.simulator_type,
SimulatorType::Hybrid,
"Default type should be Hybrid"
);
let empty_meta_json = serde_json::to_string(&meta).unwrap();
assert_eq!(
r#"{"api_version":"3.0","type":"hybrid","models":{}}"#, empty_meta_json,
"Empty meta should not have extra_methods and empty models."
);
assert!(meta.models.is_empty());
}
#[test]
fn test_meta_with_models() {
let model1 = ModelDescription::new(true, &["init_reading"], &["trades", "total"]);
let meta = Meta::new(
SimulatorType::default(),
HashMap::from([("MarktplatzModel".to_string(), model1)]),
None,
);
assert_eq!(meta.models.len(), 1, "Should have one model");
assert!(meta.extra_methods.is_none());
let meta_json = serde_json::to_string(&meta).unwrap();
assert_eq!(
r#"{"api_version":"3.0","type":"hybrid","models":{"MarktplatzModel":{"public":true,"params":["init_reading"],"attrs":["trades","total"]}}}"#,
meta_json,
"Meta should have one model and no extra methods."
);
}
#[test]
fn test_meta_optionals() {
let meta = Meta::new(
SimulatorType::default(),
HashMap::new(),
Some(vec!["foo".to_string(), "bar".to_string()]),
);
assert_eq!(
meta.extra_methods.as_ref().unwrap().len(),
2,
"Should have 2 extra methods."
);
let meta_json = serde_json::to_string(&meta).unwrap();
assert_eq!(
r#"{"api_version":"3.0","type":"hybrid","models":{},"extra_methods":["foo","bar"]}"#,
meta_json,
"JSON String should contain 'foo' and 'bar' as extra methods."
);
}
#[test]
fn test_create_result_new() {
let create_result = CreateResult::new(String::from("eid_1"), String::from("model_name"));
assert_eq!(create_result.eid, "eid_1");
assert_eq!(create_result.model_type, "model_name");
assert!(create_result.rel.is_none());
assert!(create_result.children.is_none());
assert!(create_result.extra_info.is_none());
let create_result_json = serde_json::to_string(&create_result).unwrap();
assert_eq!(
r#"{"eid":"eid_1","type":"model_name"}"#, create_result_json,
"New CreateResult should not contain any optional fields"
);
}
#[test]
fn test_create_results_filled() {
let mut create_result = CreateResult::new("eid_1".to_string(), "model_name".to_string());
create_result.rel = Some(vec!["eid_2".to_string()]);
create_result.children = Some(vec![CreateResult::new(
"child_1".to_string(),
"child".to_string(),
)]);
assert_eq!(create_result.eid, "eid_1");
assert_eq!(create_result.model_type, "model_name");
assert_eq!(create_result.rel, Some(vec!["eid_2".to_string()]));
assert!(create_result.children.is_some());
if let Some(children) = &create_result.children {
assert_eq!(children.len(), 1);
assert_eq!(children[0].eid, "child_1");
}
let create_result_json = serde_json::to_string(&create_result).unwrap();
assert_eq!(
r#"{"eid":"eid_1","type":"model_name","rel":["eid_2"],"children":[{"eid":"child_1","type":"child"}]}"#,
create_result_json,
"Filled create result should contain optional fields without extra_info"
);
}
}