Skip to main content

hypergraph_rs/readwrite/
edgelist.rs

1//! Edgelist read/write (XGI `xgi/readwrite/edgelist.py` port).
2
3use std::path::Path;
4
5use serde_json::Value;
6
7use super::ReadWriteError;
8use crate::Hypergraph;
9
10/// Split a line on `delimiter` (whitespace when `None`), dropping empties.
11fn split_line(line: &str, delimiter: Option<char>) -> Vec<String> {
12    match delimiter {
13        Some(d) => line
14            .split(d)
15            .map(|s| s.trim().to_string())
16            .filter(|s| !s.is_empty())
17            .collect(),
18        None => line.split_whitespace().map(|s| s.to_string()).collect(),
19    }
20}
21
22/// Strip the comment suffix (everything at/after the first `comments` token).
23fn strip_comment(line: &str, comments: &str) -> String {
24    match line.find(comments) {
25        Some(p) => line[..p].to_string(),
26        None => line.to_string(),
27    }
28}
29
30/// Parse an iterable of lines into a hypergraph (one edge per line). XGI `parse_edgelist`.
31pub fn parse_edgelist(
32    lines: impl IntoIterator<Item = String>,
33    delimiter: Option<char>,
34    comments: &str,
35) -> Result<Hypergraph, ReadWriteError> {
36    let mut h = Hypergraph::new();
37    for raw in lines {
38        let line = strip_comment(&raw, comments);
39        let members = split_line(&line, delimiter);
40        if members.is_empty() {
41            continue;
42        }
43        h.add_edge(members, None, Value::Null)
44            .map_err(|e| ReadWriteError::Format(format!("bad edge line: {e}")))?;
45    }
46    Ok(h)
47}
48
49/// Read a hypergraph from an edgelist file. XGI `read_edgelist`.
50pub fn read_edgelist(
51    path: &Path,
52    delimiter: Option<char>,
53    comments: &str,
54) -> Result<Hypergraph, ReadWriteError> {
55    let s = std::fs::read_to_string(path)?;
56    parse_edgelist(s.lines().map(|l| l.to_string()), delimiter, comments)
57}
58
59/// Write a hypergraph as an edgelist file (members joined by `delimiter`). XGI `write_edgelist`.
60pub fn write_edgelist(h: &Hypergraph, path: &Path, delimiter: char) -> Result<(), ReadWriteError> {
61    let mut out = String::new();
62    for eid in h.edge_ids() {
63        let members = h.members(&eid).unwrap_or_default();
64        out.push_str(&members.join(&delimiter.to_string()));
65        out.push('\n');
66    }
67    std::fs::write(path, out)?;
68    Ok(())
69}