gexf 0.1.1

Lightweight Rust library to export graphs in the GEXF format (Gephi)
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
use quick_xml::{
    Writer,
    events::{BytesStart, BytesText, Event},
};
use std::{collections::BTreeMap, io::Write};
use thiserror::Error;

/// Result alias for this crate
pub type Result<T> = std::result::Result<T, GexfError>;

#[derive(Debug, Error)]
pub enum GexfError {
    #[error("duplicate node id: {0}")]
    DuplicateNodeId(String),
    #[error("edge references unknown node id: {0}")]
    UnknownNodeId(String),
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),
    #[error("XML write error: {0}")]
    Xml(String),
}

/// Direction type for the whole graph. Per-edge overrides are not supported in core GEXF; use `Mutual` or split graphs if needed.
#[derive(Debug, Clone, Copy, Default)]
pub enum EdgeType {
    Directed,
    #[default]
    Undirected,
    Mutual,
}

impl EdgeType {
    fn as_str(&self) -> &'static str {
        match self {
            EdgeType::Directed => "directed",
            EdgeType::Undirected => "undirected",
            EdgeType::Mutual => "mutual",
        }
    }
}

/// Static vs dynamic graphs. This crate currently emits `static` graphs only.
#[derive(Debug, Clone, Copy, Default)]
pub enum GraphMode {
    #[default]
    Static,
}

impl GraphMode {
    fn as_str(&self) -> &'static str {
        match self {
            GraphMode::Static => "static",
        }
    }
}

/// RGB color (0..255 per channel)
#[derive(Debug, Clone, Copy)]
pub struct Color {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

/// 3D position (Gephi viz namespace)
#[derive(Debug, Clone, Copy)]
pub struct Position {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

/// A node in the graph
#[derive(Debug, Clone)]
pub struct Node {
    pub id: String,
    pub label: Option<String>,
    pub attributes: BTreeMap<String, String>,
    pub position: Option<Position>,
    pub size: Option<f32>,
    pub color: Option<Color>,
}

impl Node {
    pub fn new<T: Into<String>>(id: T) -> Self {
        Self {
            id: id.into(),
            label: None,
            attributes: BTreeMap::new(),
            position: None,
            size: None,
            color: None,
        }
    }

    pub fn with_label<T: Into<String>>(mut self, label: T) -> Self {
        self.label = Some(label.into());
        self
    }

    pub fn with_attr<K: Into<String>, V: Into<String>>(mut self, key: K, val: V) -> Self {
        self.attributes.insert(key.into(), val.into());
        self
    }

    pub fn with_position(mut self, x: f32, y: f32, z: f32) -> Self {
        self.position = Some(Position { x, y, z });
        self
    }

    pub fn with_size(mut self, size: f32) -> Self {
        self.size = Some(size);
        self
    }

    pub fn with_color(mut self, r: u8, g: u8, b: u8) -> Self {
        self.color = Some(Color { r, g, b });
        self
    }
}

/// An edge between two nodes
#[derive(Debug, Clone)]
pub struct Edge {
    pub id: String,
    pub source: String,
    pub target: String,
    pub weight: Option<f32>,
    pub label: Option<String>,
}

impl Edge {
    pub fn new<I: Into<String>, S: Into<String>, T: Into<String>>(
        id: I,
        source: S,
        target: T,
    ) -> Self {
        Self {
            id: id.into(),
            source: source.into(),
            target: target.into(),
            weight: None,
            label: None,
        }
    }

    pub fn with_weight(mut self, w: f32) -> Self {
        self.weight = Some(w);
        self
    }

    pub fn with_label<L: Into<String>>(mut self, label: L) -> Self {
        self.label = Some(label.into());
        self
    }
}

/// Metadata for the `<meta>` section
#[derive(Debug, Clone, Default)]
pub struct Meta {
    pub creator: Option<String>,
    pub description: Option<String>,
    /// ISO-8601 date string (e.g., 2025-10-13). If not provided, it's omitted.
    pub last_modified: Option<String>,
}

/// Main builder/graph object
#[derive(Debug, Default)]
pub struct Gexf {
    pub edge_type: EdgeType,
    pub mode: GraphMode,
    pub meta: Meta,
    nodes: BTreeMap<String, Node>,
    edges: Vec<Edge>,
}

impl Gexf {
    pub fn new(edge_type: EdgeType) -> Self {
        Self {
            edge_type,
            mode: GraphMode::Static,
            meta: Meta::default(),
            nodes: BTreeMap::new(),
            edges: Vec::new(),
        }
    }

    pub fn set_meta(mut self, meta: Meta) -> Self {
        self.meta = meta;
        self
    }

    pub fn add_node(&mut self, node: Node) -> Result<()> {
        if self.nodes.contains_key(&node.id) {
            return Err(GexfError::DuplicateNodeId(node.id));
        }
        self.nodes.insert(node.id.clone(), node);
        Ok(())
    }

    pub fn add_edge(&mut self, edge: Edge) -> Result<()> {
        if !self.nodes.contains_key(&edge.source) {
            return Err(GexfError::UnknownNodeId(edge.source));
        }
        if !self.nodes.contains_key(&edge.target) {
            return Err(GexfError::UnknownNodeId(edge.target));
        }
        self.edges.push(edge);
        Ok(())
    }

    /// Serialize to any `Write` sink.
    pub fn write<W: Write>(&self, mut sink: W) -> Result<()> {
        let mut w = Writer::new_with_indent(&mut sink, b' ', 2);

        // XML declaration
        w.write_event(Event::Decl(quick_xml::events::BytesDecl::new(
            "1.0",
            Some("UTF-8"),
            None,
        )))
        .map_err(|e| GexfError::Xml(e.to_string()))?;

        // <gexf>
        let mut gexf = BytesStart::new("gexf");
        gexf.push_attribute(("xmlns", "http://www.gexf.net/1.3draft"));
        gexf.push_attribute(("xmlns:viz", "http://www.gexf.net/1.3draft/viz"));
        gexf.push_attribute(("version", "1.3"));
        w.write_event(Event::Start(gexf))
            .map_err(|e| GexfError::Xml(e.to_string()))?;

        // <meta>
        if self.meta.creator.is_some()
            || self.meta.description.is_some()
            || self.meta.last_modified.is_some()
        {
            let mut meta_tag = BytesStart::new("meta");
            if let Some(date) = &self.meta.last_modified {
                meta_tag.push_attribute(("lastmodifieddate", date.as_str()));
            }
            w.write_event(Event::Start(meta_tag))
                .map_err(|e| GexfError::Xml(e.to_string()))?;

            if let Some(creator) = &self.meta.creator {
                w.write_event(Event::Start(BytesStart::new("creator")))
                    .map_err(|e| GexfError::Xml(e.to_string()))?;
                w.write_event(Event::Text(BytesText::new(creator)))
                    .map_err(|e| GexfError::Xml(e.to_string()))?;
                w.write_event(Event::End(BytesStart::new("creator").to_end()))
                    .map_err(|e| GexfError::Xml(e.to_string()))?;
            }
            if let Some(desc) = &self.meta.description {
                w.write_event(Event::Start(BytesStart::new("description")))
                    .map_err(|e| GexfError::Xml(e.to_string()))?;
                w.write_event(Event::Text(BytesText::new(desc)))
                    .map_err(|e| GexfError::Xml(e.to_string()))?;
                w.write_event(Event::End(BytesStart::new("description").to_end()))
                    .map_err(|e| GexfError::Xml(e.to_string()))?;
            }

            w.write_event(Event::End(BytesStart::new("meta").to_end()))
                .map_err(|e| GexfError::Xml(e.to_string()))?;
        }

        // <graph>
        let mut graph = BytesStart::new("graph");
        graph.push_attribute(("mode", self.mode.as_str()));
        graph.push_attribute(("defaultedgetype", self.edge_type.as_str()));
        w.write_event(Event::Start(graph))
            .map_err(|e| GexfError::Xml(e.to_string()))?;

        // <nodes>
        w.write_event(Event::Start(BytesStart::new("nodes")))
            .map_err(|e| GexfError::Xml(e.to_string()))?;

        for node in self.nodes.values() {
            let mut n = BytesStart::new("node");
            n.push_attribute(("id", node.id.as_str()));
            if let Some(label) = &node.label {
                n.push_attribute(("label", label.as_str()));
            }
            w.write_event(Event::Start(n))
                .map_err(|e| GexfError::Xml(e.to_string()))?;

            // <attvalues>
            if !node.attributes.is_empty() {
                w.write_event(Event::Start(BytesStart::new("attvalues")))
                    .map_err(|e| GexfError::Xml(e.to_string()))?;
                for (k, v) in &node.attributes {
                    let mut att = BytesStart::new("attvalue");
                    att.push_attribute(("for", k.as_str()));
                    att.push_attribute(("value", v.as_str()));
                    w.write_event(Event::Empty(att))
                        .map_err(|e| GexfError::Xml(e.to_string()))?;
                }
                w.write_event(Event::End(BytesStart::new("attvalues").to_end()))
                    .map_err(|e| GexfError::Xml(e.to_string()))?;
            }

            // viz namespace (position, size, color)
            if let Some(pos) = node.position {
                let mut p = BytesStart::new("viz:position");
                p.push_attribute(("x", pos.x.to_string().as_str()));
                p.push_attribute(("y", pos.y.to_string().as_str()));
                p.push_attribute(("z", pos.z.to_string().as_str()));
                w.write_event(Event::Empty(p))
                    .map_err(|e| GexfError::Xml(e.to_string()))?;
            }
            if let Some(size) = node.size {
                let mut s = BytesStart::new("viz:size");
                s.push_attribute(("value", size.to_string().as_str()));
                w.write_event(Event::Empty(s))
                    .map_err(|e| GexfError::Xml(e.to_string()))?;
            }
            if let Some(color) = node.color {
                let mut c = BytesStart::new("viz:color");
                c.push_attribute(("r", color.r.to_string().as_str()));
                c.push_attribute(("g", color.g.to_string().as_str()));
                c.push_attribute(("b", color.b.to_string().as_str()));
                w.write_event(Event::Empty(c))
                    .map_err(|e| GexfError::Xml(e.to_string()))?;
            }

            w.write_event(Event::End(BytesStart::new("node").to_end()))
                .map_err(|e| GexfError::Xml(e.to_string()))?;
        }

        w.write_event(Event::End(BytesStart::new("nodes").to_end()))
            .map_err(|e| GexfError::Xml(e.to_string()))?;

        // <edges>
        w.write_event(Event::Start(BytesStart::new("edges")))
            .map_err(|e| GexfError::Xml(e.to_string()))?;

        for e in &self.edges {
            let mut ed = BytesStart::new("edge");
            ed.push_attribute(("id", e.id.as_str()));
            ed.push_attribute(("source", e.source.as_str()));
            ed.push_attribute(("target", e.target.as_str()));
            if let Some(wt) = e.weight {
                ed.push_attribute(("weight", wt.to_string().as_str()));
            }
            if let Some(label) = &e.label {
                ed.push_attribute(("label", label.as_str()));
            }
            w.write_event(Event::Empty(ed))
                .map_err(|e| GexfError::Xml(e.to_string()))?;
        }

        w.write_event(Event::End(BytesStart::new("edges").to_end()))
            .map_err(|e| GexfError::Xml(e.to_string()))?;

        // </graph>
        w.write_event(Event::End(BytesStart::new("graph").to_end()))
            .map_err(|e| GexfError::Xml(e.to_string()))?;

        // </gexf>
        w.write_event(Event::End(BytesStart::new("gexf").to_end()))
            .map_err(|e| GexfError::Xml(e.to_string()))?;

        Ok(())
    }

    /// Serialize the graph to a UTF-8 String (convenience)
    pub fn to_string(&self) -> Result<String> {
        let mut buf = Vec::new();
        self.write(&mut buf)?;
        Ok(String::from_utf8(buf).expect("valid utf8"))
    }
}

/// Convenience builder that ensures unique incremental IDs for edges when you don't care about explicit IDs.
#[derive(Debug, Default)]
pub struct GraphBuilder {
    gexf: Gexf,
    next_edge_id: u64,
}

impl GraphBuilder {
    pub fn new(edge_type: EdgeType) -> Self {
        Self {
            gexf: Gexf::new(edge_type),
            next_edge_id: 0,
        }
    }

    pub fn meta(mut self, creator: impl Into<String>, description: impl Into<String>) -> Self {
        self.gexf.meta.creator = Some(creator.into());
        self.gexf.meta.description = Some(description.into());
        self
    }

    pub fn last_modified(mut self, date_iso: impl Into<String>) -> Self {
        self.gexf.meta.last_modified = Some(date_iso.into());
        self
    }

    pub fn add_node(mut self, node: Node) -> Result<Self> {
        self.gexf.add_node(node)?;
        Ok(self)
    }

    pub fn add_edge(
        mut self,
        source: impl Into<String>,
        target: impl Into<String>,
    ) -> Result<Self> {
        let id = format!("e{}", self.next_edge_id);
        self.next_edge_id += 1;
        let e = Edge::new(id, source.into(), target.into());
        self.gexf.add_edge(e)?;
        Ok(self)
    }

    pub fn try_build(self) -> Result<Gexf> {
        Ok(self.gexf)
    }
}

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

    #[test]
    fn basic_write() {
        let g = GraphBuilder::new(EdgeType::Directed)
            .meta("gexf", "Example graph")
            .last_modified("2025-10-13")
            .add_node(
                Node::new("n0")
                    .with_label("Alice")
                    .with_color(200, 50, 50)
                    .with_size(2.0)
                    .with_position(0.0, 0.0, 0.0),
            )
            .unwrap()
            .add_node(
                Node::new("n1")
                    .with_label("Bob")
                    .with_attr("role", "engineer"),
            )
            .unwrap()
            .add_edge("n0", "n1")
            .unwrap()
            .try_build()
            .unwrap();

        let xml = g.to_string().unwrap();
        assert!(xml.contains("<gexf"));
        assert!(xml.contains("<nodes>"));
        assert!(xml.contains("<edges>"));
        assert!(xml.contains("viz:position"));
    }
}