Skip to main content

lib_jsl_file_io/
matrix_market.rs

1//! Matrix Market exchange files (SciPy's `io.mmread`, `io.mmwrite` and `io.mminfo`).
2//!
3//! A Matrix Market file is text: a banner `%%MatrixMarket matrix <format> <field> <symmetry>`,
4//! comment lines starting with `%`, a size line, and the entries. The `coordinate` format lists
5//! `row column value` triplets (1-based) of a sparse matrix; the `array` format lists every entry
6//! of a dense matrix in column-major order. The field is `real`, `integer`, `complex` or
7//! `pattern` (no values); the symmetry `general`, `symmetric`, `skew-symmetric` or `hermitian`,
8//! in which case only the lower triangle is stored.
9//!
10//! See the book entry [Scientific data files](https://jwkunz.github.io/lib_jsl/book/foundations/scientific-files.html#matrix-market).
11
12use lib_jsl_core::ErrorsJSL;
13use ndarray::Array2;
14use num_complex::Complex;
15use std::path::Path;
16
17type C64 = Complex<f64>;
18
19/// Sparse triplets or a dense array.
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21#[non_exhaustive]
22pub enum MmFormat {
23    Coordinate,
24    Array,
25}
26
27/// The type of the entries.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29#[non_exhaustive]
30pub enum MmField {
31    Real,
32    Integer,
33    Complex,
34    /// Only the positions of the non-zeros (coordinate format).
35    Pattern,
36}
37
38/// Which part of the matrix is stored.
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40#[non_exhaustive]
41pub enum MmSymmetry {
42    General,
43    Symmetric,
44    SkewSymmetric,
45    Hermitian,
46}
47
48/// A matrix read from (or to be written to) a Matrix Market file. The entries are always the
49/// full matrix — symmetric files are expanded on reading, as SciPy's `mmread` does — as 0-based
50/// triplets; values are complex so one type serves every field (the imaginary part is zero
51/// unless the field is complex, and the value is 1 for pattern files).
52#[derive(Clone, Debug, PartialEq)]
53#[non_exhaustive]
54pub struct MatrixMarket {
55    pub nrows: usize,
56    pub ncols: usize,
57    pub format: MmFormat,
58    pub field: MmField,
59    pub symmetry: MmSymmetry,
60    pub rows: Vec<usize>,
61    pub cols: Vec<usize>,
62    pub values: Vec<C64>,
63    /// The comment lines, without their leading `%`.
64    pub comment: String,
65}
66
67impl MatrixMarket {
68    /// A sparse real matrix from 0-based triplets (general, real).
69    pub fn from_triplets(nrows: usize, ncols: usize, rows: Vec<usize>, cols: Vec<usize>, values: Vec<f64>) -> Result<Self, ErrorsJSL> {
70        if rows.len() != cols.len() || rows.len() != values.len() {
71            return Err(ErrorsJSL::IncompatibleArraySizes((rows.len(), values.len())));
72        }
73        if rows.iter().any(|&r| r >= nrows) || cols.iter().any(|&c| c >= ncols) {
74            return Err(ErrorsJSL::InvalidInputRange("MatrixMarket: an index is out of range"));
75        }
76        Ok(MatrixMarket {
77            nrows,
78            ncols,
79            format: MmFormat::Coordinate,
80            field: MmField::Real,
81            symmetry: MmSymmetry::General,
82            rows,
83            cols,
84            values: values.into_iter().map(|v| C64::new(v, 0.0)).collect(),
85            comment: String::new(),
86        })
87    }
88
89    /// A dense real matrix (array format, general).
90    pub fn from_dense(a: &Array2<f64>) -> Self {
91        let (nrows, ncols) = a.dim();
92        let (mut rows, mut cols, mut values) = (Vec::new(), Vec::new(), Vec::new());
93        for j in 0..ncols {
94            for i in 0..nrows {
95                rows.push(i);
96                cols.push(j);
97                values.push(C64::new(a[(i, j)], 0.0));
98            }
99        }
100        MatrixMarket { nrows, ncols, format: MmFormat::Array, field: MmField::Real, symmetry: MmSymmetry::General, rows, cols, values, comment: String::new() }
101    }
102
103    /// The same matrix with a different field or symmetry declared for writing (the entries
104    /// must be consistent with it: integers for `Integer`, and for a symmetry the full matrix,
105    /// of which the lower triangle is written).
106    pub fn with_field(mut self, field: MmField) -> Self {
107        self.field = field;
108        self
109    }
110
111    pub fn with_symmetry(mut self, symmetry: MmSymmetry) -> Self {
112        self.symmetry = symmetry;
113        self
114    }
115
116    pub fn with_comment(mut self, comment: &str) -> Self {
117        self.comment = comment.to_string();
118        self
119    }
120
121    /// The matrix as a dense real array (real parts; duplicates summed, as SciPy's conversion
122    /// of a COO matrix does).
123    pub fn to_dense(&self) -> Array2<f64> {
124        let mut a = Array2::zeros((self.nrows, self.ncols));
125        for k in 0..self.values.len() {
126            a[(self.rows[k], self.cols[k])] += self.values[k].re;
127        }
128        a
129    }
130
131    /// The matrix as a dense complex array.
132    pub fn to_dense_complex(&self) -> Array2<C64> {
133        let mut a = Array2::from_elem((self.nrows, self.ncols), C64::new(0.0, 0.0));
134        for k in 0..self.values.len() {
135            a[(self.rows[k], self.cols[k])] += self.values[k];
136        }
137        a
138    }
139}
140
141/// The header information of a Matrix Market file (SciPy's `mminfo`).
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143#[non_exhaustive]
144pub struct MmInfo {
145    pub nrows: usize,
146    pub ncols: usize,
147    /// Stored entries (for symmetric files, before expansion).
148    pub entries: usize,
149    pub format: MmFormat,
150    pub field: MmField,
151    pub symmetry: MmSymmetry,
152}
153
154fn bad(msg: &'static str) -> ErrorsJSL {
155    ErrorsJSL::InvalidInputRange(msg)
156}
157
158fn parse_banner(line: &str) -> Result<(MmFormat, MmField, MmSymmetry), ErrorsJSL> {
159    let words: Vec<String> = line.split_whitespace().map(|w| w.to_ascii_lowercase()).collect();
160    if words.len() != 5 || words[0] != "%%matrixmarket" || words[1] != "matrix" {
161        return Err(bad("Matrix Market: expected the banner %%MatrixMarket matrix <format> <field> <symmetry>"));
162    }
163    let format = match words[2].as_str() {
164        "coordinate" => MmFormat::Coordinate,
165        "array" => MmFormat::Array,
166        _ => return Err(bad("Matrix Market: unknown format")),
167    };
168    let field = match words[3].as_str() {
169        "real" | "double" => MmField::Real,
170        "integer" => MmField::Integer,
171        "complex" => MmField::Complex,
172        "pattern" => MmField::Pattern,
173        _ => return Err(bad("Matrix Market: unknown field")),
174    };
175    let symmetry = match words[4].as_str() {
176        "general" => MmSymmetry::General,
177        "symmetric" => MmSymmetry::Symmetric,
178        "skew-symmetric" => MmSymmetry::SkewSymmetric,
179        "hermitian" => MmSymmetry::Hermitian,
180        _ => return Err(bad("Matrix Market: unknown symmetry")),
181    };
182    if format == MmFormat::Array && field == MmField::Pattern {
183        return Err(bad("Matrix Market: the array format has no pattern field"));
184    }
185    Ok((format, field, symmetry))
186}
187
188/// Splits the text into banner, comments, size line and the remaining tokens.
189/// The banner, comments, size line and the remaining tokens of a file.
190type Parts<'a> = ((MmFormat, MmField, MmSymmetry), String, Vec<usize>, std::str::SplitWhitespace<'a>);
191
192fn split(text: &str) -> Result<Parts<'_>, ErrorsJSL> {
193    let mut rest = text;
194    let mut take_line = || -> Option<&str> {
195        if rest.is_empty() {
196            return None;
197        }
198        let (line, tail) = match rest.find('\n') {
199            Some(p) => (&rest[..p], &rest[p + 1..]),
200            None => (rest, ""),
201        };
202        rest = tail;
203        Some(line.trim_end_matches('\r'))
204    };
205    let banner = parse_banner(take_line().ok_or(bad("Matrix Market: empty file"))?)?;
206    let mut comment = String::new();
207    let size_line = loop {
208        let line = take_line().ok_or(bad("Matrix Market: missing size line"))?;
209        let t = line.trim();
210        if let Some(c) = t.strip_prefix('%') {
211            if !comment.is_empty() {
212                comment.push('\n');
213            }
214            comment.push_str(c);
215        } else if !t.is_empty() {
216            break t.to_string();
217        }
218    };
219    let size: Vec<usize> = size_line.split_whitespace().map(|w| w.parse().map_err(|_| bad("Matrix Market: bad size line"))).collect::<Result<_, _>>()?;
220    let expected = if banner.0 == MmFormat::Coordinate { 3 } else { 2 };
221    if size.len() != expected {
222        return Err(bad("Matrix Market: wrong number of values on the size line"));
223    }
224    Ok((banner, comment, size, rest.split_whitespace()))
225}
226
227/// The header of a Matrix Market file (SciPy's `mminfo`).
228pub fn mm_info(text: &str) -> Result<MmInfo, ErrorsJSL> {
229    let ((format, field, symmetry), _, size, _) = split(text)?;
230    let entries = if format == MmFormat::Coordinate {
231        size[2]
232    } else {
233        let (m, n) = (size[0], size[1]);
234        match symmetry {
235            MmSymmetry::General => m * n,
236            MmSymmetry::SkewSymmetric => n * (n.saturating_sub(1)) / 2,
237            _ => n * (n + 1) / 2,
238        }
239    };
240    Ok(MmInfo { nrows: size[0], ncols: size[1], entries, format, field, symmetry })
241}
242
243// ANCHOR: mm_decode
244/// Parses a Matrix Market file (SciPy's `mmread`). Symmetric, skew-symmetric and Hermitian
245/// matrices are expanded to the full matrix: each stored off-diagonal entry `(i, j, v)` adds
246/// `(j, i, v)`, `(j, i, −v)` or `(j, i, vĖ„)`.
247pub fn mm_decode(text: &str) -> Result<MatrixMarket, ErrorsJSL> {
248    let ((format, field, symmetry), comment, size, mut tokens) = split(text)?;
249    let (nrows, ncols) = (size[0], size[1]);
250    if symmetry != MmSymmetry::General && nrows != ncols {
251        return Err(bad("Matrix Market: a symmetric matrix must be square"));
252    }
253    let mut next_f64 = |what: &'static str| -> Result<f64, ErrorsJSL> {
254        let t = tokens.next().ok_or(bad(what))?;
255        t.parse::<f64>().or_else(|_| t.replace(['d', 'D'], "e").parse::<f64>()).map_err(|_| bad("Matrix Market: a value is not a number"))
256    };
257    let value = |next: &mut dyn FnMut(&'static str) -> Result<f64, ErrorsJSL>| -> Result<C64, ErrorsJSL> {
258        Ok(match field {
259            MmField::Pattern => C64::new(1.0, 0.0),
260            MmField::Complex => {
261                let re = next("Matrix Market: missing value")?;
262                C64::new(re, next("Matrix Market: missing imaginary part")?)
263            }
264            _ => C64::new(next("Matrix Market: missing value")?, 0.0),
265        })
266    };
267    let (mut rows, mut cols, mut values) = (Vec::new(), Vec::new(), Vec::new());
268    let mut push = |i: usize, j: usize, v: C64| {
269        rows.push(i);
270        cols.push(j);
271        values.push(v);
272        if i != j {
273            let mirrored = match symmetry {
274                MmSymmetry::General => return,
275                MmSymmetry::Symmetric => v,
276                MmSymmetry::SkewSymmetric => -v,
277                MmSymmetry::Hermitian => v.conj(),
278            };
279            rows.push(j);
280            cols.push(i);
281            values.push(mirrored);
282        }
283    };
284    match format {
285        MmFormat::Coordinate => {
286            for _ in 0..size[2] {
287                let i = next_f64("Matrix Market: missing row index")?;
288                let j = next_f64("Matrix Market: missing column index")?;
289                if !(i >= 1.0 && j >= 1.0 && i <= nrows as f64 && j <= ncols as f64 && i.fract() == 0.0 && j.fract() == 0.0) {
290                    return Err(bad("Matrix Market: an index is out of range"));
291                }
292                let v = value(&mut next_f64)?;
293                push(i as usize - 1, j as usize - 1, v);
294            }
295        }
296        MmFormat::Array => {
297            for j in 0..ncols {
298                let start = match symmetry {
299                    MmSymmetry::General => 0,
300                    MmSymmetry::SkewSymmetric => j + 1,
301                    _ => j,
302                };
303                for i in start..nrows {
304                    let v = value(&mut next_f64)?;
305                    push(i, j, v);
306                }
307                if symmetry == MmSymmetry::SkewSymmetric {
308                    push(j, j, C64::new(0.0, 0.0));
309                }
310            }
311        }
312    }
313    Ok(MatrixMarket { nrows, ncols, format, field, symmetry, rows, cols, values, comment })
314}
315// ANCHOR_END: mm_decode
316
317fn fmt_real(v: f64) -> String {
318    // The shortest representation that reads back exactly, in exponent form like SciPy's.
319    if v == 0.0 { "0.0000000000000000e+00".to_string() } else { format!("{v:e}") }
320}
321
322/// Writes a Matrix Market file (SciPy's `mmwrite`): the coordinate or array format as declared,
323/// with only the lower triangle for a symmetric matrix (the strictly lower one for a
324/// skew-symmetric one). Values are written in the shortest form that reads back exactly.
325pub fn mm_encode(m: &MatrixMarket) -> Result<String, ErrorsJSL> {
326    let sym = |s: MmSymmetry| match s {
327        MmSymmetry::General => "general",
328        MmSymmetry::Symmetric => "symmetric",
329        MmSymmetry::SkewSymmetric => "skew-symmetric",
330        MmSymmetry::Hermitian => "hermitian",
331    };
332    let fld = match m.field {
333        MmField::Real => "real",
334        MmField::Integer => "integer",
335        MmField::Complex => "complex",
336        MmField::Pattern => "pattern",
337    };
338    if m.format == MmFormat::Array && m.field == MmField::Pattern {
339        return Err(bad("Matrix Market: the array format has no pattern field"));
340    }
341    if m.symmetry != MmSymmetry::General && m.nrows != m.ncols {
342        return Err(bad("Matrix Market: a symmetric matrix must be square"));
343    }
344    let fmt = match m.format {
345        MmFormat::Coordinate => "coordinate",
346        MmFormat::Array => "array",
347    };
348    let mut out = format!("%%MatrixMarket matrix {fmt} {fld} {}\n", sym(m.symmetry));
349    for line in m.comment.lines() {
350        out.push('%');
351        out.push_str(line);
352        out.push('\n');
353    }
354    let val = |v: C64| -> String {
355        match m.field {
356            MmField::Pattern => String::new(),
357            MmField::Integer => format!(" {}", v.re as i64),
358            MmField::Complex => format!(" {} {}", fmt_real(v.re), fmt_real(v.im)),
359            MmField::Real => format!(" {}", fmt_real(v.re)),
360        }
361    };
362    let keep = |i: usize, j: usize| match m.symmetry {
363        MmSymmetry::General => true,
364        MmSymmetry::SkewSymmetric => i > j,
365        _ => i >= j,
366    };
367    match m.format {
368        MmFormat::Coordinate => {
369            let idx: Vec<usize> = (0..m.values.len()).filter(|&k| keep(m.rows[k], m.cols[k])).collect();
370            out.push_str(&format!("{} {} {}\n", m.nrows, m.ncols, idx.len()));
371            for k in idx {
372                out.push_str(&format!("{} {}{}\n", m.rows[k] + 1, m.cols[k] + 1, val(m.values[k])));
373            }
374        }
375        MmFormat::Array => {
376            let a = m.to_dense_complex();
377            out.push_str(&format!("{} {}\n", m.nrows, m.ncols));
378            for j in 0..m.ncols {
379                for i in 0..m.nrows {
380                    if keep(i, j) {
381                        out.push_str(val(a[(i, j)]).trim_start());
382                        out.push('\n');
383                    }
384                }
385            }
386        }
387    }
388    Ok(out)
389}
390
391/// Reads a Matrix Market file.
392pub fn read_mm_file(path: impl AsRef<Path>) -> Result<MatrixMarket, ErrorsJSL> {
393    let text = std::fs::read_to_string(path).map_err(|_| ErrorsJSL::RuntimeError("could not read the Matrix Market file"))?;
394    mm_decode(&text)
395}
396
397/// Writes a Matrix Market file.
398pub fn write_mm_file(path: impl AsRef<Path>, m: &MatrixMarket) -> Result<(), ErrorsJSL> {
399    std::fs::write(path, mm_encode(m)?).map_err(|_| ErrorsJSL::RuntimeError("could not write the Matrix Market file"))
400}
401
402#[cfg(test)]
403mod tests {
404    use super::*;
405
406    #[test]
407    fn round_trips_and_symmetry_expansion() {
408        let text = "%%MatrixMarket matrix coordinate real symmetric\n% a comment\n3 3 4\n1 1 2.0\n2 1 -1\n3 2 -1.5e0\n3 3 4\n";
409        let m = mm_decode(text).unwrap();
410        assert_eq!(m.comment, " a comment");
411        let a = m.to_dense();
412        assert_eq!(a[(0, 1)], -1.0);
413        assert_eq!(a[(1, 0)], -1.0);
414        assert_eq!(a[(1, 2)], -1.5);
415        assert_eq!(mm_info(text).unwrap().entries, 4);
416        let back = mm_decode(&mm_encode(&m).unwrap()).unwrap();
417        assert_eq!(back.to_dense(), a);
418        // Dense, skew-symmetric array.
419        let s = "%%MatrixMarket matrix array real skew-symmetric\n3 3\n1\n2\n3\n";
420        let d = mm_decode(s).unwrap().to_dense();
421        assert_eq!(d[(1, 0)], 1.0);
422        assert_eq!(d[(0, 1)], -1.0);
423        assert_eq!(d[(2, 1)], 3.0);
424        // Complex Hermitian and pattern.
425        let h = mm_decode("%%MatrixMarket matrix coordinate complex hermitian\n2 2 2\n1 1 1 0\n2 1 0.5 -2\n").unwrap().to_dense_complex();
426        assert_eq!(h[(0, 1)], C64::new(0.5, 2.0));
427        let p = mm_decode("%%MatrixMarket matrix coordinate pattern general\n2 3 2\n1 3\n2 1\n").unwrap();
428        assert_eq!(p.to_dense()[(0, 2)], 1.0);
429        // Exact round trip of awkward values in array format.
430        let x = Array2::from_shape_vec((2, 2), vec![0.1, -1e-300, 1.0 / 3.0, 6.02e23]).unwrap();
431        assert_eq!(mm_decode(&mm_encode(&MatrixMarket::from_dense(&x)).unwrap()).unwrap().to_dense(), x);
432    }
433}