/* 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 . */ 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" ) // WeightedGraph is an interface so we can construct adjacency matrices for // both directed and undirected graphs. type WeightedGraph interface { graph.Weighted graph.WeightedMultigraph graph.WeightedMultigraphBuilder WeightedEdges() graph.WeightedEdges } // WeightedMatrix is an interface to handle the construction of both directed // and undirected adjacency matrices. type WeightedMatrix interface { graph.Weighted SetWeightedEdge(e graph.WeightedEdge) 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 { copyEdges(g, adj) matrix := addSelfEdges(g, adj) return matrix } func copyEdges(g WeightedGraph, adj WeightedMatrix) { for edges := g.WeightedEdges(); edges.Next(); { e := edges.WeightedEdge() if e.From() == e.To() { // the simple Matrix classes don't handle self loops continue } adj.SetWeightedEdge(e) } } func addSelfEdges(g WeightedGraph, adj WeightedMatrix) *mat.Dense { matrix := 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 { matrix.Set(i, i, e.Weight()) } } return matrix }