Debian Codegraph @

graph.go

raw symbols SCIP
1 // Package graph is a library for creating generic graph data structures and
2 // modifying, analyzing, and visualizing them.
3 //
4 // # Hashes
5 //
6 // A graph consists of vertices of type T, which are identified by a hash value
7 // of type K. The hash value for a given vertex is obtained using the hashing
8 // function passed to [New]. A hashing function takes a T and returns a K.
9 //
10 // For primitive types like integers, you may use a predefined hashing function
11 // such as [IntHash] – a function that takes an integer and uses that integer as
12 // the hash value at the same time:
13 //
14 // g := graph.New(graph.IntHash)
15 //
16 // For storing custom data types, you need to provide your own hashing function.
17 // This example takes a City instance and returns its name as the hash value:
18 //
19 // cityHash := func(c City) string {
20 // return c.Name
21 // }
22 //
23 // Creating a graph using this hashing function will yield a graph of vertices
24 // of type City identified by hash values of type string.
25 //
26 // g := graph.New(cityHash)
27 //
28 // # Operations
29 //
30 // Adding vertices to a graph of integers is simple. [graph.Graph.AddVertex]
31 // takes a vertex and adds it to the graph.
32 //
33 // g := graph.New(graph.IntHash)
34 //
35 // _ = g.AddVertex(1)
36 // _ = g.AddVertex(2)
37 //
38 // Most functions accept and return only hash values instead of entire instances
39 // of the vertex type T. For example, [graph.Graph.AddEdge] creates an edge
40 // between two vertices and accepts the hash values of those vertices. Because
41 // this graph uses the [IntHash] hashing function, the vertex values and hash
42 // values are the same.
43 //
44 // _ = g.AddEdge(1, 2)
45 //
46 // All operations that modify the graph itself are methods of [Graph]. All other
47 // operations are top-level functions of by this library.
48 //
49 // For detailed usage examples, take a look at the README.
50 package graph
51
52 import "errors"
53
54 var (
55 ErrVertexNotFound = errors.New("vertex not found")
56 ErrVertexAlreadyExists = errors.New("vertex already exists")
57 ErrEdgeNotFound = errors.New("edge not found")
58 ErrEdgeAlreadyExists = errors.New("edge already exists")
59 ErrEdgeCreatesCycle = errors.New("edge would create a cycle")
60 ErrVertexHasEdges = errors.New("vertex has edges")
61 )
62
63 // Graph represents a generic graph data structure consisting of vertices of
64 // type T identified by a hash of type K.
65 type Graph[K comparable, T any] interface {
66 // Traits returns the graph's traits. Those traits must be set when creating
67 // a graph using New.
68 Traits() *Traits
69
70 // AddVertex creates a new vertex in the graph. If the vertex already exists
71 // in the graph, ErrVertexAlreadyExists will be returned.
72 //
73 // AddVertex accepts a variety of functional options to set further edge
74 // details such as the weight or an attribute:
75 //
76 // _ = graph.AddVertex("A", "B", graph.VertexWeight(4), graph.VertexAttribute("label", "my-label"))
77 //
78 AddVertex(value T, options ...func(*VertexProperties)) error
79
80 // AddVerticesFrom adds all vertices along with their properties from the
81 // given graph to the receiving graph.
82 //
83 // All vertices will be added until an error occurs. If one of the vertices
84 // already exists, ErrVertexAlreadyExists will be returned.
85 AddVerticesFrom(g Graph[K, T]) error
86
87 // Vertex returns the vertex with the given hash or ErrVertexNotFound if it
88 // doesn't exist.
89 Vertex(hash K) (T, error)
90
91 // VertexWithProperties returns the vertex with the given hash along with
92 // its properties or ErrVertexNotFound if it doesn't exist.
93 VertexWithProperties(hash K) (T, VertexProperties, error)
94
95 // RemoveVertex removes the vertex with the given hash value from the graph.
96 //
97 // The vertex is not allowed to have edges and thus must be disconnected.
98 // Potential edges must be removed first. Otherwise, ErrVertexHasEdges will
99 // be returned. If the vertex doesn't exist, ErrVertexNotFound is returned.
100 RemoveVertex(hash K) error
101
102 // AddEdge creates an edge between the source and the target vertex.
103 //
104 // If either vertex cannot be found, ErrVertexNotFound will be returned. If
105 // the edge already exists, ErrEdgeAlreadyExists will be returned. If cycle
106 // prevention has been activated using PreventCycles and if adding the edge
107 // would create a cycle, ErrEdgeCreatesCycle will be returned.
108 //
109 // AddEdge accepts functional options to set further edge properties such as
110 // the weight or an attribute:
111 //
112 // _ = g.AddEdge("A", "B", graph.EdgeWeight(4), graph.EdgeAttribute("label", "my-label"))
113 //
114 AddEdge(sourceHash, targetHash K, options ...func(*EdgeProperties)) error
115
116 // AddEdgesFrom adds all edges along with their properties from the given
117 // graph to the receiving graph.
118 //
119 // All vertices that the edges are joining have to exist already. If needed,
120 // these vertices can be added using AddVerticesFrom first. Depending on the
121 // situation, it also might make sense to clone the entire original graph.
122 AddEdgesFrom(g Graph[K, T]) error
123
124 // Edge returns the edge joining two given vertices or ErrEdgeNotFound if
125 // the edge doesn't exist. In an undirected graph, an edge with swapped
126 // source and target vertices does match.
127 Edge(sourceHash, targetHash K) (Edge[T], error)
128
129 // Edges returns a slice of all edges in the graph. These edges are of type
130 // Edge[K] and hence will contain the vertex hashes, not the vertex values.
131 Edges() ([]Edge[K], error)
132
133 // UpdateEdge updates the edge joining the two given vertices with the data
134 // provided in the given functional options. Valid functional options are:
135 // - EdgeWeight: Sets a new weight for the edge properties.
136 // - EdgeAttribute: Adds a new attribute to the edge properties.
137 // - EdgeAttributes: Sets a new attributes map for the edge properties.
138 // - EdgeData: Sets a new Data field for the edge properties.
139 //
140 // UpdateEdge accepts the same functional options as AddEdge. For example,
141 // setting the weight of an edge (A,B) to 10 would look as follows:
142 //
143 // _ = g.UpdateEdge("A", "B", graph.EdgeWeight(10))
144 //
145 // Removing a particular edge attribute is not possible at the moment. A
146 // workaround is to create a new map without the respective element and
147 // overwrite the existing attributes using the EdgeAttributes option.
148 UpdateEdge(source, target K, options ...func(properties *EdgeProperties)) error
149
150 // RemoveEdge removes the edge between the given source and target vertices.
151 // If the edge cannot be found, ErrEdgeNotFound will be returned.
152 RemoveEdge(source, target K) error
153
154 // AdjacencyMap computes an adjacency map with all vertices in the graph.
155 //
156 // There is an entry for each vertex. Each of those entries is another map
157 // whose keys are the hash values of the adjacent vertices. The value is an
158 // Edge instance that stores the source and target hash values along with
159 // the edge metadata.
160 //
161 // For a directed graph with two edges AB and AC, AdjacencyMap would return
162 // the following map:
163 //
164 // map[string]map[string]Edge[string]{
165 // "A": map[string]Edge[string]{
166 // "B": {Source: "A", Target: "B"},
167 // "C": {Source: "A", Target: "C"},
168 // },
169 // "B": map[string]Edge[string]{},
170 // "C": map[string]Edge[string]{},
171 // }
172 //
173 // This design makes AdjacencyMap suitable for a wide variety of algorithms.
174 AdjacencyMap() (map[K]map[K]Edge[K], error)
175
176 // PredecessorMap computes a predecessor map with all vertices in the graph.
177 //
178 // It has the same map layout and does the same thing as AdjacencyMap, but
179 // for ingoing instead of outgoing edges of each vertex.
180 //
181 // For a directed graph with two edges AB and AC, PredecessorMap would
182 // return the following map:
183 //
184 // map[string]map[string]Edge[string]{
185 // "A": map[string]Edge[string]{},
186 // "B": map[string]Edge[string]{
187 // "A": {Source: "A", Target: "B"},
188 // },
189 // "C": map[string]Edge[string]{
190 // "A": {Source: "A", Target: "C"},
191 // },
192 // }
193 //
194 // For an undirected graph, PredecessorMap is the same as AdjacencyMap. This
195 // is because there is no distinction between "outgoing" and "ingoing" edges
196 // in an undirected graph.
197 PredecessorMap() (map[K]map[K]Edge[K], error)
198
199 // Clone creates a deep copy of the graph and returns that cloned graph.
200 //
201 // The cloned graph will use the default in-memory store for storing the
202 // vertices and edges. If you want to utilize a custom store instead, create
203 // a new graph using NewWithStore and use AddVerticesFrom and AddEdgesFrom.
204 Clone() (Graph[K, T], error)
205
206 // Order returns the number of vertices in the graph.
207 Order() (int, error)
208
209 // Size returns the number of edges in the graph.
210 Size() (int, error)
211 }
212
213 // Edge represents an edge that joins two vertices. Even though these edges are
214 // always referred to as source and target, whether the graph is directed or not
215 // is determined by its traits.
216 type Edge[T any] struct {
217 Source T
218 Target T
219 Properties EdgeProperties
220 }
221
222 // EdgeProperties represents a set of properties that each edge possesses. They
223 // can be set when adding a new edge using the corresponding functional options:
224 //
225 // g.AddEdge("A", "B", graph.EdgeWeight(2), graph.EdgeAttribute("color", "red"))
226 //
227 // The example above will create an edge with a weight of 2 and an attribute
228 // "color" with value "red".
229 type EdgeProperties struct {
230 Attributes map[string]string
231 Weight int
232 Data any
233 }
234
235 // Hash is a hashing function that takes a vertex of type T and returns a hash
236 // value of type K.
237 //
238 // Every graph has a hashing function and uses that function to retrieve the
239 // hash values of its vertices. You can either use one of the predefined hashing
240 // functions or provide your own one for custom data types:
241 //
242 // cityHash := func(c City) string {
243 // return c.Name
244 // }
245 //
246 // The cityHash function returns the city name as a hash value. The types of T
247 // and K, in this case City and string, also define the types of the graph.
248 type Hash[K comparable, T any] func(T) K
249
250 // New creates a new graph with vertices of type T, identified by hash values of
251 // type K. These hash values will be obtained using the provided hash function.
252 //
253 // The graph will use the default in-memory store for persisting vertices and
254 // edges. To use a different [Store], use [NewWithStore].
255 func New[K comparable, T any](hash Hash[K, T], options ...func(*Traits)) Graph[K, T] {
256 return NewWithStore(hash, newMemoryStore[K, T](), options...)
257 }
258
259 // NewWithStore creates a new graph same as [New] but uses the provided store
260 // instead of the default memory store.
261 func NewWithStore[K comparable, T any](hash Hash[K, T], store Store[K, T], options ...func(*Traits)) Graph[K, T] {
262 var p Traits
263
264 for _, option := range options {
265 option(&p)
266 }
267
268 if p.IsDirected {
269 return newDirected(hash, &p, store)
270 }
271
272 return newUndirected(hash, &p, store)
273 }
274
275 // NewLike creates a graph that is "like" the given graph: It has the same type,
276 // the same hashing function, and the same traits. The new graph is independent
277 // of the original graph and uses the default in-memory storage.
278 //
279 // g := graph.New(graph.IntHash, graph.Directed())
280 // h := graph.NewLike(g)
281 //
282 // In the example above, h is a new directed graph of integers derived from g.
283 func NewLike[K comparable, T any](g Graph[K, T]) Graph[K, T] {
284 copyTraits := func(t *Traits) {
285 t.IsDirected = g.Traits().IsDirected
286 t.IsAcyclic = g.Traits().IsAcyclic
287 t.IsWeighted = g.Traits().IsWeighted
288 t.IsRooted = g.Traits().IsRooted
289 t.PreventCycles = g.Traits().PreventCycles
290 }
291
292 var hash Hash[K, T]
293
294 if g.Traits().IsDirected {
295 hash = g.(*directed[K, T]).hash
296 } else {
297 hash = g.(*undirected[K, T]).hash
298 }
299
300 return New(hash, copyTraits)
301 }
302
303 // StringHash is a hashing function that accepts a string and uses that exact
304 // string as a hash value. Using it as Hash will yield a Graph[string, string].
305 func StringHash(v string) string {
306 return v
307 }
308
309 // IntHash is a hashing function that accepts an integer and uses that exact
310 // integer as a hash value. Using it as Hash will yield a Graph[int, int].
311 func IntHash(v int) int {
312 return v
313 }
314
315 // EdgeWeight returns a function that sets the weight of an edge to the given
316 // weight. This is a functional option for the [graph.Graph.Edge] and
317 // [graph.Graph.AddEdge] methods.
318 func EdgeWeight(weight int) func(*EdgeProperties) {
319 return func(e *EdgeProperties) {
320 e.Weight = weight
321 }
322 }
323
324 // EdgeAttribute returns a function that adds the given key-value pair to the
325 // attributes of an edge. This is a functional option for the [graph.Graph.Edge]
326 // and [graph.Graph.AddEdge] methods.
327 func EdgeAttribute(key, value string) func(*EdgeProperties) {
328 return func(e *EdgeProperties) {
329 e.Attributes[key] = value
330 }
331 }
332
333 // EdgeAttributes returns a function that sets the given map as the attributes
334 // of an edge. This is a functional option for the [graph.Graph.AddEdge] and
335 // [graph.Graph.UpdateEdge] methods.
336 func EdgeAttributes(attributes map[string]string) func(*EdgeProperties) {
337 return func(e *EdgeProperties) {
338 e.Attributes = attributes
339 }
340 }
341
342 // EdgeData returns a function that sets the data of an edge to the given value.
343 // This is a functional option for the [graph.Graph.Edge] and
344 // [graph.Graph.AddEdge] methods.
345 func EdgeData(data any) func(*EdgeProperties) {
346 return func(e *EdgeProperties) {
347 e.Data = data
348 }
349 }
350
351 // VertexProperties represents a set of properties that each vertex has. They
352 // can be set when adding a vertex using the corresponding functional options:
353 //
354 // _ = g.AddVertex("A", "B", graph.VertexWeight(2), graph.VertexAttribute("color", "red"))
355 //
356 // The example above will create a vertex with a weight of 2 and an attribute
357 // "color" with value "red".
358 type VertexProperties struct {
359 Attributes map[string]string
360 Weight int
361 }
362
363 // VertexWeight returns a function that sets the weight of a vertex to the given
364 // weight. This is a functional option for the [graph.Graph.Vertex] and
365 // [graph.Graph.AddVertex] methods.
366 func VertexWeight(weight int) func(*VertexProperties) {
367 return func(e *VertexProperties) {
368 e.Weight = weight
369 }
370 }
371
372 // VertexAttribute returns a function that adds the given key-value pair to the
373 // vertex attributes. This is a functional option for the [graph.Graph.Vertex]
374 // and [graph.Graph.AddVertex] methods.
375 func VertexAttribute(key, value string) func(*VertexProperties) {
376 return func(e *VertexProperties) {
377 e.Attributes[key] = value
378 }
379 }
380
381 // VertexAttributes returns a function that sets the given map as the attributes
382 // of a vertex. This is a functional option for the [graph.Graph.AddVertex] methods.
383 func VertexAttributes(attributes map[string]string) func(*VertexProperties) {
384 return func(e *VertexProperties) {
385 e.Attributes = attributes
386 }
387 }