gv2adj/cmd/internal/markov/absorbing.go

122 lines
2.7 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 markov
import (
"errors"
"math"
"strconv"
"gonum.org/v1/gonum/graph"
"gonum.org/v1/gonum/graph/encoding"
"gonum.org/v1/gonum/graph/simple"
"gonum.org/v1/gonum/mat"
)
type AbsorbingMarkovChain struct {
*simple.WeightedDirectedGraph
}
func NewAbsorbingMarkovChain() *AbsorbingMarkovChain {
return &AbsorbingMarkovChain{WeightedDirectedGraph: simple.NewWeightedDirectedGraph(math.NaN(), 0)}
}
func (g *AbsorbingMarkovChain) IsValid() bool {
for nodes := g.Nodes(); nodes.Next(); {
u := nodes.Node().(*node)
if g.outWeightSum(u) > 1 {
return false
}
}
return true
}
func (g *AbsorbingMarkovChain) outWeightSum(u graph.Node) float64 {
sum := 0.0
for nodes := g.From(u.ID()); nodes.Next(); {
v := nodes.Node()
e := g.WeightedEdge(u.ID(), v.ID())
if e != nil {
sum += e.(*weightedEdge).W
}
}
return sum
}
func (g *AbsorbingMarkovChain) AdjacencyMatrix() mat.Matrix {
adj := simple.NewDirectedMatrix(g.Nodes().Len(), 0, math.NaN(), 0)
for edges := g.WeightedEdges(); edges.Next(); {
adj.SetWeightedEdge(edges.WeightedEdge())
}
a := mat.DenseCopyOf(adj.Matrix())
nodes := adj.Nodes()
for i := 0; nodes.Next(); i++ {
id := nodes.Node().ID()
u := g.Node(id).(*node)
a.Set(i, i, 1 - g.outWeightSum(u))
}
return a
}
func (g *AbsorbingMarkovChain) NewEdge(from, to graph.Node) graph.Edge {
e := g.WeightedDirectedGraph.NewWeightedEdge(from, to, math.NaN()).(simple.WeightedEdge)
return &weightedEdge{WeightedEdge: e}
}
func (g *AbsorbingMarkovChain) NewNode() graph.Node {
return &node{Node: g.WeightedDirectedGraph.NewNode()}
}
func (g *AbsorbingMarkovChain) SetEdge(e graph.Edge) {
g.WeightedDirectedGraph.SetWeightedEdge(e.(*weightedEdge))
}
type weightedEdge struct {
simple.WeightedEdge
}
func (e *weightedEdge) SetAttribute(attr encoding.Attribute) error {
var err error
switch attr.Key {
case "weight":
e.W, err = strconv.ParseFloat(attr.Value, 64)
default:
err = errors.New("unknown key" + attr.Key)
}
return err
}
type node struct {
graph.Node
dotID string
}
func (n *node) SetDOTID(id string) {
n.dotID = id
}
func (n *node) DOTID() string {
return n.dotID
}