gv2adj/cmd/internal/graph/common.go

75 lines
1.6 KiB
Go
Raw Normal View History

/*
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/>.
*/
2025-05-07 02:24:28 +00:00
package graph
import (
2025-05-09 01:59:58 +00:00
"gonum.org/v1/gonum/graph"
2025-05-02 05:04:00 +00:00
"gonum.org/v1/gonum/mat"
)
2025-05-09 01:59:58 +00:00
type WeightedGraph interface {
graph.Weighted
graph.WeightedMultigraph
2025-05-09 03:26:29 +00:00
graph.WeightedMultigraphBuilder
2025-05-09 01:59:58 +00:00
WeightedEdges() graph.WeightedEdges
AdjacencyMatrix() *mat.Dense
}
2025-05-09 01:59:58 +00:00
type WeightedMatrix interface {
graph.Weighted
SetWeightedEdge(e graph.WeightedEdge)
Matrix() mat.Matrix
}
2025-05-09 01:59:58 +00:00
func toAdjMatrix(g WeightedGraph, adj WeightedMatrix) *mat.Dense {
copyEdges(g, adj)
2025-05-09 03:48:33 +00:00
matrix := addSelfEdges(g, adj)
2025-05-09 01:59:58 +00:00
return matrix
}
func copyEdges(g WeightedGraph, adj WeightedMatrix) {
2025-05-02 05:04:00 +00:00
for edges := g.WeightedEdges(); edges.Next(); {
e := edges.WeightedEdge()
if e.From() == e.To() {
continue
}
adj.SetWeightedEdge(e)
2025-05-02 05:04:00 +00:00
}
2025-05-09 01:59:58 +00:00
}
2025-05-02 05:04:00 +00:00
2025-05-09 03:48:33 +00:00
func addSelfEdges(g WeightedGraph, adj WeightedMatrix) *mat.Dense {
matrix := mat.DenseCopyOf(adj.Matrix())
nodes := adj.Nodes()
2025-05-02 05:04:00 +00:00
for i := 0; nodes.Next(); i++ {
2025-05-09 03:48:33 +00:00
id := nodes.Node().ID()
u := g.Node(id)
e := g.WeightedEdge(u.ID(), u.ID())
if e != nil {
2025-05-09 01:59:58 +00:00
matrix.Set(i, i, e.Weight())
}
2025-05-02 05:04:00 +00:00
}
2025-05-09 03:48:33 +00:00
return matrix
2025-05-02 05:04:00 +00:00
}