xgraph 2.1.0

A comprehensive Rust library providing efficient graph algorithms for solving real-world problems in social network analysis, transportation optimization, recommendation systems, and more
Documentation
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! Module for CSV input/output operations on graphs
//!
//! This module provides functionality to save and load graphs to/from CSV files, preserving node
//! and edge data along with their attributes. It is designed for interoperability with external
//! tools and data storage, ensuring robust error handling for file operations and data parsing.
//!
//! # Features
//! - Save graphs to CSV files with dynamic attribute support
//! - Load graphs from CSV files with flexible parsing
//! - Preservation of graph structure, weights, and attributes
//!
//! # Examples
//!
//! Saving a graph to CSV:
//! ```rust
//! use xgraph::graph::graph::Graph;
//! use xgraph::graph::io::csv_io::CsvIO;
//!
//! let mut graph: Graph<u32, String, String> = Graph::new(false);
//! let n1 = graph.add_node("A".to_string());
//! let n2 = graph.add_node("B".to_string());
//! graph.add_edge(n1, n2, 1, "edge".to_string()).unwrap();
//! graph.save_to_csv("nodes.csv", "edges.csv").unwrap();
//! ```
//!
//! Loading a graph from CSV:
//! ```rust
//! use xgraph::graph::graph::Graph;
//! use xgraph::graph::io::csv_io::CsvIO;
//!
//! let graph = Graph::<u32, String, String>::load_from_csv("nodes.csv", "edges.csv", false).unwrap();
//! assert_eq!(graph.nodes.len(), 2);
//! ```

use crate::graph::graph::Graph;
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::hash::Hash;
use std::io::{self, BufRead, BufReader, Write};

/// Trait for CSV input/output operations on graphs.
///
/// Defines methods to save a graph to CSV files and load a graph from CSV files. Supports saving
/// and loading node and edge data along with their attributes in a structured format.
///
/// # Type Parameters
/// - `W`: The weight type of the graph edges (e.g., `u32`, `f64`).
/// - `N`: The node data type.
/// - `E`: The edge data type.
///
/// # Requirements
/// - For `save_to_csv`: `W`, `N`, and `E` must implement `Display`.
/// - For `load_from_csv`: `W`, `N`, and `E` must implement `FromStr` and `Default`, with debuggable parse errors.
pub trait CsvIO<W, N, E> {
    /// Saves the graph to CSV files.
    ///
    /// Writes the graph's nodes and edges to two separate CSV files:
    /// - `nodes_file`: Contains `node_id`, `data`, and one column per attribute key.
    /// - `edges_file`: Contains `from`, `to`, `weight`, `data`, and one column per attribute key.
    ///
    /// Attributes are dynamically determined from the graph and written as additional columns.
    /// Missing attributes for a node or edge are represented as empty strings. Fields containing
    /// commas, quotes, or line breaks are quoted following the usual CSV conventions, so the
    /// output round-trips through [`load_from_csv`](CsvIO::load_from_csv).
    ///
    /// # Arguments
    /// - `nodes_file`: The path to the file where nodes will be saved.
    /// - `edges_file`: The path to the file where edges will be saved.
    ///
    /// # Returns
    /// - `Ok(())`: On successful save.
    /// - `Err(io::Error)`: If file creation or writing fails.
    ///
    /// # Examples
    /// ```rust
    /// use xgraph::graph::graph::Graph;
    /// use xgraph::graph::io::csv_io::CsvIO;
    ///
    /// let mut graph: Graph<u32, String, String> = Graph::new(false);
    /// let n1 = graph.add_node("A".to_string());
    /// let n2 = graph.add_node("B".to_string());
    /// graph.add_edge(n1, n2, 1, "edge".to_string()).unwrap();
    /// graph.set_node_attribute(n1, "color".to_string(), "red".to_string()).unwrap();
    /// graph.save_to_csv("nodes.csv", "edges.csv").unwrap();
    /// ```
    fn save_to_csv(&self, nodes_file: &str, edges_file: &str) -> io::Result<()>
    where
        W: Copy + PartialEq + std::fmt::Display,
        N: Clone + Eq + Hash + std::fmt::Debug + std::fmt::Display,
        E: Clone + std::fmt::Debug + std::fmt::Display;

    /// Loads a graph from CSV files.
    ///
    /// Reads a graph from two CSV files:
    /// - `nodes_file`: Contains `node_id`, `data`, and attribute columns.
    /// - `edges_file`: Contains `from`, `to`, `weight`, `data`, and attribute columns.
    ///
    /// Node and edge data are parsed from the CSV using `FromStr`. The node IDs stored in the file
    /// are remapped to fresh IDs on load, and edge endpoints are translated through that mapping, so
    /// graphs with non-contiguous IDs (for example after node removals) are restored correctly.
    /// Attributes are loaded dynamically based on CSV headers. Malformed lines produce an error
    /// rather than a panic.
    ///
    /// # Arguments
    /// - `nodes_file`: The path to the file containing nodes.
    /// - `edges_file`: The path to the file containing edges.
    /// - `directed`: A boolean indicating whether the loaded graph should be directed.
    ///
    /// # Returns
    /// - `Ok(Self)`: The loaded graph on success.
    /// - `Err(io::Error)`: If file reading, parsing, or graph construction fails.
    ///
    /// # Examples
    /// ```rust
    /// use xgraph::graph::graph::Graph;
    /// use xgraph::graph::io::csv_io::CsvIO;
    ///
    /// let graph = Graph::<u32, String, String>::load_from_csv("nodes.csv", "edges.csv", false).unwrap();
    /// assert_eq!(graph.nodes.len(), 2);
    /// assert_eq!(graph.edges.len(), 1);
    /// ```
    fn load_from_csv(nodes_file: &str, edges_file: &str, directed: bool) -> io::Result<Self>
    where
        Self: Sized,
        W: Copy + PartialEq + Default + std::str::FromStr,
        N: Clone + Eq + Hash + std::fmt::Debug + std::str::FromStr,
        E: Clone + std::fmt::Debug + Default + std::str::FromStr,
        <W as std::str::FromStr>::Err: std::fmt::Debug,
        <N as std::str::FromStr>::Err: std::fmt::Debug,
        <E as std::str::FromStr>::Err: std::fmt::Debug;
}

/// Quotes a CSV field if it contains a delimiter, quote, or line break.
///
/// Quotes inside the value are doubled, matching the convention used by spreadsheet
/// tools, so the field can be recovered exactly by [`split_csv_line`].
fn escape_csv_field(value: &str) -> String {
    if value.contains([',', '"', '\n', '\r']) {
        format!("\"{}\"", value.replace('"', "\"\""))
    } else {
        value.to_string()
    }
}

/// Splits a single CSV line into its fields, honoring quoted sections.
///
/// A comma inside a quoted field is treated as data rather than a separator, and a
/// doubled quote inside a quoted field is collapsed to a single quote.
fn split_csv_line(line: &str) -> Vec<String> {
    let mut fields = Vec::new();
    let mut current = String::new();
    let mut in_quotes = false;
    let mut chars = line.chars().peekable();

    while let Some(c) = chars.next() {
        if in_quotes {
            if c == '"' {
                if chars.peek() == Some(&'"') {
                    current.push('"');
                    chars.next();
                } else {
                    in_quotes = false;
                }
            } else {
                current.push(c);
            }
        } else {
            match c {
                '"' => in_quotes = true,
                ',' => fields.push(std::mem::take(&mut current)),
                _ => current.push(c),
            }
        }
    }
    fields.push(current);
    fields
}

impl<W, N, E> CsvIO<W, N, E> for Graph<W, N, E>
where
    W: Copy + PartialEq,
    N: Clone + Eq + Hash + std::fmt::Debug,
    E: Clone + std::fmt::Debug + Default,
{
    fn save_to_csv(&self, nodes_file: &str, edges_file: &str) -> io::Result<()>
    where
        W: std::fmt::Display,
        N: std::fmt::Display,
        E: std::fmt::Display,
    {
        // Save nodes. The attribute keys form the trailing columns, sorted for a stable layout.
        let mut nodes_writer = File::create(nodes_file)?;
        let mut node_attrs: Vec<String> = self
            .nodes
            .iter()
            .flat_map(|(_, node)| node.attributes.keys())
            .collect::<HashSet<_>>()
            .into_iter()
            .cloned()
            .collect();
        node_attrs.sort();

        let mut header = vec!["node_id".to_string(), "data".to_string()];
        header.extend(node_attrs.iter().map(|k| escape_csv_field(k)));
        writeln!(nodes_writer, "{}", header.join(","))?;

        for (id, node) in self.nodes.iter() {
            let mut row = vec![id.to_string(), escape_csv_field(&node.data.to_string())];
            row.extend(node_attrs.iter().map(|key| {
                node.attributes
                    .get(key)
                    .map_or(String::new(), |v| escape_csv_field(&v.to_string()))
            }));
            writeln!(nodes_writer, "{}", row.join(","))?;
        }

        // Save edges using the same scheme, prefixed by the endpoints and weight.
        let mut edges_writer = File::create(edges_file)?;
        let mut edge_attrs: Vec<String> = self
            .edges
            .iter()
            .flat_map(|(_, edge)| edge.attributes.keys())
            .collect::<HashSet<_>>()
            .into_iter()
            .cloned()
            .collect();
        edge_attrs.sort();

        let mut header = vec![
            "from".to_string(),
            "to".to_string(),
            "weight".to_string(),
            "data".to_string(),
        ];
        header.extend(edge_attrs.iter().map(|k| escape_csv_field(k)));
        writeln!(edges_writer, "{}", header.join(","))?;

        for (_, edge) in self.edges.iter() {
            let mut row = vec![
                edge.from.to_string(),
                edge.to.to_string(),
                edge.weight.to_string(),
                escape_csv_field(&edge.data.to_string()),
            ];
            row.extend(edge_attrs.iter().map(|key| {
                edge.attributes
                    .get(key)
                    .map_or(String::new(), |v| escape_csv_field(&v.to_string()))
            }));
            writeln!(edges_writer, "{}", row.join(","))?;
        }

        Ok(())
    }

    fn load_from_csv(nodes_file: &str, edges_file: &str, directed: bool) -> io::Result<Self>
    where
        W: Default + std::str::FromStr,
        N: std::str::FromStr,
        E: std::str::FromStr,
        <W as std::str::FromStr>::Err: std::fmt::Debug,
        <N as std::str::FromStr>::Err: std::fmt::Debug,
        <E as std::str::FromStr>::Err: std::fmt::Debug,
    {
        let mut graph = Graph::new(directed);

        // Load nodes. The original IDs are remapped to freshly allocated ones, and the
        // mapping is reused below to translate edge endpoints.
        let nodes_reader = BufReader::new(File::open(nodes_file)?);
        let mut lines = nodes_reader.lines();
        let header = lines
            .next()
            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Empty nodes file"))??;
        let attr_keys: Vec<String> = split_csv_line(&header).into_iter().skip(2).collect();

        let mut id_map: HashMap<usize, usize> = HashMap::new();
        for line in lines {
            let line = line?;
            if line.is_empty() {
                continue;
            }
            let parts = split_csv_line(&line);
            let original_id: usize = parts
                .first()
                .ok_or_else(|| {
                    io::Error::new(io::ErrorKind::InvalidData, "Node line is missing an ID")
                })?
                .parse()
                .map_err(|e| {
                    io::Error::new(
                        io::ErrorKind::InvalidData,
                        format!("Node ID parse error: {:?}", e),
                    )
                })?;
            let data = parts
                .get(1)
                .map(String::as_str)
                .unwrap_or("")
                .parse()
                .map_err(|e| {
                    io::Error::new(
                        io::ErrorKind::InvalidData,
                        format!("Node data parse error: {:?}", e),
                    )
                })?;
            let node = graph.add_node(data);
            id_map.insert(original_id, node);

            for (key, value) in attr_keys.iter().zip(parts.iter().skip(2)) {
                if !value.is_empty() {
                    graph
                        .set_node_attribute(node, key.clone(), value.clone())
                        .map_err(|e| {
                            io::Error::other(format!("Failed to set node attribute: {:?}", e))
                        })?;
                }
            }
        }

        // Load edges, translating endpoints through the ID map built above.
        let edges_reader = BufReader::new(File::open(edges_file)?);
        let mut lines = edges_reader.lines();
        let header = lines
            .next()
            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Empty edges file"))??;
        let attr_keys: Vec<String> = split_csv_line(&header).into_iter().skip(4).collect();

        for line in lines {
            let line = line?;
            if line.is_empty() {
                continue;
            }
            let parts = split_csv_line(&line);
            if parts.len() < 4 {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("Edge line has too few fields: {}", line),
                ));
            }
            let from_raw: usize = parts[0].parse().map_err(|e| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("Edge 'from' parse error: {:?}", e),
                )
            })?;
            let to_raw: usize = parts[1].parse().map_err(|e| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("Edge 'to' parse error: {:?}", e),
                )
            })?;
            let weight = parts[2].parse().map_err(|e| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("Weight parse error: {:?}", e),
                )
            })?;
            let data = parts[3].parse().map_err(|e| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("Edge data parse error: {:?}", e),
                )
            })?;

            let from = id_map.get(&from_raw).copied().unwrap_or(from_raw);
            let to = id_map.get(&to_raw).copied().unwrap_or(to_raw);

            graph.add_edge(from, to, weight, data).map_err(|e| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("Add edge error: {:?}", e),
                )
            })?;

            for (key, value) in attr_keys.iter().zip(parts.iter().skip(4)) {
                if !value.is_empty() {
                    graph
                        .set_edge_attribute(from, to, key.clone(), value.clone())
                        .map_err(|e| {
                            io::Error::other(format!("Failed to set edge attribute: {:?}", e))
                        })?;
                }
            }
        }

        Ok(graph)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Tests that node/edge data and attributes survive a save/load round-trip.
    #[test]
    fn test_csv_io() {
        let mut graph = Graph::<u32, String, String>::new(false);
        let n1 = graph.add_node("A".to_string());
        let n2 = graph.add_node("B".to_string());
        graph.add_edge(n1, n2, 1, "edge".to_string()).unwrap();
        graph
            .set_node_attribute(n1, "color".to_string(), "red".to_string())
            .unwrap();
        graph
            .set_edge_attribute(n1, n2, "type".to_string(), "road".to_string())
            .unwrap();

        graph
            .save_to_csv("test_io_nodes.csv", "test_io_edges.csv")
            .unwrap();
        let loaded_graph = Graph::<u32, String, String>::load_from_csv(
            "test_io_nodes.csv",
            "test_io_edges.csv",
            false,
        )
        .unwrap();

        assert_eq!(graph.nodes.len(), loaded_graph.nodes.len());
        assert_eq!(graph.edges.len(), loaded_graph.edges.len());
        assert_eq!(
            loaded_graph.get_node_attribute(n1, "color"),
            Some(&"red".to_string())
        );
        assert_eq!(
            loaded_graph.get_edge_attribute(n1, n2, "type"),
            Some(&"road".to_string())
        );
        let edges = loaded_graph.get_all_edges();
        assert_eq!(edges[0].3, "edge".to_string());
    }

    /// Values containing the field delimiter must be quoted and recovered intact.
    #[test]
    fn test_csv_io_quoted_values() {
        let mut graph = Graph::<u32, String, String>::new(true);
        let n1 = graph.add_node("Paris, France".to_string());
        let n2 = graph.add_node("Berlin".to_string());
        graph
            .add_edge(n1, n2, 5, "rail, high-speed".to_string())
            .unwrap();

        graph
            .save_to_csv("test_quote_nodes.csv", "test_quote_edges.csv")
            .unwrap();
        let loaded = Graph::<u32, String, String>::load_from_csv(
            "test_quote_nodes.csv",
            "test_quote_edges.csv",
            true,
        )
        .unwrap();

        assert_eq!(
            loaded.get_node_attribute(n1, "missing"),
            None,
            "no spurious attributes should appear"
        );
        let nodes: Vec<_> = loaded.all_nodes().map(|(_, d)| d.clone()).collect();
        assert!(nodes.contains(&"Paris, France".to_string()));
        assert_eq!(loaded.get_all_edges()[0].3, "rail, high-speed".to_string());
    }

    /// Edges must still connect the right nodes when the saved IDs are non-contiguous.
    #[test]
    fn test_csv_io_remaps_sparse_ids() {
        let mut graph = Graph::<u32, String, String>::new(true);
        let a = graph.add_node("A".to_string());
        let b = graph.add_node("B".to_string());
        let c = graph.add_node("C".to_string());
        graph.add_edge(a, c, 7, "ac".to_string()).unwrap();
        // Remove the middle node so the surviving IDs (0 and 2) are sparse.
        graph.remove_node(b).unwrap();

        graph
            .save_to_csv("test_sparse_nodes.csv", "test_sparse_edges.csv")
            .unwrap();
        let loaded = Graph::<u32, String, String>::load_from_csv(
            "test_sparse_nodes.csv",
            "test_sparse_edges.csv",
            true,
        )
        .unwrap();

        assert_eq!(loaded.nodes.len(), 2);
        assert_eq!(loaded.edges.len(), 1);
        let (from, to, weight, data) = loaded.get_all_edges()[0].clone();
        assert_eq!(weight, 7);
        assert_eq!(data, "ac".to_string());
        assert_eq!(
            loaded.all_nodes().find(|(id, _)| *id == from).unwrap().1,
            "A"
        );
        assert_eq!(loaded.all_nodes().find(|(id, _)| *id == to).unwrap().1, "C");
    }
}