generated from habedi/template-rust-project
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathio.rs
377 lines (367 loc) · 12.9 KB
/
io.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/*!
# Input/Output (I/O) Routines
This module provides functions to read from and write to files containing graph representations.
Specifically, it supports:
- **Edge List I/O:**
- Reading an edge list from a file into a graph.
- Writing a graph's edge list to a file.
- **Adjacency List I/O:**
- Reading an adjacency list from a file into a graph.
- Writing a graph's adjacency list to a file.
Functions use the core graph abstractions defined in [`crate::core::types`](../core/types.rs)
and use the custom exception [`GraphinaException`](../exceptions/index.html#graphinaexception) for reporting errors.
The input files support comments (lines or inline comments beginning with `#` are ignored)
and allow for optional weight specifications. If a weight is missing, a default of `1.0` is used.
*/
use crate::core::exceptions::GraphinaException;
use crate::core::types::{BaseGraph, GraphConstructor};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Error, ErrorKind, Result, Write};
/// Reads an edge list from a file and populates the given graph.
///
/// Lines containing a `#` are treated as comments. Everything after the first `#` in a line is ignored.
/// Each non-comment, non-empty line must contain at least two tokens (source and target).
/// An optional third token represents the weight (default is `1.0`).
///
/// # Arguments
///
/// * `path` - A string slice that holds the path to the edge list file.
/// * `graph` - A mutable reference to the graph to be populated.
/// * `sep` - A character that separates the values in the edge list.
///
/// # Type Parameters
///
/// * `Ty` - The edge type of the graph, which must implement `GraphConstructor`.
///
/// # Returns
///
/// * `Result<()>` - An `io::Result` indicating success or failure. Failure can occur due to I/O errors,
/// or if any token fails to parse, in which case a [`GraphinaException`](../exceptions/index.html#graphinaexception)
/// is returned as part of the error message.
///
/// # Example
///
/// ```rust,no_run
/// use graphina::core::types::{Graph, NodeId};
/// use graphina::core::io::read_edge_list;
///
/// let mut graph = Graph::<i32, f32>::new();
/// // Assume "edges.txt" exists and follows the correct format.
/// read_edge_list("edges.txt", &mut graph, ',').expect("Failed to read edge list");
/// ```
pub fn read_edge_list<Ty>(path: &str, graph: &mut BaseGraph<i32, f32, Ty>, sep: char) -> Result<()>
where
Ty: GraphConstructor<i32, f32>,
{
let file = File::open(path)?;
let reader = BufReader::new(file);
let mut node_map = HashMap::new();
for line in reader.lines() {
let mut line = line?;
// Remove comments: if '#' is present, only take text before it.
if let Some(idx) = line.find('#') {
line.truncate(idx);
}
// Skip if the line is empty after removing comments.
if line.trim().is_empty() {
continue;
}
let tokens: Vec<&str> = line.trim().split(sep).map(|s| s.trim()).collect();
if tokens.len() < 2 {
continue;
}
let src_val: i32 = tokens[0].parse().map_err(|e| {
Error::new(
ErrorKind::InvalidData,
GraphinaException::new(&format!(
"Error parsing source value '{}': {}",
tokens[0], e
)),
)
})?;
let tgt_val: i32 = tokens[1].parse().map_err(|e| {
Error::new(
ErrorKind::InvalidData,
GraphinaException::new(&format!(
"Error parsing target value '{}': {}",
tokens[1], e
)),
)
})?;
let weight: f32 = if tokens.len() >= 3 {
tokens[2].parse().map_err(|e| {
Error::new(
ErrorKind::InvalidData,
GraphinaException::new(&format!("Error parsing weight '{}': {}", tokens[2], e)),
)
})?
} else {
1.0
};
let src_node = *node_map
.entry(src_val)
.or_insert_with(|| graph.add_node(src_val));
let tgt_node = *node_map
.entry(tgt_val)
.or_insert_with(|| graph.add_node(tgt_val));
graph.add_edge(src_node, tgt_node, weight);
}
Ok(())
}
/// Writes the edge list of a graph to a file.
///
/// Each line in the output file will contain the source attribute, target attribute, and weight,
/// separated by the provided separator.
///
/// # Arguments
///
/// * `path` - A string slice that holds the path to the output file.
/// * `graph` - A reference to the graph to be written.
/// * `sep` - A character that separates the values in the output file.
///
/// # Type Parameters
///
/// * `Ty` - The edge type of the graph, which must implement `GraphConstructor`.
///
/// # Returns
///
/// * `Result<()>` - An `io::Result` indicating success or failure. Failure occurs if a node attribute is missing
/// (triggering a [`GraphinaException`](../exceptions/index.html#graphinaexception)) or if writing to the file fails.
///
/// # Example
///
/// ```rust,no_run
/// use graphina::core::types::{Graph, NodeId};
/// use graphina::core::io::write_edge_list;
///
/// let mut graph = Graph::<i32, f32>::new();
/// let n1 = graph.add_node(1);
/// let n2 = graph.add_node(2);
/// graph.add_edge(n1, n2, 3.5);
/// write_edge_list("output_edges.txt", &graph, ',').expect("Failed to write edge list");
/// ```
pub fn write_edge_list<Ty>(path: &str, graph: &BaseGraph<i32, f32, Ty>, sep: char) -> Result<()>
where
Ty: GraphConstructor<i32, f32>,
{
let file = File::create(path)?;
let mut writer = BufWriter::new(file);
for (src, tgt, weight) in graph.edges() {
let src_attr = graph.node_attr(src).ok_or_else(|| {
Error::new(
ErrorKind::InvalidData,
GraphinaException::new(&format!(
"Missing node attribute for source node: {:?}",
src
)),
)
})?;
let tgt_attr = graph.node_attr(tgt).ok_or_else(|| {
Error::new(
ErrorKind::InvalidData,
GraphinaException::new(&format!(
"Missing node attribute for target node: {:?}",
tgt
)),
)
})?;
writeln!(writer, "{}{}{}{}{}", src_attr, sep, tgt_attr, sep, weight)?;
}
writer.flush()?;
Ok(())
}
/// Reads an adjacency list from a file and populates the given graph.
///
/// Each non-empty line is expected to be in the following format:
///
/// ```text
/// <node><sep><neighbor1><sep><weight1><sep><neighbor2><sep><weight2>...
/// ```
///
/// Lines containing a `#` are treated as comments. Everything after the first `#` in a line is ignored.
/// If a weight is missing for a neighbor, a default weight of `1.0` is used.
///
/// # Arguments
///
/// * `path` - A string slice holding the path to the adjacency list file.
/// * `graph` - A mutable reference to the graph to be populated.
/// * `sep` - A character that separates the tokens in the file.
///
/// # Type Parameters
///
/// * `Ty` - The edge type of the graph, which must implement `GraphConstructor`.
///
/// # Returns
///
/// * `Result<()>` - An `io::Result` indicating success or failure. Parsing errors are returned if any token
/// fails to convert to the expected type. In such cases, a [`GraphinaException`](../exceptions/index.html#graphinaexception)
/// is used to encapsulate the error.
///
/// # Example
///
/// ```rust,no_run
/// use graphina::core::types::{Graph, NodeId};
/// use graphina::core::io::read_adjacency_list;
///
/// let mut graph = Graph::<i32, f32>::new();
/// // Assume "adj_list.txt" exists and follows the correct format.
/// read_adjacency_list("adj_list.txt", &mut graph, ' ').expect("Failed to read adjacency list");
/// ```
pub fn read_adjacency_list<Ty>(
path: &str,
graph: &mut BaseGraph<i32, f32, Ty>,
sep: char,
) -> Result<()>
where
Ty: GraphConstructor<i32, f32>,
{
let file = File::open(path)?;
let reader = BufReader::new(file);
let mut node_map = HashMap::new();
for line in reader.lines() {
let mut line = line?;
// Remove comments: if '#' is present, only take text before it.
if let Some(idx) = line.find('#') {
line.truncate(idx);
}
if line.trim().is_empty() {
continue;
}
let tokens: Vec<&str> = line.trim().split(sep).map(|s| s.trim()).collect();
if tokens.is_empty() {
continue;
}
// The first token is the source node attribute.
let src_val: i32 = tokens[0].parse().map_err(|e| {
Error::new(
ErrorKind::InvalidData,
GraphinaException::new(&format!(
"Error parsing source value '{}': {}",
tokens[0], e
)),
)
})?;
let src_node = *node_map
.entry(src_val)
.or_insert_with(|| graph.add_node(src_val));
// Process subsequent tokens in pairs: neighbor and weight.
let mut i = 1;
while i < tokens.len() {
let neighbor_val: i32 = tokens[i].parse().map_err(|e| {
Error::new(
ErrorKind::InvalidData,
GraphinaException::new(&format!(
"Error parsing neighbor value '{}': {}",
tokens[i], e
)),
)
})?;
let weight: f32 = if i + 1 < tokens.len() {
tokens[i + 1].parse().map_err(|e| {
Error::new(
ErrorKind::InvalidData,
GraphinaException::new(&format!(
"Error parsing weight '{}': {}",
tokens[i + 1],
e
)),
)
})?
} else {
1.0
};
let neighbor_node = *node_map
.entry(neighbor_val)
.or_insert_with(|| graph.add_node(neighbor_val));
graph.add_edge(src_node, neighbor_node, weight);
i += 2;
}
}
Ok(())
}
/// Writes the adjacency list of a graph to a file.
///
/// Each line in the output file will be in the following format:
///
/// ```text
/// <node><sep><neighbor1>:<weight1><sep><neighbor2>:<weight2>...
/// ```
///
/// # Arguments
///
/// * `path` - A string slice holding the path to the output file.
/// * `graph` - A reference to the graph to be written.
/// * `sep` - A character that separates the tokens in the output file.
///
/// # Type Parameters
///
/// * `Ty` - The edge type of the graph, which must implement `GraphConstructor`.
///
/// # Returns
///
/// * `Result<()>` - An `io::Result` indicating success or failure. An error is returned if any node attribute
/// is missing (with a [`GraphinaException`](../exceptions/index.html#graphinaexception)) or if writing to the file fails.
///
/// # Example
///
/// ```rust,no_run
/// use graphina::core::types::{Graph, NodeId};
/// use graphina::core::io::write_adjacency_list;
///
/// let mut graph = Graph::<i32, f32>::new();
/// let n1 = graph.add_node(1);
/// let n2 = graph.add_node(2);
/// graph.add_edge(n1, n2, 2.5);
/// write_adjacency_list("output_adj.txt", &graph, ' ').expect("Failed to write adjacency list");
/// ```
pub fn write_adjacency_list<Ty>(
path: &str,
graph: &BaseGraph<i32, f32, Ty>,
sep: char,
) -> Result<()>
where
Ty: GraphConstructor<i32, f32>,
{
let file = File::create(path)?;
let mut writer = BufWriter::new(file);
// Build a mapping from each source node (by its attribute) to its neighbors.
let mut adj_map: HashMap<i32, Vec<(i32, f32)>> = HashMap::new();
for (src, tgt, weight) in graph.edges() {
let src_attr = graph.node_attr(src).ok_or_else(|| {
Error::new(
ErrorKind::InvalidData,
GraphinaException::new(&format!(
"Missing node attribute for source node: {:?}",
src
)),
)
})?;
let tgt_attr = graph.node_attr(tgt).ok_or_else(|| {
Error::new(
ErrorKind::InvalidData,
GraphinaException::new(&format!(
"Missing node attribute for target node: {:?}",
tgt
)),
)
})?;
adj_map
.entry(*src_attr)
.or_default()
.push((*tgt_attr, *weight));
}
// Write each node and its neighbors.
for (_, attr) in graph.nodes() {
write!(writer, "{}", attr)?;
if let Some(neighbors) = adj_map.get(attr) {
for (nbr, weight) in neighbors {
// Write neighbor and weight separated by a colon.
write!(writer, "{}{}:{}", sep, nbr, weight)?;
}
}
writeln!(writer)?;
}
writer.flush()?;
Ok(())
}