pixelfold 5.0.0

Terminal protein structure viewer and residue interaction network engine
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
//! Writes the residue interaction network for another tool to read.
//!
//! Three shapes: node-link JSON that a browser or a script parses directly,
//! GraphML that Cytoscape and Gephi import, and a flat edge list for a
//! dataframe.
//!
//! Every edge carries how many of the network's models it is present in and
//! that as a fraction: 1 for a single structure, from 0 to 1 for an ensemble.
//!
//! Every edge carries its summed interaction energy (kJ/mol) as a raw additive
//! magnitude. A covalent disulfide (~251 kJ/mol) is an order of magnitude above
//! any non-covalent contact, so a node-strength sum in a downstream tool will be
//! dominated by any disulfide it touches; log-scale or cap the weight there if
//! that is not wanted. The value is the honest energy, not pre-scaled.

use std::io::Write;

use anyhow::Result;
use clap::ValueEnum;
use pixelfold_core::Network;
use pixelfold_core::rin::{Edge, Node, RinAnalysis};
use serde::Serialize;
use serde_json::{Value, json};

/// How many hub residues the analysis report lists.
const TOP_HUBS: usize = 10;
/// How many connected components the analysis report lists before summarising.
const TOP_COMPONENTS: usize = 10;

/// How to write a network.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
pub enum GraphFormat {
    /// Node-link JSON: `{ "models": N, "nodes": [...], "edges": [...] }` (default)
    #[default]
    Json,
    /// GraphML, for Cytoscape and Gephi
    Graphml,
    /// The edge list as tab-separated values
    Tsv,
}

/// Write `network` to `out` in `format`.
pub fn write<W: Write + ?Sized>(out: &mut W, network: &Network, format: GraphFormat) -> Result<()> {
    match format {
        GraphFormat::Json => write_json(out, network),
        GraphFormat::Graphml => write_graphml(out, network),
        GraphFormat::Tsv => write_tsv(out, network),
    }
}

/// Write a structural analysis of `network`: its connected components,
/// the residues that bridge it (highest betweenness), and the cut residues
/// whose removal would split it.
pub fn write_analysis<W: Write + ?Sized>(
    out: &mut W,
    network: &Network,
    analysis: &RinAnalysis,
) -> Result<()> {
    let over = match network.models {
        1 => String::new(),
        models => format!(" over {models} models"),
    };
    writeln!(
        out,
        "Residue interaction network{over}: {} residues, {} edges, {} components",
        network.nodes.len(),
        network.edges.len(),
        analysis.components.len()
    )?;

    writeln!(out, "\nConnected components (largest first):")?;
    if analysis.components.is_empty() {
        writeln!(out, "  (none)")?;
    } else {
        for (rank, component) in analysis.components.iter().take(TOP_COMPONENTS).enumerate() {
            writeln!(out, "  {}. {} residues", rank + 1, component.len())?;
        }

        let extra = analysis.components.len().saturating_sub(TOP_COMPONENTS);
        if extra > 0 {
            writeln!(out, "  ... and {extra} more")?;
        }
    }

    writeln!(out, "\nTop hubs by betweenness centrality:")?;
    let mut ranked: Vec<usize> = (0..network.nodes.len()).collect();
    ranked.sort_by(|&a, &b| {
        analysis.betweenness[b]
            .total_cmp(&analysis.betweenness[a])
            .then(network.nodes[b].degree.cmp(&network.nodes[a].degree))
    });
    writeln!(
        out,
        "  {:<10} {:<5} {:<3} {:>6} {:>12}",
        "residue", "resn", "ss", "degree", "between"
    )?;
    for &i in ranked.iter().take(TOP_HUBS) {
        let node = &network.nodes[i];
        writeln!(
            out,
            "  {:<10} {:<5} {:<3} {:>6} {:>12.2}",
            node.id, node.resn, node.ss, node.degree, analysis.betweenness[i]
        )?;
    }

    writeln!(
        out,
        "\nArticulation points ({} cut residues):",
        analysis.articulation_points.len()
    )?;
    if analysis.articulation_points.is_empty() {
        writeln!(out, "  (none)")?;
    } else {
        let residues: Vec<String> = analysis
            .articulation_points
            .iter()
            .map(|&i| format!("{} {}", network.nodes[i].id, network.nodes[i].resn))
            .collect();
        writeln!(out, "  {}", residues.join(", "))?;
    }

    Ok(())
}

/// Write the shortest chain of interactions between two residues, one residue
/// per line, or a note when they are not connected.
pub fn write_path<W: Write + ?Sized>(
    out: &mut W,
    network: &Network,
    from_id: &str,
    to_id: &str,
    route: Option<&[usize]>,
) -> Result<()> {
    match route {
        None => writeln!(
            out,
            "No path between {from_id} and {to_id}: they are in different components"
        )?,
        Some(path) => {
            writeln!(
                out,
                "Shortest path {from_id} \u{2192} {to_id}: {} steps, {} residues",
                path.len().saturating_sub(1),
                path.len()
            )?;
            for &node in path {
                let node = &network.nodes[node];
                writeln!(out, "  {} {} [{}]", node.id, node.resn, node.ss)?;
            }
        }
    }

    Ok(())
}

/// Write a MolViewSpec (.mvsj) scene: the structure loaded from `url`, its
/// polymer drawn as a grey cartoon, and the network's residues picked out in
/// ball-and-stick. Mol* opens the file and reproduces the scene, so the network
/// selection becomes a shareable, diffable 3D view. `format` is the parse format
/// of the structure at `url` (`mmcif` or `pdb`), and `models` the 0-based
/// indices of its models shown, each drawn so, overlaid as the file has them.
pub fn write_mvsj<W: Write + ?Sized>(
    out: &mut W,
    network: &Network,
    url: &str,
    format: &str,
    models: &[usize],
    title: &str,
) -> Result<()> {
    let residues: Vec<Value> = network
        .nodes
        .iter()
        .map(|node| {
            let mut expr = serde_json::Map::new();
            expr.insert("auth_asym_id".to_string(), json!(node.chain));
            expr.insert("auth_seq_id".to_string(), json!(node.resi));
            if let Some(icode) = node.icode {
                expr.insert("pdbx_PDB_ins_code".to_string(), json!(icode.to_string()));
            }
            Value::Object(expr)
        })
        .collect();

    let mut components = vec![component(json!("polymer"), "cartoon", "#8a8a99")];
    if !residues.is_empty() {
        components.push(component(json!(residues), "ball_and_stick", "#ffb454"));
    }

    let structures: Vec<Value> = models
        .iter()
        .map(|&index| {
            json!({
                "kind": "structure",
                "params": { "type": "model", "model_index": index },
                "children": components
            })
        })
        .collect();
    let scene = json!({
        "metadata": { "version": "1", "title": title },
        "root": { "kind": "root", "children": [
            { "kind": "download", "params": { "url": url }, "children": [
                { "kind": "parse", "params": { "format": format }, "children": structures }
            ]}
        ]}
    });

    serde_json::to_writer_pretty(&mut *out, &scene)?;
    writeln!(out)?;

    Ok(())
}

/// A `component` node over `selector` (a preset string or an array of residue
/// expressions), drawn with one representation in one colour.
fn component(selector: Value, representation: &str, color: &str) -> Value {
    json!({
        "kind": "component",
        "params": { "selector": selector },
        "children": [{
            "kind": "representation",
            "params": { "type": representation },
            "children": [{ "kind": "color", "params": { "color": color } }]
        }]
    })
}

/// Round to two decimals, the precision the coordinates carry and is enough to keep
/// the JSON free of float noise. The intermediate is f64 so scaling by 100 cannot
/// overflow f32's integer mantissa. Every export path also rounds the same way, so
/// the JSON, TSV, and GraphML never disagree on a value.
fn round_2dp(value: f32) -> f32 {
    ((value as f64 * 100.0).round() / 100.0) as f32
}

/// A frequency to three places, for reading; the count of models beside it is
/// exact.
fn round_3dp(value: f32) -> f32 {
    ((value as f64 * 1000.0).round() / 1000.0) as f32
}

#[derive(Serialize)]
struct JsonNetwork<'a> {
    models: usize,
    nodes: Vec<JsonNode<'a>>,
    edges: Vec<JsonEdge<'a>>,
}

#[derive(Serialize)]
struct JsonNode<'a> {
    id: &'a str,
    chain: &'a str,
    resi: i32,
    icode: Option<char>,
    resn: &'a str,
    ss: char,
    degree: usize,
}

#[derive(Serialize)]
struct JsonEdge<'a> {
    source: &'a str,
    target: &'a str,
    kind: &'a str,
    count: usize,
    min_distance: f32,
    interchain: bool,
    /// Summed interaction energy (kJ/mol).
    energy: f32,
    models: usize,
    frequency: f32,
}

fn json_node(node: &Node) -> JsonNode<'_> {
    JsonNode {
        id: &node.id,
        chain: &node.chain,
        resi: node.resi,
        icode: node.icode,
        resn: &node.resn,
        ss: node.ss,
        degree: node.degree,
    }
}

fn json_edge<'a>(network: &Network, edge: &'a Edge) -> JsonEdge<'a> {
    JsonEdge {
        source: &edge.source,
        target: &edge.target,
        kind: edge.kind.label(),
        count: edge.count,
        min_distance: round_2dp(edge.min_distance),
        interchain: edge.interchain,
        energy: round_2dp(edge.energy),
        models: edge.models,
        frequency: round_3dp(network.frequency(edge)),
    }
}

fn write_json<W: Write + ?Sized>(out: &mut W, network: &Network) -> Result<()> {
    let json = JsonNetwork {
        models: network.models,
        nodes: network.nodes.iter().map(json_node).collect(),
        edges: network
            .edges
            .iter()
            .map(|edge| json_edge(network, edge))
            .collect(),
    };
    serde_json::to_writer_pretty(&mut *out, &json)?;
    writeln!(out)?;

    Ok(())
}

/// The edge list, one row per edge. Node attributes have no place in a single
/// flat table, so this carries the edges alone; JSON or GraphML carry the whole
/// graph.
fn write_tsv<W: Write + ?Sized>(out: &mut W, network: &Network) -> Result<()> {
    writeln!(out, "{}", EDGE_COLUMNS.join("\t"))?;
    for edge in &network.edges {
        writeln!(out, "{}", edge_cells(network, edge).join("\t"))?;
    }

    Ok(())
}

/// The columns of the edge list, shared by the tab-separated and aligned writers.
const EDGE_COLUMNS: [&str; 9] = [
    "source",
    "target",
    "kind",
    "count",
    "min_distance",
    "interchain",
    "energy",
    "models",
    "frequency",
];

/// One edge as the nine column cells, in [`EDGE_COLUMNS`] order.
fn edge_cells(network: &Network, edge: &Edge) -> [String; 9] {
    [
        edge.source.clone(),
        edge.target.clone(),
        edge.kind.label().to_string(),
        edge.count.to_string(),
        format!("{:.2}", round_2dp(edge.min_distance)),
        edge.interchain.to_string(),
        format!("{:.2}", round_2dp(edge.energy)),
        edge.models.to_string(),
        format!("{:.3}", round_3dp(network.frequency(edge))),
    ]
}

/// Write the edge list as aligned fixed-width columns, for reading in a terminal.
///
/// Unlike [`write_tsv`] this is deliberately not tab-separated: each column is
/// padded to its widest cell so the header lines up over the values. The caller
/// picks this only when standard output is a terminal; a file or pipe still gets
/// genuine tab-separated values from [`write_tsv`].
pub fn write_tsv_aligned<W: Write + ?Sized>(out: &mut W, network: &Network) -> Result<()> {
    let rows: Vec<[String; 9]> = network
        .edges
        .iter()
        .map(|edge| edge_cells(network, edge))
        .collect();

    // The widest cell in each column, header included, sets the column width.
    let mut widths = EDGE_COLUMNS.map(str::len);
    for row in &rows {
        for (w, cell) in widths.iter_mut().zip(row) {
            *w = (*w).max(cell.len());
        }
    }

    write_padded_row(out, &EDGE_COLUMNS.map(String::from), &widths)?;
    for row in &rows {
        write_padded_row(out, row, &widths)?;
    }

    Ok(())
}

/// Write one row with each cell left-aligned in its column width, a fixed gutter
/// between columns and no trailing spaces after the last cell.
fn write_padded_row<W: Write + ?Sized>(
    out: &mut W,
    cells: &[String; 9],
    widths: &[usize; 9],
) -> Result<()> {
    const GUTTER: usize = 2;
    let last = cells.len() - 1;
    for (i, (cell, &width)) in cells.iter().zip(widths).enumerate() {
        if i == last {
            write!(out, "{cell}")?;
        } else {
            let pad = width + GUTTER;
            write!(out, "{cell:<pad$}")?;
        }
    }
    writeln!(out)?;

    Ok(())
}

/// The GraphML attribute keys, one per node and edge field.
const KEYS: &str = concat!(
    r#"  <key id="g_models" for="graph" attr.name="models" attr.type="int"/>"#,
    "\n",
    r#"  <key id="v_chain" for="node" attr.name="chain" attr.type="string"/>"#,
    "\n",
    r#"  <key id="v_resi" for="node" attr.name="resi" attr.type="int"/>"#,
    "\n",
    r#"  <key id="v_icode" for="node" attr.name="icode" attr.type="string"/>"#,
    "\n",
    r#"  <key id="v_resn" for="node" attr.name="resn" attr.type="string"/>"#,
    "\n",
    r#"  <key id="v_ss" for="node" attr.name="ss" attr.type="string"/>"#,
    "\n",
    r#"  <key id="v_degree" for="node" attr.name="degree" attr.type="int"/>"#,
    "\n",
    r#"  <key id="e_kind" for="edge" attr.name="kind" attr.type="string"/>"#,
    "\n",
    r#"  <key id="e_count" for="edge" attr.name="count" attr.type="int"/>"#,
    "\n",
    r#"  <key id="e_distance" for="edge" attr.name="min_distance" attr.type="double"/>"#,
    "\n",
    r#"  <key id="e_interchain" for="edge" attr.name="interchain" attr.type="boolean"/>"#,
    "\n",
    r#"  <key id="e_energy" for="edge" attr.name="energy" attr.type="double"/>"#,
    "\n",
    r#"  <key id="e_models" for="edge" attr.name="models" attr.type="int"/>"#,
    "\n",
    r#"  <key id="e_frequency" for="edge" attr.name="frequency" attr.type="double"/>"#,
);

fn write_graphml<W: Write + ?Sized>(out: &mut W, network: &Network) -> Result<()> {
    writeln!(out, r#"<?xml version="1.0" encoding="UTF-8"?>"#)?;
    writeln!(
        out,
        r#"<graphml xmlns="http://graphml.graphdrawing.org/xmlns">"#
    )?;
    writeln!(out, "{KEYS}")?;
    writeln!(out, r#"  <graph edgedefault="undirected">"#)?;
    writeln!(out, r#"    <data key="g_models">{}</data>"#, network.models)?;

    for node in &network.nodes {
        writeln!(out, r#"    <node id="{}">"#, escape(&node.id))?;
        data(out, "v_chain", &escape(&node.chain))?;
        data(out, "v_resi", &node.resi.to_string())?;
        if let Some(icode) = node.icode {
            data(out, "v_icode", &escape(&icode.to_string()))?;
        }
        data(out, "v_resn", &escape(&node.resn))?;
        data(out, "v_ss", &node.ss.to_string())?;
        data(out, "v_degree", &node.degree.to_string())?;
        writeln!(out, "    </node>")?;
    }

    for edge in &network.edges {
        writeln!(
            out,
            r#"    <edge source="{}" target="{}">"#,
            escape(&edge.source),
            escape(&edge.target),
        )?;
        data(out, "e_kind", edge.kind.label())?;
        data(out, "e_count", &edge.count.to_string())?;
        data(
            out,
            "e_distance",
            &format!("{:.2}", round_2dp(edge.min_distance)),
        )?;
        data(out, "e_interchain", &edge.interchain.to_string())?;
        data(out, "e_energy", &format!("{:.2}", round_2dp(edge.energy)))?;
        data(out, "e_models", &edge.models.to_string())?;
        data(
            out,
            "e_frequency",
            &format!("{:.3}", round_3dp(network.frequency(edge))),
        )?;
        writeln!(out, "    </edge>")?;
    }

    writeln!(out, "  </graph>")?;
    writeln!(out, "</graphml>")?;

    Ok(())
}

fn data<W: Write + ?Sized>(out: &mut W, key: &str, value: &str) -> Result<()> {
    writeln!(out, r#"      <data key="{key}">{value}</data>"#)?;

    Ok(())
}

/// Escape the five XML metacharacters, so an odd chain id or residue name cannot
/// break the document.
fn escape(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for ch in text.chars() {
        match ch {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&apos;"),
            _ => out.push(ch),
        }
    }

    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use pixelfold_core::InteractionKind;
    use pixelfold_core::rin::{Edge, Network, Node};

    fn network() -> Network {
        Network {
            nodes: vec![
                Node {
                    id: "A/1".into(),
                    chain: "A".into(),
                    resi: 1,
                    icode: None,
                    resn: "LYS".into(),
                    ss: 'H',
                    degree: 1,
                },
                Node {
                    id: "A/2".into(),
                    chain: "A".into(),
                    resi: 2,
                    icode: Some('B'),
                    resn: "GLU".into(),
                    ss: 'E',
                    degree: 1,
                },
            ],
            edges: vec![Edge {
                source: "A/1".into(),
                target: "A/2".into(),
                kind: InteractionKind::SaltBridge,
                count: 1,
                min_distance: 3.456,
                interchain: false,
                energy: InteractionKind::SaltBridge.contact_energy_kj(),
                models: 1,
            }],
            models: 3,
        }
    }

    fn rendered(format: GraphFormat) -> String {
        let mut out = Vec::new();
        write(&mut out, &network(), format).expect("writing to a vec cannot fail");

        String::from_utf8(out).expect("utf8")
    }

    #[test]
    fn json_is_node_link_and_rounds_the_distance() {
        let parsed: serde_json::Value =
            serde_json::from_str(&rendered(GraphFormat::Json)).expect("valid json");

        assert_eq!(parsed["models"], 3);
        assert_eq!(parsed["edges"][0]["models"], 1);
        assert_eq!(parsed["edges"][0]["frequency"], 0.333);
        assert_eq!(parsed["nodes"][1]["icode"], "B");
        assert_eq!(parsed["edges"][0]["kind"], "salt-bridge");
        assert_eq!(parsed["edges"][0]["min_distance"], 3.46);
        assert_eq!(parsed["edges"][0]["interchain"], false);
        assert_eq!(
            parsed["edges"][0]["energy"],
            InteractionKind::SaltBridge.contact_energy_kj()
        );
    }

    #[test]
    fn the_aligned_edge_list_lines_up_columns_under_the_header() {
        // A short and a long source id, so the source column must pad to fit.
        let mut net = network();
        net.edges.push(Edge {
            source: "A/100".into(),
            target: "A/2".into(),
            kind: InteractionKind::HydrogenBond,
            count: 1,
            min_distance: 3.0,
            interchain: false,
            energy: 20.0,
            models: 3,
        });

        let mut out = Vec::new();
        write_tsv_aligned(&mut out, &net).expect("write");
        let text = String::from_utf8(out).expect("utf8");
        let lines: Vec<&str> = text.lines().collect();

        // "source" (6) is wider than "A/1"/"A/100" (<=5), so the source column is
        // 6 wide; with the 2-space gutter the target column starts at index 8.
        assert_eq!(lines[0].find("target"), Some(8));
        assert!(lines[1][8..].starts_with("A/2"), "row 1 target aligns");
        assert!(lines[2][8..].starts_with("A/2"), "row 2 target aligns");
        // It is not tab-separated: alignment uses spaces.
        assert!(!text.contains('\t'));
    }

    #[test]
    fn the_tsv_edge_list_has_a_header_and_a_row_per_edge() {
        let text = rendered(GraphFormat::Tsv);
        let lines: Vec<&str> = text.lines().collect();

        assert_eq!(
            lines[0],
            "source\ttarget\tkind\tcount\tmin_distance\tinterchain\tenergy\tmodels\tfrequency"
        );
        assert_eq!(
            lines[1],
            "A/1\tA/2\tsalt-bridge\t1\t3.46\tfalse\t17.00\t1\t0.333"
        );
    }

    #[test]
    fn graphml_is_well_formed_and_declares_its_keys() {
        let text = rendered(GraphFormat::Graphml);

        assert!(text.starts_with(r#"<?xml version="1.0" encoding="UTF-8"?>"#));
        assert!(
            text.contains(r#"<key id="e_kind" for="edge" attr.name="kind" attr.type="string"/>"#)
        );
        assert!(text.contains(r#"<node id="A/1">"#));
        assert!(text.contains(r#"<edge source="A/1" target="A/2">"#));
        assert!(text.contains("<data key=\"e_kind\">salt-bridge</data>"));
        assert!(
            text.contains(
                r#"<key id="e_energy" for="edge" attr.name="energy" attr.type="double"/>"#
            )
        );
        assert!(text.contains("<data key=\"e_energy\">17.00</data>"));
        assert!(text.contains(
            r#"<graph edgedefault="undirected">
    <data key="g_models">3</data>"#
        ));
        assert!(text.contains("<data key=\"e_models\">1</data>"));
        assert!(text.contains("<data key=\"e_frequency\">0.333</data>"));
        // The insertion code reaches the node.
        assert!(text.contains("<data key=\"v_icode\">B</data>"));
        // Every open tag is closed.
        assert_eq!(
            text.matches("<node ").count(),
            text.matches("</node>").count()
        );
        assert_eq!(
            text.matches("<edge ").count(),
            text.matches("</edge>").count()
        );
    }

    #[test]
    fn xml_metacharacters_in_a_value_are_escaped() {
        let mut net = network();
        net.nodes[0].resn = "A<&B".into();
        let mut out = Vec::new();
        write(&mut out, &net, GraphFormat::Graphml).expect("write");
        let text = String::from_utf8(out).expect("utf8");

        assert!(text.contains("A&lt;&amp;B"));
        assert!(!text.contains("A<&B"));
    }
}