gv2adj/cmd/internal/graph/graph.go

85 lines
2.1 KiB
Go

/*
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"
"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()}
}
// AbsorbingNodes returns all the nodes in the Markov chain identified as
// absorbing nodes.
func (g *DirectedGraph) AbsorbingNodes() []graph.Node {
absorbingNodes := make([]graph.Node, 0)
for nodes := g.Nodes(); nodes.Next(); {
u := nodes.Node()
successors := g.From(u.ID())
if successors.Len() != 1 {
continue
}
successors.Next()
v := successors.Node()
if u == v {
absorbingNodes = append(absorbingNodes, u)
}
}
return absorbingNodes
}
// AdjacencyMatrix returns the graph's adjacency matrix.
func (g *DirectedGraph) AdjacencyMatrix() *mat.Dense {
adj := simple.NewDirectedMatrix(g.Nodes().Len(), 0, 0, 0)
for edges := g.WeightedEdges(); edges.Next(); {
e := edges.WeightedEdge()
if e.From() == e.To() {
continue
}
adj.SetWeightedEdge(e)
}
a := mat.DenseCopyOf(adj.Matrix())
nodes := adj.Nodes()
for i := 0; nodes.Next(); i++ {
id := nodes.Node().ID()
u := g.Node(id)
e := g.WeightedEdge(u.ID(), u.ID())
if e != nil {
a.Set(i, i, e.Weight())
}
}
return a
}