mocktave 0.1.3

Run Octave/MATLAB from Rust
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
use std::fmt::{Display, Error, Formatter};
use std::num::ParseFloatError;
use std::{collections::HashMap, str::FromStr};

use regex::{Captures, Match};

use human_regex::{
    any, beginning, digit, end, exactly, multi_line_mode, named_capture, one_or_more, or,
    printable, text, whitespace, word, zero_or_more, zero_or_one,
};

/// Possible types that can be returned from Octave through this library. These can also be used to
/// create convenient inputs to a function created using `wrap`
/// ```
/// use mocktave::OctaveType;
/// ```
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub enum OctaveType {
    Scalar(f64),
    Matrix(Vec<Vec<f64>>),
    String(String),
    CellArray(Vec<Vec<OctaveType>>),
    Empty,
    Error(String),
}

impl Default for OctaveType {
    fn default() -> Self {
        OctaveType::Empty
    }
}

impl Display for OctaveType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match &self {
                OctaveType::Scalar(scalar) => {
                    format!("{scalar}")
                }
                OctaveType::Matrix(vec) => {
                    format!("{vec:?}")
                }
                OctaveType::String(string) => {
                    format!("{string}")
                }
                OctaveType::CellArray(ot) => {
                    format!("{ot:?}")
                }
                OctaveType::Empty => {
                    format!("")
                }
                OctaveType::Error(message) => {
                    format!("Error: {message}")
                }
            }
        )
    }
}

impl OctaveType {
    /// Unwrap a scalar octave type into f64
    /// ```
    /// let x: f64 = mocktave::OctaveType::Scalar(0.0).try_into_f64().unwrap();
    /// ```
    pub fn try_into_f64(self) -> Result<f64, ()> {
        if let OctaveType::Scalar(value) = self {
            return Ok(value.into());
        } else {
            Err(())
        }
    }
    /// Unwrap a string octave type into String
    /// ```
    /// let x: String = mocktave::OctaveType::String("0.0".to_string()).try_into_string().unwrap();
    /// ```
    pub fn try_into_string(self) -> Result<String, ()> {
        if let OctaveType::String(value) = self {
            return Ok(value);
        } else {
            Err(())
        }
    }
    /// Unwrap a matrix octave type into vec<vec<f64>>
    /// ```
    /// let x: Vec<Vec<f64>> = mocktave::OctaveType::Matrix(vec![vec![0.0_f64;2];2]).try_into_vec_f64().unwrap();
    /// ```
    pub fn try_into_vec_f64(self) -> Result<Vec<Vec<f64>>, ()> {
        if let OctaveType::Matrix(value) = self {
            return Ok(value);
        } else {
            Err(())
        }
    }
    /// Unwrap a cell array octave type into vec<vec<octavetype>>
    /// ```
    /// let x: Vec<Vec<mocktave::OctaveType>> = mocktave::OctaveType::CellArray(vec![vec![mocktave::OctaveType::Scalar(1.0)]]).try_into_vec_octave_type().unwrap();
    /// ```
    pub fn try_into_vec_octave_type(self) -> Result<Vec<Vec<OctaveType>>, ()> {
        if let OctaveType::CellArray(value) = self {
            return Ok(value);
        } else {
            Err(())
        }
    }
}

/// Contains the workspace that resulted from running the octave command in `eval`
#[derive(Debug, Clone)]
pub struct InterpreterResults {
    /// Raw output
    pub raw: String,
    /// Scalar variables
    scalars: HashMap<String, f64>,
    /// Matrix variables
    matrices: HashMap<String, Vec<Vec<f64>>>,
    /// String variables
    strings: HashMap<String, String>,
    /// String variables
    cell_arrays: HashMap<String, OctaveType>,
}

impl InterpreterResults {
    /// Get unchecked
    pub fn get_unchecked(&self, name: &str) -> OctaveType {
        match self.get_scalar_named(name) {
            None => match self.get_matrix_named(name) {
                None => match self.get_string_named(name) {
                    None => match self.get_cell_array_named(name) {
                        None => OctaveType::Empty,
                        Some(cell_array) => cell_array,
                    },
                    Some(string) => OctaveType::String(string),
                },
                Some(matrix) => OctaveType::Matrix(matrix),
            },
            Some(scalar) => OctaveType::Scalar(scalar),
        }
    }
    /// Get a scalar by name
    pub fn get_scalar_named(&self, name: &str) -> Option<f64> {
        self.scalars.get(name).cloned()
    }
    /// Get a matrix by name
    pub fn get_matrix_named(&self, name: &str) -> Option<Vec<Vec<f64>>> {
        self.matrices.get(name).cloned()
    }
    /// Get a string by name
    pub fn get_string_named(&self, name: &str) -> Option<String> {
        self.strings.get(name).cloned()
    }
    /// Get a string by name
    pub fn get_cell_array_named(&self, name: &str) -> Option<OctaveType> {
        self.cell_arrays.get(name).cloned()
    }
}

impl Default for InterpreterResults {
    fn default() -> Self {
        InterpreterResults {
            raw: "".to_string(),
            scalars: Default::default(),
            matrices: Default::default(),
            strings: Default::default(),
            cell_arrays: Default::default(),
        }
    }
}
impl From<String> for InterpreterResults {
    fn from(output: String) -> Self {
        // Instantiate results and save raw output
        let mut results = InterpreterResults {
            raw: output.clone(),
            ..Default::default()
        };

        // Make a scalar match and parse the output
        let scalar_match = multi_line_mode(
            beginning()
                + text("# name: ")
                + named_capture(one_or_more(word()), "name")
                + text("\n# type: scalar\n")
                + named_capture(exactly(1, beginning() + one_or_more(any()) + end()), "data"),
        );

        for capture in scalar_match.to_regex().captures_iter(&output) {
            let (name, value) = parse_scalar_capture(capture);
            results.scalars.insert(name, value);
        }

        // Make a string capture and parse the output
        let string_match = multi_line_mode(
            beginning()
                + text("# name: ")
                + named_capture(one_or_more(word()), "name")
                + or(&[text("\n# type: sq_string"), text("\n# type: string")])
                + text("\n# elements: ")
                + named_capture(one_or_more(digit()), "elements")
                + text("\n# length: ")
                + named_capture(one_or_more(digit()), "length")
                + text("\n")
                + named_capture(exactly(1, beginning() + one_or_more(any()) + end()), "data"),
        );

        for capture in string_match.to_regex().captures_iter(&output) {
            let (name, value) = parse_string_capture(capture);
            results.strings.insert(name, value);
        }

        let matrix_match = multi_line_mode(
            beginning()
                + text("# name: ")
                + named_capture(one_or_more(word()), "name")
                + or(&[text("\n# type: matrix"), text("\n# type: diagonal matrix")])
                + text("\n# rows: ")
                + named_capture(one_or_more(digit()), "rows")
                + text("\n# columns: ")
                + named_capture(one_or_more(digit()), "columns")
                + text("\n")
                + named_capture(zero_or_more(one_or_more(printable()) + text("\n")), "data"),
        );

        for capture in matrix_match.to_regex().captures_iter(&output) {
            let (name, value) = parse_matrix_capture(capture);
            results.matrices.insert(name, value);
        }

        // # name: g
        // # type: cell
        // # rows: 1
        // # columns: 2
        // # name: <cell-element>
        // # type: sq_string
        // # elements: 1
        // # length: 1
        // a
        //
        //
        //
        // # name: <cell-element>
        // # type: sq_string
        // # elements: 1
        // # length: 1
        // b
        //
        //

        let cell_array_match = multi_line_mode(
            beginning()
                + text("# name: ")
                + named_capture(one_or_more(word()), "name")
                + text("\n# type: cell")
                + text("\n# rows: ")
                + named_capture(one_or_more(digit()), "rows")
                + text("\n# columns: ")
                + named_capture(one_or_more(digit()), "columns"),
        );

        let cell_element_match = multi_line_mode(
            beginning()
                + named_capture(text("# name: <cell-element>\n"), "name")
                + text("# type: ")
                + named_capture(one_or_more(word()), "type")
                + text("\n# rows: ")
                + zero_or_more(named_capture(one_or_more(digit()), "rows"))
                + text("\n# columns: ")
                + zero_or_more(named_capture(one_or_more(digit()), "columns"))
                + text("\n# elements: ")
                + zero_or_more(named_capture(one_or_more(digit()), "elements"))
                + text("\n# length: ")
                + zero_or_more(named_capture(one_or_more(digit()), "length"))
                + zero_or_one(named_capture(
                    one_or_more(whitespace() + beginning() + one_or_more(any())),
                    "data",
                )),
        );

        for capture in cell_array_match.to_regex().captures_iter(&output) {
            let (name, value) = parse_cell_array_capture(
                capture,
                cell_element_match
                    .to_regex()
                    .captures_iter(&output)
                    .map(|x| x)
                    .collect::<Vec<Captures>>(),
            );
            results.cell_arrays.insert(name, value);
        }

        results
    }
}

fn parse_scalar_capture(capture: Captures) -> (String, f64) {
    (
        capture
            .name("name")
            .expect("Name not found")
            .as_str()
            .to_string(),
        f64::from_str(
            &capture
                .name("data")
                .expect("No value for scalar data.")
                .as_str()
                .replace('\n', ""),
        )
        .expect("Could not parse f64 from string."),
    )
}

fn parse_string_capture(capture: Captures) -> (String, String) {
    let name = capture
        .name("name")
        .expect("Name not found")
        .as_str()
        .to_string();
    (
        name.clone(),
        capture
            .name("data")
            .expect(&format!("No value named {name} for string data."))
            .as_str()
            .to_string(),
    )
}

fn parse_cell_array_capture(
    capture: Captures,
    mut elements: Vec<Captures>,
) -> (String, OctaveType) {
    println!("{elements:?}");

    let name = capture
        .name("name")
        .expect("Name not found")
        .as_str()
        .to_string();

    let rows = usize::from_str(capture.name("rows").expect("No key named rows.").as_str())
        .expect("Could not parse usize from string.");
    let columns = usize::from_str(
        capture
            .name("columns")
            .expect("No key named columns.")
            .as_str(),
    )
    .expect("Could not parse usize from string.");

    let mut cell_array = vec![vec![OctaveType::Empty; columns]; rows];

    //     for i in 0..rows {
    //         for j in 0..columns {
    //             cell_array[i][j] = match element.name("type").unwrap().as_str() {
    //                 "sq_string" | "string" => {
    //                     OctaveType::String(parse_string_capture(element).1.replacen("\n", "", 1))
    //                 }
    //                 "scalar" => OctaveType::Scalar(parse_scalar_capture(element).1),
    //                 "matrix" => OctaveType::Matrix(parse_matrix_capture(element).1),
    //                 &_ => OctaveType::Empty,
    //             };
    //         }
    //     }

    (name, OctaveType::CellArray(cell_array))
}

fn parse_matrix_capture(capture: Captures) -> (String, Vec<Vec<f64>>) {
    let name = capture
        .name("name")
        .expect("Name not found")
        .as_str()
        .to_string();
    let rows = usize::from_str(capture.name("rows").expect("No key named rows.").as_str())
        .expect("Could not parse usize from string.");
    let columns = usize::from_str(
        capture
            .name("columns")
            .expect("No key named columns.")
            .as_str(),
    )
    .expect("Could not parse usize from string.");

    let mut matrix = vec![vec![0.0_f64; columns]; rows];
    matrix = match capture.name("data") {
        None => matrix,
        Some(s) => {
            if capture.get(2).unwrap().as_str().contains("diagonal") {
                s.as_str()
                    .replacen('\n', " ", rows - 1)
                    .replace('\n', "")
                    .split(' ')
                    .map(|elem| match f64::from_str(elem) {
                        Ok(val) => val,
                        Err(_) => f64::NAN,
                    })
                    .enumerate()
                    .map(|(idx, element)| matrix[idx][idx] = element)
                    .for_each(drop);
            } else {
                let data = s
                    .as_str()
                    .replacen(' ', "", 1)
                    .replace('\n', "")
                    .split(' ')
                    .map(|elem| match f64::from_str(elem) {
                        Ok(val) => val,
                        Err(_) => f64::NAN,
                    })
                    .collect::<Vec<f64>>();
                let mut counter: usize = 0;
                for i in 0..rows {
                    for j in 0..columns {
                        matrix[i][j] = data[counter];
                        counter += 1;
                    }
                }
            }
            matrix
        }
    };

    (name, matrix)
}