henad-core 0.3.0

Model authoring traits, primitives and shared types of Henad, a parallel agent-based modelling engine.
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! Parameter values written as text, read and checked against their descriptors.

use std::fmt;
use std::num::{ParseFloatError, ParseIntError};
use std::str::ParseBoolError;

use crate::params::{ParamDescriptor, ParamKind, ParamValue};

/// A parameter value that cannot be read, or does not fit its descriptor.
///
/// The `source` of text that cannot be parsed as its kind is the parser's error.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValueError {
    /// Text that cannot be parsed as an `f32`.
    NotANumber {
        /// Text as given.
        raw: String,
        /// Error of the `f32` parser.
        source: ParseFloatError,
    },
    /// Text that cannot be parsed as a `u32`.
    NotAnInteger {
        /// Text as given.
        raw: String,
        /// Error of the `u32` parser.
        source: ParseIntError,
    },
    /// Text that cannot be parsed as a `bool`.
    NotABool {
        /// Text as given.
        raw: String,
        /// Error of the `bool` parser.
        source: ParseBoolError,
    },
    /// A number outside the descriptor's inclusive bounds. A non-finite number is outside every bound.
    OutOfRange {
        /// Number as text.
        value: String,
        /// Lower bound as text.
        min: String,
        /// Upper bound as text.
        max: String,
    },
    /// Neither the index nor the name of an option.
    UnknownOption {
        /// Text as given, or the index as text.
        raw: String,
        /// Options of the parameter.
        options: &'static [&'static str],
    },
    /// An id no descriptor has.
    UnknownParam {
        /// Id as given.
        id: String,
        /// Ids the descriptors have.
        known: Vec<&'static str>,
    },
    /// An override with no `=` between the id and the value.
    BadOverride {
        /// Override as given.
        raw: String,
    },
    /// A value that parameter `id` rejects.
    Param {
        /// Id of the parameter.
        id: String,
        /// Reason the descriptor rejects the value.
        source: Box<Self>,
    },
    /// A value passed to [`check_value`] whose kind differs from the descriptor's kind.
    WrongKind {
        /// Kind that the descriptor accepts.
        expected: ValueKind,
        /// Kind of the value.
        found: ValueKind,
        /// Value as text.
        value: String,
    },
}

/// Kind of a parameter value, as [`ValueError::WrongKind`] reports it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValueKind {
    /// An `f32`.
    F32,
    /// A `u32`.
    U32,
    /// A `bool`.
    Bool,
    /// An index into a choice's options.
    Choice,
}

impl fmt::Display for ValueKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::F32 => "f32",
            Self::U32 => "u32",
            Self::Bool => "bool",
            Self::Choice => "choice",
        })
    }
}

impl fmt::Display for ValueError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotANumber { raw, .. } => write!(f, "'{raw}' is not a number"),
            Self::NotAnInteger { raw, .. } => write!(f, "'{raw}' is not an integer"),
            Self::NotABool { raw, .. } => write!(f, "'{raw}' is not a bool"),
            Self::OutOfRange { value, min, max } => write!(f, "{value} is outside {min}..={max}"),
            Self::UnknownOption { raw, options } if raw.parse::<usize>().is_ok() => {
                write!(f, "index {raw} is not one of {options:?}")
            }
            Self::UnknownOption { raw, options } => write!(f, "'{raw}' is not one of {options:?}"),
            Self::UnknownParam { id, .. } => write!(f, "model has no parameter '{id}'"),
            Self::BadOverride { raw } => write!(f, "bad --set '{raw}', expected ID=VALUE"),
            Self::Param { id, .. } => write!(f, "parameter '{id}'"),
            Self::WrongKind { expected, found, value } => {
                let example = match expected {
                    ValueKind::F32 => "an f32 value such as 1.0f32",
                    ValueKind::U32 => "a u32 value such as 1u32",
                    ValueKind::Bool => "a bool value",
                    ValueKind::Choice => "a choice such as ParamValue::Choice(0)",
                };
                write!(f, "expected {example}, found the {found} {value}")
            }
        }
    }
}

impl std::error::Error for ValueError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::NotANumber { source, .. } => Some(source),
            Self::NotAnInteger { source, .. } => Some(source),
            Self::NotABool { source, .. } => Some(source),
            Self::Param { source, .. } => Some(source),
            _ => None,
        }
    }
}

/// Splits each `--set ID=VALUE` string into an `(id, value)` pair at its first `=`.
///
/// # Errors
///
/// Returns [`ValueError::BadOverride`] for a string with no `=`.
pub fn parse_overrides(raw: &[String]) -> Result<Vec<(String, String)>, ValueError> {
    raw.iter()
        .map(|pair| {
            let (id, value) = pair
                .split_once('=')
                .ok_or_else(|| ValueError::BadOverride { raw: pair.clone() })?;
            Ok((id.to_owned(), value.to_owned()))
        })
        .collect()
}

/// Returns every descriptor's default value, with `overrides` applied in order by id.
///
/// # Errors
///
/// Returns [`ValueError::UnknownParam`] for an id no descriptor has, and [`ValueError::Param`] for a
/// value that its descriptor rejects.
pub fn resolve_params(
    descriptors: &[ParamDescriptor],
    overrides: &[(String, String)],
) -> Result<Vec<ParamValue>, ValueError> {
    let mut values: Vec<ParamValue> = descriptors
        .iter()
        .map(|descriptor| descriptor.kind.default_value())
        .collect();

    for (id, raw) in overrides {
        let index = descriptors
            .iter()
            .position(|descriptor| descriptor.id == *id)
            .ok_or_else(|| ValueError::UnknownParam {
                id: id.clone(),
                known: descriptors.iter().map(|descriptor| descriptor.id).collect(),
            })?;
        values[index] = parse_value(&descriptors[index].kind, raw).map_err(|error| ValueError::Param {
            id: id.clone(),
            source: Box::new(error),
        })?;
    }

    Ok(values)
}

/// Reads `raw` as a value of `kind`, and checks it with [`check_value`].
///
/// For a choice, `raw` is read as an option name first, then as an option index.
///
/// # Errors
///
/// Returns [`ValueError`] when `raw` cannot be parsed as the kind, or [`check_value`] rejects it.
pub fn parse_value(kind: &ParamKind, raw: &str) -> Result<ParamValue, ValueError> {
    let value = match kind {
        ParamKind::F32 { .. } => ParamValue::F32(raw.parse().map_err(|source| ValueError::NotANumber {
            raw: raw.to_owned(),
            source,
        })?),
        ParamKind::U32 { .. } => ParamValue::U32(raw.parse().map_err(|source| ValueError::NotAnInteger {
            raw: raw.to_owned(),
            source,
        })?),
        ParamKind::Bool { .. } => ParamValue::Bool(raw.parse().map_err(|source| ValueError::NotABool {
            raw: raw.to_owned(),
            source,
        })?),
        ParamKind::Choice { options, .. } => {
            let index = options
                .iter()
                .position(|option| *option == raw)
                .or_else(|| raw.parse::<usize>().ok())
                .ok_or_else(|| ValueError::UnknownOption {
                    raw: raw.to_owned(),
                    options,
                })?;
            ParamValue::Choice(index)
        }
    };
    check_value(kind, &value)?;
    Ok(value)
}

/// Checks `value` against the type, bounds and options of `kind`.
///
/// # Errors
///
/// Returns [`ValueError::OutOfRange`] for a number outside the bounds or not finite,
/// [`ValueError::UnknownOption`] for an index past the options, and [`ValueError::WrongKind`] for a value of another
/// kind. A `u32` is never accepted as a choice index.
pub fn check_value(kind: &ParamKind, value: &ParamValue) -> Result<(), ValueError> {
    let out_of_range = |value: &dyn fmt::Display, min: &dyn fmt::Display, max: &dyn fmt::Display| {
        Err(ValueError::OutOfRange {
            value: value.to_string(),
            min: min.to_string(),
            max: max.to_string(),
        })
    };
    match (kind, value) {
        (ParamKind::F32 { min, max, .. }, ParamValue::F32(number)) => {
            if number.is_finite() && number >= min && number <= max {
                Ok(())
            } else {
                out_of_range(number, min, max)
            }
        }
        (ParamKind::U32 { min, max, .. }, ParamValue::U32(number)) => {
            if number >= min && number <= max {
                Ok(())
            } else {
                out_of_range(number, min, max)
            }
        }
        (ParamKind::Bool { .. }, ParamValue::Bool(_)) => Ok(()),
        (ParamKind::Choice { options, .. }, ParamValue::Choice(index)) if *index < options.len() => Ok(()),
        (ParamKind::Choice { options, .. }, ParamValue::Choice(index)) => Err(ValueError::UnknownOption {
            raw: index.to_string(),
            options,
        }),
        (kind, other) => Err(ValueError::WrongKind {
            expected: param_kind(kind),
            found: value_kind(other),
            value: plain_text(other),
        }),
    }
}

/// Returns the kind of value that `kind` accepts.
fn param_kind(kind: &ParamKind) -> ValueKind {
    match kind {
        ParamKind::F32 { .. } => ValueKind::F32,
        ParamKind::U32 { .. } => ValueKind::U32,
        ParamKind::Bool { .. } => ValueKind::Bool,
        ParamKind::Choice { .. } => ValueKind::Choice,
    }
}

/// Returns the kind of `value`.
fn value_kind(value: &ParamValue) -> ValueKind {
    match value {
        ParamValue::F32(_) => ValueKind::F32,
        ParamValue::U32(_) => ValueKind::U32,
        ParamValue::Bool(_) => ValueKind::Bool,
        ParamValue::Choice(_) => ValueKind::Choice,
    }
}

/// Returns `value` as text that [`parse_value`] reads back unchanged.
///
/// A number is written in its shortest round-trip form, and a choice as its option name.
pub fn format_value(kind: &ParamKind, value: &ParamValue) -> String {
    match (kind, value) {
        (ParamKind::Choice { options, .. }, ParamValue::Choice(index)) => options
            .get(*index)
            .map_or_else(|| index.to_string(), |&name| name.to_owned()),
        _ => plain_text(value),
    }
}

/// Returns `value` as text without its descriptor, so a choice is written as its index.
fn plain_text(value: &ParamValue) -> String {
    match value {
        ParamValue::F32(number) => number.to_string(),
        ParamValue::U32(number) => number.to_string(),
        ParamValue::Bool(flag) => flag.to_string(),
        ParamValue::Choice(index) => index.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::{ValueError, ValueKind, check_value, format_value, parse_overrides, parse_value, resolve_params};
    use crate::helpers::{bool_param, f32_param, u32_param};
    use crate::params::{ParamApply, ParamDescriptor, ParamFormat, ParamKind, ParamValue};

    const OPTIONS: &[&str] = &["moore", "von_neumann"];

    fn descriptors() -> Vec<ParamDescriptor> {
        vec![
            u32_param("num_agents", "Agents", 1000, 1, 5_000_000),
            f32_param("cohesion", "Cohesion", 0.5, 0.0, 1.0, None),
            ParamDescriptor {
                id: "neighborhood",
                label: "Neighborhood",
                kind: ParamKind::Choice {
                    options: OPTIONS,
                    default: 0,
                },
                apply: ParamApply::Live,
                format: ParamFormat::Plain,
            },
        ]
    }

    fn resolve(raw: &str) -> Result<Vec<ParamValue>, ValueError> {
        let overrides = parse_overrides(&[raw.to_owned()])?;
        resolve_params(&descriptors(), &overrides)
    }

    /// Returns the error's message followed by each source's message, joined by ": ".
    fn message(error: &ValueError) -> String {
        let mut text = error.to_string();
        let mut source = std::error::Error::source(error);
        while let Some(inner) = source {
            text = format!("{text}: {inner}");
            source = inner.source();
        }
        text
    }

    #[test]
    fn an_override_replaces_one_default_and_leaves_the_rest() {
        let values = resolve("num_agents=2500").expect("2500 agents is in range");
        assert_eq!(values[0], ParamValue::U32(2500));
        assert_eq!(values[1], ParamValue::F32(0.5));
        assert_eq!(values[2], ParamValue::Choice(0));
    }

    /// A slider cannot request four billion agents, and `--set` cannot either. Unchecked, the number would go
    /// straight to `init`.
    #[test]
    fn a_value_outside_the_descriptor_range_is_refused() {
        let error = resolve("num_agents=4000000000").expect_err("4e9 agents is over the maximum");
        assert!(message(&error).contains("5000000"), "{}", message(&error));

        let error = resolve("num_agents=0").expect_err("0 agents is under the minimum");
        assert!(message(&error).contains("num_agents"), "{}", message(&error));

        assert!(resolve("cohesion=1.5").is_err(), "1.5 is over the maximum");
        assert!(resolve("cohesion=-0.5").is_err(), "-0.5 is under the minimum");
        assert!(resolve("cohesion=nan").is_err(), "NaN is in no range");
    }

    /// Both ends of the range are allowed.
    #[test]
    fn the_limits_themselves_are_accepted() {
        assert_eq!(resolve("cohesion=0").expect("the minimum")[1], ParamValue::F32(0.0));
        assert_eq!(resolve("cohesion=1").expect("the maximum")[1], ParamValue::F32(1.0));
        assert_eq!(
            resolve("num_agents=5000000").expect("the maximum")[0],
            ParamValue::U32(5_000_000)
        );
    }

    /// A choice is an index into the option list, by number or by label.
    #[test]
    fn a_choice_index_is_checked_against_the_options() {
        assert_eq!(
            resolve("neighborhood=1").expect("index 1 exists")[2],
            ParamValue::Choice(1)
        );
        assert_eq!(
            resolve("neighborhood=von_neumann").expect("a label")[2],
            ParamValue::Choice(1)
        );
        assert!(resolve("neighborhood=2").is_err(), "there is no third option");
        assert!(resolve("neighborhood=hexagonal").is_err(), "no such label");
    }

    #[test]
    fn an_unknown_parameter_is_refused() {
        assert!(resolve("no_such_param=1").is_err());
        assert!(
            parse_overrides(&["num_agents".to_owned()]).is_err(),
            "no '=' in the pair"
        );
    }

    #[test]
    fn text_of_the_wrong_kind_keeps_the_parser_error() {
        let error = resolve("num_agents=abc").expect_err("not an integer");
        assert_eq!(
            message(&error),
            "parameter 'num_agents': 'abc' is not an integer: invalid digit found in string",
            "the parser's error is the last source"
        );
        let error = resolve("cohesion=high").expect_err("not a number");
        assert!(
            message(&error).ends_with("invalid float literal"),
            "{}",
            message(&error)
        );
    }

    #[test]
    fn a_formatted_value_parses_back_to_itself() {
        let mut descriptors = descriptors();
        descriptors.push(bool_param("wrap", "Wrap", true));
        let cases = [
            (0, ParamValue::U32(1)),
            (0, ParamValue::U32(5_000_000)),
            (1, ParamValue::F32(0.0)),
            (1, ParamValue::F32(0.1)),
            (1, ParamValue::F32(1.0 / 3.0)),
            (1, ParamValue::F32(f32::from_bits(1))),
            (1, ParamValue::F32(1.0)),
            (2, ParamValue::Choice(0)),
            (2, ParamValue::Choice(1)),
            (3, ParamValue::Bool(false)),
            (3, ParamValue::Bool(true)),
        ];
        for (index, value) in cases {
            let kind = &descriptors[index].kind;
            let text = format_value(kind, &value);
            assert_eq!(parse_value(kind, &text), Ok(value), "{text}");
        }
        assert_eq!(
            format_value(&descriptors[2].kind, &ParamValue::Choice(1)),
            "von_neumann"
        );
    }

    /// A name that looks like a number is matched as a name first. Read as an index, option "0" at index 1 would
    /// come back as option 0.
    #[test]
    fn a_choice_reads_an_option_name_before_an_index() {
        let kind = ParamKind::Choice {
            options: &["low", "0"],
            default: 0,
        };
        assert_eq!(parse_value(&kind, "0"), Ok(ParamValue::Choice(1)), "the name wins");
        assert_eq!(
            parse_value(&kind, "1"),
            Ok(ParamValue::Choice(1)),
            "an index still reads"
        );
        let kind = ParamKind::Choice {
            options: &["low", "2"],
            default: 0,
        };
        for index in 0..2 {
            let value = ParamValue::Choice(index);
            assert_eq!(parse_value(&kind, &format_value(&kind, &value)), Ok(value));
        }
    }

    #[test]
    fn a_value_that_does_not_fit_its_kind_is_refused() {
        let descriptors = descriptors();
        assert!(check_value(&descriptors[0].kind, &ParamValue::F32(10.0)).is_err());
        assert!(check_value(&descriptors[1].kind, &ParamValue::U32(0)).is_err());
        assert!(check_value(&descriptors[1].kind, &ParamValue::F32(f32::INFINITY)).is_err());
        assert!(check_value(&descriptors[2].kind, &ParamValue::Choice(2)).is_err());
        assert_eq!(check_value(&descriptors[2].kind, &ParamValue::Choice(1)), Ok(()));
    }

    /// The message for a value of another kind includes the literal that fits.
    #[test]
    fn a_value_of_another_kind_names_both_kinds() {
        let descriptors = descriptors();
        let error = check_value(&descriptors[1].kind, &ParamValue::U32(1)).expect_err("a u32 for an f32");
        assert_eq!(
            error,
            ValueError::WrongKind {
                expected: ValueKind::F32,
                found: ValueKind::U32,
                value: "1".to_owned(),
            }
        );
        assert_eq!(
            error.to_string(),
            "expected an f32 value such as 1.0f32, found the u32 1"
        );
        let error = check_value(&descriptors[0].kind, &ParamValue::F32(256.0)).expect_err("an f32 for a u32");
        assert_eq!(
            error.to_string(),
            "expected a u32 value such as 1u32, found the f32 256"
        );
        let error = check_value(&descriptors[2].kind, &ParamValue::U32(1)).expect_err("a u32 for a choice");
        assert!(
            matches!(
                error,
                ValueError::WrongKind {
                    expected: ValueKind::Choice,
                    found: ValueKind::U32,
                    ..
                }
            ),
            "{error:?}"
        );
        assert_eq!(
            error.to_string(),
            "expected a choice such as ParamValue::Choice(0), found the u32 1"
        );
        let wrap = bool_param("wrap", "Wrap", true);
        let error = check_value(&wrap.kind, &ParamValue::Choice(0)).expect_err("a choice for a bool");
        assert_eq!(error.to_string(), "expected a bool value, found the choice 0");
    }
}