Skip to main content

lib_jsl_file_io/
harwell_boeing.rs

1//! Harwell-Boeing sparse matrix files (SciPy's `io.hb_read` and `io.hb_write`).
2//!
3//! A Harwell-Boeing file is fixed-width Fortran text: a title and key, the numbers of lines in
4//! each section, the matrix type (`RUA`: real, unsymmetric, assembled), the dimensions and
5//! number of entries, the Fortran formats of the sections, and then the 1-based column pointers,
6//! row indices and values of the matrix in compressed sparse column form.
7//!
8//! Reading supports real and pattern matrices, unsymmetric, rectangular, symmetric and
9//! skew-symmetric (expanded to the full matrix, as for Matrix Market), with any integer format
10//! and `E`, `D` or `F` real formats; writing produces `RUA` files laid out as SciPy's.
11//! Complex and elemental matrices and right-hand sides are not supported (nor by SciPy).
12//!
13//! See the book entry [Scientific data files](https://jwkunz.github.io/lib_jsl/book/foundations/scientific-files.html#harwell-boeing).
14
15use lib_jsl_core::ErrorsJSL;
16use std::path::Path;
17
18/// A sparse matrix in compressed sparse column form, as read from or written to a
19/// Harwell-Boeing file (0-based).
20#[derive(Clone, Debug, PartialEq)]
21#[non_exhaustive]
22pub struct HarwellBoeing {
23    pub title: String,
24    pub key: String,
25    pub nrows: usize,
26    pub ncols: usize,
27    /// `ncols + 1` column pointers.
28    pub col_ptr: Vec<usize>,
29    pub row_indices: Vec<usize>,
30    /// The values (1 for a pattern matrix).
31    pub values: Vec<f64>,
32}
33
34impl HarwellBoeing {
35    /// A matrix from compressed sparse column arrays, with SciPy's default title and key.
36    pub fn new(nrows: usize, ncols: usize, col_ptr: Vec<usize>, row_indices: Vec<usize>, values: Vec<f64>) -> Result<Self, ErrorsJSL> {
37        if col_ptr.len() != ncols + 1 || row_indices.len() != values.len() || col_ptr[ncols] != values.len() || col_ptr.windows(2).any(|w| w[1] < w[0]) || row_indices.iter().any(|&r| r >= nrows) {
38            return Err(ErrorsJSL::InvalidInputRange("HarwellBoeing: inconsistent compressed sparse column arrays"));
39        }
40        Ok(HarwellBoeing { title: "Default title".into(), key: "0".into(), nrows, ncols, col_ptr, row_indices, values })
41    }
42
43    /// The matrix as dense rows.
44    #[allow(clippy::needless_range_loop)]
45    pub fn to_dense(&self) -> Vec<Vec<f64>> {
46        let mut a = vec![vec![0.0; self.ncols]; self.nrows];
47        for j in 0..self.ncols {
48            for k in self.col_ptr[j]..self.col_ptr[j + 1] {
49                a[self.row_indices[k]][j] += self.values[k];
50            }
51        }
52        a
53    }
54}
55
56fn bad(msg: &'static str) -> ErrorsJSL {
57    ErrorsJSL::InvalidInputRange(msg)
58}
59
60/// A Fortran edit descriptor `(r Xw.d)`, with an optional scale factor `kP` ignored.
61#[derive(Clone, Copy, Debug)]
62struct FortranFormat {
63    repeat: usize,
64    width: usize,
65}
66
67fn parse_format(f: &str) -> Result<FortranFormat, ErrorsJSL> {
68    let s: String = f.trim().trim_start_matches('(').trim_end_matches(')').to_ascii_uppercase();
69    // Drop a scale factor such as "1P," or "1P".
70    let s = match s.find('P') {
71        Some(p) if s[..p].chars().all(|c| c.is_ascii_digit() || c == '-') => s[p + 1..].trim_start_matches(',').to_string(),
72        _ => s,
73    };
74    let letter = s.find(|c: char| c.is_ascii_alphabetic()).ok_or(bad("Harwell-Boeing: bad format"))?;
75    let repeat = if letter == 0 { 1 } else { s[..letter].parse().map_err(|_| bad("Harwell-Boeing: bad format"))? };
76    let rest = &s[letter + 1..];
77    let width_str = rest.split('.').next().unwrap_or("");
78    let width = width_str.parse().map_err(|_| bad("Harwell-Boeing: bad format width"))?;
79    if !matches!(&s[letter..letter + 1], "I" | "E" | "D" | "F" | "G") {
80        return Err(bad("Harwell-Boeing: unsupported format"));
81    }
82    Ok(FortranFormat { repeat, width })
83}
84
85/// Reads `count` fixed-width fields from the given lines.
86fn read_fields<'a>(lines: &mut impl Iterator<Item = &'a str>, nlines: usize, fmt: FortranFormat, count: usize) -> Result<Vec<String>, ErrorsJSL> {
87    let mut out = Vec::with_capacity(count);
88    for _ in 0..nlines {
89        let line = lines.next().ok_or(bad("Harwell-Boeing: truncated"))?;
90        let chars: Vec<char> = line.chars().collect();
91        for k in 0..fmt.repeat {
92            if out.len() == count {
93                break;
94            }
95            let (a, b) = (k * fmt.width, ((k + 1) * fmt.width).min(chars.len()));
96            if a >= chars.len() {
97                break;
98            }
99            let field: String = chars[a..b].iter().collect();
100            if !field.trim().is_empty() {
101                out.push(field.trim().to_string());
102            }
103        }
104    }
105    if out.len() != count {
106        return Err(bad("Harwell-Boeing: wrong number of entries in a section"));
107    }
108    Ok(out)
109}
110
111fn int_at(line: &str, from: usize, width: usize) -> Result<usize, ErrorsJSL> {
112    let s: String = line.chars().skip(from).take(width).collect();
113    let s = s.trim();
114    if s.is_empty() {
115        return Ok(0);
116    }
117    s.parse().map_err(|_| bad("Harwell-Boeing: bad integer in the header"))
118}
119
120// ANCHOR: hb_read
121/// Parses a Harwell-Boeing file (SciPy's `hb_read`). Symmetric and skew-symmetric matrices,
122/// which store one triangle, are expanded to the full matrix.
123pub fn hb_decode(text: &str) -> Result<HarwellBoeing, ErrorsJSL> {
124    let mut lines = text.lines();
125    let l1 = lines.next().ok_or(bad("Harwell-Boeing: empty file"))?;
126    let title: String = l1.chars().take(72).collect::<String>().trim_end().to_string();
127    let key: String = l1.chars().skip(72).take(8).collect::<String>().trim().to_string();
128    let l2 = lines.next().ok_or(bad("Harwell-Boeing: missing line 2"))?;
129    let (ptrcrd, indcrd, valcrd, rhscrd) = (int_at(l2, 14, 14)?, int_at(l2, 28, 14)?, int_at(l2, 42, 14)?, int_at(l2, 56, 14)?);
130    let l3 = lines.next().ok_or(bad("Harwell-Boeing: missing line 3"))?;
131    let mxtype: String = l3.chars().take(3).collect::<String>().to_ascii_uppercase();
132    let (nrows, ncols, nnz) = (int_at(l3, 14, 14)?, int_at(l3, 28, 14)?, int_at(l3, 42, 14)?);
133    let l4 = lines.next().ok_or(bad("Harwell-Boeing: missing line 4"))?;
134    let col = |a: usize, w: usize| -> String { l4.chars().skip(a).take(w).collect() };
135    let (ptrfmt, indfmt, valfmt) = (parse_format(&col(0, 16))?, parse_format(&col(16, 16))?, col(32, 20));
136    if rhscrd > 0 {
137        lines.next();
138    }
139    let mt: Vec<char> = mxtype.chars().collect();
140    if mt.len() != 3 || mt[2] != 'A' {
141        return Err(bad("Harwell-Boeing: only assembled matrices are supported"));
142    }
143    if !matches!(mt[0], 'R' | 'P') {
144        return Err(bad("Harwell-Boeing: complex matrices are not supported"));
145    }
146    let ptr: Vec<usize> = read_fields(&mut lines, ptrcrd, ptrfmt, ncols + 1)?.iter().map(|s| s.parse::<usize>().map_err(|_| bad("Harwell-Boeing: bad pointer"))).collect::<Result<_, _>>()?;
147    let ind: Vec<usize> = read_fields(&mut lines, indcrd, indfmt, nnz)?.iter().map(|s| s.parse::<usize>().map_err(|_| bad("Harwell-Boeing: bad index"))).collect::<Result<_, _>>()?;
148    let vals: Vec<f64> = if mt[0] == 'P' {
149        vec![1.0; nnz]
150    } else {
151        read_fields(&mut lines, valcrd, parse_format(&valfmt)?, nnz)?
152            .iter()
153            .map(|s| {
154                let s = s.replace(['D', 'd'], "E");
155                // Fortran allows the 'E' to be omitted before a signed exponent: 1.5-03.
156                s.parse::<f64>().or_else(|_| {
157                    let p = s[1..].rfind(['+', '-']).map(|p| p + 1).ok_or(bad("Harwell-Boeing: bad value"))?;
158                    format!("{}E{}", &s[..p], &s[p..]).parse::<f64>().map_err(|_| bad("Harwell-Boeing: bad value"))
159                })
160            })
161            .collect::<Result<_, _>>()?
162    };
163    if ptr.first() != Some(&1) || ptr.windows(2).any(|w| w[1] < w[0]) || *ptr.last().expect("non-empty") != nnz + 1 || ind.iter().any(|&r| r == 0 || r > nrows) {
164        return Err(bad("Harwell-Boeing: inconsistent pointers or indices"));
165    }
166    let col_ptr: Vec<usize> = ptr.iter().map(|p| p - 1).collect();
167    let row_indices: Vec<usize> = ind.iter().map(|r| r - 1).collect();
168    let mut hb = HarwellBoeing { title, key, nrows, ncols, col_ptr, row_indices, values: vals };
169    if matches!(mt[1], 'S' | 'Z' | 'H') {
170        // Expand the stored triangle into full compressed columns.
171        let sign = if mt[1] == 'Z' { -1.0 } else { 1.0 };
172        let mut cols: Vec<Vec<(usize, f64)>> = vec![Vec::new(); ncols];
173        for j in 0..ncols {
174            for k in hb.col_ptr[j]..hb.col_ptr[j + 1] {
175                let (i, v) = (hb.row_indices[k], hb.values[k]);
176                cols[j].push((i, v));
177                if i != j {
178                    cols[i].push((j, sign * v));
179                }
180            }
181        }
182        let mut cp = vec![0];
183        let (mut ri, mut vv) = (Vec::new(), Vec::new());
184        for c in cols.iter_mut() {
185            c.sort_by_key(|e| e.0);
186            for &(i, v) in c.iter() {
187                ri.push(i);
188                vv.push(v);
189            }
190            cp.push(ri.len());
191        }
192        hb.col_ptr = cp;
193        hb.row_indices = ri;
194        hb.values = vv;
195    }
196    Ok(hb)
197}
198// ANCHOR_END: hb_read
199
200/// `v` as Fortran writes it with `E25.16` under Python formatting: one digit before the point,
201/// sixteen after, and a signed exponent of at least two digits.
202fn fmt_e(v: f64) -> String {
203    let s = format!("{v:.16E}");
204    let (m, e) = s.split_once('E').expect("exponent form");
205    let e: i32 = e.parse().expect("integer exponent");
206    format!("{m}E{}{:02}", if e < 0 { '-' } else { '+' }, e.abs())
207}
208
209/// Writes a Harwell-Boeing file (SciPy's `hb_write`), as a real unsymmetric assembled (`RUA`)
210/// matrix with SciPy's choice of formats: integers as wide as the largest needs plus one, as
211/// many per 80-column line as fit, and values in `(3E25.16)`.
212pub fn hb_encode(hb: &HarwellBoeing) -> Result<String, ErrorsJSL> {
213    let nnz = hb.values.len();
214    if hb.col_ptr.len() != hb.ncols + 1 || hb.row_indices.len() != nnz || hb.col_ptr[hb.ncols] != nnz {
215        return Err(bad("HarwellBoeing: inconsistent compressed sparse column arrays"));
216    }
217    let int_format = |max: usize| -> (usize, usize) {
218        let w = max.to_string().len() + 1;
219        (80 / w, w)
220    };
221    let ptr: Vec<usize> = hb.col_ptr.iter().map(|p| p + 1).collect();
222    let ind: Vec<usize> = hb.row_indices.iter().map(|r| r + 1).collect();
223    let (pn, pw) = int_format(*ptr.iter().max().unwrap_or(&1));
224    let (inn, iw) = int_format(*ind.iter().max().unwrap_or(&1));
225    let (vn, vw) = (3, 25);
226    let lines_for = |count: usize, per: usize| count.div_ceil(per);
227    let (ptrcrd, indcrd, valcrd) = (lines_for(ptr.len(), pn), lines_for(ind.len(), inn), lines_for(nnz, vn));
228    let mut out = String::new();
229    out.push_str(&format!("{:<72}{:<8}\n", hb.title.chars().take(72).collect::<String>(), hb.key.chars().take(8).collect::<String>()));
230    out.push_str(&format!("{:>14}{:>14}{:>14}{:>14}\n", ptrcrd + indcrd + valcrd, ptrcrd, indcrd, valcrd));
231    out.push_str(&format!("{:<14}{:>14}{:>14}{:>14}{:>14}\n", "RUA", hb.nrows, hb.ncols, nnz, 0));
232    out.push_str(&format!("{:<16}{:<16}{:<20}{:<20}\n", format!("({pn}I{pw})"), format!("({inn}I{iw})"), format!("({vn}E{vw}.16)"), ""));
233    for chunk in ptr.chunks(pn) {
234        out.push_str(&chunk.iter().map(|p| format!("{p:>pw$}")).collect::<String>());
235        out.push('\n');
236    }
237    for chunk in ind.chunks(inn) {
238        out.push_str(&chunk.iter().map(|p| format!("{p:>iw$}")).collect::<String>());
239        out.push('\n');
240    }
241    for chunk in hb.values.chunks(vn) {
242        out.push_str(&chunk.iter().map(|&v| format!("{:>vw$}", fmt_e(v))).collect::<String>());
243        out.push('\n');
244    }
245    Ok(out)
246}
247
248/// Reads a Harwell-Boeing file.
249pub fn read_hb_file(path: impl AsRef<Path>) -> Result<HarwellBoeing, ErrorsJSL> {
250    hb_decode(&std::fs::read_to_string(path).map_err(|_| ErrorsJSL::RuntimeError("could not read the Harwell-Boeing file"))?)
251}
252
253/// Writes a Harwell-Boeing file.
254pub fn write_hb_file(path: impl AsRef<Path>, hb: &HarwellBoeing) -> Result<(), ErrorsJSL> {
255    std::fs::write(path, hb_encode(hb)?).map_err(|_| ErrorsJSL::RuntimeError("could not write the Harwell-Boeing file"))
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261
262    #[test]
263    fn round_trip_and_symmetric() {
264        let hb = HarwellBoeing::new(4, 3, vec![0, 2, 3, 5], vec![0, 3, 1, 0, 2], vec![1.5, -2.0, 1e-300, 6.02e23, 1.0 / 3.0]).unwrap();
265        let text = hb_encode(&hb).unwrap();
266        assert_eq!(hb_decode(&text).unwrap(), hb);
267        assert!(text.lines().nth(2).unwrap().starts_with("RUA"));
268        // A symmetric file storing the lower triangle, with D exponents.
269        let s = "symmetric test                                                          KEY     \n\
270                 \x20            3             1             1             1\n\
271                 RSA                        3             3             4             0\n\
272                 (4I3)           (4I3)           (4D12.4)            \n\
273                 \x20 1  3  4  5\n\
274                 \x20 1  2  2  3\n\
275                 \x20 2.0000D+00 -1.0000D+00  3.0000D+00  4.0000D+00\n";
276        let m = hb_decode(s).unwrap();
277        assert_eq!(m.key, "KEY");
278        assert_eq!(m.to_dense(), vec![vec![2.0, -1.0, 0.0], vec![-1.0, 3.0, 0.0], vec![0.0, 0.0, 4.0]]);
279    }
280}