Skip to content

Solve dense systems and least squares

Use this guide when a coefficient matrix or design fits in dense memory. It starts with allocating one-shot calls, then introduces retained factors, pivoting, row scaling, and workspaces only when repeated work creates a reason for them.

import gale.linalg.*

solve factors the matrix once and accepts a vector or a matrix of right-hand sides:

val system = Matrix(2, 2)(
3.0, 1.0,
1.0, 2.0
)
val rhs = Vec(9.0, 8.0)
system.solve(rhs).map(_.toSeq)
// res0: Either[LinAlgError, Seq[Double]] = Right(Vector(2.0, 3.0))
val rhsColumns = Matrix(2, 2)(
9.0, 4.0,
8.0, 5.0
)
system.solve(rhsColumns).map(_.valuesRowMajor)
// res1: Either[LinAlgError, Seq[Double]] = Right(Vector(2.0, 0.6, 3.0, 2.2))

Retain system.lu.orThrow when separate calls reuse the same general square matrix. Retain system.cholesky.orThrow when the matrix is symmetric positive definite and that premise is part of the application.

The design below has an intercept and slope. QRPivoting.Column recomputes candidate norms exactly, reports the selected permutation, and applies the same deterministic rank policy on the JVM and Scala.js.

val design = Matrix(5, 2)(
1.0, 0.0,
1.0, 1.0,
1.0, 2.0,
1.0, 3.0,
1.0, 4.0
)
val observations = Vec(1.0, 3.0, 5.0, 7.0, 9.0)
val options = QROptions(pivoting = QRPivoting.Column)
// options: QROptions = QROptions(pivoting = Column, rankTolerance = None)
val qr = design.qr(options)
// qr: QR = QR(
// reflectors = gale.linalg.DMat@9e71dcb,
// tau = Array(1.0, 1.374976423257013),
// r = gale.linalg.DMat@2faab1a8,
// diagnostics = FactorizationDiagnostics(
// info = 0,
// rank = Some(2),
// rankTolerance = Some(1.2161883888976236E-14)
// ),
// columnPermutation = gale.linalg.ColumnPermutation@565534c0,
// options = QROptions(pivoting = Column, rankTolerance = None)
// )
(
qr.solveLeastSquares(observations).orThrow.toSeq,
qr.diagnostics.rank,
qr.columnPermutation.toIndexSeq
)
// res2: Tuple3[Seq[Double], Option[Int], IndexedSeq[Int]] = (
// Vector(0.9999999999999991, 2.0),
// Some(2),
// ArraySeq(1, 0)
// )

With pivoting, qr.q * qr.r reconstructs the input columns in qr.columnPermutation order. Returned coefficients are unpermuted back to the original design order. A rank-deficient or underdetermined least-squares solve returns a typed Left; the factorization itself remains available for rank and orthogonal-transform operations.

For those systems, use SVD-backed minimumNormLeastSquares with an explicit singular-value cutoff. See minimum-norm solves and subspaces for reusable factors, numerical-rank semantics and projection operations.

solveLeastSquaresWith transforms the right-hand side in caller-owned scratch and returns an independently owned coefficient vector or matrix:

val solveWorkspace = DenseWorkspace.forQRSolve(
observations = design.rows,
rightHandSides = 2
)
val responseMatrix = Matrix.tabulate(design.rows, 2): (row, col) =>
observations(row) + col.toDouble
val firstFit = qr
.solveLeastSquaresWith(responseMatrix, solveWorkspace)
.orThrow
val secondFit = qr
.solveLeastSquaresWith(responseMatrix, solveWorkspace)
.orThrow
(firstFit.valuesRowMajor, secondFit.valuesRowMajor)
// res3: Tuple2[Seq[Double], Seq[Double]] = (
// Vector(0.9999999999999991, 1.9999999999999996, 2.0, 2.0),
// Vector(0.9999999999999991, 1.9999999999999996, 2.0, 2.0)
// )

Reusing solveWorkspace cannot mutate firstFit. The workspace grows when a later request needs more primitive cells and never shrinks. It is sequential mutable state, so concurrent workers need separate instances.

Apply row scales without a temporary matrix

Section titled “Apply row scales without a temporary matrix”

An outer algorithm may need the algebraic system diag(scales) * design and the matching response diag(scales) * observations. Gale can construct and solve that QR without materializing either scaled input:

val rowScales = Vec(1.0, 1.0, 0.5, 0.5, 0.25)
val pipelineWorkspace = DenseWorkspace.empty
val scaledQr = design
.qrScaledRows(rowScales, options, pipelineWorkspace)
.orThrow
// scaledQr: QR = QR(
// reflectors = gale.linalg.DMat@41bd25ea,
// tau = Array(1.0, 1.0745933511476684),
// r = gale.linalg.DMat@21196aec,
// diagnostics = FactorizationDiagnostics(
// info = 0,
// rank = Some(2),
// rankTolerance = Some(5.087681048627601E-15)
// ),
// columnPermutation = gale.linalg.ColumnPermutation@634444d3,
// options = QROptions(pivoting = Column, rankTolerance = None)
// )
val scaledFit = scaledQr
.solveLeastSquaresScaledRowsWith(
observations,
rowScales,
pipelineWorkspace
)
.orThrow
scaledFit.toSeq
// res4: Seq[Double] = Vector(1.0000000000000002, 2.0)

These are row multipliers, not statistical weights. Zero and negative finite scales are algebraically valid; non-finite or wrongly sized scales are rejected. If an application starts from non-negative weights, it owns the decision to pass their square roots.

When a design is filled once and immediately factored, a builder can transfer its row-major storage directly into QR’s working factor:

val transientDesign = design.toBuilder
val consumedQr = transientDesign.consumeQR(options, DenseWorkspace.empty)
// consumedQr: QR = QR(
// reflectors = gale.linalg.DMat@437d1a34,
// tau = Array(1.0, 1.374976423257013),
// r = gale.linalg.DMat@6e8d283e,
// diagnostics = FactorizationDiagnostics(
// info = 0,
// rank = Some(2),
// rankTolerance = Some(1.2161883888976236E-14)
// ),
// columnPermutation = gale.linalg.ColumnPermutation@444f2c3e,
// options = QROptions(pivoting = Column, rankTolerance = None)
// )
consumedQr.diagnostics.rank
// res5: Option[Int] = Some(2)

consumeQR permanently closes the builder. It does not leave a mutable alias to the factor. Use builder.result() instead when the immutable matrix itself must remain available.

DctBasis.columns constructs explicit columns of a DCT-II basis. Rows index samples; component zero is constant. Select a contiguous range to avoid allocating unused components:

val cosineColumns = DctBasis.columns(samples = 8, first = 1, count = 3).orThrow
(cosineColumns.rows, cosineColumns.cols)
// res6: Tuple2[Int, Int] = (8, 3)

The default DctNormalization.Orthonormal makes the columns orthonormal on the complete sample grid. Unscaled returns the cosine values without scaling. The factory uses O(samples × count) time and storage. An empty range returns a matrix with the requested row count and zero columns. Invalid component ranges, nonpositive sample counts, and shapes exceeding Int.MaxValue elements return LinAlgError.InvalidArgument before allocation.

This is an explicit basis matrix, not a fast transform. The caller supplies the component range and owns sampling units, cutoff selection, and any statistical interpretation. After selecting a subset of rows, refactor the retained design; the original full-grid orthonormality does not generally survive row removal.

Need Route Execution and ownership
one general solve a.solve(rhs) allocating owned result; typed failure
several square solves retain a.lu.orThrow or a.cholesky.orThrow factor once, owned results
one least-squares fit design.leastSquares(y, options) portable explicit QR policy
several fits retain design.qr(options) reuse factor; owned results
reduce transformed-RHS allocation qr.solveLeastSquaresWith(rhs, workspace) borrowed scratch, owned result
avoid scaled design/RHS temporaries qrScaledRows plus scaled solve same row scales on both algebraic inputs
factor a transient fill buffer builder.consumeQR storage transfer; builder closes

Read Reusable workspaces for requirement composition and Factorization capabilities when a generic algorithm consumes retained factors.