Debian Codegraph @

debian/missing-sources/nalgebra/src/io/matrix_market.rs

raw
1 use std::fs;
2 use std::path::Path;
3
4 use crate::RealField;
5 use crate::sparse::CsMatrix;
6 use pest::Parser;
7
8 #[derive(Parser)]
9 #[grammar = "io/matrix_market.pest"]
10 struct MatrixMarketParser;
11
12 // TODO: return an Error instead of an Option.
13 /// Parses a Matrix Market file at the given path, and returns the corresponding sparse matrix.
14 pub fn cs_matrix_from_matrix_market<T: RealField, P: AsRef<Path>>(path: P) -> Option<CsMatrix<T>> {
15 let file = fs::read_to_string(path).ok()?;
16 cs_matrix_from_matrix_market_str(&file)
17 }
18
19 // TODO: return an Error instead of an Option.
20 /// Parses a Matrix Market file described by the given string, and returns the corresponding sparse matrix.
21 pub fn cs_matrix_from_matrix_market_str<T: RealField>(data: &str) -> Option<CsMatrix<T>> {
22 let file = MatrixMarketParser::parse(Rule::Document, data)
23 .unwrap()
24 .next()?;
25 let mut shape = (0, 0, 0);
26 let mut rows: Vec<usize> = Vec::new();
27 let mut cols: Vec<usize> = Vec::new();
28 let mut data: Vec<T> = Vec::new();
29
30 for line in file.into_inner() {
31 match line.as_rule() {
32 Rule::Header => {}
33 Rule::Shape => {
34 let mut inner = line.into_inner();
35 shape.0 = inner.next()?.as_str().parse::<usize>().ok()?;
36 shape.1 = inner.next()?.as_str().parse::<usize>().ok()?;
37 shape.2 = inner.next()?.as_str().parse::<usize>().ok()?;
38 }
39 Rule::Entry => {
40 let mut inner = line.into_inner();
41 // NOTE: indices are 1-based.
42 rows.push(inner.next()?.as_str().parse::<usize>().ok()? - 1);
43 cols.push(inner.next()?.as_str().parse::<usize>().ok()? - 1);
44 data.push(crate::convert(inner.next()?.as_str().parse::<f64>().ok()?));
45 }
46 _ => return None, // TODO: return an Err instead.
47 }
48 }
49
50 Some(CsMatrix::from_triplet(
51 shape.0, shape.1, &rows, &cols, &data,
52 ))
53 }