fa

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

fa/GPArotation_GPFoblq.go

fa/GPArotation_GPForth.go

fa/GPArotation_vgQ_bentler.go

fa/GPArotation_vgQ_geomin.go

fa/GPArotation_vgQ_oblimin.go

fa/GPArotation_vgQ_quartimax.go

fa/GPArotation_vgQ_quartimin.go

fa/GPArotation_vgQ_simplimax.go

fa/GPArotation_vgQ_varimax.go

fa/dsyevr_wrapper.go

Adapter that exposes our pure-Go dsyevr implementation with the same interface as statslinalg.SymmetricEigenDescending — eigenvalues in DESCENDING order, eigenvectors as columns of a Dense matrix.

fa/fa.go

fa/factor2cluster.go

fa/kaiser_varimax.go

fa/lapack_blas2.go

BLAS-2 routines used by the dsyevr port: dgemv, dger, dswap. These supplement the BLAS-1 set in lbfgsb_blas.go (daxpy/dcopy/ddot/dnrm2/ dscal). Strict Fortran-reference accumulation order: J outer / I inner.

All matrices are column-major flat []float64 with explicit `lda`.

fa/lapack_dlaebz.go

dlaebz — workhorse bisection / interval-refinement routine for symmetric tridiagonal eigenvalue computations. Used by dstebz (and indirectly by dsyevr's bisection-fallback path).

Faithful translation of LAPACK 3.12.1 reference Fortran (dlaebz.f). We keep the column-major (mmax, 2) layout for ab and nab — the caller is responsible for allocating those as length-(2*mmax) flat slices addressed as ab[(jp-1)*mmax + (ji-1)].

fa/lapack_dlagt.go

dlagtf — LU factorization of an n-by-n tridiagonal matrix T - λI

(with row interchanges via diagonal pivoting).

dlagts — solve the system (T - λI) x = scaled y for y given the

factor from dlagtf. Used by dstein for inverse-iteration
eigenvector refinement.

Faithful translations of LAPACK 3.12.1 dlagtf.f and dlagts.f.

fa/lapack_dlansy.go

dlansy — symmetric matrix norm. Faithful translation of LAPACK 3.12.1 dlansy.f. Supports norm = 'M' (max abs), '1'/'O'/'I' (1-norm or inf-norm; equal for symmetric matrices), 'F'/'E' (Frobenius).

fa/lapack_dlar1v.go

dlar1v — compute the (scaled) r-th column of (LDL^T - λI)^{-1} via twisted factorization. Used by dlarrv as the per-eigenvector kernel of the MRRR algorithm. Faithful translation of LAPACK 3.12.1 dlar1v.f.

fa/lapack_dlarrb.go

dlarrb — local-bisection refinement of selected eigenvalues of an

LDL^T factored tridiagonal, using twisted-factorization
Sturm counts (dlaneg).

dlaneg — Sturm-sequence negcount via twisted factorization, with

NaN-tolerant block-loop safety. Used by dlarrb.

Faithful translations of LAPACK 3.12.1 dlarrb.f and dlaneg.f.

fa/lapack_dlarrd.go

dlarrd — compute the eigenvalues of a symmetric tridiagonal matrix to suitable accuracy. Auxiliary code called by dstemr (and dstebz).

Faithful translation of LAPACK 3.12.1 reference Fortran (dlarrd.f).

fa/lapack_dlarre.go

dlarre — given a tridiagonal matrix T, set up base RRRs (one per split block) and compute initial eigenvalue approximations to be refined later by dlarrv.

Faithful translation of LAPACK 3.12.1 dlarre.f. dqds calls into gonum's Dlasq2 (already a faithful Go port of the reference).

fa/lapack_dlarrf.go

dlarrf — given an LDL^T representation of a tridiagonal matrix and a cluster of close eigenvalues, find a new RRR L(+) D(+) L(+)^T such that at least one of its eigenvalues is relatively isolated.

Faithful translation of LAPACK 3.12.1 dlarrf.f.

fa/lapack_dlarrj.go

dlarrj — limited bisection refinement of selected eigenvalues of a symmetric tridiagonal matrix (the unfactored form). Used by dstemr. Faithful translation of LAPACK 3.12.1 dlarrj.f.

fa/lapack_dlarrv.go

dlarrv — compute the eigenvectors of L D L^T given the eigenvalues from dlarre. Maintains a cluster representation tree: each cluster is either a singleton (compute its eigenvector via dlar1v + RQI) or a non-trivial cluster (compute a child RRR via dlarrf and recurse).

Faithful translation of LAPACK 3.12.1 dlarrv.f.

fa/lapack_dlaruv_mm.go

dlaruvMM is the LAPACK MM(128,4) seed-multiplier table from reference dlaruv.f. Indexed [i-1][j-1] vs Fortran MM(I, J).

fa/lapack_dormtr.go

dormtr — apply the orthogonal Q (from dsytrd's tridiagonal reduction) to a matrix C: C := Q*C, Q^T*C, C*Q, or C*Q^T. Used by dsyevr to transform tridiagonal-basis eigenvectors back to the original basis.

Implementation strategy: we cannot reuse gonum's Dormqr because gonum uses ROW-MAJOR storage (dense[i*ld + j]), while our entire LAPACK port is column-major (Fortran convention dense[(j-1)*ld + (i-1)]). So we:

  1. Build the explicit Q via our dorgtr (column-major, already validated against gonum's EigenSym in dsyev).
  2. Multiply Q (or Q^T) by C in column-major into a temporary, copy back to C.

fa/lapack_dstebz.go

dstebz — compute selected eigenvalues of a symmetric tridiagonal matrix T by bisection (Sturm-sequence). Operates on T directly, not on an LDL^T factor (cf. dlarrd which works after a base RRR has been formed). Used by dsyevr in the bisection-fallback path.

Faithful translation of LAPACK 3.12.1 dstebz.f.

fa/lapack_dstein.go

dstein — compute eigenvectors of a symmetric tridiagonal matrix by inverse iteration starting from given eigenvalues. Used by dsyevr's bisection-fallback path (paired with dstebz which produces the eigenvalues themselves).

Faithful translation of LAPACK 3.12.1 dstein.f.

fa/lapack_dstemr.go

dstemr — compute selected eigenvalues and (optionally) eigenvectors of a real symmetric tridiagonal matrix using the MRRR algorithm (multiple-relatively-robust-representations). Driver that calls dlarre + dlarrv. Faithful translation of LAPACK 3.12.1 dstemr.f.

fa/lapack_dsterf.go

dsterf — eigenvalues-only QL/QR with implicit shift on a symmetric tridiagonal matrix. Delegates to gonum's bit-equivalent Dsterf.

fa/lapack_dsyevr.go

dsyevr — public driver for symmetric eigenproblem.

  1. dsytrd: A → tridiagonal T = Q^T A Q
  2. dstemr (MRRR) for eigenvalues + eigenvectors of T (fallback to dstebz/dstein if MRRR fails)
  3. dormtr: apply Q to map eigenvectors back to A's basis
  4. rescale + sort

Faithful translation of LAPACK 3.12.1 dsyevr.f. Currently restricted to UPLO='L' (matches dormtr's only-implemented path).

fa/lapack_eigen_helpers.go

Shared LAPACK helper routines used by the dsyevr / dstemr eigenvalue path. Currently only dlae2 (2×2 symmetric eigenvalues, delegates to gonum) is needed by live code.

This file previously held dsteqr (QL/QR tridiagonal eigensolver), dsyev (top-level QL/QR driver), dlaset (matrix initialization), dlasclG (general matrix scaling). All removed once the MRRR dsyevr path proved sufficient for R-parity. R itself uses dsyevr.

fa/lapack_helpers.go

Foundational LAPACK leaf routines used by the dsyevr port:

dlartg  — generate a plane rotation (Givens) — dlartg.f90
dlanst  — norm of a real symmetric tridiagonal — dlanst.f
dlaev2  — eigenvalues / eigenvectors of a 2x2 symmetric matrix — dlaev2.f
dlasrt  — quicksort sort doubles ascending or descending — dlasrt.f
dlarfg  — generate an elementary Householder reflector — dlarfg.f
dlapy2  — sqrt(x^2 + y^2) avoiding overflow — dlapy2.f
dlassq  — sum-of-squares with overflow scaling — dlassq.f

These are pure-Go faithful translations of the Fortran reference for LAPACK 3.12.1 (the version that ships with R 4.5.x). Conventions:

  • Slice arguments use 1-based indexing semantics shifted to 0-based by `idx-1` adjustments at access sites; the rest of the code reads identically to the Fortran reference for line-by-line review.
  • Matrix arguments are column-major flat []float64 with explicit leading dimension `lda` so BLAS-style strides translate verbatim.
  • Stride / `incx` is honored exactly matching reference BLAS.

fa/lapack_helpers_shim.go

Replaces our hand-ported scalar / 1D LAPACK helpers with thin shims delegating to gonum. Each function listed here was originally a faithful translation of the LAPACK 3.12.1 Fortran reference; gonum's implementations are likewise faithful, so the ALGORITHM is identical to R's reference LAPACK. For these scalar / 1D routines there is no BLAS accumulation order to worry about, so substitution is bit-exact equivalent.

Functions delegated:

dlapy2, dlae2, dlaev2, dlartg, dlassq, dlanst, dlasrt, dsterf, dlarfg

Functions NOT delegated (require column-major layout; gonum is row-major): dlansy, dlaset, dlascl, dlarf, dlasr, dgemv, dger, dsymv, dsyr2, dlatrd, dsytrd, dorgtr, dsteqr.

fa/lapack_householder.go

Householder reflector application (dlarf) and plane-rotation sequence application (dlasr). Used by dsytrd, dorgtr, dormtr, dsteqr in the dsyevr port. Faithful translations of LAPACK 3.12.1 reference Fortran.

fa/lapack_rrr_leaves.go

Small leaf routines underpinning the MRRR eigenvalue path:

dlarra — split a tridiagonal matrix into independent sub-blocks.
dlarrc — Sturm-sequence eigenvalue counting in an interval.
dlaruv — multiplicative congruential RNG returning N<=128 reals
          in (0,1). Auxiliary for dlarnv.
dlarnv — vectorised RNG (uniform/normal) wrapping dlaruv.

Faithful translations of LAPACK 3.12.1 reference Fortran.

fa/lapack_rrr_small.go

Small RRR (relatively robust representations) helpers used by the dsyevr code path.

dlarrr  — Determine if relative-accuracy preserving computations
          are advisable for a tridiagonal matrix.
dlarrk  — Compute one eigenvalue of a symmetric tridiagonal matrix
          by bisection.

Faithful translations of LAPACK 3.12.1 reference Fortran (dlarrr.f / dlarrk.f). Both are leaves — no further LAPACK dependencies.

fa/lapack_tridiag.go

Tridiagonal-reduction layer for the dsyevr port:

dsymv  — symmetric matrix-vector multiply (BLAS-2)
dsyr2  — symmetric rank-2 update         (BLAS-2)
dlatrd — reduce nb panel of A to tridiagonal form (LAPACK aux)
dsytrd — reduce A to symmetric tridiagonal T = Q^T A Q (LAPACK)
dorgtr — generate the orthogonal Q from dsytrd's reflectors
dormtr — apply Q (or Q^T) to a matrix

Faithful translations of LAPACK 3.12.1 reference Fortran. We use the UNBLOCKED path throughout (NB=1) since our matrices are small (n < 50) and blocking only matters for cache-friendly large-n performance. Numerical results of unblocked == blocked for symmetric tridiag reduction (the only difference is BLAS-3 vs BLAS-2 call mix).

All matrices are column-major flat []float64; only the upper triangle is referenced when uplo='U', only the lower when uplo='L'.

fa/lbfgsb.go

Pure-Go port of the L-BFGS-B v3.0 reference implementation by Ciyou Zhu, Richard Byrd, Jorge Nocedal and Jose Luis Morales (3-clause BSD). The goal is bit-near-perfect parity with R's optim(method = "L-BFGS-B"), which wraps the same Fortran. The port is split across several files:

lbfgsb.go         - public entry, lbfgsbState, public driver loop
lbfgsb_blas.go    - BLAS-1 (daxpy/dcopy/ddot/dnrm2/dscal) + dpofa/dtrsl
lbfgsb_lnsrch.go  - dcsrch + dcstep (Moré-Thuente line search)
lbfgsb_setulb.go  - setulb / mainlb driver, errclb, active, projgr,
                    cmprlb, freev, hpsolb, matupd
lbfgsb_cauchy.go  - cauchy (generalized Cauchy point) + bmv
lbfgsb_form.go    - formk, formt
lbfgsb_subsm.go   - subsm (subspace minimization)

All matrices are stored Fortran-style (column-major flattened []float64) so BLAS calls and stride/`incx` arguments translate verbatim.

fa/lbfgsb_blas.go

Faithful port of the BLAS-1 and LINPACK routines used by Byrd-Lu- Nocedal-Zhu L-BFGS-B (lbfgsb.f v3.0, Netlib). The port preserves Fortran's 1-based indexing through explicit `-1` adjustments at the call sites; index arguments inside these primitives stay Fortran-style for line-by-line review against the reference implementation.

All matrix arguments are Fortran column-major: element (i, j) of a matrix `a` declared `a(lda, *)` lives at `a[(j-1)*lda + (i-1)]` from the start of the slice. Stride/`incx` arguments of BLAS routines are honored exactly to match the original behavior.

Source: lbfgsb 3.0 by Ciyou Zhu, Richard Byrd, Jorge Nocedal and Jose Luis Morales (3-clause BSD).

fa/lbfgsb_cauchy.go

Port of subroutine cauchy in lbfgsb.f v3.0. Computes the generalized Cauchy point (the first local minimizer of the quadratic model along the projected steepest-descent path P(x - t·g, l, u)).

fa/lbfgsb_driver.go

Port of subroutines setulb + mainlb from lbfgsb.f v3.0. Because Go has closures we collapse the Fortran reverse-communication driver into a single direct call: when mainlb wanted f / g it would set task = "FG_*" and return; here we evaluate directly via the caller's `eval` function.

fa/lbfgsb_form.go

Ports of subroutines formk and formt from lbfgsb.f v3.0. These build and Cholesky-factorize the middle matrices of the compact L-BFGS form used by the subspace minimization (formk) and the Cauchy point (formt).

fa/lbfgsb_helpers.go

Direct ports of the small bookkeeping subroutines from lbfgsb.f v3.0:

active   — initial active-set classification + projection
projgr   — infinity norm of the projected gradient
errclb   — input error checking
freev    — find free / leaving / entering variables at the GCP
hpsolb   — heap-based pop of the smallest breakpoint
matupd   — update the (s, y) pairs and the SY/SS matrices
cmprlb   — compute the reduced gradient r = -Z'B(xcp - xk) - Z'g
lnsrlb   — driver for the Moré-Thuente line search
bmv      — multiply the 2m × 2m middle matrix in the compact L-BFGS form

All routines preserve Fortran's 1-based semantics through explicit `idx-1` adjustments at access sites; matrix arguments are column-major flattened []float64 with leading dimension `lda`.

fa/lbfgsb_lnsrch.go

Moré-Thuente line search (Minpack-2 dcsrch / dcstep) used by L-BFGS-B. Faithful line-by-line port of the Fortran reference.

Convention: the algorithm is reverse-communication. The caller invokes dcsrch repeatedly; each call sets `task` to one of:

  • "FG": evaluate f and g at the current stp and call again
  • "CONV": converged (Armijo + curvature both satisfied)
  • "WARN": convergence not achievable (returns best step found)
  • "ERROR: <msg>": invalid input

fa/lbfgsb_subsm.go

Port of subroutine subsm from lbfgsb.f v3.0 (with the Morales–Nocedal 2010 backtracking-projection refinement).

Computes an approximate solution to the subspace problem

min  Q(x) = r'(x − xcp) + 1/2 (x − xcp)' B (x − xcp)
s.t. l ≤ x ≤ u, x_i = xcp_i for i ∈ A(xcp)

using the compact L-BFGS direction d = (1/θ)·r + (1/θ²)·Z'·W·K^{-1}·W'·Z·r, then safeguarding by projection / backtracking.

fa/psych_Promax.go

fa/psych_faRotations.go

fa/psych_fac.go

fa/psych_pinv.go

fa/psych_smc.go

fa/psych_target_rot.go

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BentlerQ

func BentlerQ(loadings *mat.Dense, normalize bool, eps float64, maxIter int) map[string]any

BentlerQ performs Bentler's criterion rotation (oblique). Mirrors GPArotation::bentlerQ

func BentlerT

func BentlerT(loadings *mat.Dense, normalize bool, eps float64, maxIter int) map[string]any

BentlerT performs Bentler's criterion rotation. Mirrors GPArotation::bentlerT

func FaRotations

func FaRotations(loadings *mat.Dense, r *mat.Dense, rotate string, hyper float64, nRotations int, promaxPower int, geominDelta float64, eps float64, maxIter int) any

FaRotations performs rotation selection with optional random restarts. FaRotations applies a factor rotation. promaxPower (R: m, default 4) is honored for the "promax" rotation; geominDelta (R: delta, default 0.01) is honored for "geomint" / "geominq". Pass <= 0 to use defaults.

func Factor2Cluster

func Factor2Cluster(loadings *mat.Dense) *mat.Dense

Factor2Cluster creates a cluster structure from factor loadings. Mirrors GPArotation::factor2cluster: assigns each variable to the factor with the highest |loading| if that exceeds cut (R default 0.3), else no cluster.

Preserves the sign of the dominant loading (R uses sign(L[i, j*])): a variable that loads -0.85 on factor j is assigned -1, not +1, in the cluster matrix. The previous implementation always wrote +1.

func GPFoblq

func GPFoblq(A *mat.Dense, Tmat *mat.Dense, normalize bool, eps float64, maxit int, method string, gamma float64) (map[string]any, error)

GPFoblq performs oblique GPA rotation. Transliteration of GPArotation::GPFoblq from R.

func GPForth

func GPForth(A *mat.Dense, Tmat *mat.Dense, normalize bool, eps float64, maxit int, method string, criterionParam float64) (map[string]any, error)

GPForth performs orthogonal rotation using GPA. Mirrors GPArotation::GPForth exactly GPForth performs orthogonal Gradient Projection rotation. criterionParam is a method-specific scalar (currently only used by geomin as ε; ignored by varimax/quartimax/bentler). Pass <= 0 to use the per-method default.

func GeominQ

func GeominQ(loadings *mat.Dense, normalize bool, eps float64, maxIter int, delta float64) map[string]any

GeominQ performs geomin rotation (oblique). Mirrors GPArotation::geominQ

func GeominT

func GeominT(loadings *mat.Dense, normalize bool, eps float64, maxIter int, delta float64) map[string]any

GeominT performs geomin rotation. Mirrors GPArotation::geominT

func KaiserVarimaxWithRotationMatrix

func KaiserVarimaxWithRotationMatrix(A *mat.Dense, normalize bool, maxIter int, epsilon float64) (*mat.Dense, *mat.Dense, error)

KaiserVarimaxWithRotationMatrix returns stats::varimax-style rotated loadings and the orthogonal rotation matrix.

func NormalizingWeight

func NormalizingWeight(A *mat.Dense, normalize bool) *mat.VecDense

NormalizingWeight computes normalizing weights for GPA rotation. Mirrors GPArotation::NormalizingWeight for Kaiser normalization.

func Oblimin

func Oblimin(loadings *mat.Dense, normalize bool, eps float64, maxIter int, gamma float64) map[string]any

Oblimin performs oblimin rotation. Mirrors GPArotation::oblimin

func Pinv

func Pinv(X *mat.Dense, tol float64) (*mat.Dense, error)

Pinv computes the Moore-Penrose pseudo-inverse of a matrix. Mirrors psych::Pinv exactly

func Promax

func Promax(x *mat.Dense, m int, normalize bool) map[string]any

Promax performs Promax rotation. Mirrors psych::Promax exactly

func Quartimax

func Quartimax(loadings *mat.Dense, normalize bool, eps float64, maxIter int) map[string]any

Quartimax performs quartimax rotation. Mirrors GPArotation::quartimax

func Quartimin

func Quartimin(loadings *mat.Dense, normalize bool, eps float64, maxIter int) map[string]any

Quartimin performs quartimin rotation. Mirrors GPArotation::quartimin

func Rotate

func Rotate(loadings *mat.Dense, method string, opts *RotOpts) (*mat.Dense, *mat.Dense, *mat.Dense, bool, error)

Rotate performs factor rotation on loadings. This is a wrapper around FaRotations for compatibility.

func Simplimax

func Simplimax(loadings *mat.Dense, normalize bool, eps float64, maxIter int, k int) map[string]any

Simplimax performs simplimax rotation. Mirrors GPArotation::simplimax

func Smc

func Smc(r *mat.Dense, opts *SmcOptions) (*mat.VecDense, map[string]interface{})

Smc computes the squared multiple correlations (SMC) for a correlation matrix. Mirrors psych::smc with complete NA handling and covar/pairwise options

func SymmetricEigenDescendingDsyevr added in v0.2.17

func SymmetricEigenDescendingDsyevr(a mat.Matrix) ([]float64, *mat.Dense, bool)

SymmetricEigenDescendingDsyevr is the exported wrapper. R-bit-perfect alternative to statslinalg.SymmetricEigenDescending. Use this for downstream stages (e.g. inverse-symmetric-sqrt in Anderson-Rubin scoring) that must agree with R's eigen() at ULP level.

func TargetRot

func TargetRot(x *mat.Dense) (loadings, rotmat, Phi *mat.Dense, err error)

TargetRot performs target rotation on an unrotated loading matrix x against an automatically derived cluster target. Mirrors psych::target.rot.

func Varimax

func Varimax(loadings *mat.Dense, normalize bool, eps float64, maxIter int) map[string]any

Varimax performs varimax rotation. Mirrors GPArotation::Varimax

Types

type FacOptions

type FacOptions struct {
	NFactors      int
	NObs          float64
	Rotate        string
	Scores        string
	Residuals     bool
	SMC           interface{} // bool or []float64
	Covar         bool
	Missing       bool
	Impute        string
	MinErr        float64
	MaxIter       int
	Symmetric     bool
	Warnings      bool
	Fm            string
	Alpha         float64
	ObliqueScores bool
	NpObs         *mat.Dense
	Use           string
	Cor           string
	Correct       float64
	Weight        []float64
	NRotations    int
	Hyper         float64
	Smooth        bool

	// L-BFGS-B parameters used by ML / MINRES extraction. Defaults match
	// R's stats::optim: OptimFactr=1e7, OptimMaxIter=100. Caller can tighten
	// OptimFactr (down to 1) for machine-precision convergence on flat
	// objective surfaces (e.g. Heywood-prone problems where the default
	// terminates prematurely).
	OptimFactr   float64
	OptimMaxIter int
}

FacOptions represents options for the Fac function

type FacResult

type FacResult struct {
	Values        []float64
	Rotation      string
	NObs          float64
	NpObs         *mat.Dense
	Communality   []float64
	Loadings      *mat.Dense
	Fit           float64
	Residual      *mat.Dense
	R             *mat.Dense
	Communalities []float64
	Uniquenesses  []float64
	EValues       []float64
	Model         *mat.Dense
	Fm            string
	RotMat        *mat.Dense
	Phi           *mat.Dense
	Structure     *mat.Dense
	Method        string
	Scores        *mat.Dense
	R2Scores      []float64
	Weights       *mat.Dense
	Factors       int
	Hyperplane    []float64
	Vaccounted    *mat.Dense
	ECV           []float64
	Converged     bool // True if iterative extraction converged (always true for PCA / PAF that iterates within minErr)
	Iterations    int  // Number of iterations used by ML / MINRES L-BFGS-B
}

FacResult represents the result of factor analysis

func Fac

func Fac(r *mat.Dense, opts *FacOptions) (*FacResult, error)

Fac performs factor analysis using various methods (mirrors psych::fac)

type RotOpts

type RotOpts struct {
	Eps           float64
	MaxIter       int
	Alpha0        float64
	Gamma         float64 // Oblimin gamma
	GeominEpsilon float64 // Geomin delta (R psych default 0.01)
	PromaxPower   int
	Restarts      int
}

RotOpts represents rotation options

type SmcOptions

type SmcOptions struct {
	Covar    bool    // If true, use covariance matrix instead of correlation
	Pairwise bool    // If true, use pairwise correlations for NA handling
	Tol      float64 // Tolerance for matrix inversion
}

SmcOptions represents options for Smc function

Jump to

Keyboard shortcuts

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