sem

package
v1.0.0-alpha.19 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package sem is the structural equation model (SEM) estimator behind MAT_SEM: a lavaan / semopy model description fitted by maximum likelihood to a sample covariance matrix.

Its default setup is semopy 2.3.11's default covariance-structure model (semopy.Model, obj="MLW", solver="SLSQP", mimic_lavaan=False): the same variable classification, parameter set and fixings, the same Wishart ML objective minimised by a port of SciPy's SLSQP (slsqp.go) with semopy's settings, the same expected-information standard errors and the same fit statistics — so a fit over the same data gives semopy's numbers, its early stop at ftol included. Options select a converging Fisher-scoring solver and the rank-2 derivative computation instead.

The package reads only a covariance matrix and a row count; it is no-execute safe (stdlib, gonum) and imported by both the resolver (internal/vectors: model validation at predict time) and the engine (internal/processing: the finalizer).

Index

Constants

View Source
const (
	OpRegression  = "~"
	OpMeasurement = "=~"
	OpCovariance  = "~~"
)

Operators of the model syntax.

Variables

This section is empty.

Functions

func ComputeStats

func ComputeStats(fit *Fit, desc string) error

ComputeStats fills fit.Stats; desc is the model description, used to fit semopy's baseline (independence) model on the same covariance.

Types

type Effects

type Effects struct {
	// contains filtered or unexported fields
}

Effects maps operator -> left variable -> right variable -> multiplier, keeping first-seen order at every level (semopy iterates dicts in insertion order, which fixes its parameter order).

func Parse

func Parse(desc string) (*Effects, error)

Parse reads a model description in semopy / lavaan syntax: one statement per line, `#` comments, `=~` (measurement), `~` (regression) and `~~` (covariance), comma-separated left sides, `+`-separated right sides and optional `mult*` prefixes. semopy's operation commands (START, BOUND, DEFINE, ...) are not supported.

type Estimate

type Estimate struct {
	LVal, Op, RVal string
	Value          float64
	StdValue       float64
	Free           bool
	SE, Z, P       float64
	Param          string
}

Estimate is one row of the parameter table, laid out like semopy's Model.inspect(std_est=True): lval op rval, the estimate, the standardized estimate, and (free parameters only) SE, z and p.

func SpecifiedRows

func SpecifiedRows(m *Model) []Estimate

SpecifiedRows lists the parameter-table rows of an unfitted model, in Fit.Estimates' order, with every figure NaN: the rows an undefined input still reports.

func (Estimate) Key

func (e Estimate) Key() string

Key is "lval op rval".

type Fit

type Fit struct {
	Model      *Model
	N          float64
	Objective  float64 // the minimised Wishart ML discrepancy F
	Iterations int
	Converged  bool
	Status     string // the solver's exit message
	Options    Options
	Sample     *mat.SymDense // S over Model.Observed
	Implied    *mat.SymDense // Σ(θ̂)
	Estimates  []Estimate
	Stats      Stats
	// contains filtered or unexported fields
}

Fit is a fitted model.

func FitCov

func FitCov(m *Model, s *mat.SymDense, n float64, opt Options) (*Fit, error)

FitCov fits the model to a sample covariance matrix S (over m.Observed, divisor N — semopy's biased covariance) from n rows.

type Information

type Information string

Information selects how the expected information tr(Σ⁻¹∂Σ_kΣ⁻¹∂Σ_l) and the gradient are computed. Both give the same figures up to rounding.

const (
	// InformationDense forms every ∂Σ_k as a dense matrix, as semopy
	// does (the default).
	InformationDense Information = "dense"
	// InformationRank2 uses ∂Σ_k = Σ(a·bᵀ + b·aᵀ): every trace reduces
	// to dot products of Σ⁻¹-transformed vectors, O(k²·p) instead of
	// O(k·p³ + k²·p²).
	InformationRank2 Information = "rank2"
)

type Model

type Model struct {
	// Observed is the model's observed variables in semopy's order: the
	// sorted outputs (variables with no outgoing arrow), then the other
	// observed variables sorted. Sample and implied covariances use it.
	Observed []string
	// Inner is the non-output variables: sorted latents, then sorted
	// observed inner variables (Beta and Psi index it).
	Inner []string
	// contains filtered or unexported fields
}

Model is a parsed, specified SEM: the variable classification and the parameter table, before any data is seen.

func NewModel

func NewModel(desc string, baseline bool) (*Model, error)

NewModel specifies the model a description describes, with semopy's defaults (variances of every endogenous and latent variable free, observed exogenous (co)variances fixed to the sample, exogenous latents free to covary, the first indicator of each latent fixed to 1). baseline builds semopy's independence model instead.

type Mult

type Mult struct {
	Set   bool
	Fixed bool
	Value float64
	Label string
}

Mult is the multiplier written before a right-hand variable: none (a free parameter), a fixed number ("0.5*x") or a parameter label ("a*x", equality across every place the label is used).

type Options

type Options struct {
	// Solver is the optimiser (default SolverSLSQP).
	Solver Solver
	// Information is the derivative computation (default
	// InformationDense).
	Information Information
	// Ftol is SLSQP's ftol (default 1e-6, SciPy's and semopy's).
	Ftol float64
	// MaxIter caps the iterations (default 10000 for SLSQP — semopy's
	// setting — and 500 for Fisher scoring).
	MaxIter int
	// GradTol is Fisher scoring's stop: every free gradient entry below
	// it in absolute value (default 1e-10).
	GradTol float64
}

Options configure the fit. The zero value is semopy's default setup.

func (Options) Validate

func (o Options) Validate() error

Validate reports an unknown solver or information mode.

type Solver

type Solver string

Solver selects the optimiser.

const (
	// SolverSLSQP is SciPy's SLSQP as semopy calls it (the default): the
	// same iterates, the same early stop at ftol, the same result.
	SolverSLSQP Solver = "slsqp"
	// SolverFisher is damped Fisher scoring (Levenberg–Marquardt on the
	// expected information): converges to the optimum to GradTol.
	SolverFisher Solver = "fisher"
)

type Stats

type Stats struct {
	DoF          float64
	DoFBaseline  float64
	Chi2         float64
	Chi2P        float64
	Chi2Baseline float64
	CFI, GFI     float64
	AGFI, NFI    float64
	TLI, RMSEA   float64
	AIC, BIC     float64
	LogLik       float64
	NParams      int
}

Stats are semopy.calc_stats' figures, with semopy's definitions — including its conventions: LogLik is the minimised discrepancy F (semopy's calc_likelihood returns obj_mlw), AIC = 2(k − F), BIC = ln(N)·k − 2F, and GFI equals NFI.

Jump to

Keyboard shortcuts

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