pub fn from_ascii<G>(text: &str) -> Result<Data<G>, Error>where
G: IndexGraph + Buildable,
Expand description
Create a graph from ASCII art drawing with edge weights.
Parses an ASCII-art drawing and generates the corresponding graph.
Node are *
or letters (except for v
which is used to draw directed
edges), edges are sequences of -
, |
, /
and \
characters. Edges may
cross as in the example below.
Weights are non-negative numbers along the edges. Edges without explicit
weight receive the weight 0. The edge weights are returned in a vector in
the order of creation (although the order is undefined – usually this
corresponds to g.edge_id
).
use rs_graph::traits::*;
use rs_graph::linkedlistgraph::LinkedListGraph;
use rs_graph::string::{Data, from_ascii};
let Data{ graph: g, weights, nodes } = from_ascii::<LinkedListGraph>(r"
a b
| |
----|-----
/ 223 | \
| | / |
| --|- |
\ / | /
- *-10--").unwrap();
assert_eq!(g.neighs(g.id2node(nodes[&'a'])).map(|(e,_)| weights[g.edge_id(e)]).collect::<Vec<_>>(), vec![223]);
assert_eq!(g.neighs(g.id2node(nodes[&'b'])).map(|(e,_)| weights[g.edge_id(e)]).collect::<Vec<_>>(), vec![10]);
Usually edges are undirected. Directed edges can be inserted by ending an
edge in one of the characters <
, >
, ^
, v
or @
(where the @
can
be used in place of any of the other head characters; for diagonal directed
connections it is the only alternative).
use rs_graph::traits::*;
use rs_graph::linkedlistgraph::LinkedListGraph;
use rs_graph::string::{Data, from_ascii};
let Data { graph: g, nodes, .. } = from_ascii::<LinkedListGraph>(r"
* * *
\ | /
@v@
*->a<-*
@^@
/ | \
* * *").unwrap();
let a = g.id2node(nodes[&'a']);
assert_eq!(g.num_nodes(), 9);
assert_eq!(g.num_edges(), 8);
for u in g.nodes() {
if u == a {
assert_eq!(g.inedges(u).count(), 8);
assert_eq!(g.outedges(u).count(), 0);
} else {
assert_eq!(g.inedges(u).count(), 0);
assert_eq!(g.outedges(u).count(), 1);
}
}
Nodes are created (and thus numbered) row-wise. Nodes that have a character
label can be access through the nodes
field of the returned data. The
order of the edges is undefined.
Note: this function is meant to be used in test cases, it should not be used in production code.