File: weighted_example_test.go

package info (click to toggle)
golang-gonum-v1-gonum 0.15.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 18,792 kB
  • sloc: asm: 6,252; fortran: 5,271; sh: 377; ruby: 211; makefile: 98
file content (95 lines) | stat: -rw-r--r-- 2,230 bytes parent folder | download
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
// Copyright ©2019 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package dot_test

import (
	"fmt"
	"log"
	"math"
	"strconv"

	"gonum.org/v1/gonum/graph"
	"gonum.org/v1/gonum/graph/encoding"
	"gonum.org/v1/gonum/graph/encoding/dot"
	"gonum.org/v1/gonum/graph/simple"
)

// dotGraph provides a shim for interaction between the DOT
// unmarshaler and a simple.WeightedUndirectedGraph.
type dotGraph struct {
	*simple.WeightedUndirectedGraph
}

func newDotGraph() *dotGraph {
	return &dotGraph{WeightedUndirectedGraph: simple.NewWeightedUndirectedGraph(0, 0)}
}

// NewEdge returns a DOT-aware edge.
func (g *dotGraph) NewEdge(from, to graph.Node) graph.Edge {
	e := g.WeightedUndirectedGraph.NewWeightedEdge(from, to, math.NaN()).(simple.WeightedEdge)
	return &weightedEdge{WeightedEdge: e}
}

// NewNode returns a DOT-aware node.
func (g *dotGraph) NewNode() graph.Node {
	return &node{Node: g.WeightedUndirectedGraph.NewNode()}
}

// SetEdge is a shim to allow the DOT unmarshaler to
// add weighted edges to a graph.
func (g *dotGraph) SetEdge(e graph.Edge) {
	g.WeightedUndirectedGraph.SetWeightedEdge(e.(*weightedEdge))
}

// weightedEdge is a DOT-aware weighted edge.
type weightedEdge struct {
	simple.WeightedEdge
}

// SetAttribute sets the weight of the receiver.
func (e *weightedEdge) SetAttribute(attr encoding.Attribute) error {
	if attr.Key != "weight" {
		return fmt.Errorf("unable to unmarshal node DOT attribute with key %q", attr.Key)
	}
	var err error
	e.W, err = strconv.ParseFloat(attr.Value, 64)
	return err
}

// node is a DOT-aware node.
type node struct {
	graph.Node
	dotID string
}

// SetDOTID sets the DOT ID of the node.
func (n *node) SetDOTID(id string) { n.dotID = id }

func (n *node) String() string { return n.dotID }

const ug = `
graph {
	a
	b
	c
	a--b ["weight"=0.5]
	a--c ["weight"=1]
}
`

func ExampleUnmarshal_weighted() {
	dst := newDotGraph()
	err := dot.Unmarshal([]byte(ug), dst)
	if err != nil {
		log.Fatal(err)
	}
	for _, e := range graph.EdgesOf(dst.Edges()) {
		fmt.Printf("%+v\n", e.(*weightedEdge).WeightedEdge)
	}

	// Unordered output:
	// {F:a T:b W:0.5}
	// {F:a T:c W:1}
}