models

package
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 11, 2026 License: MIT Imports: 15 Imported by: 0

README

models

Package models provides graphical model structures including Bayesian networks, Markov networks, factor graphs, junction trees, and structural equation models.

Import path: github.com/asymmetric-effort/datascience/lib/pgm/models

Types

Type Description
BayesianNetwork DAG with TabularCPDs; supports inference, prediction, do-calculus
DiscreteBayesianNetwork BayesianNetwork with discrete-specific validation and forward sampling
LinearGaussianBayesianNetwork BN with LinearGaussianCPDs for continuous variables
FunctionalBayesianNetwork BN with arbitrary FunctionalCPDs
DynamicBayesianNetwork Two-time-slice BN (2TBN) for temporal modeling
NaiveBayes Star-topology classifier (class -> features)
MarkovNetwork Undirected graphical model (MRF) with discrete factor potentials
DiscreteMarkovNetwork MarkovNetwork with additional discrete validation
FactorGraph Bipartite graph of variable and factor nodes
ClusterGraph Graph of variable clusters connected by separation sets
JunctionTree Clique tree for exact inference, built from BN or MN
MarkovChain Discrete-time finite-state Markov chain
SEM Linear Structural Equation Model with OLS fitting

BayesianNetwork

import (
    "github.com/asymmetric-effort/datascience/lib/pgm/models"
    "github.com/asymmetric-effort/datascience/lib/pgm/factors"
)

bn := models.NewBayesianNetwork()
bn.AddNode("Rain")
bn.AddNode("Sprinkler")
bn.AddNode("Wet")
bn.AddEdge("Rain", "Wet")
bn.AddEdge("Sprinkler", "Wet")

// Add CPDs
rainCPD, _ := factors.NewTabularCPD("Rain", 2,
    [][]float64{{0.8}, {0.2}}, nil, nil)
bn.AddCPD(rainCPD)

// Validate
err := bn.CheckModel()

// Do-calculus intervention
mutilated, _ := bn.Do(map[string]int{"Rain": 1})

// Get probability of a state assignment
prob, _ := bn.GetStateProbability(map[string]int{"Rain": 1, "Wet": 1})

// Save/Load BIF format
bn.Save("model.bif")
loaded, _ := models.LoadBayesianNetwork("model.bif")

// Generate random network
randBN, _ := models.GetRandomBayesianNetwork(5, 4, 2)

LinearGaussianBayesianNetwork

lgbn := models.NewLinearGaussianBayesianNetwork()
lgbn.AddNode("X")
lgbn.AddNode("Y")
lgbn.AddEdge("X", "Y")

cpd, _ := factors.NewLinearGaussianCPD("Y", 1.0, []float64{0.5}, 0.1, []string{"X"})
lgbn.AddLinearGaussianCPD(cpd)

// Fit from data
lgbn.Fit(data)

// Simulate samples
samples, _ := lgbn.Simulate(1000)

// Joint Gaussian parameters
mu, sigma, _ := lgbn.ToJointGaussian()

NaiveBayes

nb, _ := models.NewNaiveBayes("Class", []string{"F1", "F2", "F3"})
nb.Fit(trainingData)
predictions, _ := nb.Predict(testData)
probabilities, _ := nb.PredictProbability(testData)

MarkovNetwork

mn := models.NewMarkovNetwork()
mn.AddNode("A")
mn.AddNode("B")
mn.AddEdge("A", "B")

factor, _ := factors.NewDiscreteFactor([]string{"A", "B"}, []int{2, 2},
    []float64{0.5, 0.8, 0.1, 0.0})
mn.AddFactor(factor)

z, _ := mn.GetPartitionFunction()
jt, _ := mn.ToJunctionTree()

SEM

sem := models.NewSEM()
sem.AddEquation("Y", []string{"X"}, []float64{0.5}, 1.0, 0.1)

// Or parse from lavaan syntax
sem2, _ := models.FromLavaan("Y ~ X1 + X2\nZ ~ Y")

// Fit from data
sem.Fit(data)

// Implied covariance matrix
sigma, _ := sem.ImpliedCovarianceMatrix()

// Generate samples
samples, _ := sem.GenerateSamples(1000)

// LISREL matrices
lisrel, _ := sem.ToLisrel()

DynamicBayesianNetwork

dbn := models.NewDynamicBayesianNetwork()
dbn.Initial().AddNode("X")
dbn.Transition().AddNode("X")
dbn.Transition().AddNode("X_prev")

ifaceNodes := dbn.GetInterfaceNodes()

MarkovChain

mc, _ := models.NewMarkovChain(
    [][]float64{{0.7, 0.3}, {0.4, 0.6}},
    []string{"Sunny", "Rainy"},
)

pi, _ := mc.StationaryDistribution()
samples, _ := mc.Sample(100, 0, 42)
isErg := mc.IsErgodic()

JunctionTree

jt, _ := bn.ToJunctionTree()
cliques := jt.Cliques()
seps := jt.SeparatorSets()
err := jt.CheckModel() // running intersection property

Documentation

Overview

Package models provides graphical model structures including Bayesian networks, Markov networks, and factor graphs.

Index

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:

  1. Every node has a CPD.
  2. Each CPD's evidence matches the node's parents in the DAG.
  3. 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

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

func (bn *BayesianNetwork) Predict(data *tabgo.DataFrame) (*tabgo.DataFrame, error)

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

func (bn *BayesianNetwork) PredictProbability(data *tabgo.DataFrame) (map[string][]float64, error)

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

type ClusterEdge struct {
	Cluster1 int
	Cluster2 int
	SepSet   []string
}

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:

  1. At least one cluster exists.
  2. Each edge's separation set must be a subset of the intersection of the two connected clusters' variable sets.
  3. 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

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.

func (*DiscreteBayesianNetwork) Simulate

func (dbn *DiscreteBayesianNetwork) Simulate(n int, seed int64) (*tabgo.DataFrame, error)

Simulate generates n data points by forward sampling the network. It returns a DataFrame with one column per node, in topological order. The seed parameter controls the random number generator (use 0 for non-deterministic behavior).

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

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

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

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

func (dbn *DynamicBayesianNetwork) Simulate(nTimeSteps int, seed int64) (*tabgo.DataFrame, error)

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:

  1. At least one variable exists.
  2. At least one factor exists.
  3. Every factor's variables exist in the graph with matching cardinalities.
  4. 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:

  1. Every node has a FunctionalCPD.
  2. Each CPD's evidence matches the node's parents in the DAG.
  3. Each CPD passes Validate().

func (*FunctionalBayesianNetwork) Copy

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

type IndependenceAssertion struct {
	Event1 []string
	Event2 []string
	Given  []string
}

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:

  1. Get factors via bn.ToMarkovFactors()
  2. Build moral graph via graphgo.Moralize()
  3. Find elimination order (min-degree heuristic)
  4. Triangulate moral graph
  5. Find max cliques via graphgo.MaxCliques()
  6. Build junction tree via graphgo.BuildJunctionTree()
  7. 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:

  1. Every node has a LinearGaussianCPD.
  2. Each CPD's evidence matches the node's parents in the DAG.
  3. Each CPD passes Validate().

func (*LinearGaussianBayesianNetwork) Copy

Copy returns a deep copy of the LinearGaussianBayesianNetwork.

func (*LinearGaussianBayesianNetwork) Fit

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

func (mc *MarkovChain) GenerateSample(n int, startState int, seed int64) ([]int, error)

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

func (mc *MarkovChain) Sample(n int, startState int, seed int64) ([]int, error)

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:

  1. 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.
  2. 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:

  1. Building a graphgo.Graph from the undirected graph
  2. Finding a min-degree elimination order
  3. Triangulating the graph
  4. Finding maximal cliques
  5. Building the junction tree
  6. 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

func (nb *NaiveBayes) ActiveTrailNodes(variable string, observed map[string]bool) ([]string, error)

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

func FromGraph(dag *base.DAG) (*SEM, error)

FromGraph creates an SEM from a DAG. Each variable gets an equation with zero coefficients and unit variance.

func FromLavaan

func FromLavaan(syntax string) (*SEM, error)

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

func FromLisrel(spec string) (*SEM, error)

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

func FromRAM(spec string) (*SEM, error)

FromRAM creates an SEM from a RAM (Reticular Action Model) specification. It accepts the same syntax as FromLisrel.

func NewSEM

func NewSEM() *SEM

NewSEM creates a new empty SEM.

func (*SEM) ActiveTrailNodes

func (s *SEM) ActiveTrailNodes(variable string, observed map[string]bool) ([]string, error)

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

func (s *SEM) CheckModel() error

CheckModel validates the SEM:

  1. Every node in the DAG has an equation.
  2. Each equation's parents match the node's parents in the DAG.
  3. Variance must be non-negative.

func (*SEM) Fit

func (s *SEM) Fit(data *tabgo.DataFrame) error

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

func (s *SEM) GenerateSamples(nSamples int) (*tabgo.DataFrame, error)

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

func (s *SEM) GetScalingIndicators() []string

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

func (s *SEM) ImpliedCovarianceMatrix() ([][]float64, error)

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

func (s *SEM) Moralize() *graphgo.Graph

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) SetParams

func (s *SEM) SetParams(variable string, coefficients []float64, intercept, variance float64) error

SetParams sets the parameters for an existing equation.

func (*SEM) ToLisrel

func (s *SEM) ToLisrel() (map[string][][]float64, error)

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

func (s *SEM) ToSEMGraph() *SEM

ToSEMGraph returns the SEM itself, as it already is a SEM graph representation.

func (*SEM) ToStandardLisrel

func (s *SEM) ToStandardLisrel() (map[string][][]float64, error)

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".

func (*SEM) Variables

func (s *SEM) Variables() []string

Variables returns a sorted list of all variables in the SEM.

type SEMEquation

type SEMEquation struct {
	Variable     string
	Parents      []string
	Coefficients []float64
	Intercept    float64
	Variance     float64
}

SEMEquation represents a single structural equation:

variable = intercept + sum(coefficients[i] * parents[i]) + error

where error ~ N(0, variance).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL