hypergraph_rs/readwrite/
bipartite.rs1use std::path::Path;
4
5use super::ReadWriteError;
6use crate::Hypergraph;
7
8fn split_line(line: &str, delimiter: Option<char>) -> Vec<String> {
9 match delimiter {
10 Some(d) => line
11 .split(d)
12 .map(|s| s.trim().to_string())
13 .filter(|s| !s.is_empty())
14 .collect(),
15 None => line.split_whitespace().map(|s| s.to_string()).collect(),
16 }
17}
18
19fn strip_comment(line: &str, comments: &str) -> String {
20 match line.find(comments) {
21 Some(p) => line[..p].to_string(),
22 None => line.to_string(),
23 }
24}
25
26pub fn parse_bipartite_edgelist(
29 lines: impl IntoIterator<Item = String>,
30 delimiter: Option<char>,
31 comments: &str,
32 dual: bool,
33) -> Result<Hypergraph, ReadWriteError> {
34 let mut h = Hypergraph::new();
35 let (node_col, edge_col) = if dual { (1, 0) } else { (0, 1) };
36 for raw in lines {
37 let line = strip_comment(&raw, comments);
38 let toks = split_line(&line, delimiter);
39 if toks.is_empty() {
40 continue;
41 }
42 if toks.len() < 2 {
43 return Err(ReadWriteError::Format(
44 "each line must contain at least two entries".into(),
45 ));
46 }
47 let node = &toks[node_col];
48 let edge = &toks[edge_col];
49 h.add_node_to_edge(edge, node)
50 .map_err(|e| ReadWriteError::Format(format!("bad incidence: {e}")))?;
51 }
52 Ok(h)
53}
54
55pub fn read_bipartite_edgelist(
57 path: &Path,
58 delimiter: Option<char>,
59 comments: &str,
60 dual: bool,
61) -> Result<Hypergraph, ReadWriteError> {
62 let s = std::fs::read_to_string(path)?;
63 parse_bipartite_edgelist(s.lines().map(|l| l.to_string()), delimiter, comments, dual)
64}
65
66pub fn write_bipartite_edgelist(
68 h: &Hypergraph,
69 path: &Path,
70 delimiter: char,
71) -> Result<(), ReadWriteError> {
72 let mut out = String::new();
73 for eid in h.edge_ids() {
74 for node in h.members(&eid).unwrap_or_default() {
75 out.push_str(&node);
76 out.push(delimiter);
77 out.push_str(&eid);
78 out.push('\n');
79 }
80 }
81 std::fs::write(path, out)?;
82 Ok(())
83}