Documentation
¶
Overview ¶
Package models provides graphical model structures including Bayesian networks, Markov networks, and factor graphs.
Index ¶
- type BayesianNetwork
- func (bn *BayesianNetwork) AddCPD(cpd *factors.TabularCPD) error
- func (bn *BayesianNetwork) AddEdge(from, to string) error
- func (bn *BayesianNetwork) AddNode(node string) error
- func (bn *BayesianNetwork) CheckModel() error
- func (bn *BayesianNetwork) Children(node string) []string
- func (bn *BayesianNetwork) Copy() *BayesianNetwork
- func (bn *BayesianNetwork) Do(nodes map[string]int) (*BayesianNetwork, error)
- func (bn *BayesianNetwork) Edges() [][2]string
- func (bn *BayesianNetwork) FitUpdate(data *tabgo.DataFrame, nPrevSamples int) error
- func (bn *BayesianNetwork) GetAllStates() map[string][]string
- func (bn *BayesianNetwork) GetCPD(variable string) *factors.TabularCPD
- func (bn *BayesianNetwork) GetCPDs() []*factors.TabularCPD
- func (bn *BayesianNetwork) GetCardinality(node string) (int, error)
- func (bn *BayesianNetwork) GetFactorizedProduct() ([]*factors.DiscreteFactor, error)
- func (bn *BayesianNetwork) GetMarkovBlanket(node string) ([]string, error)
- func (bn *BayesianNetwork) GetRandomCPDs(nStates int, seed int64) error
- func (bn *BayesianNetwork) GetStateProbability(states map[string]int) (float64, error)
- func (bn *BayesianNetwork) GetStates(variable string) []string
- func (bn *BayesianNetwork) HasEdge(from, to string) bool
- func (bn *BayesianNetwork) HasNode(node string) bool
- func (bn *BayesianNetwork) IsIMap(jpd *factors.JointProbabilityDistribution) (bool, error)
- func (bn *BayesianNetwork) Nodes() []string
- func (bn *BayesianNetwork) NumberOfEdges() int
- func (bn *BayesianNetwork) NumberOfNodes() int
- func (bn *BayesianNetwork) Parents(node string) []string
- func (bn *BayesianNetwork) Predict(data *tabgo.DataFrame) (*tabgo.DataFrame, error)
- func (bn *BayesianNetwork) PredictProbability(data *tabgo.DataFrame) (map[string][]float64, error)
- func (bn *BayesianNetwork) RemoveCPD(variable string)
- func (bn *BayesianNetwork) RemoveNode(node string) error
- func (bn *BayesianNetwork) RemoveNodes(nodes ...string) error
- func (bn *BayesianNetwork) Save(filename string) error
- func (bn *BayesianNetwork) SetStates(variable string, stateNames []string) error
- func (bn *BayesianNetwork) Simulate(n int, evidence map[string]int, seed int64) (*tabgo.DataFrame, error)
- func (bn *BayesianNetwork) ToJunctionTree() (*JunctionTree, error)
- func (bn *BayesianNetwork) ToMarkovFactors() ([]*factors.DiscreteFactor, error)
- func (bn *BayesianNetwork) TopologicalOrder() ([]string, error)
- type Cluster
- type ClusterEdge
- type ClusterGraph
- func (cg *ClusterGraph) AddCluster(variables []string, clusterFactors []*factors.DiscreteFactor) int
- func (cg *ClusterGraph) AddEdge(cluster1, cluster2 int, sepSet []string) error
- func (cg *ClusterGraph) AddFactors(clusterIndex int, newFactors []*factors.DiscreteFactor) error
- func (cg *ClusterGraph) AddNode(variables []string) int
- func (cg *ClusterGraph) CheckModel() error
- func (cg *ClusterGraph) CliqueBeliefs() (map[int]*factors.DiscreteFactor, error)
- func (cg *ClusterGraph) Clusters() []Cluster
- func (cg *ClusterGraph) Copy() *ClusterGraph
- func (cg *ClusterGraph) Edges() []ClusterEdge
- func (cg *ClusterGraph) GetCardinality() map[string]int
- func (cg *ClusterGraph) GetFactors() []*factors.DiscreteFactor
- func (cg *ClusterGraph) GetPartitionFunction() (float64, error)
- func (cg *ClusterGraph) RemoveFactors()
- type DiscreteBayesianNetwork
- func (dbn *DiscreteBayesianNetwork) AddCPD(cpd *factors.TabularCPD) error
- func (dbn *DiscreteBayesianNetwork) CheckModel() error
- func (dbn *DiscreteBayesianNetwork) Copy() *DiscreteBayesianNetwork
- func (dbn *DiscreteBayesianNetwork) FitWith(estimateFn func(*BayesianNetwork, *tabgo.DataFrame) error, ...) error
- func (dbn *DiscreteBayesianNetwork) Simulate(n int, seed int64) (*tabgo.DataFrame, error)
- type DiscreteMarkovNetwork
- type DynamicBayesianNetwork
- func (dbn *DynamicBayesianNetwork) ActiveTrailNodes(variables []string, observed []string) map[string]bool
- func (dbn *DynamicBayesianNetwork) AddEdge(from, to string) error
- func (dbn *DynamicBayesianNetwork) AddInitialCPD(cpd *factors.TabularCPD) error
- func (dbn *DynamicBayesianNetwork) AddNode(node string) error
- func (dbn *DynamicBayesianNetwork) AddTransitionCPD(cpd *factors.TabularCPD) error
- func (dbn *DynamicBayesianNetwork) CheckModel() error
- func (dbn *DynamicBayesianNetwork) Copy() *DynamicBayesianNetwork
- func (dbn *DynamicBayesianNetwork) Fit(data *tabgo.DataFrame) error
- func (dbn *DynamicBayesianNetwork) GetCPDs() []*factors.TabularCPD
- func (dbn *DynamicBayesianNetwork) GetConstantBN(slice int) (*BayesianNetwork, error)
- func (dbn *DynamicBayesianNetwork) GetInterEdges() [][2]string
- func (dbn *DynamicBayesianNetwork) GetInterfaceNodes() []string
- func (dbn *DynamicBayesianNetwork) GetIntraEdges() [][2]string
- func (dbn *DynamicBayesianNetwork) GetMarkovBlanket(node string) ([]string, error)
- func (dbn *DynamicBayesianNetwork) GetSliceNodes(slice int) ([]string, error)
- func (dbn *DynamicBayesianNetwork) Initial() *BayesianNetwork
- func (dbn *DynamicBayesianNetwork) InitializeInitialState(probs map[string][]float64) error
- func (dbn *DynamicBayesianNetwork) Moralize() *graphgo.Graph
- func (dbn *DynamicBayesianNetwork) RemoveCPDs(variables ...string)
- func (dbn *DynamicBayesianNetwork) Simulate(nTimeSteps int, seed int64) (*tabgo.DataFrame, error)
- func (dbn *DynamicBayesianNetwork) States() map[string][]string
- func (dbn *DynamicBayesianNetwork) Transition() *BayesianNetwork
- type FactorGraph
- func (fg *FactorGraph) AddEdge(variable string, factorIndex int) error
- func (fg *FactorGraph) AddFactor(f *factors.DiscreteFactor) error
- func (fg *FactorGraph) AddVariable(name string, card int) error
- func (fg *FactorGraph) CheckModel() error
- func (fg *FactorGraph) Copy() *FactorGraph
- func (fg *FactorGraph) GetCardinality(variable string) (int, error)
- func (fg *FactorGraph) GetFactorNodes() [][]string
- func (fg *FactorGraph) GetFactors() []*factors.DiscreteFactor
- func (fg *FactorGraph) GetFactorsOf(variable string) []*factors.DiscreteFactor
- func (fg *FactorGraph) GetPartitionFunction() (float64, error)
- func (fg *FactorGraph) GetPointMassMessage(variable string, state int) (*factors.DiscreteFactor, error)
- func (fg *FactorGraph) GetUniformMessage(variable string) (*factors.DiscreteFactor, error)
- func (fg *FactorGraph) GetVariables() []string
- func (fg *FactorGraph) RemoveFactors()
- func (fg *FactorGraph) ToJunctionTree() (*JunctionTree, error)
- func (fg *FactorGraph) ToMarkovNetwork() (*MarkovNetwork, error)
- type FunctionalBayesianNetwork
- func (fbn *FunctionalBayesianNetwork) AddFunctionalCPD(cpd *factors.FunctionalCPD) error
- func (fbn *FunctionalBayesianNetwork) CheckModel() error
- func (fbn *FunctionalBayesianNetwork) Copy() *FunctionalBayesianNetwork
- func (fbn *FunctionalBayesianNetwork) GetFunctionalCPD(variable string) *factors.FunctionalCPD
- type IndependenceAssertion
- type JunctionTree
- func (jt *JunctionTree) AddEdge(cliqueA, cliqueB int) error
- func (jt *JunctionTree) CheckModel() error
- func (jt *JunctionTree) Cliques() [][]string
- func (jt *JunctionTree) Copy() *JunctionTree
- func (jt *JunctionTree) GetCliqueFactors(clique []string) []*factors.DiscreteFactor
- func (jt *JunctionTree) SeparatorSets() map[string][]string
- func (jt *JunctionTree) States() map[string]int
- type LinearGaussianBayesianNetwork
- func (lgbn *LinearGaussianBayesianNetwork) AddLinearGaussianCPD(cpd *factors.LinearGaussianCPD) error
- func (lgbn *LinearGaussianBayesianNetwork) CheckModel() error
- func (lgbn *LinearGaussianBayesianNetwork) Copy() *LinearGaussianBayesianNetwork
- func (lgbn *LinearGaussianBayesianNetwork) Fit(data *tabgo.DataFrame) error
- func (lgbn *LinearGaussianBayesianNetwork) GetCardinality(node string) (int, error)
- func (lgbn *LinearGaussianBayesianNetwork) GetLinearGaussianCPD(variable string) *factors.LinearGaussianCPD
- func (lgbn *LinearGaussianBayesianNetwork) GetRandomCPDs() error
- func (lgbn *LinearGaussianBayesianNetwork) IsIMap(independencies []IndependenceAssertion) (bool, error)
- func (lgbn *LinearGaussianBayesianNetwork) LogLikelihood(data *tabgo.DataFrame) (float64, error)
- func (lgbn *LinearGaussianBayesianNetwork) Predict(data *tabgo.DataFrame) (map[string][]float64, error)
- func (lgbn *LinearGaussianBayesianNetwork) PredictProbability(data *tabgo.DataFrame) ([]float64, error)
- func (lgbn *LinearGaussianBayesianNetwork) RemoveCPDs()
- func (lgbn *LinearGaussianBayesianNetwork) Save(filename string) error
- func (lgbn *LinearGaussianBayesianNetwork) Simulate(nSamples int) (*tabgo.DataFrame, error)
- func (lgbn *LinearGaussianBayesianNetwork) ToJointGaussian() ([]float64, [][]float64, error)
- func (lgbn *LinearGaussianBayesianNetwork) ToMarkovModel() error
- type MarkovChain
- func (mc *MarkovChain) AddTransitionModel(matrix [][]float64) error
- func (mc *MarkovChain) AddVariable(name string)
- func (mc *MarkovChain) AddVariablesFrom(other *MarkovChain)
- func (mc *MarkovChain) Copy() *MarkovChain
- func (mc *MarkovChain) GenerateSample(n int, startState int, seed int64) ([]int, error)
- func (mc *MarkovChain) IsAbsorbing() bool
- func (mc *MarkovChain) IsErgodic() bool
- func (mc *MarkovChain) IsStationarity(dist []float64) (bool, error)
- func (mc *MarkovChain) NumStates() int
- func (mc *MarkovChain) ProbFromSample(sequence []int) ([][]float64, error)
- func (mc *MarkovChain) RandomState(seed int64) (int, error)
- func (mc *MarkovChain) Sample(n int, startState int, seed int64) ([]int, error)
- func (mc *MarkovChain) SetStartState(state int) (int, error)
- func (mc *MarkovChain) StateNames() []string
- func (mc *MarkovChain) StationaryDistribution() ([]float64, error)
- func (mc *MarkovChain) TransitionMatrix() [][]float64
- type MarkovNetwork
- func (mn *MarkovNetwork) AddEdge(u, v string) error
- func (mn *MarkovNetwork) AddFactor(f *factors.DiscreteFactor) error
- func (mn *MarkovNetwork) AddNode(node string) error
- func (mn *MarkovNetwork) CheckModel() error
- func (mn *MarkovNetwork) Copy() *MarkovNetwork
- func (mn *MarkovNetwork) Edges() [][2]string
- func (mn *MarkovNetwork) GetCardinality(node string) (int, error)
- func (mn *MarkovNetwork) GetFactors() []*factors.DiscreteFactor
- func (mn *MarkovNetwork) GetFactorsOf(variable string) []*factors.DiscreteFactor
- func (mn *MarkovNetwork) GetLocalIndependencies(node string) ([]*independencies.IndependenceAssertion, error)
- func (mn *MarkovNetwork) GetPartitionFunction() (float64, error)
- func (mn *MarkovNetwork) MarkovBlanket(node string) []string
- func (mn *MarkovNetwork) Neighbors(node string) []string
- func (mn *MarkovNetwork) Nodes() []string
- func (mn *MarkovNetwork) RemoveFactor(variables []string)
- func (mn *MarkovNetwork) States() map[string]int
- func (mn *MarkovNetwork) ToBayesianModel() (*BayesianNetwork, error)
- func (mn *MarkovNetwork) ToFactorGraph() (*FactorGraph, error)
- func (mn *MarkovNetwork) ToJunctionTree() (*JunctionTree, error)
- func (mn *MarkovNetwork) Triangulate(heuristic string) (*MarkovNetwork, error)
- type NaiveBayes
- func (nb *NaiveBayes) ActiveTrailNodes(variable string, observed map[string]bool) ([]string, error)
- func (nb *NaiveBayes) AddEdge(from, to string) error
- func (nb *NaiveBayes) AddEdgesFrom(from string, toList []string) error
- func (nb *NaiveBayes) ClassVariable() string
- func (nb *NaiveBayes) Features() []string
- func (nb *NaiveBayes) Fit(data *tabgo.DataFrame) error
- func (nb *NaiveBayes) LocalIndependencies() *independencies.Independencies
- func (nb *NaiveBayes) Predict(data *tabgo.DataFrame) ([]int, error)
- func (nb *NaiveBayes) PredictProbability(data *tabgo.DataFrame) ([][]float64, error)
- type SEM
- func (s *SEM) ActiveTrailNodes(variable string, observed map[string]bool) ([]string, error)
- func (s *SEM) AddEquation(variable string, parents []string, coefficients []float64, ...) error
- func (s *SEM) CheckModel() error
- func (s *SEM) Fit(data *tabgo.DataFrame) error
- func (s *SEM) GenerateSamples(nSamples int) (*tabgo.DataFrame, error)
- func (s *SEM) GetEquation(variable string) *SEMEquation
- func (s *SEM) GetScalingIndicators() []string
- func (s *SEM) ImpliedCovarianceMatrix() ([][]float64, error)
- func (s *SEM) Moralize() *graphgo.Graph
- func (s *SEM) SetParams(variable string, coefficients []float64, intercept, variance float64) error
- func (s *SEM) ToLisrel() (map[string][][]float64, error)
- func (s *SEM) ToSEMGraph() *SEM
- func (s *SEM) ToStandardLisrel() (map[string][][]float64, error)
- func (s *SEM) Variables() []string
- type SEMEquation
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type BayesianNetwork ¶
type BayesianNetwork struct {
// contains filtered or unexported fields
}
BayesianNetwork represents a Bayesian network — a DAG where each node is associated with a conditional probability distribution (CPD).
func GetRandomBayesianNetwork ¶
func GetRandomBayesianNetwork(nNodes, nEdges, nStates int) (*BayesianNetwork, error)
GetRandomBayesianNetwork generates a random BayesianNetwork with the specified number of nodes, edges, and states per node.
func LoadBayesianNetwork ¶
func LoadBayesianNetwork(filename string) (*BayesianNetwork, error)
LoadBayesianNetwork reads a BIF file and returns a new BayesianNetwork.
func NewBayesianNetwork ¶
func NewBayesianNetwork() *BayesianNetwork
NewBayesianNetwork creates a new empty BayesianNetwork.
func (*BayesianNetwork) AddCPD ¶
func (bn *BayesianNetwork) AddCPD(cpd *factors.TabularCPD) error
AddCPD stores a CPD for its variable. The variable must be a node in the DAG.
func (*BayesianNetwork) AddEdge ¶
func (bn *BayesianNetwork) AddEdge(from, to string) error
AddEdge adds a directed edge from -> to. Both nodes must exist and the edge must not create a cycle.
func (*BayesianNetwork) AddNode ¶
func (bn *BayesianNetwork) AddNode(node string) error
AddNode adds a node to the network.
func (*BayesianNetwork) CheckModel ¶
func (bn *BayesianNetwork) CheckModel() error
CheckModel validates the Bayesian network:
- Every node has a CPD.
- Each CPD's evidence matches the node's parents in the DAG.
- Each CPD passes Validate().
func (*BayesianNetwork) Children ¶
func (bn *BayesianNetwork) Children(node string) []string
Children returns the sorted children of a node.
func (*BayesianNetwork) Copy ¶
func (bn *BayesianNetwork) Copy() *BayesianNetwork
Copy returns a deep copy of the BayesianNetwork.
func (*BayesianNetwork) Do ¶
func (bn *BayesianNetwork) Do(nodes map[string]int) (*BayesianNetwork, error)
Do performs a causal intervention (do-calculus). For each node in the nodes map, the incoming edges are removed and the node's CPD is replaced with a delta distribution that assigns probability 1 to the specified state. Returns a new (mutilated) BayesianNetwork; the original is not modified. Do delegates to doImpl with the default CPD creator, preserving the public API signature.
func (*BayesianNetwork) Edges ¶
func (bn *BayesianNetwork) Edges() [][2]string
Edges returns all directed edges as [2]string pairs, sorted lexicographically.
func (*BayesianNetwork) FitUpdate ¶
func (bn *BayesianNetwork) FitUpdate(data *tabgo.DataFrame, nPrevSamples int) error
FitUpdate delegates to fitUpdateImpl with the default CPD creator, preserving the public API signature.
func (*BayesianNetwork) GetAllStates ¶
func (bn *BayesianNetwork) GetAllStates() map[string][]string
GetAllStates returns a map from each variable to its state names.
func (*BayesianNetwork) GetCPD ¶
func (bn *BayesianNetwork) GetCPD(variable string) *factors.TabularCPD
GetCPD returns the CPD for the given variable, or nil if none is set.
func (*BayesianNetwork) GetCPDs ¶
func (bn *BayesianNetwork) GetCPDs() []*factors.TabularCPD
GetCPDs returns all CPDs, sorted by variable name.
func (*BayesianNetwork) GetCardinality ¶
func (bn *BayesianNetwork) GetCardinality(node string) (int, error)
GetCardinality returns the cardinality of a node from its CPD. An error is returned if the node has no CPD.
func (*BayesianNetwork) GetFactorizedProduct ¶
func (bn *BayesianNetwork) GetFactorizedProduct() ([]*factors.DiscreteFactor, error)
GetFactorizedProduct returns all CPDs converted to discrete factors. CheckModel is called first to ensure the network is valid.
func (*BayesianNetwork) GetMarkovBlanket ¶
func (bn *BayesianNetwork) GetMarkovBlanket(node string) ([]string, error)
GetMarkovBlanket returns the Markov blanket of a node: its parents, children, and parents of its children (co-parents), excluding the node itself.
func (*BayesianNetwork) GetRandomCPDs ¶
func (bn *BayesianNetwork) GetRandomCPDs(nStates int, seed int64) error
GetRandomCPDs generates random TabularCPDs for all nodes in the network based on graph structure. Each node gets a CPD with the given number of states. Columns are normalized to sum to 1. The seed controls the RNG.
func (*BayesianNetwork) GetStateProbability ¶
func (bn *BayesianNetwork) GetStateProbability(states map[string]int) (float64, error)
GetStateProbability computes P(states) -- the joint probability of a complete or partial state assignment -- using variable elimination. GetStateProbability delegates to getStateProbabilityImpl with the real BN as factorizer and the default VE querier, preserving the public API signature.
func (*BayesianNetwork) GetStates ¶
func (bn *BayesianNetwork) GetStates(variable string) []string
GetStates returns the state names for a variable, or nil if none are set.
func (*BayesianNetwork) HasEdge ¶
func (bn *BayesianNetwork) HasEdge(from, to string) bool
HasEdge returns true if the directed edge exists in the network.
func (*BayesianNetwork) HasNode ¶
func (bn *BayesianNetwork) HasNode(node string) bool
HasNode returns true if the node exists in the network.
func (*BayesianNetwork) IsIMap ¶
func (bn *BayesianNetwork) IsIMap(jpd *factors.JointProbabilityDistribution) (bool, error)
IsIMap checks whether this BayesianNetwork is an I-map (independence map) of the given joint probability distribution. A BN is an I-map if every independence implied by the BN structure (via d-separation) also holds in the JPD.
func (*BayesianNetwork) Nodes ¶
func (bn *BayesianNetwork) Nodes() []string
Nodes returns a sorted list of all nodes in the network.
func (*BayesianNetwork) NumberOfEdges ¶
func (bn *BayesianNetwork) NumberOfEdges() int
NumberOfEdges returns the number of edges.
func (*BayesianNetwork) NumberOfNodes ¶
func (bn *BayesianNetwork) NumberOfNodes() int
NumberOfNodes returns the number of nodes.
func (*BayesianNetwork) Parents ¶
func (bn *BayesianNetwork) Parents(node string) []string
Parents returns the sorted parents of a node.
func (*BayesianNetwork) Predict ¶
Predict fills in missing values (nil) in a DataFrame using variable elimination inference. For each row, variables with nil values are treated as query variables and non-nil variables are treated as evidence. The most likely (MAP) assignment is used to fill in missing values. Predict delegates to predictImpl with the real BN as factorizer and the default VE querier, preserving the public API signature.
func (*BayesianNetwork) PredictProbability ¶
PredictProbability returns the probability distribution over missing variables for each row. The returned map contains variable name -> slice of probabilities (one per state, concatenated across rows). PredictProbability delegates to predictProbabilityImpl with the real BN as factorizer and the default VE querier, preserving the public API signature.
func (*BayesianNetwork) RemoveCPD ¶
func (bn *BayesianNetwork) RemoveCPD(variable string)
RemoveCPD removes the CPD for the given variable.
func (*BayesianNetwork) RemoveNode ¶
func (bn *BayesianNetwork) RemoveNode(node string) error
RemoveNode removes a node from the network, along with its CPD and all connected edges (both incoming and outgoing).
func (*BayesianNetwork) RemoveNodes ¶
func (bn *BayesianNetwork) RemoveNodes(nodes ...string) error
RemoveNodes removes multiple nodes from the network. If any node is not found, an error is returned and nodes already removed are not restored.
func (*BayesianNetwork) Save ¶
func (bn *BayesianNetwork) Save(filename string) error
Save writes the BayesianNetwork to a BIF file.
func (*BayesianNetwork) SetStates ¶
func (bn *BayesianNetwork) SetStates(variable string, stateNames []string) error
SetStates sets the state names for a variable.
func (*BayesianNetwork) Simulate ¶
func (bn *BayesianNetwork) Simulate(n int, evidence map[string]int, seed int64) (*tabgo.DataFrame, error)
Simulate generates n samples from the Bayesian network using forward (ancestral) sampling. If evidence is non-nil, rejection sampling is used to condition on the evidence. The seed controls the RNG. Returns a DataFrame with one column per variable and one row per accepted sample.
func (*BayesianNetwork) ToJunctionTree ¶
func (bn *BayesianNetwork) ToJunctionTree() (*JunctionTree, error)
ToJunctionTree converts this BayesianNetwork to a JunctionTree by delegating to NewJunctionTreeFromBN.
func (*BayesianNetwork) ToMarkovFactors ¶
func (bn *BayesianNetwork) ToMarkovFactors() ([]*factors.DiscreteFactor, error)
ToMarkovFactors converts all CPDs to discrete factors suitable for inference. CheckModel is called first to ensure the network is valid.
func (*BayesianNetwork) TopologicalOrder ¶
func (bn *BayesianNetwork) TopologicalOrder() ([]string, error)
TopologicalOrder returns a topological ordering of the network nodes.
type Cluster ¶
type Cluster struct {
Variables []string
Factors []*factors.DiscreteFactor
}
Cluster represents a cluster of variables with associated factors.
type ClusterEdge ¶
ClusterEdge represents an edge between two clusters with a separation set.
type ClusterGraph ¶
type ClusterGraph struct {
// contains filtered or unexported fields
}
ClusterGraph represents a cluster graph — a graph of clusters of variables with factors, connected by edges with separation sets. Unlike a junction tree, a cluster graph need not be a tree and need not satisfy the running intersection property.
func NewClusterGraph ¶
func NewClusterGraph() *ClusterGraph
NewClusterGraph creates a new empty ClusterGraph.
func (*ClusterGraph) AddCluster ¶
func (cg *ClusterGraph) AddCluster(variables []string, clusterFactors []*factors.DiscreteFactor) int
AddCluster adds a cluster with the given variables and factors to the graph. Returns the index of the newly added cluster.
func (*ClusterGraph) AddEdge ¶
func (cg *ClusterGraph) AddEdge(cluster1, cluster2 int, sepSet []string) error
AddEdge adds an edge between two clusters with a separation set.
func (*ClusterGraph) AddFactors ¶
func (cg *ClusterGraph) AddFactors(clusterIndex int, newFactors []*factors.DiscreteFactor) error
AddFactors adds factors to the cluster at the given index.
func (*ClusterGraph) AddNode ¶
func (cg *ClusterGraph) AddNode(variables []string) int
AddNode is an alias for AddCluster. It adds a cluster with the given variables and no factors, returning the cluster index.
func (*ClusterGraph) CheckModel ¶
func (cg *ClusterGraph) CheckModel() error
CheckModel validates the cluster graph:
- At least one cluster exists.
- Each edge's separation set must be a subset of the intersection of the two connected clusters' variable sets.
- No duplicate edges between the same pair of clusters.
func (*ClusterGraph) CliqueBeliefs ¶
func (cg *ClusterGraph) CliqueBeliefs() (map[int]*factors.DiscreteFactor, error)
CliqueBeliefs runs a simple loopy belief propagation on the cluster graph and returns the belief (product of factors) for each cluster as a map from cluster index to a DiscreteFactor. For each cluster, the belief is the product of all its factors, normalized.
func (*ClusterGraph) Clusters ¶
func (cg *ClusterGraph) Clusters() []Cluster
Clusters returns a copy of all clusters.
func (*ClusterGraph) Copy ¶
func (cg *ClusterGraph) Copy() *ClusterGraph
Copy returns a deep copy of the ClusterGraph.
func (*ClusterGraph) Edges ¶
func (cg *ClusterGraph) Edges() []ClusterEdge
Edges returns a copy of all edges.
func (*ClusterGraph) GetCardinality ¶
func (cg *ClusterGraph) GetCardinality() map[string]int
GetCardinality collects the cardinality of each variable from the factors in the cluster graph. Returns a map from variable name to cardinality.
func (*ClusterGraph) GetFactors ¶
func (cg *ClusterGraph) GetFactors() []*factors.DiscreteFactor
GetFactors returns all factors across all clusters.
func (*ClusterGraph) GetPartitionFunction ¶
func (cg *ClusterGraph) GetPartitionFunction() (float64, error)
GetPartitionFunction computes the partition function (the sum over all assignments of the product of all factors in the cluster graph).
func (*ClusterGraph) RemoveFactors ¶
func (cg *ClusterGraph) RemoveFactors()
RemoveFactors removes all factors from all clusters.
type DiscreteBayesianNetwork ¶
type DiscreteBayesianNetwork struct {
*BayesianNetwork
}
DiscreteBayesianNetwork is a Bayesian network where all variables are discrete. It embeds *BayesianNetwork and adds discrete-specific validation, fitting (via injected estimator functions), and forward sampling.
func NewDiscreteBayesianNetwork ¶
func NewDiscreteBayesianNetwork() *DiscreteBayesianNetwork
NewDiscreteBayesianNetwork creates a new empty DiscreteBayesianNetwork.
func (*DiscreteBayesianNetwork) AddCPD ¶
func (dbn *DiscreteBayesianNetwork) AddCPD(cpd *factors.TabularCPD) error
AddCPD stores a CPD for its variable. In addition to the base BayesianNetwork checks, it validates that all cardinalities are positive and finite.
func (*DiscreteBayesianNetwork) CheckModel ¶
func (dbn *DiscreteBayesianNetwork) CheckModel() error
CheckModel validates the discrete Bayesian network. It calls the base BayesianNetwork.CheckModel() and then performs additional discrete-specific checks:
- All state cardinalities must be positive integers (already enforced by TabularCPD construction, but re-verified here).
- If state names are set for a variable, the number of state names must match the variable's cardinality in its CPD.
- State names referenced across CPDs must be consistent: if a parent variable has state names set, the evidence cardinality in child CPDs must match the number of states.
func (*DiscreteBayesianNetwork) Copy ¶
func (dbn *DiscreteBayesianNetwork) Copy() *DiscreteBayesianNetwork
Copy returns a deep copy of the DiscreteBayesianNetwork.
func (*DiscreteBayesianNetwork) FitWith ¶
func (dbn *DiscreteBayesianNetwork) FitWith(estimateFn func(*BayesianNetwork, *tabgo.DataFrame) error, data *tabgo.DataFrame) error
FitWith fits the model parameters from data using a caller-supplied estimation function. This avoids circular imports between the models and learning packages.
The estimateFn receives the underlying BayesianNetwork (so it can set CPDs) and the data, and should return an error on failure.
type DiscreteMarkovNetwork ¶
type DiscreteMarkovNetwork struct {
*MarkovNetwork
}
DiscreteMarkovNetwork is a Markov network where all variables are discrete. It embeds *MarkovNetwork and adds discrete-specific validation.
func NewDiscreteMarkovNetwork ¶
func NewDiscreteMarkovNetwork() *DiscreteMarkovNetwork
NewDiscreteMarkovNetwork creates a new empty DiscreteMarkovNetwork.
func (*DiscreteMarkovNetwork) AddFactor ¶
func (dmn *DiscreteMarkovNetwork) AddFactor(f *factors.DiscreteFactor) error
AddFactor adds a factor to the network with additional discrete-specific checks: all cardinalities must be positive and all values must be finite.
func (*DiscreteMarkovNetwork) CheckModel ¶
func (dmn *DiscreteMarkovNetwork) CheckModel() error
CheckModel validates the discrete Markov network. It calls MarkovNetwork.CheckModel() and then performs additional discrete-specific checks:
- All factor cardinalities must be positive integers.
- All factor values must be finite (no NaN or Inf).
- All factor values must be non-negative (valid potentials).
func (*DiscreteMarkovNetwork) Copy ¶
func (dmn *DiscreteMarkovNetwork) Copy() *DiscreteMarkovNetwork
Copy returns a deep copy of the DiscreteMarkovNetwork.
type DynamicBayesianNetwork ¶
type DynamicBayesianNetwork struct {
// contains filtered or unexported fields
}
DynamicBayesianNetwork represents a two-time-slice Bayesian network (2TBN). It consists of an initial network for t=0 and a transition network for t→t+1. Interface nodes are those that appear in both time slices, connecting them.
func NewDynamicBayesianNetwork ¶
func NewDynamicBayesianNetwork() *DynamicBayesianNetwork
NewDynamicBayesianNetwork creates a new empty DynamicBayesianNetwork.
func (*DynamicBayesianNetwork) ActiveTrailNodes ¶
func (dbn *DynamicBayesianNetwork) ActiveTrailNodes(variables []string, observed []string) map[string]bool
ActiveTrailNodes returns the set of nodes reachable from the given nodes via active trails in the initial network, given the observed set. Uses d-separation logic from the underlying DAG.
func (*DynamicBayesianNetwork) AddEdge ¶
func (dbn *DynamicBayesianNetwork) AddEdge(from, to string) error
AddEdge adds a directed edge to both the initial and transition networks.
func (*DynamicBayesianNetwork) AddInitialCPD ¶
func (dbn *DynamicBayesianNetwork) AddInitialCPD(cpd *factors.TabularCPD) error
AddInitialCPD adds a CPD to the initial (t=0) time slice. The CPD's variable must be a node in the initial network.
func (*DynamicBayesianNetwork) AddNode ¶
func (dbn *DynamicBayesianNetwork) AddNode(node string) error
AddNode adds a node to both the initial and transition networks.
func (*DynamicBayesianNetwork) AddTransitionCPD ¶
func (dbn *DynamicBayesianNetwork) AddTransitionCPD(cpd *factors.TabularCPD) error
AddTransitionCPD adds a CPD to the transition (t→t+1) network. The CPD's variable must be a node in the transition network.
func (*DynamicBayesianNetwork) CheckModel ¶
func (dbn *DynamicBayesianNetwork) CheckModel() error
CheckModel validates both the initial and transition networks.
func (*DynamicBayesianNetwork) Copy ¶
func (dbn *DynamicBayesianNetwork) Copy() *DynamicBayesianNetwork
Copy returns a deep copy of the DynamicBayesianNetwork.
func (*DynamicBayesianNetwork) Fit ¶
func (dbn *DynamicBayesianNetwork) Fit(data *tabgo.DataFrame) error
Fit learns the CPD parameters from time-series data. The data is a DataFrame where each column corresponds to a variable and each row is a time step. The initial CPDs are estimated from the first row, and the transition CPDs are estimated from consecutive row pairs.
func (*DynamicBayesianNetwork) GetCPDs ¶
func (dbn *DynamicBayesianNetwork) GetCPDs() []*factors.TabularCPD
GetCPDs returns all CPDs from both initial and transition networks, sorted by variable name. Initial CPDs come first, then transition CPDs for any variables not already listed from the initial network.
func (*DynamicBayesianNetwork) GetConstantBN ¶
func (dbn *DynamicBayesianNetwork) GetConstantBN(slice int) (*BayesianNetwork, error)
GetConstantBN returns a static BayesianNetwork representing one time slice. If slice==0, the initial network is returned (as a copy); otherwise the transition network is returned (as a copy).
func (*DynamicBayesianNetwork) GetInterEdges ¶
func (dbn *DynamicBayesianNetwork) GetInterEdges() [][2]string
GetInterEdges returns edges that connect two time slices. These are edges in the transition network where the source is an interface node (present in the initial network) and the target is only in the transition network, or both are interface nodes but the edge represents a temporal connection. In the 2TBN representation, inter-slice edges are all edges in the transition network.
func (*DynamicBayesianNetwork) GetInterfaceNodes ¶
func (dbn *DynamicBayesianNetwork) GetInterfaceNodes() []string
GetInterfaceNodes returns the sorted list of nodes that appear in both the initial and transition networks, i.e., the nodes connecting time slices.
func (*DynamicBayesianNetwork) GetIntraEdges ¶
func (dbn *DynamicBayesianNetwork) GetIntraEdges() [][2]string
GetIntraEdges returns edges within a single time slice (edges where both endpoints are in the same network). Returns the initial network's edges.
func (*DynamicBayesianNetwork) GetMarkovBlanket ¶
func (dbn *DynamicBayesianNetwork) GetMarkovBlanket(node string) ([]string, error)
GetMarkovBlanket returns the Markov blanket of a node in the initial network: parents, children, and co-parents.
func (*DynamicBayesianNetwork) GetSliceNodes ¶
func (dbn *DynamicBayesianNetwork) GetSliceNodes(slice int) ([]string, error)
GetSliceNodes returns the sorted list of nodes for a given time slice. slice=0 returns initial network nodes; slice=1 returns transition network nodes.
func (*DynamicBayesianNetwork) Initial ¶
func (dbn *DynamicBayesianNetwork) Initial() *BayesianNetwork
Initial returns the initial (t=0) BayesianNetwork.
func (*DynamicBayesianNetwork) InitializeInitialState ¶
func (dbn *DynamicBayesianNetwork) InitializeInitialState(probs map[string][]float64) error
InitializeInitialState sets the initial state CPDs using a map of variable name to probability distribution (slice of probabilities for each state).
func (*DynamicBayesianNetwork) Moralize ¶
func (dbn *DynamicBayesianNetwork) Moralize() *graphgo.Graph
Moralize returns the moral graph of the initial network as an undirected graphgo.Graph. The moral graph connects co-parents and drops edge directions.
func (*DynamicBayesianNetwork) RemoveCPDs ¶
func (dbn *DynamicBayesianNetwork) RemoveCPDs(variables ...string)
RemoveCPDs removes CPDs for the given variables from both initial and transition networks.
func (*DynamicBayesianNetwork) Simulate ¶
Simulate generates time-series data by forward sampling the DBN for the given number of time steps. Returns a DataFrame with one column per variable and one row per time step.
func (*DynamicBayesianNetwork) States ¶
func (dbn *DynamicBayesianNetwork) States() map[string][]string
States returns a map from variable name to state names for all variables in the initial network that have state names set.
func (*DynamicBayesianNetwork) Transition ¶
func (dbn *DynamicBayesianNetwork) Transition() *BayesianNetwork
Transition returns the transition (t→t+1) BayesianNetwork.
type FactorGraph ¶
type FactorGraph struct {
// contains filtered or unexported fields
}
FactorGraph represents a factor graph — a bipartite graph of variable nodes and factor nodes. Each factor is connected to the variables in its scope.
func NewFactorGraph ¶
func NewFactorGraph() *FactorGraph
NewFactorGraph creates a new empty FactorGraph.
func (*FactorGraph) AddEdge ¶
func (fg *FactorGraph) AddEdge(variable string, factorIndex int) error
AddEdge adds an edge between a variable node and a factor node (identified by its index in the factor list). This verifies that the variable is in the factor's scope and that the factor exists.
func (*FactorGraph) AddFactor ¶
func (fg *FactorGraph) AddFactor(f *factors.DiscreteFactor) error
AddFactor adds a factor node to the graph. All variables in the factor's scope must already exist in the graph, and their cardinalities must match.
func (*FactorGraph) AddVariable ¶
func (fg *FactorGraph) AddVariable(name string, card int) error
AddVariable adds a variable node with the given name and cardinality. Returns an error if the variable already exists or cardinality is invalid.
func (*FactorGraph) CheckModel ¶
func (fg *FactorGraph) CheckModel() error
CheckModel validates the factor graph:
- At least one variable exists.
- At least one factor exists.
- Every factor's variables exist in the graph with matching cardinalities.
- Every variable is referenced by at least one factor.
func (*FactorGraph) Copy ¶
func (fg *FactorGraph) Copy() *FactorGraph
Copy returns a deep copy of the FactorGraph.
func (*FactorGraph) GetCardinality ¶
func (fg *FactorGraph) GetCardinality(variable string) (int, error)
GetCardinality returns the cardinality of the given variable. Returns an error if the variable does not exist.
func (*FactorGraph) GetFactorNodes ¶
func (fg *FactorGraph) GetFactorNodes() [][]string
GetFactorNodes returns a list of factor descriptions. Each entry is the list of variables in the factor's scope.
func (*FactorGraph) GetFactors ¶
func (fg *FactorGraph) GetFactors() []*factors.DiscreteFactor
GetFactors returns all factors in the graph.
func (*FactorGraph) GetFactorsOf ¶
func (fg *FactorGraph) GetFactorsOf(variable string) []*factors.DiscreteFactor
GetFactorsOf returns all factors that include the given variable in their scope. Returns nil if the variable does not exist or has no factors.
func (*FactorGraph) GetPartitionFunction ¶
func (fg *FactorGraph) GetPartitionFunction() (float64, error)
GetPartitionFunction computes the partition function (sum of the product of all factors over all possible assignments).
func (*FactorGraph) GetPointMassMessage ¶
func (fg *FactorGraph) GetPointMassMessage(variable string, state int) (*factors.DiscreteFactor, error)
GetPointMassMessage creates a delta factor for a variable where only the specified state has value 1.0 and all others are 0.0.
func (*FactorGraph) GetUniformMessage ¶
func (fg *FactorGraph) GetUniformMessage(variable string) (*factors.DiscreteFactor, error)
GetUniformMessage creates a uniform factor for a variable where all states have equal probability (1/cardinality).
func (*FactorGraph) GetVariables ¶
func (fg *FactorGraph) GetVariables() []string
GetVariables returns a sorted list of all variable names.
func (*FactorGraph) RemoveFactors ¶
func (fg *FactorGraph) RemoveFactors()
RemoveFactors removes all factors from the graph and clears the variable-to-factor mappings.
func (*FactorGraph) ToJunctionTree ¶
func (fg *FactorGraph) ToJunctionTree() (*JunctionTree, error)
ToJunctionTree converts the factor graph to a junction tree. This creates a moral graph from the factor scopes (each factor's variables form a clique), triangulates it, finds maximal cliques, and builds the clique tree.
func (*FactorGraph) ToMarkovNetwork ¶
func (fg *FactorGraph) ToMarkovNetwork() (*MarkovNetwork, error)
ToMarkovNetwork converts the factor graph to a Markov network. For each factor, edges are added between all pairs of variables in its scope. All factors are added to the resulting Markov network.
type FunctionalBayesianNetwork ¶
type FunctionalBayesianNetwork struct {
*BayesianNetwork
// contains filtered or unexported fields
}
FunctionalBayesianNetwork is a Bayesian network where nodes use FunctionalCPDs instead of TabularCPDs. It embeds *BayesianNetwork for graph structure (nodes, edges) and stores functional CPDs in a separate map.
func NewFunctionalBayesianNetwork ¶
func NewFunctionalBayesianNetwork() *FunctionalBayesianNetwork
NewFunctionalBayesianNetwork creates a new empty FunctionalBayesianNetwork.
func (*FunctionalBayesianNetwork) AddFunctionalCPD ¶
func (fbn *FunctionalBayesianNetwork) AddFunctionalCPD(cpd *factors.FunctionalCPD) error
AddFunctionalCPD stores a FunctionalCPD for its variable. It validates that the variable exists in the graph and that the CPD's evidence matches the node's parents in the DAG.
func (*FunctionalBayesianNetwork) CheckModel ¶
func (fbn *FunctionalBayesianNetwork) CheckModel() error
CheckModel validates the FunctionalBayesianNetwork:
- Every node has a FunctionalCPD.
- Each CPD's evidence matches the node's parents in the DAG.
- Each CPD passes Validate().
func (*FunctionalBayesianNetwork) Copy ¶
func (fbn *FunctionalBayesianNetwork) Copy() *FunctionalBayesianNetwork
Copy returns a deep copy of the FunctionalBayesianNetwork.
func (*FunctionalBayesianNetwork) GetFunctionalCPD ¶
func (fbn *FunctionalBayesianNetwork) GetFunctionalCPD(variable string) *factors.FunctionalCPD
GetFunctionalCPD returns the FunctionalCPD for the given variable, or nil if none is set.
type IndependenceAssertion ¶
IndependenceAssertion represents a conditional independence statement X _|_ Y | Z for use with IsIMap. Event1 and Event2 are the two variable sets, and Given is the conditioning set.
type JunctionTree ¶
type JunctionTree struct {
// contains filtered or unexported fields
}
JunctionTree represents a junction tree (clique tree) — a tree of cliques with separator sets, used for exact inference in graphical models.
func NewJunctionTreeFromBN ¶
func NewJunctionTreeFromBN(bn *BayesianNetwork) (*JunctionTree, error)
NewJunctionTreeFromBN builds a junction tree from a BayesianNetwork.
Steps:
- Get factors via bn.ToMarkovFactors()
- Build moral graph via graphgo.Moralize()
- Find elimination order (min-degree heuristic)
- Triangulate moral graph
- Find max cliques via graphgo.MaxCliques()
- Build junction tree via graphgo.BuildJunctionTree()
- Assign factors to cliques (each factor goes to the smallest clique containing all its variables)
func (*JunctionTree) AddEdge ¶
func (jt *JunctionTree) AddEdge(cliqueA, cliqueB int) error
AddEdge adds an undirected edge between two cliques identified by their indices. This is used to manually construct or modify junction trees.
func (*JunctionTree) CheckModel ¶
func (jt *JunctionTree) CheckModel() error
CheckModel verifies the running intersection property: for every variable, the set of cliques containing that variable forms a connected subtree.
func (*JunctionTree) Cliques ¶
func (jt *JunctionTree) Cliques() [][]string
Cliques returns a copy of all cliques in the junction tree.
func (*JunctionTree) Copy ¶
func (jt *JunctionTree) Copy() *JunctionTree
Copy returns a deep copy of the JunctionTree.
func (*JunctionTree) GetCliqueFactors ¶
func (jt *JunctionTree) GetCliqueFactors(clique []string) []*factors.DiscreteFactor
GetCliqueFactors returns the factors assigned to a clique identified by its variable set. The clique must match exactly (order-independent).
func (*JunctionTree) SeparatorSets ¶
func (jt *JunctionTree) SeparatorSets() map[string][]string
SeparatorSets returns a copy of the separator sets, keyed by edge key.
func (*JunctionTree) States ¶
func (jt *JunctionTree) States() map[string]int
States returns a map from variable name to its state count, derived from the factors assigned to cliques.
type LinearGaussianBayesianNetwork ¶
type LinearGaussianBayesianNetwork struct {
*BayesianNetwork
// contains filtered or unexported fields
}
LinearGaussianBayesianNetwork is a Bayesian network where every node has a LinearGaussianCPD instead of a TabularCPD. It embeds *BayesianNetwork for graph structure (nodes, edges) and stores LG CPDs in a separate map.
func GetRandomLinearGaussianBayesianNetwork ¶
func GetRandomLinearGaussianBayesianNetwork(nNodes, nEdges int) (*LinearGaussianBayesianNetwork, error)
GetRandom generates a random LinearGaussianBayesianNetwork with the given number of nodes and edges.
func LoadLinearGaussianBayesianNetwork ¶
func LoadLinearGaussianBayesianNetwork(filename string) (*LinearGaussianBayesianNetwork, error)
Load reads a LinearGaussianBayesianNetwork from a file written by Save.
func NewLinearGaussianBayesianNetwork ¶
func NewLinearGaussianBayesianNetwork() *LinearGaussianBayesianNetwork
NewLinearGaussianBayesianNetwork creates a new empty LinearGaussianBayesianNetwork.
func (*LinearGaussianBayesianNetwork) AddLinearGaussianCPD ¶
func (lgbn *LinearGaussianBayesianNetwork) AddLinearGaussianCPD(cpd *factors.LinearGaussianCPD) error
AddLinearGaussianCPD stores a LinearGaussianCPD for its variable. It validates that the variable exists in the graph and that the CPD's evidence matches the node's parents in the DAG.
func (*LinearGaussianBayesianNetwork) CheckModel ¶
func (lgbn *LinearGaussianBayesianNetwork) CheckModel() error
CheckModel validates the LinearGaussianBayesianNetwork:
- Every node has a LinearGaussianCPD.
- Each CPD's evidence matches the node's parents in the DAG.
- Each CPD passes Validate().
func (*LinearGaussianBayesianNetwork) Copy ¶
func (lgbn *LinearGaussianBayesianNetwork) Copy() *LinearGaussianBayesianNetwork
Copy returns a deep copy of the LinearGaussianBayesianNetwork.
func (*LinearGaussianBayesianNetwork) Fit ¶
func (lgbn *LinearGaussianBayesianNetwork) Fit(data *tabgo.DataFrame) error
Fit estimates LinearGaussianCPD parameters from data using OLS per node.
func (*LinearGaussianBayesianNetwork) GetCardinality ¶
func (lgbn *LinearGaussianBayesianNetwork) GetCardinality(node string) (int, error)
GetCardinality returns an error for LinearGaussianBayesianNetwork since continuous variables do not have a finite cardinality.
func (*LinearGaussianBayesianNetwork) GetLinearGaussianCPD ¶
func (lgbn *LinearGaussianBayesianNetwork) GetLinearGaussianCPD(variable string) *factors.LinearGaussianCPD
GetLinearGaussianCPD returns the LinearGaussianCPD for the given variable, or nil if none is set.
func (*LinearGaussianBayesianNetwork) GetRandomCPDs ¶
func (lgbn *LinearGaussianBayesianNetwork) GetRandomCPDs() error
GetRandomCPDs generates and assigns random LinearGaussianCPDs for all nodes. Each node gets betas drawn uniformly from [-1, 1], mean from [-5, 5], and variance from (0, 2].
func (*LinearGaussianBayesianNetwork) IsIMap ¶
func (lgbn *LinearGaussianBayesianNetwork) IsIMap(independencies []IndependenceAssertion) (bool, error)
IsIMap checks whether the network structure is an I-map of the given independence assertions. A BN is an I-map if every independence implied by its structure (via d-separation) is also present in the given set of independencies. The method checks all pairs of non-adjacent nodes: for each such pair (A, B), it uses the DAG's d-separation test with the parents of A as the conditioning set, and verifies that the resulting independence is contained in the provided assertions.
func (*LinearGaussianBayesianNetwork) LogLikelihood ¶
func (lgbn *LinearGaussianBayesianNetwork) LogLikelihood(data *tabgo.DataFrame) (float64, error)
LogLikelihood computes the log-likelihood of the data given the model. Each row's log-likelihood is the sum of log P(x_i | parents(x_i)) for each variable.
func (*LinearGaussianBayesianNetwork) Predict ¶
func (lgbn *LinearGaussianBayesianNetwork) Predict(data *tabgo.DataFrame) (map[string][]float64, error)
Predict returns the predicted (conditional mean) value of each node for each row, evaluated in topological order. Returns a map from variable name to a slice of predicted values.
func (*LinearGaussianBayesianNetwork) PredictProbability ¶
func (lgbn *LinearGaussianBayesianNetwork) PredictProbability(data *tabgo.DataFrame) ([]float64, error)
PredictProbability returns the log-PDF of each row in data given the model. The result is a slice of length data.Len() where each element is the log P(row | model).
func (*LinearGaussianBayesianNetwork) RemoveCPDs ¶
func (lgbn *LinearGaussianBayesianNetwork) RemoveCPDs()
RemoveCPDs removes all LinearGaussianCPDs from the network.
func (*LinearGaussianBayesianNetwork) Save ¶
func (lgbn *LinearGaussianBayesianNetwork) Save(filename string) error
Save writes the LinearGaussianBayesianNetwork to a file in a simple text format (BIF-like for LG networks).
func (*LinearGaussianBayesianNetwork) Simulate ¶
func (lgbn *LinearGaussianBayesianNetwork) Simulate(nSamples int) (*tabgo.DataFrame, error)
Simulate samples continuous data from the linear Gaussian BN.
func (*LinearGaussianBayesianNetwork) ToJointGaussian ¶
func (lgbn *LinearGaussianBayesianNetwork) ToJointGaussian() ([]float64, [][]float64, error)
ToJointGaussian computes the joint Gaussian distribution implied by the linear Gaussian BN. Returns the mean vector and covariance matrix, with variables in sorted order.
func (*LinearGaussianBayesianNetwork) ToMarkovModel ¶
func (lgbn *LinearGaussianBayesianNetwork) ToMarkovModel() error
ToMarkovModel converts the LG BN to a set of factors by computing the joint Gaussian and returning a single factor representing the joint distribution. For continuous models this returns an error since discrete factors are not directly applicable.
type MarkovChain ¶
type MarkovChain struct {
// contains filtered or unexported fields
}
MarkovChain represents a discrete-time Markov chain with a finite state space. The transition matrix T[i][j] gives the probability of transitioning from state i to state j.
func NewMarkovChain ¶
func NewMarkovChain(transitionMatrix [][]float64, stateNames []string) (*MarkovChain, error)
NewMarkovChain creates a new MarkovChain. transitionMatrix must be square and each row must sum to 1 (within tolerance). stateNames must match the number of states, or be nil (in which case states are unnamed).
func (*MarkovChain) AddTransitionModel ¶
func (mc *MarkovChain) AddTransitionModel(matrix [][]float64) error
AddTransitionModel sets the transition matrix for the chain. The provided matrix must be square with the same size as the current number of states, and each row must sum to 1 (within tolerance).
func (*MarkovChain) AddVariable ¶
func (mc *MarkovChain) AddVariable(name string)
AddVariable adds a new state to the Markov chain. The transition probabilities for the new state (row and column) are initialized to a uniform distribution. Existing rows are re-normalized.
func (*MarkovChain) AddVariablesFrom ¶
func (mc *MarkovChain) AddVariablesFrom(other *MarkovChain)
AddVariablesFrom copies state names and transition probabilities from another MarkovChain, adding any states not already present. If the source has unnamed states, they are added with generated names.
func (*MarkovChain) Copy ¶
func (mc *MarkovChain) Copy() *MarkovChain
Copy returns a deep copy of the MarkovChain.
func (*MarkovChain) GenerateSample ¶
GenerateSample generates a slice of n sampled state indices starting from startState, using the given seed for reproducibility.
func (*MarkovChain) IsAbsorbing ¶
func (mc *MarkovChain) IsAbsorbing() bool
IsAbsorbing returns true if the Markov chain has at least one absorbing state (a state i where T[i][i] == 1).
func (*MarkovChain) IsErgodic ¶
func (mc *MarkovChain) IsErgodic() bool
IsErgodic returns true if the Markov chain is ergodic (irreducible and aperiodic). Irreducibility is checked by verifying that all states can reach all other states. Aperiodicity is checked by verifying that the GCD of return times to each state is 1 (approximated by checking that T^k has all positive entries for some k).
func (*MarkovChain) IsStationarity ¶
func (mc *MarkovChain) IsStationarity(dist []float64) (bool, error)
IsStationarity tests whether the given distribution is stationary for this Markov chain (i.e., pi * T = pi within tolerance).
func (*MarkovChain) NumStates ¶
func (mc *MarkovChain) NumStates() int
NumStates returns the number of states.
func (*MarkovChain) ProbFromSample ¶
func (mc *MarkovChain) ProbFromSample(sequence []int) ([][]float64, error)
ProbFromSample estimates transition probabilities from a sequence of state indices. Returns a new transition matrix where T[i][j] is the fraction of times state i was followed by state j.
func (*MarkovChain) RandomState ¶
func (mc *MarkovChain) RandomState(seed int64) (int, error)
RandomState samples a state index from the stationary distribution.
func (*MarkovChain) Sample ¶
Sample generates a sequence of n state indices starting from startState. seed controls the random number generator (use 0 for non-deterministic).
func (*MarkovChain) SetStartState ¶
func (mc *MarkovChain) SetStartState(state int) (int, error)
SetStartState is a convenience that validates a start state index. It returns an error if the index is out of range; otherwise it returns the validated index. (MarkovChain is stateless regarding "current state", so this simply validates.)
func (*MarkovChain) StateNames ¶
func (mc *MarkovChain) StateNames() []string
StateNames returns a copy of the state names, or nil if unnamed.
func (*MarkovChain) StationaryDistribution ¶
func (mc *MarkovChain) StationaryDistribution() ([]float64, error)
StationaryDistribution computes the stationary distribution pi such that pi * T = pi, using the power iteration method.
func (*MarkovChain) TransitionMatrix ¶
func (mc *MarkovChain) TransitionMatrix() [][]float64
TransitionMatrix returns a deep copy of the transition matrix.
type MarkovNetwork ¶
type MarkovNetwork struct {
// contains filtered or unexported fields
}
MarkovNetwork represents a Markov random field (MRF) — an undirected graphical model where each factor (potential) is defined over a clique of the graph.
func NewMarkovNetwork ¶
func NewMarkovNetwork() *MarkovNetwork
NewMarkovNetwork creates a new empty MarkovNetwork.
func (*MarkovNetwork) AddEdge ¶
func (mn *MarkovNetwork) AddEdge(u, v string) error
AddEdge adds an undirected edge between u and v. Both nodes must exist.
func (*MarkovNetwork) AddFactor ¶
func (mn *MarkovNetwork) AddFactor(f *factors.DiscreteFactor) error
AddFactor adds a factor to the network. All variables in the factor's scope must be nodes in the graph. Returns an error if any variable is missing or if the factor is nil.
func (*MarkovNetwork) AddNode ¶
func (mn *MarkovNetwork) AddNode(node string) error
AddNode adds a node (variable) to the network.
func (*MarkovNetwork) CheckModel ¶
func (mn *MarkovNetwork) CheckModel() error
CheckModel validates the Markov network:
- Every factor's scope variables must be connected by edges: for every pair of variables in a factor, the edge must exist in the graph.
- Every node must be covered by at least one factor.
func (*MarkovNetwork) Copy ¶
func (mn *MarkovNetwork) Copy() *MarkovNetwork
Copy returns a deep copy of the MarkovNetwork.
func (*MarkovNetwork) Edges ¶
func (mn *MarkovNetwork) Edges() [][2]string
Edges returns all undirected edges in canonical form (A < B), sorted lexicographically.
func (*MarkovNetwork) GetCardinality ¶
func (mn *MarkovNetwork) GetCardinality(node string) (int, error)
GetCardinality returns the cardinality of a node as determined from its factors. Returns an error if no factor covers the node.
func (*MarkovNetwork) GetFactors ¶
func (mn *MarkovNetwork) GetFactors() []*factors.DiscreteFactor
GetFactors returns all factors, in insertion order.
func (*MarkovNetwork) GetFactorsOf ¶
func (mn *MarkovNetwork) GetFactorsOf(variable string) []*factors.DiscreteFactor
GetFactorsOf returns all factors that include the given variable in their scope. Returns nil if the variable has no factors.
func (*MarkovNetwork) GetLocalIndependencies ¶
func (mn *MarkovNetwork) GetLocalIndependencies(node string) ([]*independencies.IndependenceAssertion, error)
GetLocalIndependencies returns the local Markov property independence assertions for a node. In a Markov network, a node is conditionally independent of all non-neighbors given its neighbors (Markov blanket).
func (*MarkovNetwork) GetPartitionFunction ¶
func (mn *MarkovNetwork) GetPartitionFunction() (float64, error)
GetPartitionFunction computes Z, the partition function, by summing the product of all factors over all joint assignments. This is only feasible for small models.
func (*MarkovNetwork) MarkovBlanket ¶
func (mn *MarkovNetwork) MarkovBlanket(node string) []string
MarkovBlanket returns the Markov blanket of a node, which in an undirected model is simply the set of neighbors.
func (*MarkovNetwork) Neighbors ¶
func (mn *MarkovNetwork) Neighbors(node string) []string
Neighbors returns the sorted neighbors of a node in the undirected graph.
func (*MarkovNetwork) Nodes ¶
func (mn *MarkovNetwork) Nodes() []string
Nodes returns a sorted list of all nodes in the network.
func (*MarkovNetwork) RemoveFactor ¶
func (mn *MarkovNetwork) RemoveFactor(variables []string)
RemoveFactor removes all factors whose variable set exactly matches the given variables (order-independent).
func (*MarkovNetwork) States ¶
func (mn *MarkovNetwork) States() map[string]int
States returns a map from each variable name to its cardinality, as extracted from the factors in the network. Variables with no factors are not included.
func (*MarkovNetwork) ToBayesianModel ¶
func (mn *MarkovNetwork) ToBayesianModel() (*BayesianNetwork, error)
ToBayesianModel converts the Markov network to a Bayesian network by triangulating the graph and finding a topological ordering of the resulting DAG. The CPDs are derived from the factors.
func (*MarkovNetwork) ToFactorGraph ¶
func (mn *MarkovNetwork) ToFactorGraph() (*FactorGraph, error)
ToFactorGraph converts the Markov network to a factor graph.
func (*MarkovNetwork) ToJunctionTree ¶
func (mn *MarkovNetwork) ToJunctionTree() (*JunctionTree, error)
ToJunctionTree constructs a junction tree from the Markov network by:
- Building a graphgo.Graph from the undirected graph
- Finding a min-degree elimination order
- Triangulating the graph
- Finding maximal cliques
- Building the junction tree
- Assigning factors to cliques
func (*MarkovNetwork) Triangulate ¶
func (mn *MarkovNetwork) Triangulate(heuristic string) (*MarkovNetwork, error)
Triangulate returns a triangulated copy of the Markov network. The heuristic parameter selects the elimination ordering heuristic: "min_degree" (default), "min_fill".
type NaiveBayes ¶
type NaiveBayes struct {
*BayesianNetwork
// contains filtered or unexported fields
}
NaiveBayes represents a Naive Bayes classifier — a Bayesian network with a star topology where the class variable is the root and all features are conditionally independent given the class.
func NewNaiveBayes ¶
func NewNaiveBayes(classVariable string, features []string) (*NaiveBayes, error)
NewNaiveBayes creates a new NaiveBayes model with the given class variable and feature variables. It constructs a star topology DAG where classVariable is a parent of each feature.
func (*NaiveBayes) ActiveTrailNodes ¶
ActiveTrailNodes returns the set of nodes reachable from the given variable via active trails given the observed variables. In a naive Bayes structure (class -> features), the d-separation rules simplify:
- From the class variable: all features not in observed are reachable, plus any observed feature (since it's a direct child). All features are reachable.
- From a feature: the class is reachable unless it is observed and there is no other path. With evidence on a feature (v-structure at class), the class and other features become reachable. Without evidence on the feature, the class is reachable and through it all non-observed features.
This implements a BFS on the augmented DAG following Bayes-ball rules.
func (*NaiveBayes) AddEdge ¶
func (nb *NaiveBayes) AddEdge(from, to string) error
AddEdge overrides the embedded BayesianNetwork's AddEdge to enforce the star topology: only edges from the class variable to a feature are allowed.
func (*NaiveBayes) AddEdgesFrom ¶
func (nb *NaiveBayes) AddEdgesFrom(from string, toList []string) error
AddEdgesFrom adds multiple edges from the given parent to the given children. Each edge must satisfy the star topology constraint.
func (*NaiveBayes) ClassVariable ¶
func (nb *NaiveBayes) ClassVariable() string
ClassVariable returns the name of the class variable.
func (*NaiveBayes) Features ¶
func (nb *NaiveBayes) Features() []string
Features returns a copy of the feature variable names.
func (*NaiveBayes) Fit ¶
func (nb *NaiveBayes) Fit(data *tabgo.DataFrame) error
Fit estimates parameters from data using maximum likelihood estimation (MLE). The DataFrame must contain columns for the class variable and all features. All values must be non-negative integers representing discrete state indices. Fit delegates to nbFitImpl with the default CPD creator, preserving the public API signature.
func (*NaiveBayes) LocalIndependencies ¶
func (nb *NaiveBayes) LocalIndependencies() *independencies.Independencies
LocalIndependencies returns the set of independence assertions implied by the naive Bayes structure. In a naive Bayes model, every pair of features is conditionally independent given the class variable:
(f_i _|_ f_j | classVariable) for all i != j
func (*NaiveBayes) Predict ¶
func (nb *NaiveBayes) Predict(data *tabgo.DataFrame) ([]int, error)
Predict returns the predicted class (index of highest posterior probability) for each row in data.
func (*NaiveBayes) PredictProbability ¶
func (nb *NaiveBayes) PredictProbability(data *tabgo.DataFrame) ([][]float64, error)
PredictProbability returns the posterior probability of each class for each row in data. The result is a slice of length data.Len(), where each element is a slice of class probabilities.
type SEM ¶
type SEM struct {
// contains filtered or unexported fields
}
SEM represents a linear Structural Equation Model (SEM). The model is defined by a DAG and a set of linear equations, one per variable.
func FromGraph ¶
FromGraph creates an SEM from a DAG. Each variable gets an equation with zero coefficients and unit variance.
func FromLavaan ¶
FromLavaan parses lavaan model syntax into an SEM. Each line of the form "Y ~ X1 + X2" creates an equation for Y with parents X1, X2, zero coefficients, zero intercept, and unit variance. Blank lines and lines without "~" are ignored.
func FromLisrel ¶
FromLisrel creates an SEM from a simplified LISREL matrix specification. The syntax is a set of lines, each of the form:
variable: parent1=coeff1 parent2=coeff2 variance=v intercept=i
If no parents are specified, the variable is exogenous. Variance defaults to 1.0 and intercept defaults to 0.0 if not specified.
func FromRAM ¶
FromRAM creates an SEM from a RAM (Reticular Action Model) specification. It accepts the same syntax as FromLisrel.
func (*SEM) ActiveTrailNodes ¶
ActiveTrailNodes returns the set of nodes reachable from variable via active trails given the observed variables, using Bayes-ball on the underlying DAG.
func (*SEM) AddEquation ¶
func (s *SEM) AddEquation(variable string, parents []string, coefficients []float64, intercept, variance float64) error
AddEquation adds a structural equation for a variable. If the variable or its parents do not yet exist in the DAG, they are added automatically. Edges are added from each parent to the variable.
func (*SEM) CheckModel ¶
CheckModel validates the SEM:
- Every node in the DAG has an equation.
- Each equation's parents match the node's parents in the DAG.
- Variance must be non-negative.
func (*SEM) Fit ¶
Fit estimates SEM parameters from data using OLS (ordinary least squares) per equation. The DataFrame must contain columns for all variables. The DAG structure must be set up (via AddEquation or by constructing equations with zero coefficients) before calling Fit.
func (*SEM) GenerateSamples ¶
GenerateSamples simulates data from the SEM by sampling in topological order. Each variable is computed as: value = intercept + sum(coeff * parentValue) + N(0, variance).
func (*SEM) GetEquation ¶
func (s *SEM) GetEquation(variable string) *SEMEquation
GetEquation returns the equation for the given variable, or nil if none is set.
func (*SEM) GetScalingIndicators ¶
GetScalingIndicators returns one indicator variable per latent variable. In a basic SEM, this returns all root nodes (nodes with no parents) as they serve as natural scaling indicators for identification.
func (*SEM) ImpliedCovarianceMatrix ¶
ImpliedCovarianceMatrix computes the model-implied covariance matrix using path tracing. For a linear SEM: Sigma = (I - B)^{-1} * Psi * ((I - B)^{-1})^T where B is the matrix of path coefficients and Psi is the diagonal matrix of error variances.
Variables are ordered alphabetically. Returns the covariance matrix and an error if the model is invalid or the matrix is not invertible.
func (*SEM) Moralize ¶
Moralize returns the moral graph of the SEM's DAG as a graphgo.Graph. The moral graph connects all co-parents and drops edge directions.
func (*SEM) ToLisrel ¶
ToLisrel converts the SEM to LISREL matrix representation. Returns a map with keys "B" (Beta, structural coefficients among endogenous), "Gamma" (effects of exogenous on endogenous), "Psi" (error covariances), and "Phi" (exogenous covariances). Variables are ordered alphabetically within their category. Exogenous variables are those with no parents in the DAG (roots).
func (*SEM) ToSEMGraph ¶
ToSEMGraph returns the SEM itself, as it already is a SEM graph representation.
func (*SEM) ToStandardLisrel ¶
ToStandardLisrel converts the SEM to standardized LISREL matrix representation. The B matrix is scaled so that implied variances are 1 (standardized coefficients). Returns the same keys as ToLisrel: "B", "Gamma", "Psi", "Phi".
Source Files
¶
- bayesian_network.go
- bayesian_network_methods.go
- bayesian_network_parity.go
- cluster_graph.go
- cluster_graph_methods.go
- di_interfaces.go
- discrete_bayesian_network.go
- discrete_markov_network.go
- doc.go
- dynamic_bn.go
- dynamic_bn_methods.go
- factor_graph.go
- factor_graph_methods.go
- functional_bn.go
- junction_tree.go
- linear_gaussian_bn.go
- markov_chain.go
- markov_chain_methods.go
- markov_network.go
- naive_bayes.go
- safepath.go
- sem.go