roma_lib 0.1.1

A Rust metaheuristics framework inspired by jMetal for optimization and experimentation.
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::io::{Error, ErrorKind};
use std::path::Path;

#[derive(Debug, Clone)]
enum JsonValue {
    Object(BTreeMap<String, JsonValue>),
    Array(Vec<JsonValue>),
    String(String),
    Number(String),
    Bool(bool),
    Null,
}

#[derive(Debug, Clone)]
enum PathToken {
    Key(String),
    Index(usize),
}

struct JsonParser<'a> {
    input: &'a [u8],
    index: usize,
}

impl<'a> JsonParser<'a> {
    fn new(input: &'a str) -> Self {
        Self {
            input: input.as_bytes(),
            index: 0,
        }
    }

    fn parse(mut self) -> Result<JsonValue, String> {
        self.skip_whitespace();
        let value = self.parse_value()?;
        self.skip_whitespace();

        if self.index != self.input.len() {
            return Err("Unexpected trailing characters in JSON".to_string());
        }

        Ok(value)
    }

    fn parse_value(&mut self) -> Result<JsonValue, String> {
        self.skip_whitespace();
        match self.peek_byte() {
            Some(b'{') => self.parse_object(),
            Some(b'[') => self.parse_array(),
            Some(b'"') => Ok(JsonValue::String(self.parse_string()?)),
            Some(b't') => self.parse_true(),
            Some(b'f') => self.parse_false(),
            Some(b'n') => self.parse_null(),
            Some(b'-') | Some(b'0'..=b'9') => self.parse_number(),
            _ => Err("Invalid JSON value".to_string()),
        }
    }

    fn parse_object(&mut self) -> Result<JsonValue, String> {
        self.consume_byte(b'{')?;
        self.skip_whitespace();

        let mut map = BTreeMap::new();
        if self.peek_byte() == Some(b'}') {
            self.index += 1;
            return Ok(JsonValue::Object(map));
        }

        loop {
            self.skip_whitespace();
            let key = self.parse_string()?;
            self.skip_whitespace();
            self.consume_byte(b':')?;
            self.skip_whitespace();
            let value = self.parse_value()?;
            map.insert(key, value);
            self.skip_whitespace();

            match self.peek_byte() {
                Some(b',') => {
                    self.index += 1;
                }
                Some(b'}') => {
                    self.index += 1;
                    break;
                }
                _ => return Err("Expected ',' or '}' in JSON object".to_string()),
            }
        }

        Ok(JsonValue::Object(map))
    }

    fn parse_array(&mut self) -> Result<JsonValue, String> {
        self.consume_byte(b'[')?;
        self.skip_whitespace();

        let mut values = Vec::new();
        if self.peek_byte() == Some(b']') {
            self.index += 1;
            return Ok(JsonValue::Array(values));
        }

        loop {
            self.skip_whitespace();
            values.push(self.parse_value()?);
            self.skip_whitespace();

            match self.peek_byte() {
                Some(b',') => {
                    self.index += 1;
                }
                Some(b']') => {
                    self.index += 1;
                    break;
                }
                _ => return Err("Expected ',' or ']' in JSON array".to_string()),
            }
        }

        Ok(JsonValue::Array(values))
    }

    fn parse_string(&mut self) -> Result<String, String> {
        self.consume_byte(b'"')?;
        let mut result = String::new();

        while let Some(ch) = self.next_byte() {
            match ch {
                b'"' => return Ok(result),
                b'\\' => {
                    let escaped = self
                        .next_byte()
                        .ok_or_else(|| "Unexpected end of input in string escape".to_string())?;
                    match escaped {
                        b'"' => result.push('"'),
                        b'\\' => result.push('\\'),
                        b'/' => result.push('/'),
                        b'b' => result.push('\u{0008}'),
                        b'f' => result.push('\u{000C}'),
                        b'n' => result.push('\n'),
                        b'r' => result.push('\r'),
                        b't' => result.push('\t'),
                        b'u' => {
                            let code_point = self.parse_unicode_escape()?;
                            let Some(decoded) = char::from_u32(code_point) else {
                                return Err("Invalid unicode escape sequence".to_string());
                            };
                            result.push(decoded);
                        }
                        _ => return Err("Invalid escape sequence in JSON string".to_string()),
                    }
                }
                _ => result.push(ch as char),
            }
        }

        Err("Unterminated JSON string".to_string())
    }

    fn parse_unicode_escape(&mut self) -> Result<u32, String> {
        let mut value = 0u32;
        for _ in 0..4 {
            let byte = self
                .next_byte()
                .ok_or_else(|| "Unexpected end while parsing unicode escape".to_string())?;
            value = (value << 4)
                + match byte {
                    b'0'..=b'9' => (byte - b'0') as u32,
                    b'a'..=b'f' => 10 + (byte - b'a') as u32,
                    b'A'..=b'F' => 10 + (byte - b'A') as u32,
                    _ => return Err("Invalid unicode escape digit".to_string()),
                };
        }
        Ok(value)
    }

    fn parse_number(&mut self) -> Result<JsonValue, String> {
        let start = self.index;

        if self.peek_byte() == Some(b'-') {
            self.index += 1;
        }

        self.consume_digits()?;

        if self.peek_byte() == Some(b'.') {
            self.index += 1;
            self.consume_digits()?;
        }

        if matches!(self.peek_byte(), Some(b'e') | Some(b'E')) {
            self.index += 1;
            if matches!(self.peek_byte(), Some(b'+') | Some(b'-')) {
                self.index += 1;
            }
            self.consume_digits()?;
        }

        let text = std::str::from_utf8(&self.input[start..self.index])
            .map_err(|_| "Invalid number encoding".to_string())?
            .to_string();

        Ok(JsonValue::Number(text))
    }

    fn consume_digits(&mut self) -> Result<(), String> {
        let mut consumed = false;
        while matches!(self.peek_byte(), Some(b'0'..=b'9')) {
            consumed = true;
            self.index += 1;
        }

        if !consumed {
            return Err("Expected at least one digit".to_string());
        }

        Ok(())
    }

    fn parse_true(&mut self) -> Result<JsonValue, String> {
        self.consume_literal(b"true")?;
        Ok(JsonValue::Bool(true))
    }

    fn parse_false(&mut self) -> Result<JsonValue, String> {
        self.consume_literal(b"false")?;
        Ok(JsonValue::Bool(false))
    }

    fn parse_null(&mut self) -> Result<JsonValue, String> {
        self.consume_literal(b"null")?;
        Ok(JsonValue::Null)
    }

    fn consume_literal(&mut self, literal: &[u8]) -> Result<(), String> {
        for expected in literal {
            let byte = self
                .next_byte()
                .ok_or_else(|| "Unexpected end while parsing JSON literal".to_string())?;
            if &byte != expected {
                return Err("Invalid JSON literal".to_string());
            }
        }
        Ok(())
    }

    fn consume_byte(&mut self, expected: u8) -> Result<(), String> {
        let byte = self
            .next_byte()
            .ok_or_else(|| format!("Expected byte '{}', found end of input", expected as char))?;
        if byte != expected {
            return Err(format!(
                "Expected byte '{}', found '{}'",
                expected as char, byte as char
            ));
        }

        Ok(())
    }

    fn skip_whitespace(&mut self) {
        while matches!(self.peek_byte(), Some(b' ' | b'\n' | b'\r' | b'\t')) {
            self.index += 1;
        }
    }

    fn peek_byte(&self) -> Option<u8> {
        self.input.get(self.index).copied()
    }

    fn next_byte(&mut self) -> Option<u8> {
        let out = self.peek_byte();
        if out.is_some() {
            self.index += 1;
        }
        out
    }
}

fn parse_json_path(path: &str) -> Result<Vec<PathToken>, String> {
    if path.trim().is_empty() {
        return Ok(Vec::new());
    }

    let bytes = path.as_bytes();
    let mut index = 0usize;
    let mut tokens = Vec::new();

    while index < bytes.len() {
        if bytes[index] == b'.' {
            index += 1;
            continue;
        }

        if bytes[index] == b'[' {
            index += 1;
            let start = index;
            while index < bytes.len() && bytes[index].is_ascii_digit() {
                index += 1;
            }

            if start == index {
                return Err("Array index in path cannot be empty".to_string());
            }

            if index >= bytes.len() || bytes[index] != b']' {
                return Err("Missing closing ']' in path".to_string());
            }

            let number_str = std::str::from_utf8(&bytes[start..index])
                .map_err(|_| "Invalid UTF-8 in array index".to_string())?;
            let idx = number_str
                .parse::<usize>()
                .map_err(|_| "Invalid array index in path".to_string())?;

            tokens.push(PathToken::Index(idx));
            index += 1;
            continue;
        }

        let start = index;
        while index < bytes.len() && bytes[index] != b'.' && bytes[index] != b'[' {
            index += 1;
        }

        let key = std::str::from_utf8(&bytes[start..index])
            .map_err(|_| "Invalid UTF-8 in path key".to_string())?
            .trim();

        if key.is_empty() {
            return Err("Path key cannot be empty".to_string());
        }

        tokens.push(PathToken::Key(key.to_string()));
    }

    Ok(tokens)
}

fn resolve_path<'a>(root: &'a JsonValue, path: &str) -> Result<Option<&'a JsonValue>, String> {
    let tokens = parse_json_path(path)?;
    let mut current = root;

    for token in tokens {
        match token {
            PathToken::Key(key) => {
                let JsonValue::Object(map) = current else {
                    return Ok(None);
                };
                let Some(next) = map.get(&key) else {
                    return Ok(None);
                };
                current = next;
            }
            PathToken::Index(index) => {
                let JsonValue::Array(list) = current else {
                    return Ok(None);
                };
                let Some(next) = list.get(index) else {
                    return Ok(None);
                };
                current = next;
            }
        }
    }

    Ok(Some(current))
}

fn scalar_to_string(value: &JsonValue) -> Option<String> {
    match value {
        JsonValue::String(x) => Some(x.clone()),
        JsonValue::Number(x) => Some(x.clone()),
        JsonValue::Bool(x) => Some(x.to_string()),
        JsonValue::Null => Some("null".to_string()),
        JsonValue::Object(_) | JsonValue::Array(_) => None,
    }
}

fn flatten_to_map(value: &JsonValue, prefix: &str, out: &mut HashMap<String, String>) {
    match value {
        JsonValue::Object(map) => {
            for (key, child) in map {
                let next_prefix = if prefix.is_empty() {
                    key.clone()
                } else {
                    format!("{}.{}", prefix, key)
                };
                flatten_to_map(child, &next_prefix, out);
            }
        }
        JsonValue::Array(items) => {
            for (i, child) in items.iter().enumerate() {
                let next_prefix = format!("{}[{}]", prefix, i);
                flatten_to_map(child, &next_prefix, out);
            }
        }
        _ => {
            if !prefix.is_empty() {
                if let Some(text) = scalar_to_string(value) {
                    out.insert(prefix.to_string(), text);
                }
            }
        }
    }
}

fn parse_json_file(path: &Path) -> std::io::Result<JsonValue> {
    let text = fs::read_to_string(path)?;
    JsonParser::new(&text)
        .parse()
        .map_err(|e| Error::new(ErrorKind::InvalidData, format!("Invalid JSON: {}", e)))
}

/// Reads a scalar value from a JSON string using a path expression.
pub fn get_json_value_from_str(json: &str, key_path: &str) -> std::io::Result<Option<String>> {
    let root = JsonParser::new(json)
        .parse()
        .map_err(|e| Error::new(ErrorKind::InvalidData, format!("Invalid JSON: {}", e)))?;

    let value = resolve_path(&root, key_path)
        .map_err(|e| Error::new(ErrorKind::InvalidInput, format!("Invalid path: {}", e)))?;

    Ok(value.and_then(scalar_to_string))
}

/// Reads a scalar value from JSON using a path expression like `config.algorithm.population` or `items[0].weight`.
pub fn get_json_value(path: &Path, key_path: &str) -> std::io::Result<Option<String>> {
    let root = parse_json_file(path)?;
    let value = resolve_path(&root, key_path)
        .map_err(|e| Error::new(ErrorKind::InvalidInput, format!("Invalid path: {}", e)))?;

    Ok(value.and_then(scalar_to_string))
}

fn array_values_to_strings(items: &[JsonValue]) -> std::io::Result<Vec<String>> {
    let mut values = Vec::with_capacity(items.len());
    for item in items {
        let Some(text) = scalar_to_string(item) else {
            return Err(Error::new(
                ErrorKind::InvalidData,
                "JSON array must contain only scalar values",
            ));
        };
        values.push(text);
    }

    Ok(values)
}

fn number_from_json_value(value: &JsonValue) -> std::io::Result<f64> {
    let Some(text) = scalar_to_string(value) else {
        return Err(Error::new(
            ErrorKind::InvalidData,
            "JSON value must be a scalar number",
        ));
    };

    text.parse::<f64>().map_err(|_| {
        Error::new(
            ErrorKind::InvalidData,
            format!("JSON value '{}' is not a valid f64", text),
        )
    })
}
 
/// Reads a scalar array from a JSON string using a path expression.
pub fn get_json_array_values_from_str(json: &str, key_path: &str) -> std::io::Result<Vec<String>> {
    let root = JsonParser::new(json)
        .parse()
        .map_err(|e| Error::new(ErrorKind::InvalidData, format!("Invalid JSON: {}", e)))?;

    let value = resolve_path(&root, key_path)
        .map_err(|e| Error::new(ErrorKind::InvalidInput, format!("Invalid path: {}", e)))?;

    let Some(value) = value else {
        return Ok(Vec::new());
    };

    let JsonValue::Array(items) = value else {
        return Err(Error::new(
            ErrorKind::InvalidData,
            "JSON path must point to an array",
        ));
    };

    array_values_to_strings(items)
}

/// Reads a scalar array from a JSON file using a path expression.
pub fn get_json_array_values(path: &Path, key_path: &str) -> std::io::Result<Vec<String>> {
    let root = parse_json_file(path)?;
    let value = resolve_path(&root, key_path)
        .map_err(|e| Error::new(ErrorKind::InvalidInput, format!("Invalid path: {}", e)))?;

    let Some(value) = value else {
        return Ok(Vec::new());
    };

    let JsonValue::Array(items) = value else {
        return Err(Error::new(
            ErrorKind::InvalidData,
            "JSON path must point to an array",
        ));
    };

    array_values_to_strings(items)
}

/// Reads an array-of-arrays numeric matrix from a JSON string using a path expression.
pub fn get_json_number_matrix_from_str(
    json: &str,
    key_path: &str,
) -> std::io::Result<Vec<Vec<f64>>> {
    let root = JsonParser::new(json)
        .parse()
        .map_err(|e| Error::new(ErrorKind::InvalidData, format!("Invalid JSON: {}", e)))?;

    let value = resolve_path(&root, key_path)
        .map_err(|e| Error::new(ErrorKind::InvalidInput, format!("Invalid path: {}", e)))?;

    let Some(value) = value else {
        return Ok(Vec::new());
    };

    let JsonValue::Array(rows) = value else {
        return Err(Error::new(
            ErrorKind::InvalidData,
            "JSON path must point to an array of arrays",
        ));
    };

    let mut matrix = Vec::with_capacity(rows.len());
    for row in rows {
        let JsonValue::Array(cells) = row else {
            return Err(Error::new(
                ErrorKind::InvalidData,
                "JSON matrix rows must be arrays",
            ));
        };

        let mut parsed_row = Vec::with_capacity(cells.len());
        for cell in cells {
            parsed_row.push(number_from_json_value(cell)?);
        }
        matrix.push(parsed_row);
    }

    Ok(matrix)
}

/// Reads an array-of-arrays numeric matrix from a JSON file using a path expression.
pub fn get_json_number_matrix(path: &Path, key_path: &str) -> std::io::Result<Vec<Vec<f64>>> {
    let root = parse_json_file(path)?;
    let value = resolve_path(&root, key_path)
        .map_err(|e| Error::new(ErrorKind::InvalidInput, format!("Invalid path: {}", e)))?;

    let Some(value) = value else {
        return Ok(Vec::new());
    };

    let JsonValue::Array(rows) = value else {
        return Err(Error::new(
            ErrorKind::InvalidData,
            "JSON path must point to an array of arrays",
        ));
    };

    let mut matrix = Vec::with_capacity(rows.len());
    for row in rows {
        let JsonValue::Array(cells) = row else {
            return Err(Error::new(
                ErrorKind::InvalidData,
                "JSON matrix rows must be arrays",
            ));
        };

        let mut parsed_row = Vec::with_capacity(cells.len());
        for cell in cells {
            parsed_row.push(number_from_json_value(cell)?);
        }
        matrix.push(parsed_row);
    }

    Ok(matrix)
}

/// Reads an array of JSON objects and flattens each object into a map.
///
/// If `records_path` is empty, the root value is expected to be an array.
/// Otherwise, the value at the provided path must be an array.
pub fn read_json_records(
    path: &Path,
    records_path: &str,
) -> std::io::Result<Vec<HashMap<String, String>>> {
    let root = parse_json_file(path)?;
    let target = if records_path.trim().is_empty() {
        Some(&root)
    } else {
        resolve_path(&root, records_path)
            .map_err(|e| Error::new(ErrorKind::InvalidInput, format!("Invalid path: {}", e)))?
    };

    let Some(value) = target else {
        return Ok(Vec::new());
    };

    let JsonValue::Array(items) = value else {
        return Err(Error::new(
            ErrorKind::InvalidData,
            "JSON records path must point to an array",
        ));
    };

    let mut records = Vec::new();
    for item in items {
        let JsonValue::Object(map) = item else {
            continue;
        };
        let mut record = HashMap::new();
        flatten_to_map(&JsonValue::Object(map.clone()), "", &mut record);
        records.push(record);
    }

    Ok(records)
}

#[cfg(test)]
mod tests {
    use super::{
        get_json_array_values_from_str, get_json_number_matrix_from_str, get_json_value_from_str,
    };

    #[test]
    fn reads_scalar_value_from_json_path() {
        let json = r#"{"config":{"budget":{"type":"iterations","value":120}}}"#;

        let value = get_json_value_from_str(json, "config.budget.type")
            .expect("json path lookup should succeed");

        assert_eq!(value.as_deref(), Some("iterations"));
    }

    #[test]
    fn reads_scalar_array_values_from_json_path() {
        let json = r#"{"seeds":[42,43,44]}"#;

        let values = get_json_array_values_from_str(json, "seeds")
            .expect("json array lookup should succeed");

        assert_eq!(values, vec!["42", "43", "44"]);
    }

    #[test]
    fn reads_number_matrix_from_json_path() {
        let json = r#"{"distance_matrix":[[0.0,1.5],[1.5,0.0]]}"#;

        let matrix = get_json_number_matrix_from_str(json, "distance_matrix")
            .expect("json matrix lookup should succeed");

        assert_eq!(matrix, vec![vec![0.0, 1.5], vec![1.5, 0.0]]);
    }
}