gv2adj/cmd/internal/graph/common.go

71 lines
1.6 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/mat"
)
type WeightedGraph interface {
graph.Weighted
graph.WeightedMultigraph
graph.WeightedMultigraphBuilder
WeightedEdges() graph.WeightedEdges
AdjacencyMatrix() *mat.Dense
}
type WeightedMatrix interface {
graph.Weighted
SetWeightedEdge(e graph.WeightedEdge)
Matrix() mat.Matrix
}
func toAdjMatrix(g WeightedGraph, adj WeightedMatrix) *mat.Dense {
copyEdges(g, adj)
matrix := mat.DenseCopyOf(adj.Matrix())
addSelfEdges(g, matrix)
return matrix
}
func copyEdges(g WeightedGraph, adj WeightedMatrix) {
for edges := g.WeightedEdges(); edges.Next(); {
e := edges.WeightedEdge()
if e.From() == e.To() {
continue
}
adj.SetWeightedEdge(e)
}
}
func addSelfEdges(g WeightedGraph, matrix mat.Mutable) {
nodes := g.Nodes()
for i := 0; nodes.Next(); i++ {
u := nodes.Node()
e := g.WeightedEdge(u.ID(), u.ID())
if e != nil {
matrix.Set(i, i, e.Weight())
}
}
}