Debian Codegraph @

draw/draw.go

raw symbols SCIP
1 // Package draw provides functions for visualizing graph structures. At this
2 // time, draw supports the DOT language which can be interpreted by Graphviz,
3 // Grappa, and others.
4 package draw
5
6 import (
7 "fmt"
8 "io"
9 "text/template"
10
11 "github.com/dominikbraun/graph"
12 )
13
14 // ToDo: This template should be simplified and split into multiple templates.
15 const dotTemplate = `strict {{.GraphType}} {
16 {{range $k, $v := .Attributes}}
17 {{$k}}="{{$v}}";
18 {{end}}
19 {{range $s := .Statements}}
20 "{{.Source}}" {{if .Target}}{{$.EdgeOperator}} "{{.Target}}" [ {{range $k, $v := .EdgeAttributes}}{{$k}}="{{$v}}", {{end}} weight={{.EdgeWeight}} ]{{else}}[ {{range $k, $v := .SourceAttributes}}{{$k}}="{{$v}}", {{end}} weight={{.SourceWeight}} ]{{end}};
21 {{end}}
22 }
23 `
24
25 type description struct {
26 GraphType string
27 Attributes map[string]string
28 EdgeOperator string
29 Statements []statement
30 }
31
32 type statement struct {
33 Source interface{}
34 Target interface{}
35 SourceWeight int
36 SourceAttributes map[string]string
37 EdgeWeight int
38 EdgeAttributes map[string]string
39 }
40
41 // DOT renders the given graph structure in DOT language into an io.Writer, for
42 // example a file. The generated output can be passed to Graphviz or other
43 // visualization tools supporting DOT.
44 //
45 // The following example renders a directed graph into a file my-graph.gv:
46 //
47 // g := graph.New(graph.IntHash, graph.Directed())
48 //
49 // _ = g.AddVertex(1)
50 // _ = g.AddVertex(2)
51 // _ = g.AddVertex(3, graph.VertexAttribute("style", "filled"), graph.VertexAttribute("fillcolor", "red"))
52 //
53 // _ = g.AddEdge(1, 2, graph.EdgeWeight(10), graph.EdgeAttribute("color", "red"))
54 // _ = g.AddEdge(1, 3)
55 //
56 // file, _ := os.Create("./my-graph.gv")
57 // _ = draw.DOT(g, file)
58 //
59 // To generate an SVG from the created file using Graphviz, use a command such
60 // as the following:
61 //
62 // dot -Tsvg -O my-graph.gv
63 //
64 // Another possibility is to use os.Stdout as an io.Writer, print the DOT output
65 // to stdout, and pipe it as follows:
66 //
67 // go run main.go | dot -Tsvg > output.svg
68 //
69 // DOT also accepts the [GraphAttribute] functional option, which can be used to
70 // add global attributes when rendering the graph:
71 //
72 // _ = draw.DOT(g, file, draw.GraphAttribute("label", "my-graph"))
73 func DOT[K comparable, T any](g graph.Graph[K, T], w io.Writer, options ...func(*description)) error {
74 desc, err := generateDOT(g, options...)
75 if err != nil {
76 return fmt.Errorf("failed to generate DOT description: %w", err)
77 }
78
79 return renderDOT(w, desc)
80 }
81
82 // GraphAttribute is a functional option for the [DOT] method.
83 func GraphAttribute(key, value string) func(*description) {
84 return func(d *description) {
85 d.Attributes[key] = value
86 }
87 }
88
89 func generateDOT[K comparable, T any](g graph.Graph[K, T], options ...func(*description)) (description, error) {
90 desc := description{
91 GraphType: "graph",
92 Attributes: make(map[string]string),
93 EdgeOperator: "--",
94 Statements: make([]statement, 0),
95 }
96
97 for _, option := range options {
98 option(&desc)
99 }
100
101 if g.Traits().IsDirected {
102 desc.GraphType = "digraph"
103 desc.EdgeOperator = "->"
104 }
105
106 adjacencyMap, err := g.AdjacencyMap()
107 if err != nil {
108 return desc, err
109 }
110
111 for vertex, adjacencies := range adjacencyMap {
112 _, sourceProperties, err := g.VertexWithProperties(vertex)
113 if err != nil {
114 return desc, err
115 }
116
117 stmt := statement{
118 Source: vertex,
119 SourceWeight: sourceProperties.Weight,
120 SourceAttributes: sourceProperties.Attributes,
121 }
122 desc.Statements = append(desc.Statements, stmt)
123
124 for adjacency, edge := range adjacencies {
125 stmt := statement{
126 Source: vertex,
127 Target: adjacency,
128 EdgeWeight: edge.Properties.Weight,
129 EdgeAttributes: edge.Properties.Attributes,
130 }
131 desc.Statements = append(desc.Statements, stmt)
132 }
133 }
134
135 return desc, nil
136 }
137
138 func renderDOT(w io.Writer, d description) error {
139 tpl, err := template.New("dotTemplate").Parse(dotTemplate)
140 if err != nil {
141 return fmt.Errorf("failed to parse template: %w", err)
142 }
143
144 return tpl.Execute(w, d)
145 }