Compare commits

..

10 Commits

Author SHA1 Message Date
filifa d8c1296dec add README 2025-05-10 00:07:48 -04:00
filifa df30e34590 add precision 6 to output strings 2025-05-10 00:04:42 -04:00
filifa 21e3ff5e74 change wording of error 2025-05-09 23:00:53 -04:00
filifa 2b49d8dd51 return errors instead of panicking 2025-05-09 22:50:21 -04:00
filifa 4cac82441a update comments 2025-05-09 22:36:18 -04:00
filifa 99d144532e update flags 2025-05-09 22:09:39 -04:00
filifa a0f7da8a09 add description 2025-05-09 22:09:23 -04:00
filifa 405b7c9414 remove my graph types 2025-05-09 00:32:59 -04:00
filifa 5bd49f2037 change type names 2025-05-08 23:57:28 -04:00
filifa 90c5547710 revert an earlier buggy simplification 2025-05-08 23:48:33 -04:00
7 changed files with 87 additions and 122 deletions

25
README.md Normal file
View File

@ -0,0 +1,25 @@
# gv2adj
gv2adj computes adjacency matrices (either weighted or unweighted) for Graphviz
graphs (both directed and undirected).
## Usage
To get the adjacency matrix of a graph in `graph.gv`:
```
gv2adj -f graph.gv
```
To get the matrix, but using the values stored in the `len` attribute as edge weights:
```
gv2adj -f graph.gv --weight-attr len
```
Say the nodes in the graph are named `foo`, `bar`, and `baz`. To order the rows and columns of the matrix so they correspond to `bar`, `baz`, `foo`:
```
gv2adj -f graph.gv --order bar,baz,foo
```
## Quirks
* If the `--weight-attr` flag is supplied, but an edge does not have the given
attribute, NaN will be output for that edge.
* If there are multiple edges going from node `a` to node `b`, the matrix entry
will be the sum of the two.

View File

@ -18,19 +18,23 @@ package graph
import ( import (
"gonum.org/v1/gonum/graph" "gonum.org/v1/gonum/graph"
"gonum.org/v1/gonum/graph/multi"
"gonum.org/v1/gonum/graph/simple"
"gonum.org/v1/gonum/mat" "gonum.org/v1/gonum/mat"
) )
// WeightedGraph is an interface so we can construct adjacency matrices for
// both directed and undirected graphs.
type WeightedGraph interface { type WeightedGraph interface {
graph.Weighted graph.Weighted
graph.WeightedMultigraph graph.WeightedMultigraph
graph.WeightedMultigraphBuilder graph.WeightedMultigraphBuilder
WeightedEdges() graph.WeightedEdges WeightedEdges() graph.WeightedEdges
AdjacencyMatrix() *mat.Dense
} }
// WeightedMatrix is an interface to handle the construction of both directed
// and undirected adjacency matrices.
type WeightedMatrix interface { type WeightedMatrix interface {
graph.Weighted graph.Weighted
@ -38,10 +42,25 @@ type WeightedMatrix interface {
Matrix() mat.Matrix Matrix() mat.Matrix
} }
// AdjacencyMatrix returns the graph's adjacency matrix.
func AdjacencyMatrix(g WeightedGraph) *mat.Dense {
var adj WeightedMatrix
switch g.(type) {
case *multi.WeightedDirectedGraph:
adj = simple.NewDirectedMatrix(g.Nodes().Len(), 0, 0, 0)
case *multi.WeightedUndirectedGraph:
adj = simple.NewUndirectedMatrix(g.Nodes().Len(), 0, 0, 0)
default:
panic("not a graph type we handle")
}
matrix := toAdjMatrix(g, adj)
return matrix
}
func toAdjMatrix(g WeightedGraph, adj WeightedMatrix) *mat.Dense { func toAdjMatrix(g WeightedGraph, adj WeightedMatrix) *mat.Dense {
copyEdges(g, adj) copyEdges(g, adj)
matrix := mat.DenseCopyOf(adj.Matrix()) matrix := addSelfEdges(g, adj)
addSelfEdges(g, matrix)
return matrix return matrix
} }
@ -50,6 +69,7 @@ func copyEdges(g WeightedGraph, adj WeightedMatrix) {
for edges := g.WeightedEdges(); edges.Next(); { for edges := g.WeightedEdges(); edges.Next(); {
e := edges.WeightedEdge() e := edges.WeightedEdge()
if e.From() == e.To() { if e.From() == e.To() {
// the simple Matrix classes don't handle self loops
continue continue
} }
@ -57,14 +77,19 @@ func copyEdges(g WeightedGraph, adj WeightedMatrix) {
} }
} }
func addSelfEdges(g WeightedGraph, matrix mat.Mutable) { func addSelfEdges(g WeightedGraph, adj WeightedMatrix) *mat.Dense {
nodes := g.Nodes() matrix := mat.DenseCopyOf(adj.Matrix())
nodes := adj.Nodes()
for i := 0; nodes.Next(); i++ { for i := 0; nodes.Next(); i++ {
u := nodes.Node() id := nodes.Node().ID()
u := g.Node(id)
e := g.WeightedEdge(u.ID(), u.ID()) e := g.WeightedEdge(u.ID(), u.ID())
if e != nil { if e != nil {
matrix.Set(i, i, e.Weight()) matrix.Set(i, i, e.Weight())
} }
} }
return matrix
} }

View File

@ -1,41 +0,0 @@
/*
Copyright © 2025 filifa
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package graph
import (
"gonum.org/v1/gonum/graph/multi"
"gonum.org/v1/gonum/graph/simple"
"gonum.org/v1/gonum/mat"
)
// DirectedGraph embeds a multi.WeightedDirectedGraph (as opposed to
// simple.WeightedDirectedGraph) to handle self loops.
type DirectedGraph struct {
*multi.WeightedDirectedGraph
}
// NewDirectedGraph returns a graph with no nodes or edges.
func NewDirectedGraph() *DirectedGraph {
return &DirectedGraph{WeightedDirectedGraph: multi.NewWeightedDirectedGraph()}
}
// AdjacencyMatrix returns the graph's adjacency matrix.
func (g *DirectedGraph) AdjacencyMatrix() *mat.Dense {
adj := simple.NewDirectedMatrix(g.Nodes().Len(), 0, 0, 0)
matrix := toAdjMatrix(g, adj)
return matrix
}

View File

@ -25,7 +25,7 @@ import (
"gonum.org/v1/gonum/graph/multi" "gonum.org/v1/gonum/graph/multi"
) )
// DOTWeightedGraph is a graph to unmarshal DOT graphs. // DOTWeightedGraph is a struct to unmarshal DOT graphs.
type DOTWeightedGraph struct { type DOTWeightedGraph struct {
igraph.WeightedGraph igraph.WeightedGraph
WeightAttribute string WeightAttribute string
@ -33,11 +33,12 @@ type DOTWeightedGraph struct {
// NewDOTDirectedGraph returns a graph with no nodes or edges. // NewDOTDirectedGraph returns a graph with no nodes or edges.
func NewDOTDirectedGraph(weightAttr string) DOTWeightedGraph { func NewDOTDirectedGraph(weightAttr string) DOTWeightedGraph {
return DOTWeightedGraph{WeightedGraph: igraph.NewDirectedGraph(), WeightAttribute: weightAttr} return DOTWeightedGraph{WeightedGraph: multi.NewWeightedDirectedGraph(), WeightAttribute: weightAttr}
} }
// NewDOTUndirectedGraph returns a graph with no nodes or edges.
func NewDOTUndirectedGraph(weightAttr string) DOTWeightedGraph { func NewDOTUndirectedGraph(weightAttr string) DOTWeightedGraph {
return DOTWeightedGraph{WeightedGraph: igraph.NewUndirectedGraph(), WeightAttribute: weightAttr} return DOTWeightedGraph{WeightedGraph: multi.NewWeightedUndirectedGraph(), WeightAttribute: weightAttr}
} }
// NewLine returns a DOT-aware weighted line. // NewLine returns a DOT-aware weighted line.

View File

@ -48,8 +48,8 @@ type weightedLine struct {
weightAttribute string weightAttribute string
} }
// SetAttribute enables storing the weight read from a DOT file. It errors if // SetAttribute enables storing the weight read from a DOT file. It only errors
// an attribute is read that can't be stored in a weightedLine. // if the weight can't be parsed as a float.
func (e *weightedLine) SetAttribute(attr encoding.Attribute) error { func (e *weightedLine) SetAttribute(attr encoding.Attribute) error {
var err error var err error

View File

@ -1,41 +0,0 @@
/*
Copyright © 2025 filifa
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package graph
import (
"gonum.org/v1/gonum/graph/multi"
"gonum.org/v1/gonum/graph/simple"
"gonum.org/v1/gonum/mat"
)
// UndirectedGraph embeds a multi.WeightedUndirectedGraph (as opposed to
// simple.WeightedUndirectedGraph) to handle self loops.
type UndirectedGraph struct {
*multi.WeightedUndirectedGraph
}
// NewUndirectedGraph returns a graph with no nodes or edges.
func NewUndirectedGraph() *UndirectedGraph {
return &UndirectedGraph{WeightedUndirectedGraph: multi.NewWeightedUndirectedGraph()}
}
// AdjacencyMatrix returns the graph's adjacency matrix.
func (g *UndirectedGraph) AdjacencyMatrix() *mat.Dense {
adj := simple.NewUndirectedMatrix(g.Nodes().Len(), 0, 0, 0)
matrix := toAdjMatrix(g, adj)
return matrix
}

View File

@ -21,6 +21,7 @@ import (
"fmt" "fmt"
"os" "os"
igraph "scm.dairydemon.net/filifa/gv2adj/cmd/internal/graph"
idot "scm.dairydemon.net/filifa/gv2adj/cmd/internal/graph/dot" idot "scm.dairydemon.net/filifa/gv2adj/cmd/internal/graph/dot"
"github.com/spf13/cobra" "github.com/spf13/cobra"
@ -43,27 +44,29 @@ var nodeOrder []string
// rootCmd represents the base command when called without any subcommands // rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{ var rootCmd = &cobra.Command{
Use: "gv2adj", Use: "gv2adj",
Short: "A brief description of your application", Short: "Compute adjacency matrices for Graphviz graphs",
Long: `A longer description that spans multiple lines and likely contains Long: `Compute adjacency matrices (either weighted or unweighted) for Graphviz graphs (both directed and undirected).
examples and usage of using your application. For example:
Cobra is a CLI library for Go that empowers applications. Compute an unweighted adjacency matrix:
This application is a tool to generate the needed files gv2adj -f <dot file>
to quickly create a Cobra application.`,
Compute a weighted adjacency matrix, where weights are stored in the 'len' attribute of each edge:
gv2adj -f <dot file> --weight-attr len
`,
// Uncomment the following line if your bare application // Uncomment the following line if your bare application
// has an action associated with it: // has an action associated with it:
Run: parse, RunE: parse,
} }
func parse(cmd *cobra.Command, args []string) { func parse(cmd *cobra.Command, args []string) error {
data, err := os.ReadFile(file) data, err := os.ReadFile(file)
if err != nil { if err != nil {
panic(err) return err
} }
ast, err := dotfmt.ParseBytes(data) ast, err := dotfmt.ParseBytes(data)
if err != nil { if err != nil {
panic(err) return err
} }
first := ast.Graphs[0] first := ast.Graphs[0]
@ -76,19 +79,20 @@ func parse(cmd *cobra.Command, args []string) {
err = dot.UnmarshalMulti(data, graph) err = dot.UnmarshalMulti(data, graph)
if err != nil { if err != nil {
panic(err) return err
} }
matrix, err := orderedAdjMatrix(graph) matrix, err := orderedAdjMatrix(graph.WeightedGraph)
if err != nil { if err != nil {
panic(err) return err
} }
outputMatrix(matrix) outputMatrix(matrix)
return nil
} }
func orderedAdjMatrix(g idot.DOTWeightedGraph) (*mat.Dense, error) { func orderedAdjMatrix(g igraph.WeightedGraph) (*mat.Dense, error) {
matrix := g.AdjacencyMatrix() matrix := igraph.AdjacencyMatrix(g)
if len(nodeOrder) == 0 { if len(nodeOrder) == 0 {
return matrix, nil return matrix, nil
} }
@ -107,7 +111,7 @@ func orderedAdjMatrix(g idot.DOTWeightedGraph) (*mat.Dense, error) {
var ok bool var ok bool
newOrder[node.ID()], ok = nodeIndexes[id] newOrder[node.ID()], ok = nodeIndexes[id]
if !ok { if !ok {
return nil, errors.New("node '" + id + "' not in given order") return nil, errors.New("node '" + id + "' not found in given order")
} }
} }
@ -130,9 +134,9 @@ func outputMatrix(matrix mat.Matrix) {
// for matlab and python formats, %#v outputs as matrix and %v is // for matlab and python formats, %#v outputs as matrix and %v is
// oneline, but for standard format, it's the opposite, so we xor // oneline, but for standard format, it's the opposite, so we xor
if (matlabFmt || pythonFmt) != oneline { if (matlabFmt || pythonFmt) != oneline {
fmt.Printf("%#v\n", out) fmt.Printf("%#.6v\n", out)
} else { } else {
fmt.Printf("%v\n", out) fmt.Printf("%.6v\n", out)
} }
} }
@ -146,14 +150,6 @@ func Execute() {
} }
func init() { func init() {
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.gv2adj.yaml)")
// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().StringVarP(&file, "file", "f", "", "dot file") rootCmd.Flags().StringVarP(&file, "file", "f", "", "dot file")
rootCmd.MarkFlagRequired("file") rootCmd.MarkFlagRequired("file")
@ -163,7 +159,7 @@ func init() {
rootCmd.Flags().BoolVar(&oneline, "oneline", false, "output on one line") rootCmd.Flags().BoolVar(&oneline, "oneline", false, "output on one line")
rootCmd.Flags().StringVar(&weightAttr, "weight-attr", "", "edge attribute to use as weight") rootCmd.Flags().StringVarP(&weightAttr, "weight-attr", "w", "", "edge attribute to use as weight")
rootCmd.Flags().StringSliceVarP(&nodeOrder, "order", "o", nil, "order of nodes in rows/columns of output") rootCmd.Flags().StringSliceVarP(&nodeOrder, "order", "o", nil, "list the graph node names in the order they should be placed in the matrix")
} }