1use std::fmt::Write as _;
22use std::path::Path;
23
24use crate::Error;
25use crate::graph::{Graph, GraphBuilder, WeightedGraph};
26use crate::legacy::Scanner;
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub enum Format {
31 Lists,
32 EdgeList,
33 Graph6,
34 Sparse6,
35 MatrixMarket,
36 Dot,
37 GraphML,
38 WeightedLists,
39}
40
41impl Format {
42 pub const ALL: [(Format, &'static str); 8] = [
44 (Format::Lists, "lists"),
45 (Format::EdgeList, "edgelist"),
46 (Format::Graph6, "graph6"),
47 (Format::Sparse6, "sparse6"),
48 (Format::MatrixMarket, "mtx"),
49 (Format::Dot, "dot"),
50 (Format::GraphML, "graphml"),
51 (Format::WeightedLists, "wlists"),
52 ];
53
54 pub fn name(self) -> &'static str {
56 Format::ALL.iter().find(|(f, _)| *f == self).unwrap().1
57 }
58
59 pub fn from_path(path: &Path) -> Option<Format> {
61 let ext = path.extension()?.to_str()?.to_ascii_lowercase();
62 Some(match ext.as_str() {
63 "txt" | "lists" | "adj" => Format::Lists,
64 "edges" | "edgelist" | "el" | "csv" | "tsv" => Format::EdgeList,
65 "g6" | "graph6" => Format::Graph6,
66 "s6" | "sparse6" => Format::Sparse6,
67 "mtx" | "mm" => Format::MatrixMarket,
68 "dot" | "gv" => Format::Dot,
69 "graphml" => Format::GraphML,
70 _ => return None,
71 })
72 }
73
74 pub fn readable(self) -> bool {
76 !matches!(self, Format::Dot | Format::GraphML)
77 }
78}
79
80impl std::str::FromStr for Format {
81 type Err = String;
82
83 fn from_str(s: &str) -> Result<Self, Self::Err> {
84 let s = s.to_ascii_lowercase();
85 let alias = match s.as_str() {
86 "legacy" | "adj" => "lists",
87 "edges" | "el" | "csv" => "edgelist",
88 "g6" => "graph6",
89 "s6" => "sparse6",
90 "matrixmarket" | "mm" => "mtx",
91 "gv" | "graphviz" => "dot",
92 "weighted-lists" => "wlists",
93 other => other,
94 };
95 Format::ALL
96 .iter()
97 .find(|(_, n)| *n == alias)
98 .map(|(f, _)| *f)
99 .ok_or_else(|| {
100 let names: Vec<_> = Format::ALL.iter().map(|(_, n)| *n).collect();
101 format!(
102 "unknown format '{s}' (expected one of: {})",
103 names.join(", ")
104 )
105 })
106 }
107}
108
109#[derive(Clone, Debug, Default)]
111pub struct WriteOptions<'a> {
112 pub highlight: &'a [usize],
114}
115
116pub fn parse(text: &str, format: Format) -> Result<Graph, Error> {
119 let mut graphs = parse_all(text, format)?;
120 match graphs.len() {
121 1 => Ok(graphs.pop().unwrap()),
122 0 => Err(Error::Parse {
123 line: None,
124 msg: format!("no {} graph found", format.name()),
125 }),
126 count => Err(Error::MultipleGraphs(count)),
127 }
128}
129
130pub fn parse_all(text: &str, format: Format) -> Result<Vec<Graph>, Error> {
134 match format {
135 Format::Lists => Ok(vec![parse_lists(text)?]),
136 Format::WeightedLists => Ok(vec![parse_weighted_lists(text)?.structure()]),
137 Format::EdgeList => Ok(vec![parse_edge_list(text)?]),
138 Format::MatrixMarket => Ok(vec![parse_matrix_market(text)?]),
139 Format::Graph6 | Format::Sparse6 => {
140 let header = if format == Format::Graph6 {
141 ">>graph6<<"
142 } else {
143 ">>sparse6<<"
144 };
145 let mut graphs = Vec::new();
146 for (i, line) in text.lines().enumerate() {
147 let line = line.trim();
148 let line = if i == 0 {
149 line.strip_prefix(header).unwrap_or(line)
150 } else {
151 line
152 };
153 if line.is_empty() {
154 continue;
155 }
156 let g = if format == Format::Graph6 {
157 parse_graph6(line)
158 } else {
159 parse_sparse6(line)
160 };
161 graphs.push(g.map_err(|e| at_line(e, i + 1))?);
162 }
163 Ok(graphs)
164 }
165 Format::Dot | Format::GraphML => Err(Error::Invalid(format!(
166 "reading {} is not supported",
167 format.name()
168 ))),
169 }
170}
171
172pub fn holds_many(format: Format) -> bool {
174 matches!(format, Format::Graph6 | Format::Sparse6)
175}
176
177pub fn to_string_all(graphs: &[Graph], format: Format) -> Result<String, Error> {
179 if graphs.len() != 1 && !holds_many(format) {
180 return Err(Error::Invalid(format!(
181 "{} holds a single graph, but {} were given; use graph6 or sparse6",
182 format.name(),
183 graphs.len()
184 )));
185 }
186 Ok(graphs
187 .iter()
188 .map(|g| to_string(g, format, &WriteOptions::default()))
189 .collect())
190}
191
192fn at_line(e: Error, line: usize) -> Error {
193 match e {
194 Error::Parse { msg, .. } => Error::Parse {
195 line: Some(line),
196 msg,
197 },
198 other => other,
199 }
200}
201
202pub fn to_string(g: &Graph, format: Format, options: &WriteOptions) -> String {
204 match format {
205 Format::Lists => write_lists(g),
206 Format::EdgeList => write_edge_list(g),
207 Format::Graph6 => write_graph6(g) + "\n",
208 Format::Sparse6 => write_sparse6(g) + "\n",
209 Format::MatrixMarket => write_matrix_market(g),
210 Format::Dot => write_dot(g, options.highlight),
211 Format::GraphML => write_graphml(g, options.highlight),
212 Format::WeightedLists => write_weighted_lists(&WeightedGraph::from_graph(g)),
213 }
214}
215
216pub fn holds_weights(format: Format) -> bool {
218 matches!(
219 format,
220 Format::EdgeList
221 | Format::MatrixMarket
222 | Format::WeightedLists
223 | Format::Dot
224 | Format::GraphML
225 )
226}
227
228pub fn parse_weighted(text: &str, format: Format) -> Result<WeightedGraph, Error> {
231 match format {
232 Format::WeightedLists => parse_weighted_lists(text),
233 Format::EdgeList => parse_weighted_edge_list(text),
234 Format::MatrixMarket => parse_weighted_matrix_market(text),
235 _ => Ok(WeightedGraph::from_graph(&parse(text, format)?)),
236 }
237}
238
239pub fn to_string_weighted(
241 g: &WeightedGraph,
242 format: Format,
243 options: &WriteOptions,
244) -> Result<String, Error> {
245 Ok(match format {
246 Format::WeightedLists => write_weighted_lists(g),
247 Format::EdgeList => {
248 let mut s = format!(
249 "# vertices: {}\n# edges: {}\n# total weight: {}\n",
250 g.num_vertices(),
251 g.num_edges(),
252 g.total_weight()
253 );
254 for (u, v, w) in g.edges() {
255 writeln!(s, "{u} {v} {w}").unwrap();
256 }
257 s
258 }
259 Format::MatrixMarket => {
260 let n = g.num_vertices();
261 let mut s = format!(
262 "%%MatrixMarket matrix coordinate integer symmetric\n{n} {n} {}\n",
263 g.num_edges()
264 );
265 for (u, v, w) in g.edges() {
266 writeln!(s, "{} {} {w}", v + 1, u + 1).unwrap();
267 }
268 s
269 }
270 Format::Dot | Format::GraphML => {
271 let base = to_string(&g.structure(), format, options);
272 add_weights(&base, g, format)
273 }
274 other => {
275 return Err(Error::Invalid(format!(
276 "{} cannot store edge weights; use edgelist, mtx or wlists",
277 other.name()
278 )));
279 }
280 })
281}
282
283pub type Scores = (usize, Vec<(usize, usize, f64)>);
285
286pub fn parse_scores(text: &str, format: Format) -> Result<Scores, Error> {
291 let score = |line: usize, f: &str| {
292 f.parse::<f64>()
293 .ok()
294 .filter(|s| s.is_finite() && *s >= 0.0)
295 .ok_or_else(|| parse_error(line, format!("'{f}' is not a non-negative number")))
296 };
297 let mut triples = Vec::new();
298 match format {
299 Format::EdgeList => {
300 let mut declared = None;
301 for (i, line) in text.lines().enumerate() {
302 let line = line.trim();
303 if let Some(comment) = line.strip_prefix('#').or_else(|| line.strip_prefix('%')) {
304 if let Some(n) = comment.trim().strip_prefix("vertices:") {
305 declared = Some(
306 n.trim()
307 .parse::<usize>()
308 .map_err(|_| parse_error(i + 1, "bad vertex count"))?,
309 );
310 }
311 continue;
312 }
313 if line.is_empty() {
314 continue;
315 }
316 let f: Vec<&str> = line
317 .split(|c: char| c == ',' || c.is_whitespace())
318 .filter(|f| !f.is_empty())
319 .collect();
320 if f.len() < 2 {
321 return Err(parse_error(
322 i + 1,
323 "expected two vertices and an optional score",
324 ));
325 }
326 let num = |x: &str| {
327 x.parse::<usize>()
328 .map_err(|_| parse_error(i + 1, format!("'{x}' is not a vertex number")))
329 };
330 let s = f.get(2).map_or(Ok(1.0), |x| score(i + 1, x))?;
331 triples.push((num(f[0])?, num(f[1])?, s));
332 }
333 let n = declared.unwrap_or_else(|| {
334 triples
335 .iter()
336 .map(|&(u, v, _)| u.max(v) + 1)
337 .max()
338 .unwrap_or(0)
339 });
340 Ok((n, triples))
341 }
342 Format::MatrixMarket => {
343 if text
345 .lines()
346 .next()
347 .unwrap_or("")
348 .to_ascii_lowercase()
349 .split_whitespace()
350 .nth(3)
351 != Some("pattern")
352 {
353 let mut size = None;
354 for (i, line) in text.lines().enumerate().skip(1) {
355 let line = line.trim();
356 if line.is_empty() || line.starts_with('%') {
357 continue;
358 }
359 let f: Vec<&str> = line.split_whitespace().collect();
360 let num = |x: &str| {
361 x.parse::<usize>()
362 .map_err(|_| parse_error(i + 1, format!("'{x}' is not an index")))
363 };
364 match size {
365 None => size = Some(num(f.first().copied().unwrap_or(""))?),
366 Some(n) => {
367 if f.len() < 3 {
368 return Err(parse_error(i + 1, "expected 'row column value'"));
369 }
370 let (r, c) = (num(f[0])?, num(f[1])?);
371 if r == 0 || c == 0 || r > n || c > n {
372 return Err(parse_error(
373 i + 1,
374 format!("index out of range [1, {n}]"),
375 ));
376 }
377 if r != c {
378 triples.push((r - 1, c - 1, score(i + 1, f[2])?));
379 }
380 }
381 }
382 }
383 parse_matrix_market(text)?;
384 return Ok((size.unwrap_or(0), triples));
385 }
386 let g = parse_matrix_market(text)?;
387 Ok((
388 g.num_vertices(),
389 g.edges().map(|(u, v)| (u, v, 1.0)).collect(),
390 ))
391 }
392 _ => Err(Error::Invalid(format!(
393 "{} files hold no scores: use an edge list or a Matrix Market file",
394 format.name()
395 ))),
396 }
397}
398
399pub fn read_scores_file(path: &Path, format: Option<Format>) -> Result<Scores, Error> {
402 let format = format.or_else(|| Format::from_path(path)).ok_or_else(|| {
403 Error::Invalid(format!(
404 "cannot tell the format of {} from its extension; specify it",
405 path.display()
406 ))
407 })?;
408 parse_scores(&std::fs::read_to_string(path)?, format)
409}
410
411pub fn read_weighted_file(path: &Path, format: Option<Format>) -> Result<WeightedGraph, Error> {
413 let format = format.or_else(|| Format::from_path(path)).ok_or_else(|| {
414 Error::Invalid(format!(
415 "cannot tell the format of {} from its extension; specify it",
416 path.display()
417 ))
418 })?;
419 parse_weighted(&std::fs::read_to_string(path)?, format)
420}
421
422pub fn write_weighted_file(
424 g: &WeightedGraph,
425 path: &Path,
426 format: Option<Format>,
427 options: &WriteOptions,
428) -> Result<(), Error> {
429 let format = format.or_else(|| Format::from_path(path)).ok_or_else(|| {
430 Error::Invalid(format!(
431 "cannot tell the format of {} from its extension; specify it",
432 path.display()
433 ))
434 })?;
435 std::fs::write(path, to_string_weighted(g, format, options)?)?;
436 Ok(())
437}
438
439fn add_weights(base: &str, g: &WeightedGraph, format: Format) -> String {
442 let mut weights = g.edges().map(|(_, _, w)| w);
443 let mut out = String::with_capacity(base.len() + g.num_edges() * 24);
444 for line in base.lines() {
445 let t = line.trim_start();
446 let is_edge = match format {
447 Format::Dot => t.contains(" -- "),
448 _ => t.starts_with("<edge "),
449 };
450 if format == Format::GraphML && t.starts_with("<graph ") {
451 out.push_str(
452 " <key id=\"weight\" for=\"edge\" attr.name=\"weight\" attr.type=\"int\"/>\n",
453 );
454 }
455 if is_edge {
456 let w = weights.next().unwrap();
457 if format == Format::Dot {
458 let attrs = format!("label=\"{w}\", penwidth={}", 1.0 + f64::from(w).ln());
459 if let Some(stripped) = line.strip_suffix("];") {
460 writeln!(out, "{stripped}, {attrs}];").unwrap();
461 } else {
462 writeln!(out, "{} [{attrs}];", line.trim_end_matches(';')).unwrap();
463 }
464 } else {
465 let open = line.trim_end_matches("/>");
466 writeln!(out, "{open}><data key=\"weight\">{w}</data></edge>").unwrap();
467 }
468 continue;
469 }
470 out.push_str(line);
471 out.push('\n');
472 }
473 out
474}
475
476fn parse_weighted_lists(text: &str) -> Result<WeightedGraph, Error> {
477 let mut sc = Scanner::new(text);
478 let mut rows: Vec<Vec<i64>> = vec![Vec::new()];
479 while let Some(x) = sc.next_int() {
480 if x == -1 {
481 rows.push(Vec::new());
482 } else {
483 rows.last_mut().unwrap().push(x);
484 }
485 }
486 if !rows.pop().unwrap().is_empty() {
487 return Err(Error::Parse {
488 line: None,
489 msg: "the last adjacency list is not terminated by -1".into(),
490 });
491 }
492 let n = rows.len() as i64;
493 let mut edges = Vec::new();
494 for (i, row) in rows.iter().enumerate() {
495 for &x in row {
496 if x < 0 {
497 return Err(parse_error(i + 1, format!("invalid entry {x}")));
498 }
499 let (v, w) = ((x % n) as usize, x / n + 1);
500 if w > 255 {
501 return Err(parse_error(
502 i + 1,
503 format!("entry {x} encodes weight {w}; weights must be at most 255"),
504 ));
505 }
506 edges.push((i, v, w as u32));
507 }
508 }
509 WeightedGraph::from_weighted_edges(rows.len(), edges)
510}
511
512fn write_weighted_lists(g: &WeightedGraph) -> String {
513 let n = g.num_vertices();
515 let mut s = String::new();
516 for u in 0..n {
517 for &v in g.neighbors(u).iter().filter(|&&v| v as usize > u) {
518 let w = usize::from(g.weight(u, v as usize));
519 write!(s, "{} ", v as usize + (w - 1) * n).unwrap();
520 }
521 s.push_str("-1\n");
522 }
523 s
524}
525
526fn parse_weighted_edge_list(text: &str) -> Result<WeightedGraph, Error> {
527 let mut declared = None;
528 let mut edges = Vec::new();
529 for (i, line) in text.lines().enumerate() {
530 let line = line.trim();
531 if let Some(comment) = line.strip_prefix('#').or_else(|| line.strip_prefix('%')) {
532 if let Some(n) = comment.trim().strip_prefix("vertices:") {
533 declared = Some(
534 n.trim()
535 .parse::<usize>()
536 .map_err(|_| parse_error(i + 1, "bad vertex count"))?,
537 );
538 }
539 continue;
540 }
541 if line.is_empty() {
542 continue;
543 }
544 let fields: Vec<&str> = line
545 .split(|c: char| c == ',' || c.is_whitespace())
546 .filter(|f| !f.is_empty())
547 .collect();
548 if fields.len() < 2 {
549 return Err(parse_error(
550 i + 1,
551 "expected two vertices and an optional weight",
552 ));
553 }
554 let num = |f: &str| {
555 f.parse::<usize>()
556 .map_err(|_| parse_error(i + 1, format!("'{f}' is not a vertex number")))
557 };
558 let w = match fields.get(2) {
559 None => 1,
560 Some(f) => f.parse::<u32>().map_err(|_| {
561 parse_error(i + 1, format!("'{f}' is not a positive integer weight"))
562 })?,
563 };
564 edges.push((num(fields[0])?, num(fields[1])?, w));
565 }
566 let n = declared.unwrap_or_else(|| {
567 edges
568 .iter()
569 .map(|&(u, v, _)| u.max(v) + 1)
570 .max()
571 .unwrap_or(0)
572 });
573 WeightedGraph::from_weighted_edges(n, edges)
574}
575
576fn parse_weighted_matrix_market(text: &str) -> Result<WeightedGraph, Error> {
577 let header = text.lines().next().unwrap_or("").to_ascii_lowercase();
578 if header.split_whitespace().nth(3) == Some("pattern") {
579 return Ok(WeightedGraph::from_graph(&parse_matrix_market(text)?));
580 }
581 let mut size = None;
582 let mut edges = Vec::new();
583 for (i, line) in text.lines().enumerate().skip(1) {
584 let line = line.trim();
585 if line.is_empty() || line.starts_with('%') {
586 continue;
587 }
588 let f: Vec<&str> = line.split_whitespace().collect();
589 let num = |s: &str| {
590 s.parse::<usize>()
591 .map_err(|_| parse_error(i + 1, format!("'{s}' is not an index")))
592 };
593 match size {
594 None => size = Some(num(f.first().copied().unwrap_or(""))?),
595 Some(n) => {
596 if f.len() < 3 {
597 return Err(parse_error(i + 1, "expected 'row column value'"));
598 }
599 let (r, c) = (num(f[0])?, num(f[1])?);
600 if r == 0 || c == 0 || r > n || c > n {
601 return Err(parse_error(i + 1, format!("index out of range [1, {n}]")));
602 }
603 let value: f64 = f[2]
604 .parse()
605 .map_err(|_| parse_error(i + 1, format!("'{}' is not a number", f[2])))?;
606 if value == 0.0 || r == c {
607 continue;
608 }
609 if value.fract() != 0.0 || !(1.0..=255.0).contains(&value) {
610 return Err(parse_error(
611 i + 1,
612 format!("weight {value} is not an integer between 1 and 255"),
613 ));
614 }
615 edges.push((r - 1, c - 1, value as u32));
616 }
617 }
618 }
619 parse_matrix_market(text)?;
621 WeightedGraph::from_weighted_edges(size.unwrap_or(0), edges)
622}
623
624pub fn read_file(path: &Path, format: Option<Format>) -> Result<Graph, Error> {
626 let format = format.or_else(|| Format::from_path(path)).ok_or_else(|| {
627 Error::Invalid(format!(
628 "cannot tell the format of {} from its extension; specify it",
629 path.display()
630 ))
631 })?;
632 let text = std::fs::read_to_string(path)?;
633 parse(&text, format)
634}
635
636pub fn read_file_all(path: &Path, format: Option<Format>) -> Result<Vec<Graph>, Error> {
638 let format = format.or_else(|| Format::from_path(path)).ok_or_else(|| {
639 Error::Invalid(format!(
640 "cannot tell the format of {} from its extension; specify it",
641 path.display()
642 ))
643 })?;
644 let text = std::fs::read_to_string(path)?;
645 parse_all(&text, format)
646}
647
648pub fn write_file(
650 g: &Graph,
651 path: &Path,
652 format: Option<Format>,
653 options: &WriteOptions,
654) -> Result<(), Error> {
655 let format = format.or_else(|| Format::from_path(path)).ok_or_else(|| {
656 Error::Invalid(format!(
657 "cannot tell the format of {} from its extension; specify it",
658 path.display()
659 ))
660 })?;
661 std::fs::write(path, to_string(g, format, options))?;
662 Ok(())
663}
664
665fn parse_error(line: usize, msg: impl Into<String>) -> Error {
666 Error::Parse {
667 line: Some(line),
668 msg: msg.into(),
669 }
670}
671
672fn parse_lists(text: &str) -> Result<Graph, Error> {
675 let mut sc = Scanner::new(text);
676 let mut rows: Vec<Vec<i64>> = vec![Vec::new()];
677 while let Some(x) = sc.next_int() {
678 if x == -1 {
679 rows.push(Vec::new());
680 } else {
681 rows.last_mut().unwrap().push(x);
682 }
683 }
684 if !rows.pop().unwrap().is_empty() {
685 return Err(Error::Parse {
686 line: None,
687 msg: "the last adjacency list is not terminated by -1".into(),
688 });
689 }
690 let n = rows.len();
691 let mut b = GraphBuilder::new(n);
692 for (i, row) in rows.iter().enumerate() {
693 for &x in row {
694 if x < 0 || x as usize >= n {
695 return Err(parse_error(
696 i + 1,
697 format!("vertex {x} is out of range [0, {n})"),
698 ));
699 }
700 if x as usize != i {
701 b.set(i, x as usize, true);
702 }
703 }
704 }
705 Ok(b.build())
706}
707
708fn write_lists(g: &Graph) -> String {
709 let mut s = String::new();
710 for u in 0..g.num_vertices() {
711 for &v in g.neighbors(u).iter().filter(|&&v| v as usize > u) {
712 write!(s, " {v}").unwrap();
713 }
714 s.push_str("-1\n");
715 }
716 s
717}
718
719fn parse_edge_list(text: &str) -> Result<Graph, Error> {
722 let mut declared = None;
723 let mut edges = Vec::new();
724 for (i, line) in text.lines().enumerate() {
725 let line = line.trim();
726 if let Some(comment) = line.strip_prefix('#').or_else(|| line.strip_prefix('%')) {
727 if let Some(n) = comment.trim().strip_prefix("vertices:") {
728 declared = Some(
729 n.trim()
730 .parse::<usize>()
731 .map_err(|_| parse_error(i + 1, "bad vertex count"))?,
732 );
733 }
734 continue;
735 }
736 if line.is_empty() {
737 continue;
738 }
739 let mut fields = line
740 .split(|c: char| c == ',' || c.is_whitespace())
741 .filter(|f| !f.is_empty());
742 let mut endpoint = || -> Result<usize, Error> {
743 let f = fields
744 .next()
745 .ok_or_else(|| parse_error(i + 1, "expected two vertices"))?;
746 f.parse()
747 .map_err(|_| parse_error(i + 1, format!("'{f}' is not a vertex number")))
748 };
749 let (u, v) = (endpoint()?, endpoint()?);
750 edges.push((u, v));
751 }
752 let n = declared.unwrap_or_else(|| edges.iter().map(|&(u, v)| u.max(v) + 1).max().unwrap_or(0));
753 Graph::from_edges(n, edges)
754}
755
756fn write_edge_list(g: &Graph) -> String {
757 let mut s = format!(
758 "# vertices: {}\n# edges: {}\n",
759 g.num_vertices(),
760 g.num_edges()
761 );
762 for (u, v) in g.edges() {
763 writeln!(s, "{u} {v}").unwrap();
764 }
765 s
766}
767
768fn encode_n(n: usize, out: &mut Vec<u8>) {
771 if n <= 62 {
772 out.push(n as u8 + 63);
773 } else if n <= 258_047 {
774 out.push(126);
775 for shift in [12, 6, 0] {
776 out.push(((n >> shift) & 63) as u8 + 63);
777 }
778 } else {
779 out.extend([126, 126]);
780 for shift in [30, 24, 18, 12, 6, 0] {
781 out.push(((n >> shift) & 63) as u8 + 63);
782 }
783 }
784}
785
786fn decode_n(bytes: &[u8]) -> Result<(usize, &[u8]), Error> {
787 let bad = || Error::Parse {
788 line: Some(1),
789 msg: "truncated or invalid vertex count".into(),
790 };
791 let value = |chunk: &[u8]| {
792 chunk.iter().try_fold(0usize, |acc, &c| {
793 (63..=126)
794 .contains(&c)
795 .then(|| acc << 6 | (c - 63) as usize)
796 })
797 };
798 match bytes {
799 [126, 126, rest @ ..] if rest.len() >= 6 => {
800 Ok((value(&rest[..6]).ok_or_else(bad)?, &rest[6..]))
801 }
802 [126, rest @ ..] if rest.len() >= 3 => Ok((value(&rest[..3]).ok_or_else(bad)?, &rest[3..])),
803 [c, rest @ ..] if (63..=125).contains(c) => Ok(((c - 63) as usize, rest)),
804 _ => Err(bad()),
805 }
806}
807
808fn six_bit_groups(data: &[u8]) -> Result<Vec<u8>, Error> {
809 data.iter()
810 .map(|&c| {
811 (63..=126)
812 .contains(&c)
813 .then(|| c - 63)
814 .ok_or_else(|| Error::Parse {
815 line: Some(1),
816 msg: format!("invalid character {:?}", c as char),
817 })
818 })
819 .collect()
820}
821
822fn pack_bits(bits: &[bool], out: &mut Vec<u8>) {
823 for chunk in bits.chunks(6) {
824 let mut x = 0u8;
825 for (k, &b) in chunk.iter().enumerate() {
826 x |= u8::from(b) << (5 - k);
827 }
828 out.push(x + 63);
829 }
830}
831
832fn parse_graph6(line: &str) -> Result<Graph, Error> {
834 let (n, data) = decode_n(line.as_bytes())?;
835 let groups = six_bit_groups(data)?;
836 let needed = (n * n.saturating_sub(1) / 2).div_ceil(6);
837 if groups.len() != needed {
838 return Err(Error::Parse {
839 line: Some(1),
840 msg: format!(
841 "expected {needed} data bytes for {n} vertices, got {}",
842 groups.len()
843 ),
844 });
845 }
846 let mut b = GraphBuilder::new(n);
847 let mut k = 0;
848 for j in 1..n {
849 for i in 0..j {
850 if groups[k / 6] >> (5 - k % 6) & 1 == 1 {
851 b.set(i, j, true);
852 }
853 k += 1;
854 }
855 }
856 Ok(b.build())
857}
858
859pub fn write_graph6(g: &Graph) -> String {
861 let n = g.num_vertices();
862 let mut out = Vec::new();
863 encode_n(n, &mut out);
864 let mut bits = Vec::with_capacity(n * n.saturating_sub(1) / 2);
865 for j in 1..n {
866 for i in 0..j {
867 bits.push(g.has_edge(i, j));
868 }
869 }
870 pack_bits(&bits, &mut out);
871 String::from_utf8(out).unwrap()
872}
873
874fn sparse6_k(n: usize) -> usize {
875 let mut k = 1;
876 while (1usize << k) < n {
877 k += 1;
878 }
879 k
880}
881
882fn parse_sparse6(line: &str) -> Result<Graph, Error> {
884 let body = line.strip_prefix(':').ok_or_else(|| Error::Parse {
885 line: Some(1),
886 msg: "sparse6 data must start with ':'".into(),
887 })?;
888 let (n, data) = decode_n(body.as_bytes())?;
889 let groups = six_bit_groups(data)?;
890 let k = sparse6_k(n);
891 let total = groups.len() * 6;
892 let bit = |p: usize| groups[p / 6] >> (5 - p % 6) & 1;
893 let mut b = GraphBuilder::new(n);
894 let (mut pos, mut v) = (0usize, 0usize);
895 while pos + 1 + k <= total {
896 let flag = bit(pos);
897 let mut x = 0usize;
898 for t in 0..k {
899 x = x << 1 | bit(pos + 1 + t) as usize;
900 }
901 pos += 1 + k;
902 if flag == 1 {
903 v += 1;
904 }
905 if x >= n || v >= n {
906 break;
907 }
908 if x > v {
909 v = x;
910 } else if x != v {
911 b.set(x, v, true);
912 }
913 }
914 Ok(b.build())
915}
916
917pub fn write_sparse6(g: &Graph) -> String {
919 let n = g.num_vertices();
920 let k = sparse6_k(n);
921 let mut bits = Vec::new();
922 let push = |bits: &mut Vec<bool>, x: usize| {
923 for t in (0..k).rev() {
924 bits.push(x >> t & 1 == 1);
925 }
926 };
927 let mut cur = 0usize;
928 for v in 0..n {
929 for &u in g.neighbors(v).iter().filter(|&&u| (u as usize) < v) {
930 let u = u as usize;
931 if v == cur {
932 bits.push(false);
933 push(&mut bits, u);
934 } else if v == cur + 1 {
935 cur += 1;
936 bits.push(true);
937 push(&mut bits, u);
938 } else {
939 cur = v;
940 bits.push(true);
941 push(&mut bits, v);
942 bits.push(false);
943 push(&mut bits, u);
944 }
945 }
946 }
947 let padding = (6 - bits.len() % 6) % 6;
948 if k < 6 && n == (1 << k) && padding >= k && cur + 1 < n {
949 bits.push(false);
950 }
951 let padding = (6 - bits.len() % 6) % 6;
952 bits.extend(std::iter::repeat_n(true, padding));
953 let mut out = vec![b':'];
954 encode_n(n, &mut out);
955 pack_bits(&bits, &mut out);
956 String::from_utf8(out).unwrap()
957}
958
959fn parse_matrix_market(text: &str) -> Result<Graph, Error> {
962 let mut lines = text.lines().enumerate();
963 let (_, header) = lines.next().ok_or_else(|| parse_error(1, "empty file"))?;
964 let h: Vec<String> = header
965 .split_whitespace()
966 .map(str::to_ascii_lowercase)
967 .collect();
968 if h.len() < 5 || h[0] != "%%matrixmarket" || h[1] != "matrix" || h[2] != "coordinate" {
969 return Err(parse_error(
970 1,
971 "expected a '%%MatrixMarket matrix coordinate ...' header",
972 ));
973 }
974 let pattern = h[3] == "pattern";
975 let mut size = None;
976 let mut edges = Vec::new();
977 for (i, line) in lines {
978 let line = line.trim();
979 if line.is_empty() || line.starts_with('%') {
980 continue;
981 }
982 let f: Vec<&str> = line.split_whitespace().collect();
983 let num = |s: &str| {
984 s.parse::<usize>()
985 .map_err(|_| parse_error(i + 1, format!("'{s}' is not an index")))
986 };
987 match size {
988 None => {
989 if f.len() < 3 {
990 return Err(parse_error(i + 1, "expected 'rows columns entries'"));
991 }
992 let (r, c) = (num(f[0])?, num(f[1])?);
993 if r != c {
994 return Err(parse_error(
995 i + 1,
996 format!("an adjacency matrix must be square, got {r} x {c}"),
997 ));
998 }
999 size = Some(r);
1000 }
1001 Some(n) => {
1002 if f.len() < 2 {
1003 return Err(parse_error(i + 1, "expected 'row column [value]'"));
1004 }
1005 let (r, c) = (num(f[0])?, num(f[1])?);
1006 if r == 0 || c == 0 || r > n || c > n {
1007 return Err(parse_error(i + 1, format!("index out of range [1, {n}]")));
1008 }
1009 let nonzero = pattern
1010 || f.get(2)
1011 .and_then(|v| v.parse::<f64>().ok())
1012 .is_some_and(|v| v != 0.0);
1013 if nonzero && r != c {
1014 edges.push((r - 1, c - 1));
1015 }
1016 }
1017 }
1018 }
1019 Graph::from_edges(
1020 size.ok_or_else(|| parse_error(1, "missing size line"))?,
1021 edges,
1022 )
1023}
1024
1025fn write_matrix_market(g: &Graph) -> String {
1026 let n = g.num_vertices();
1027 let mut s = format!(
1028 "%%MatrixMarket matrix coordinate pattern symmetric\n{n} {n} {}\n",
1029 g.num_edges()
1030 );
1031 for (u, v) in g.edges() {
1033 writeln!(s, "{} {}", v + 1, u + 1).unwrap();
1034 }
1035 s
1036}
1037
1038fn write_dot(g: &Graph, highlight: &[usize]) -> String {
1041 let n = g.num_vertices();
1042 let mut marked = vec![false; n];
1043 for &v in highlight.iter().filter(|&&v| v < n) {
1044 marked[v] = true;
1045 }
1046 let mut s = String::from("graph G {\n");
1047 if n > 20 {
1048 s.push_str(" layout=sfdp;\n overlap=false;\n splines=false;\n node [shape=point, width=0.05, height=0.05];\n");
1049 } else {
1050 s.push_str(" layout=neato;\n overlap=false;\n node [shape=circle];\n");
1051 }
1052 if !highlight.is_empty() {
1053 s.push_str(" edge [color=gray70];\n");
1054 for v in (0..n).filter(|&v| marked[v]) {
1055 writeln!(s, " {v} [color=red, style=filled, fillcolor=red];").unwrap();
1056 }
1057 }
1058 for (u, v) in g.edges() {
1059 if marked[u] && marked[v] {
1060 writeln!(s, " {u} -- {v} [color=red, penwidth=2];").unwrap();
1061 } else {
1062 writeln!(s, " {u} -- {v};").unwrap();
1063 }
1064 }
1065 for v in (0..n).filter(|&v| g.degree(v) == 0 && !marked[v]) {
1066 writeln!(s, " {v};").unwrap();
1067 }
1068 s.push_str("}\n");
1069 s
1070}
1071
1072fn write_graphml(g: &Graph, highlight: &[usize]) -> String {
1073 let n = g.num_vertices();
1074 let mut marked = vec![false; n];
1075 for &v in highlight.iter().filter(|&&v| v < n) {
1076 marked[v] = true;
1077 }
1078 let mut s = String::from(concat!(
1079 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n",
1080 "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\" ",
1081 "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ",
1082 "xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd\">\n",
1083 ));
1084 if !highlight.is_empty() {
1085 s.push_str(" <key id=\"in_subgraph\" for=\"node\" attr.name=\"in_subgraph\" attr.type=\"boolean\"><default>false</default></key>\n");
1086 }
1087 s.push_str(" <graph id=\"G\" edgedefault=\"undirected\">\n");
1088 for (v, &is_marked) in marked.iter().enumerate() {
1089 if is_marked {
1090 writeln!(
1091 s,
1092 " <node id=\"n{v}\"><data key=\"in_subgraph\">true</data></node>"
1093 )
1094 .unwrap();
1095 } else {
1096 writeln!(s, " <node id=\"n{v}\"/>").unwrap();
1097 }
1098 }
1099 for (u, v) in g.edges() {
1100 writeln!(s, " <edge source=\"n{u}\" target=\"n{v}\"/>").unwrap();
1101 }
1102 s.push_str(" </graph>\n</graphml>\n");
1103 s
1104}
1105
1106#[cfg(test)]
1107mod tests {
1108 use super::*;
1109
1110 #[test]
1111 fn scores_read_from_edge_lists_and_matrix_market() {
1112 let (n, t) =
1113 parse_scores("# vertices: 4\n0 1 2.5\n1,2,0.25\n2 3\n", Format::EdgeList).unwrap();
1114 assert_eq!((n, t), (4, vec![(0, 1, 2.5), (1, 2, 0.25), (2, 3, 1.0)]));
1115 let mtx =
1116 "%%MatrixMarket matrix coordinate real symmetric\n3 3 3\n2 1 1.5\n3 3 9\n3 1 0.75\n";
1117 let (n, t) = parse_scores(mtx, Format::MatrixMarket).unwrap();
1118 assert_eq!((n, t), (3, vec![(1, 0, 1.5), (2, 0, 0.75)]));
1119 assert!(parse_scores("0 1 -2\n", Format::EdgeList).is_err());
1120 assert!(parse_scores("0 1 x\n", Format::EdgeList).is_err());
1121 assert!(parse_scores("", Format::Graph6).is_err());
1122 }
1123
1124 fn sample() -> Graph {
1125 Graph::from_edges(9, [(0, 1), (0, 2), (1, 2), (5, 6), (7, 8), (2, 8)]).unwrap()
1126 }
1127
1128 #[test]
1129 fn round_trips() {
1130 let g = sample();
1131 for format in [
1132 Format::Lists,
1133 Format::EdgeList,
1134 Format::Graph6,
1135 Format::Sparse6,
1136 Format::MatrixMarket,
1137 ] {
1138 let text = to_string(&g, format, &WriteOptions::default());
1139 assert_eq!(parse(&text, format).unwrap(), g, "{format:?}: {text}");
1140 }
1141 for n in [0, 1, 2, 62, 63, 64, 100, 300] {
1142 let g = Graph::from_edges(n, (1..n).step_by(3).map(|i| (i - 1, i))).unwrap();
1143 assert_eq!(parse_graph6(&write_graph6(&g)).unwrap(), g, "graph6 n={n}");
1144 assert_eq!(
1145 parse_sparse6(&write_sparse6(&g)).unwrap(),
1146 g,
1147 "sparse6 n={n}"
1148 );
1149 }
1150 }
1151
1152 #[test]
1153 fn known_encodings() {
1154 let g = Graph::from_edges(5, [(0, 2), (0, 4), (1, 3), (3, 4)]).unwrap();
1156 assert_eq!(write_graph6(&g), "DQc");
1157 let s = Graph::from_edges(7, [(0, 1), (0, 2), (1, 2), (5, 6)]).unwrap();
1158 assert_eq!(write_sparse6(&s), ":Fa@x^");
1159 assert_eq!(parse_sparse6(":Fa@x^").unwrap(), s);
1160 }
1161
1162 #[test]
1163 fn multi_graph_files() {
1164 let graphs: Vec<Graph> = (2..6)
1165 .map(|n| Graph::from_edges(n, (1..n).map(|i| (i - 1, i))).unwrap())
1166 .collect();
1167 for format in [Format::Graph6, Format::Sparse6] {
1168 let text = to_string_all(&graphs, format).unwrap();
1169 assert_eq!(text.lines().count(), 4);
1170 assert_eq!(parse_all(&text, format).unwrap(), graphs);
1171 assert!(matches!(
1172 parse(&text, format),
1173 Err(Error::MultipleGraphs(4))
1174 ));
1175 let header = if format == Format::Graph6 {
1177 ">>graph6<<"
1178 } else {
1179 ">>sparse6<<"
1180 };
1181 let padded = format!(
1182 "{header}{}\n\n {}\n",
1183 text.lines().next().unwrap(),
1184 text.lines().nth(1).unwrap()
1185 );
1186 assert_eq!(parse_all(&padded, format).unwrap(), graphs[..2].to_vec());
1187 }
1188 let err = parse_all("A_\nDQc\nD!!\n", Format::Graph6)
1190 .unwrap_err()
1191 .to_string();
1192 assert!(err.starts_with("line 3:"), "{err}");
1193 assert!(to_string_all(&graphs, Format::EdgeList).is_err());
1194 assert!(matches!(
1195 parse("", Format::Graph6),
1196 Err(Error::Parse { .. })
1197 ));
1198 }
1199
1200 #[test]
1201 fn weighted_round_trips() {
1202 let g = WeightedGraph::from_weighted_edges(
1203 9,
1204 [(0, 1, 3), (0, 2, 1), (5, 6, 127), (7, 8, 2), (2, 8, 255)],
1205 )
1206 .unwrap();
1207 for format in [
1208 Format::WeightedLists,
1209 Format::EdgeList,
1210 Format::MatrixMarket,
1211 ] {
1212 let text = to_string_weighted(&g, format, &WriteOptions::default()).unwrap();
1213 assert_eq!(
1214 parse_weighted(&text, format).unwrap(),
1215 g,
1216 "{format:?}: {text}"
1217 );
1218 }
1219 let lists =
1221 to_string_weighted(&g, Format::WeightedLists, &WriteOptions::default()).unwrap();
1222 assert_eq!(lists.lines().next().unwrap(), "19 2 -1");
1223 assert_eq!(
1225 parse_weighted("DQc", Format::Graph6)
1226 .unwrap()
1227 .total_weight(),
1228 4
1229 );
1230 assert!(to_string_weighted(&g, Format::Graph6, &WriteOptions::default()).is_err());
1231 assert_eq!(parse(&lists, Format::WeightedLists).unwrap(), g.structure());
1233 let dot =
1234 to_string_weighted(&g, Format::Dot, &WriteOptions { highlight: &[5, 6] }).unwrap();
1235 assert!(
1236 dot.contains("5 -- 6 [color=red, penwidth=2, label=\"127\"")
1237 && dot.contains("0 -- 1 [label=\"3\""),
1238 "{dot}"
1239 );
1240 let gml = to_string_weighted(&g, Format::GraphML, &WriteOptions::default()).unwrap();
1241 assert_eq!(gml.matches("<data key=\"weight\">").count(), 5);
1242 assert!(
1243 parse_weighted(
1244 "%%MatrixMarket matrix coordinate real symmetric\n3 3 1\n2 1 1.5\n",
1245 Format::MatrixMarket
1246 )
1247 .is_err()
1248 );
1249 }
1250
1251 #[test]
1252 fn edge_lists_keep_isolated_vertices() {
1253 let g = parse_edge_list("# vertices: 5\n0,1\n3 4\n").unwrap();
1254 assert_eq!((g.num_vertices(), g.num_edges()), (5, 2));
1255 assert_eq!(parse_edge_list("1 2\n").unwrap().num_vertices(), 3);
1256 }
1257
1258 #[test]
1259 fn matrix_market_accepts_weighted_general_matrices() {
1260 let text = "%%MatrixMarket matrix coordinate real general\n% a comment\n3 3 4\n1 2 1.5\n2 1 1.5\n3 3 2.0\n1 3 0\n";
1261 let g = parse_matrix_market(text).unwrap();
1262 assert_eq!(g.edges().collect::<Vec<_>>(), vec![(0, 1)]);
1263 }
1264}