Skip to content

Moving a Breeze linear algebra workload to Gale

Gale can replace the linear algebra part of a Breeze program when the program works mainly with real Double vectors and matrices. Gale provides dense arithmetic and factorizations, compressed sparse matrices, iterative solvers, and selected eigenvalue and singular-value routines. The shared API runs on the JVM and Scala.js.

Gale is not source-compatible with Breeze, and it does not replace Breeze’s probability, statistics, signal-processing, plotting, machine learning, or tensor modules. gale.optim has its own optimizers, including L-BFGS, L-BFGS-B, accelerated proximal gradient, Levenberg–Marquardt, CMA-ES, an augmented Lagrangian, and a box quasi-Newton method. Only LBFGS and LBFGSB are checked against breeze.optimize; see Replace Breeze L-BFGS and L-BFGS-B. Use this guide to check the supported linear algebra operations and to see how migrated code changes.

Gale uses zero-based indices. Slice endpoints are half-open: the starting index is included and the ending index is not.

Task Breeze Gale
Construct a vector DenseVector(1.0, 2.0, 3.0) Vec(1.0, 2.0, 3.0)
Construct a matrix DenseMatrix((1.0, 2.0), (3.0, 4.0)) Matrix(2, 2)(1.0, 2.0, 3.0, 4.0)
Read the shape a.rows, a.cols, x.length the same
Read an element a(i, j), x(i) the same
Select a row a(i, ::).t a.row(i)
Select a column a(::, j) a.col(j)
Select a contiguous submatrix a(r0 until r1, c0 until c1) a.slice(r0, r1, c0, c1)
Select rows by index Breeze indexing with :: a.gatherRows(indices)
Replace one value mutate a copy with copy(i, j) = value a.updated(i, j, value)

Matrix(rows, cols)(values*) reads the values in row-major order. Matrix.dense(rows, cols)(values*) is the more explicit spelling of the same operation.

import gale.linalg.*
val a = Matrix(3, 3)(
1.0, 2.0, 3.0,
4.0, 5.0, 6.0,
7.0, 8.0, 9.0
)
(a.rows, a.cols)
// res0: Tuple2[Int, Int] = (3, 3)
a(1, 2)
// res1: Double = 6.0
a.row(1).toSeq
// res2: Seq[Double] = Vector(4.0, 5.0, 6.0)
a.col(0).toSeq
// res3: Seq[Double] = Vector(1.0, 4.0, 7.0)
a.slice(0, 2, 1, 3).valuesRowMajor
// res4: Seq[Double] = Vector(2.0, 3.0, 5.0, 6.0)

row, col, slice, and t return views. A view does not copy the selected values. gatherRows and gatherColumns return new matrices because an indexed selection may reorder or repeat entries.

a.gatherRows(IndexedSeq(2, 0)).valuesRowMajor
// res5: Seq[Double] = Vector(7.0, 8.0, 9.0, 1.0, 2.0, 3.0)
a.gatherColumns(IndexedSeq(2, 2, 0)).valuesRowMajor
// res6: Seq[Double] = Vector(3.0, 3.0, 1.0, 6.0, 6.0, 4.0, 9.0, 9.0, 7.0)
val changed = a.updated(0, 0, 10.0)
(a(0, 0), changed(0, 0))
// res7: Tuple2[Double, Double] = (1.0, 10.0)

Vectors follow the same rule. x.slice(from, until) returns a view, x.gather(indices) returns a copy, and x.updated(i, value) returns a new vector. Use a builder when filling many entries.

Use tabulate when each value can be computed from its row and column. Gale also provides direct constructors for zero matrices, identity matrices, and common sparse structures.

val zeroVector = Vec.zeros(4)
val identity3 = Matrix.eye(3)
val tridiagonal4 = Matrix.tabulate(4, 4): (row, col) =>
if row == col then 2.0
else if math.abs(row - col) == 1 then -1.0
else 0.0
zeroVector.toSeq
// res8: Seq[Double] = Vector(0.0, 0.0, 0.0, 0.0)
(identity3 * Vec(1.0, 2.0, 3.0)).toSeq
// res9: Seq[Double] = Vector(1.0, 2.0, 3.0)
(tridiagonal4 * Vec.fill(4)(1.0)).toSeq
// res10: Seq[Double] = Vector(1.0, 0.0, 0.0, 1.0)

Matrix.tabulate constructs a dense matrix. If most of the generated values would be zero, build a sparse matrix or define an operator instead; both choices are shown below.

Ordinary * performs an algebraic matrix product. Import gale.syntax.all.* for pointwise matrix operations.

import gale.syntax.all.*
val x = Vec(1.0, 0.5, -1.0)
val ax = a * x
val gram = a.t * a
val scaled = a * 2.0
val squared = a.pointwise * a
val regularized = gram.addToDiagonal(1e-6)
ax.toSeq
// res11: Seq[Double] = Vector(-1.0, 0.5, 2.0)
gram.valuesRowMajor
// res12: Seq[Double] = Vector(
// 66.0,
// 78.0,
// 90.0,
// 78.0,
// 93.0,
// 108.0,
// 90.0,
// 108.0,
// 126.0
// )
scaled.valuesRowMajor
// res13: Seq[Double] = Vector(
// 2.0,
// 4.0,
// 6.0,
// 8.0,
// 10.0,
// 12.0,
// 14.0,
// 16.0,
// 18.0
// )
squared.valuesRowMajor
// res14: Seq[Double] = Vector(
// 1.0,
// 4.0,
// 9.0,
// 16.0,
// 25.0,
// 36.0,
// 49.0,
// 64.0,
// 81.0
// )
regularized(0, 0)
// res15: Double = 66.000001

The main dense operations are:

Task Gale call
Vector addition, subtraction, scaling x + y, x - y, x * scalar
Dot product and Euclidean norm x.dot(y), x.norm2
Matrix addition, subtraction, and scaling a + b, a - b, a * scalar, scalar * a
Matrix-vector and matrix-matrix products a * x, a * b
Transpose a.t
Elementwise multiply, divide, or map a.pointwise * b, a.pointwise / b, a.pointwise.map(f)
Add a scalar to the diagonal a.addToDiagonal(value)
Average a matrix with its transpose a.symmetrizedAverage
Kronecker product a.kron(b)
Sums, means, extrema x.sum, x.mean, x.max, x.argmax, a.sum(Axis.Cols)
Vector and matrix norms x.norm1, x.normInf, a.norm1, a.normInf, a.normFrobenius
Named elementwise functions Numerics.exp(a), Numerics.log(x), Numerics.sigmoid(x)
Log-sum-exp (Breeze softmax(v)) Numerics.logSumExp(x)

Call solve for a square system. A vector right-hand side returns one solution; a matrix right-hand side returns one solution in each column. Gale factors the coefficient matrix once for the call.

val system2 = Matrix(2, 2)(
3.0, 1.0,
1.0, 2.0
)
val rhs2 = Vec(9.0, 8.0)
val rhsMatrix2 = Matrix(2, 2)(
9.0, 4.0,
8.0, 5.0
)
system2.solve(rhs2).map(_.toSeq)
// res16: Either[LinAlgError, Seq[Double]] = Right(Vector(2.0, 3.0))
system2.solve(rhsMatrix2).map(_.valuesRowMajor)
// res17: Either[LinAlgError, Seq[Double]] = Right(Vector(2.0, 0.6, 3.0, 2.2))

Use leastSquares for a tall system. The following design has an intercept column and a slope column. The observations follow 1 + 2x, so the fitted coefficients should be close to (1, 2).

val design4x2 = Matrix(4, 2)(
1.0, 0.0,
1.0, 1.0,
1.0, 2.0,
1.0, 3.0
)
val observations4 = Vec(1.0, 3.0, 5.0, 7.0)
design4x2.leastSquares(observations4).map(_.toSeq)
// res18: Either[LinAlgError, Seq[Double]] = Right(Vector(1.0, 2.0))

Both methods return Either[LinAlgError, A]. A singular square matrix, a rank-deficient design, or a right-hand side with the wrong shape returns Left(error).

Use a.lu, a.cholesky, or a.qr when you need the factor itself or when separate calls reuse the same coefficient matrix. LU and Cholesky can fail, so they return Either. QR factorization is defined for every dense matrix and returns a QR directly.

val qr4x2 = design4x2.qr
// qr4x2: QR = QR(
// reflectors = gale.linalg.DMat@710d9e8b,
// tau = Array(1.5, 1.0),
// r = gale.linalg.DMat@233082f9,
// diagnostics = FactorizationDiagnostics(
// info = 0,
// rank = Some(2),
// rankTolerance = Some(3.972054645195637E-15)
// ),
// columnPermutation = gale.linalg.ColumnPermutation@24bb8fb6,
// options = QROptions(pivoting = Disabled, rankTolerance = None)
// )
(qr4x2.r.rows, qr4x2.r.cols, qr4x2.diagnostics.rank)
// res19: Tuple3[Int, Int, Option[Int]] = (4, 2, Some(2))
system2.cholesky.map(_.lower.valuesRowMajor)
// res20: Either[LinAlgError, Seq[Double]] = Right(
// Vector(1.7320508075688772, 0.0, 0.5773502691896258, 1.2909944487358056)
// )

See Factorization capabilities for the common interfaces implemented by LU, Cholesky, and QR factors.

Use Eigen.eigSymmetric when a real square matrix is symmetric. The result stores eigenvalues in ascending algebraic order. Ask for EigenVectors.ValuesOnly when eigenvectors are not needed.

import gale.spectral.*
val symmetric3 = Matrix(3, 3)(
2.0, -1.0, 0.0,
-1.0, 2.0, -1.0,
0.0, -1.0, 2.0
)
val symmetricSpectrum = Eigen.eigSymmetric(
symmetric3,
EigenSelection.All,
EigenVectors.ValuesOnly
)
// symmetricSpectrum: Either[LinAlgError, EigenDecomposition] = Right(
// EigenDecomposition(
// eigenvalues = gale.linalg.DVec@53c67b13,
// eigenvectors = gale.linalg.DMat@20a02f50,
// diagnostics = SpectralDiagnostics(3,3,gale.linalg.DVec@4a67230f,0.0,0,None,true,None)
// )
// )
symmetricSpectrum.map(_.eigenvalues.toSeq)
// res21: Either[LinAlgError, Seq[Double]] = Right(
// Vector(0.5857864376269051, 2.0, 3.414213562373095)
// )

a.svd computes a full economy-size singular value decomposition. If a is m × n, Gale returns U with shape m × k and Vᵀ with shape k × n, where k = min(m, n).

symmetric3.svd.map: result =>
(
result.singularValues.toSeq,
(result.u.rows, result.u.cols),
(result.vt.rows, result.vt.cols)
)
// res22: Either[LinAlgError, Tuple3[Seq[Double], Tuple2[Int, Int], Tuple2[Int, Int]]] = Right(
// (
// Vector(3.4142135623730945, 1.9999999999999991, 0.5857864376269044),
// (3, 3),
// (3, 3)
// )
// )

Use Svds.svd when only the largest or smallest singular values are needed. Use the operator overloads of Eigen and Svds when the matrix is too large to store. Iterative spectral results include residuals and convergence counts; call requireConverged when the program requires every requested result.

Gale also supports:

  • dense nonsymmetric eigendecomposition through Eigen.eigNonsymmetric;
  • dense generalized symmetric-definite problems through Eigen.eigSymmetricGeneralized;
  • matrix-free generalized symmetric-definite problems through LOBPCG or generalized block Lanczos; and
  • pseudo-inverses through a.pinv.

Read Matrix-free generalized symmetric eigensolving before choosing between LOBPCG and generalized block Lanczos.

Build a coordinate matrix by adding its stored entries, then convert it to CSR or CSC. CSR is the usual choice for repeated row-oriented matrix-vector products. CSC gives efficient access by column.

import gale.sparse.*
val sparseA = Sparse
.coo(3, 3)
.add(0, 0, 2.0)
.add(0, 1, -1.0)
.add(1, 0, -1.0)
.add(1, 1, 2.0)
.add(1, 2, -1.0)
.add(2, 1, -1.0)
.add(2, 2, 2.0)
.toCSR()
(sparseA.nnz, (sparseA * Vec(1.0, 2.0, 3.0)).toSeq)
// res23: Tuple2[Int, Seq[Double]] = (7, Vector(0.0, 0.0, 4.0))

The builder sorts coordinates, handles duplicates according to a DuplicatePolicy, and keeps explicit zeros (including duplicates that sum to zero) in the compressed matrix; call pruneZeros to drop them. Use Sparse.cooChecked when malformed input or non-finite values should be returned as LinAlgError rather than thrown.

Sparse.diagonal, Sparse.identity, Sparse.zero, and Sparse.permutation construct common structures without passing through a coordinate builder. CSR and CSC support element access, rows, columns, transpose, addition, subtraction, scalar multiplication, and conversion to dense storage.

Gale’s default sparse-direct provider is none. Use an iterative solver, or import gale.sparse.direct.pure.given for portable sparse Cholesky on a canonical square CSR. That import is not SuiteSparse and does not provide sparse LU or QR. Those, plus C Wasm, each need their own spec in a future version; see Scala.js sparse-direct.

Breeze spells reductions as functions (sum(v), argmax(v)) and per-axis reductions with broadcasting (sum(a(::, *))). Gale spells them as methods and names the result axis with Axis. Axis.Rows gives one value per row, and Axis.Cols one value per column.

Breeze Gale Note
sum(v), sum(a) v.sum, a.sum sumExact is correctly rounded and the same on every platform.
breeze.stats.mean(v) v.mean sum / n, recomputed as Σ(x_i / n) if the sum overflows.
max(v), min(v) v.max, v.min
argmax(v), argmin(v) v.argmax, v.argmin A matrix returns (row, col).
sum(a(::, *)).t a.sum(Axis.Cols) Breeze returns a transposed row vector; Gale returns a DVec.
sum(a(*, ::)) a.sum(Axis.Rows) The same holds for mean, max, and min.
norm(v, 1), norm(v), norm(v, Double.PositiveInfinity) v.norm1, v.norm2, v.normInf
norm(a.toDenseVector) a.normFrobenius
max column / row absolute sum a.norm1, a.normInf The induced matrix norms; Breeze has no direct call.
breeze.numerics.exp(v), log, log1p, expm1 Numerics.exp(v), log, log1p, expm1 Same java.lang.Math results on the JVM.
breeze.numerics.sigmoid(v) Numerics.sigmoid(v) Breeze’s 1/(1+exp(-x)) for x >= -36, t/(1+t) with t = exp(x) below; agrees within 4 ulps above about -709.78.
softmax(v) Numerics.logSumExp(v) Naming trap: Breeze’s softmax is the scalar log-sum-exp.
exp(v - softmax(v)) Numerics.softmax(v) Gale’s softmax is the normalized probability vector.
v - softmax(v) Numerics.logSoftmax(v)
softmax(a(*, ::)) Numerics.logSumExp(a, Axis.Rows) softmax(a, Axis.Rows) normalizes each row.
val logits = Vec(1000.0, 1000.0, -1000.0)
Numerics.logSumExp(logits)
// res24: Double = 1000.6931471805599
Numerics.softmax(logits).toSeq
// res25: Seq[Double] = Vector(0.5, 0.5, 0.0)
val scores = Matrix(2, 3)(
1.0, 5.0, 2.0,
4.0, 0.0, 4.0
)
scores.sum(Axis.Cols).toSeq
// res26: Seq[Double] = Vector(5.0, 5.0, 6.0)
scores.max(Axis.Rows).toSeq
// res27: Seq[Double] = Vector(5.0, 4.0)
scores.argmax
// res28: Tuple2[Int, Int] = (0, 1)
(scores.norm1, scores.normInf, scores.normFrobenius)
// res29: Tuple3[Double, Double, Double] = (6.0, 8.0, 7.874007874011811)

gale.sparse.SparseVector covers the everyday use of Breeze’s SparseVector. Build it from unsorted (index, value) pairs. Repeated indices are summed by default, as in Breeze’s VectorBuilder, and explicit zeros stay stored until compact.

Breeze Gale
VectorBuilder + toSparseVector, SparseVector(n)(pairs*) SparseVector.fromEntries(n, pairs) (or tryFromEntries)
SparseVector.zeros[Double](n) SparseVector.zeros(n)
v.activeSize, v(i) v.activeSize, v(i)
v.activeKeysIterator, v.activeValuesIterator v.activeIndices, v.activeValues, v.foreachActive
v.compact() (in place) v.compact (returns a new vector)
v.toDenseVector v.toDense
x dot y, x dot dense x.dot(y), x.dot(dense)
x + y, x - y, x * alpha the same
sum(v), max(v), min(v), norm(v, p) v.sum, v.max, v.min, v.norm1, v.norm2, v.normInf
csc * sparseVector csr * sparseVector (dense result)
a stored column of a CSCMatrix csc.colSparse(j), csr.rowSparse(i)
val sv = SparseVector.fromEntries(5, Seq(3 -> 2.0, 1 -> 1.0, 3 -> 0.5, 4 -> 0.0))
// sv: SparseVector = SparseVector(5)(1 -> 1.0, 3 -> 2.5, 4 -> 0.0)
(sv.activeSize, sv.activeIndices, sv.compact.activeSize)
// res30: Tuple3[Int, IndexedSeq[Int], Int] = (3, ArraySeq(1, 3, 4), 2)
(sv.max, sv.min, sv.dot(Vec(1.0, 1.0, 1.0, 1.0, 1.0)))
// res31: Tuple3[Double, Double, Double] = (2.5, 0.0, 3.5)
val x3 = SparseVector.fromEntries(3, Seq(0 -> 1.0, 2 -> 1.0))
// x3: SparseVector = SparseVector(3)(0 -> 1.0, 2 -> 1.0)
(sparseA * x3).toSeq
// res32: Seq[Double] = Vector(2.0, -2.0, 2.0)

Both libraries agree on several sparse rules that a port could easily get wrong. Cancellations from + and - stay stored, and so do entries scaled by 0.0. max and min include the implicit zero. A product skips a NaN or infinity that faces an implicit zero, so x.dot(y) can differ from x.toDense.dot(y.toDense).

Most of these are deliberate Gale choices. One is a Breeze bug (marked below). sbt parityTest pins each one: it checks Gale’s documented result and Breeze’s observed result (ReductionsNumericsParitySuite and SparseVectorParitySuite). The numerical contract states the Gale rules.

Case Gale Breeze 2.1
argmax/argmin with a NaN index of the first NaN skips the NaN unless it comes first
argmin ties first minimum last minimum
Matrix argmax/argmin ties and NaN row-major order, first NaN column-major order (argmin takes the last tie), NaN skipped
max/min of 0.0 and -0.0 the first one max is 0.0, min is -0.0
Empty max, mean, per-axis max throw LinAlgError.EmptyInput -Inf, 0.0, -Inf per line
Empty min, argmax throw LinAlgError.EmptyInput throw IllegalArgumentException
norm2, Frobenius with entries near 1e300 or 1e-300 scaled; finite and nonzero overflows to +Inf, underflows to 0.0
Log-sum-exp with a +Inf entry +Inf softmax returns -Inf (Breeze bug: its max.isInfinite guard for all -Inf also catches +Inf)
sigmoid(x) for -745 < x < -709.78 subnormal ≈ exp(x) exactly 0.0
Sparse max/min of a length-0 vector throw LinAlgError.EmptyInput max is -Inf; min throws
Sparse duplicate indices DuplicatePolicy.Sum (default), Last, or Error always summed
Sparse compact returns a new vector mutates in place
Sparse matrix × sparse vector CSR * SparseVector returns a dense DVec CSCMatrix * SparseVector returns a SparseVector
Explicit zeros added to a sparse matrix builder kept by toCSR() / toCSC() dropped by CSCMatrix.Builder
Out-of-range sparse apply LinAlgError.IndexOutOfBounds IndexOutOfBoundsException

Summation results agree within the forward error bound of two differently associated sums, 2·n·ε·Σ|x|. They are not bit-identical, because both libraries may reassociate. When a result must not depend on the summation order, use sumExact.

Dense matrices, sparse matrices, and custom operators all implement DoubleLinearOperator. The iterative solvers accept that interface rather than requiring a particular storage format.

Use conjugate gradient (cg) for a symmetric positive-definite operator. bicgstab and gmres handle general nonsymmetric square systems. lsqr solves least-squares problems without forming AᵀA; cgnr solves the normal equations and is best reserved for well-conditioned problems.

import gale.solvers.*
val knownSolution = Vec(1.0, 2.0, 3.0)
val iterative = cg(
sparseA,
sparseA * knownSolution,
SolverConfig(tolerance = 1e-12, maxIterations = 20)
)
// iterative: SolverResult = Converged(
// x = gale.linalg.DVec@2f8de53,
// iterations = 3,
// residual = 1.0007415106216802E-16
// )
(iterative.converged, iterative.iterations, iterative.x.toSeq)
// res33: Tuple3[Boolean, Int, Seq[Double]] = (true, 3, Vector(1.0, 2.0, 3.0))

An iterative solver returns SolverResult.Converged or SolverResult.NotConverged. Both results contain the last iterate, iteration count, and residual. Check converged before using the solution when the requested tolerance is a requirement.

Use LinearOperator.fromFunction when code can compute A x without storing the entries of A. The function receives an input vector and a mutable output vector. It must write every output element.

This operator applies a one-dimensional second-difference stencil:

val stencilSize = 5
// stencilSize: Int = 5
val stencil = LinearOperator.fromFunction(stencilSize, stencilSize):
(input, output) =>
var i = 0
while i < stencilSize do
val left = if i == 0 then 0.0 else input(i - 1)
val right = if i + 1 == stencilSize then 0.0 else input(i + 1)
output(i) = 2.0 * input(i) - left - right
i += 1
val expectedStencilSolution = Vec.tabulate(stencilSize)(i => i.toDouble + 1.0)
val stencilResult = cg(
stencil,
stencil * expectedStencilSolution,
SolverConfig(tolerance = 1e-12, maxIterations = 20)
)
// stencilResult: SolverResult = Converged(
// x = gale.linalg.DVec@180705e8,
// iterations = 5,
// residual = 6.50339954533191E-16
// )
(stencilResult.converged, stencilResult.x.toSeq)
// res34: Tuple2[Boolean, Seq[Double]] = (
// true,
// Vector(1.0000000000000002, 2.0000000000000004, 3.0, 4.0, 5.0)
// )

Use LinearOperator.fromFunctions when an algorithm also needs Aᵀx, as LSQR and partial SVD do. Operator composition, scaling, row restriction, column restriction, adjoints, and matrix-free Kronecker products are available without materializing the combined matrix.

Breeze has a general slicing language built around ::. Gale uses separate methods for a row, column, contiguous slice, and indexed gather. Rows, columns, slices, and transposes are views. Gathers are copies because they may reorder or repeat values.

Gale matrices do not change after construction. updated returns a new matrix; it does not alter the original. A builder is intended for bulk construction. Views can share data safely because ordinary Gale values cannot modify it.

unsafeFromBreezeView is different. It shares data with a mutable Breeze value, so changing the Breeze matrix also changes what Gale reads.

Breeze commonly throws when a numerical operation fails. Gale’s factorization, solve, and spectral entry points return Either[LinAlgError, A] for structural failures. Library code can inspect the error. Tests and small applications can call .orThrow when stopping immediately is appropriate.

Iterative methods use a different result because a non-converged iterate can still be useful. They return a result with the current estimate and diagnostics; the caller decides whether the reported convergence is sufficient.

conditionEstimate is a 1-norm estimate. It is not Breeze’s exact SVD-based 2-norm condition number. Gale uses a different name because the returned quantity and its computational cost differ. LU reports SingularMatrix only on an exact-zero (or NaN) pivot; a reconstructed near-singular plant is not a portable +∞ fixture. See the numerical contract.

Gale’s full SVD returns economy-size factors rather than full square factors. Symmetric eigenvalue and Cholesky routines read the lower triangle of the input as the symmetric matrix. If a migrated program may receive asymmetric data, validate or symmetrize it before the call.

Signs, pivot choices, and bases inside repeated eigenspaces may differ even when two decompositions represent the same mathematical result. Compare reconstruction errors, residuals, orthogonality, and subspaces rather than raw factor entries.

Differential checks against Breeze 2.1 for these common operations live in the parity/ module (sbt parityTest). Operations with no honest Breeze reference — generalized eigen / GSVD / QZ, sparse-direct factorization, near-cutoff rank / pinv / cond, and Krylov algorithm diagnostics — are checked against NumPy / SciPy fixtures in the same module. The table below is the migration surface; the parity README tracks which rows are cross-checked.

Task Gale API Important difference
Dense vectors and matrices DVec, DMat, Vec, Matrix Real Double values; ordinary results are immutable.
Dense arithmetic +, -, *, dot, norm2, pointwise Pointwise matrix operations require gale.syntax.all.*.
Reductions sum, mean, max, min, argmax, argmin, per-axis sum(Axis.Rows) Empty mean/max/min/argmax throw LinAlgError.EmptyInput; Axis.Rows gives one value per row, like sum(A(*, ::)).
Norms norm1, norm2, normInf, normFrobenius Matrix norm1/normInf are the induced column/row-sum norms.
Log-sum-exp and softmax Numerics.logSumExp, Numerics.softmax Breeze’s softmax(v) is the scalar log-sum-exp; Gale’s softmax is the normalized vector.
Square solve with vector or matrix RHS A.solve(b), A.solve(B) Returns Either; matrix RHS is factored once.
Inverse A.inverse (Breeze inv(A)) Returns Either; singular input is Left(SingularMatrix(k)) where Breeze throws. Prefer A.solve(B) for A⁻¹B.
Least squares A.leastSquares(b) or A.leastSquares(B) Tall, full-column-rank systems; rank deficiency is reported.
LU, Cholesky, QR, determinant A.lu, A.cholesky, A.qr, A.det Typed factors and failures; legal signs and pivots may differ.
Rank A.rankEstimate Numerical estimate with Gale’s tolerance policy.
Condition number A.conditionEstimate Estimates the 1-norm condition number, not the exact SVD 2-norm.
Symmetric eigenproblem Eigen.eigSymmetric Eigenvalues are returned in ascending algebraic order.
Nonsymmetric eigenproblem Eigen.eigNonsymmetric Complex conjugate pairs use Gale’s typed complex accessors.
Generalized symmetric-definite eigenproblem Eigen.eigSymmetricGeneralized Requires a symmetric A and positive-definite metric B.
Partial matrix-free eigenproblem operator overloads of Eigen Returns diagnostics and the converged pairs.
Full or partial SVD A.svd, Svds.svd Full factors use economy shapes; partial results include diagnostics.
Pseudo-inverse A.pinv Rank cutoff may differ near the numerical-rank boundary.
Kronecker product A.kron(B) or operator Kronecker product The operator form avoids materializing the product.
Sparse matrix-vector products COO, CSR, CSC, Banded, Diagonal Sparse formats and canonicalization rules differ from Breeze.
Iterative linear solve cg, bicgstab, gmres, lsqr, cgnr Non-convergence returns the last iterate and diagnostics.
Matrix-free computation DoubleLinearOperator The caller supplies A x, and sometimes Aᵀx, without exposing entries.
Dense and sparse conversion gale.interop.breeze.* Gale-to-Breeze conversion always copies.

Add gale-interop-breeze while a codebase still accepts or returns Breeze values. Convert to Gale before the numerical work and convert back only where an existing interface still requires Breeze:

import gale.interop.breeze.*
val galeA = fromBreezeCopy(breezeMatrix)
val galeB = fromBreezeCopy(breezeVector)
val result = galeA.solve(galeB)
val breezeResult = result.map(x => toBreezeCopy(x))

The module also contains BreezeMigration shims for old call sites whose Breeze-typed signatures cannot yet change. Those shims throw on failure. Treat them as temporary adapters, not as the Gale API for new code.

unsafeFromBreezeView creates a zero-copy view when the Breeze value has positive strides. Use it only when aliasing is intentional and the Breeze owner will not mutate the data during the Gale operation. Gale-to-Breeze conversion always copies.

Do not assume that Gale or Breeze is faster for every operation. Measure the operations, sizes, JVM, and backend used by the application.

In the most recent recorded comparison (an AMD Zen 5 server, JDK 25, Breeze 2.1 with its scalar Java11BLAS fallback), pure Gale was faster on 124 of 151 operation-and-size pairs, tied on 13, and slower on 4; 10 pairs were not like-for-like and carry no verdict. Against Breeze on VectorBLAS, Gale with the Vector backend imported was faster on 118, tied on 14, and slower on 9. The remaining gaps and their causes are listed in the benchmark dashboard. The result does not describe Breeze with native BLAS/LAPACK enabled, and it does not predict another processor or JVM.

Gale also has optional JVM Vector API and native FFM backends. They route only supported operations, layouts, and measured problem sizes. A small or strided operation may still use the portable implementation. See the JDK 22 Vector comparison and Numerical contract before choosing a backend.

If your Breeze build ran with --add-modules=jdk.incubator.vector, netlib used VectorBLAS automatically. Gale does not switch on that flag alone: keep the flag and add import gale.backend.jvm.vector.given where the products are written, as described in Enabling SIMD. Without the import, Gale compares its pure kernels with Breeze’s SIMD BLAS, and large dense products will be slower than they need to be.

Gale’s LBFGS.minimize and LBFGSB.minimize solve the same problems as Breeze’s breeze.optimize.LBFGS and breeze.optimize.LBFGSB: a smooth objective with an analytic gradient, unconstrained or inside a box. The two libraries stop for different reasons, so default settings in Breeze and in Gale do not return points of the same accuracy. Configure the stopping rule explicitly when results must match.

These are the only gale.optim solvers with Breeze parity tests. The other solvers in gale.optim (AcceleratedProximal, LevenbergMarquardt, CMAES, AugmentedLagrangian, BoxQuasiNewton) have no counterpart checked here.

Breeze Gale Notes
DiffFunction[DenseVector[Double]] DifferentiableObjective Gale callbacks receive an n × 1 DMat and return Either.
new LBFGS(maxIter, m, tolerance) LBFGSConfig(maxIterations, tolerance, historySize) Breeze defaults: maxIter = -1 (no limit), m = 7, tolerance = 1e-9. Gale defaults: 1000, 10, FirstOrderTolerance.strict.
new LBFGSB(l, u, maxIter, m, tolerance) LBFGSBConfig(...) with MatrixBoxBounds.from(l, u) Breeze defaults: maxIter = 100, m = 5, tolerance = 1e-8.
StrongWolfeLineSearch with c1 = 1e-4, c2 = 0.9 (fixed) c1, c2 in the config Same defaults; Gale lets them be changed.
maxZoomIter, maxLineSearchIter (10 each in LBFGS, 64 in LBFGSB) maxLineSearch (default 40) One trial budget per line search. LBFGSConfig.maximumStep caps the step.
first trial step: 1/‖d‖₂ on iteration 0 in LBFGS, else 1; always 1 in LBFGSB the same rule, fixed Gale LBFGS also uses 1/‖d‖₂ after a history reset, whenever d = −∇f is unscaled.
evaluation count (wrap the DiffFunction) solution.evaluations.callbacks Gale counts every callback, including rejected trials.
minimizeAndReturnState(f, x0).convergenceReason solution.status Converged, IterationLimit, LineSearchFailed, EvaluationLimit, Cancelled, NumericalStagnation.

Gale stops when the residual satisfies ‖r(x)‖∞ ≤ absolute + relative · max(1, ‖r(x₀)‖∞), with the tolerances from FirstOrderTolerance.from(absolute, relative). For LBFGS, r is the gradient. For LBFGSB, r is the unit projected-gradient step x − clamp(x − ∇f(x), l, u). Converged therefore certifies the returned point.

Breeze’s default check stops at the first of these conditions:

  • the iteration limit;
  • the current value is within tolerance · |f(x₀)| of the largest of the last 20 values;
  • ‖∇f‖₂ ≤ max(tolerance · |f(x)|, 1e-8);
  • the line search failed twice in a row.

LBFGSB also stops as soon as ‖r(x)‖∞ < 1e-5. That limit is hard-coded, so the tolerance argument cannot make Breeze LBFGSB stop at a smaller residual.

To reproduce Gale’s rule in Breeze LBFGS, pass a custom check:

import breeze.optimize.FirstOrderMinimizer.*
val tau = 1e-8 // absolute + relative * max(1, ‖∇f(x₀)‖∞)
val check = ConvergenceCheck.fromPartialFunction[DenseVector[Double]] {
case s if breeze.linalg.max(breeze.numerics.abs(s.grad)) <= tau => GradientConverged
} || maxIterationsReached[DenseVector[Double]](20000) || searchFailed[DenseVector[Double]]
val breezeLbfgs = new LBFGS[DenseVector[Double]](check, m = 10)

Breeze LBFGSB does not take a check. A subclass can drive the inherited infiniteIterations iterator and stop on the projected-gradient residual. The parity suite does this.

The equivalent Gale configuration:

import gale.optim.*
val optTolerance = FirstOrderTolerance.from(absolute = 1e-8, relative = 0.0).toOption.get
// optTolerance: FirstOrderTolerance = FirstOrderTolerance(
// absolute = 1.0E-8,
// relative = 0.0
// )
val optObjective = DifferentiableObjective(2): x =>
val (a, b) = (x(0, 0), x(1, 0))
val value = (1 - a) * (1 - a) + 100 * (b - a * a) * (b - a * a)
val gradient = DMat.tabulate(2, 1): (row, _) =>
if row == 0 then -2 * (1 - a) - 400 * a * (b - a * a) else 200 * (b - a * a)
Right(ObjectiveEvaluation(value, gradient))
.toOption.get
val optStart = DMat.tabulate(2, 1)((row, _) => if row == 0 then -1.2 else 1.0)
val optUnconstrained = LBFGS
.minimize(optObjective, optStart, LBFGSConfig(tolerance = optTolerance, historySize = 10))
.toOption.get
// optUnconstrained: FirstOrderSolution = FirstOrderSolution(
// primal = gale.linalg.DMat@1ef68887,
// dual = None,
// objective = 2.468577772730986E-21,
// status = Converged,
// certificate = FirstOrderCertificate(
// primal = ValueSummary(
// rows = 2,
// columns = 1,
// sum = 2.000000000032345,
// squaredNorm = 2.0000000000646896,
// maxAbs = 1.000000000023191
// ),
// dual = None,
// objective = 2.468577772730986E-21,
// primalResidual = 1.9350632207882973E-9,
// dualResidual = 0.0,
// objectiveChange = 0.0,
// iterations = 35,
// settings = FirstOrderSettings(
// method = LBFGS,
// maxIterations = 1000,
// tolerance = FirstOrderTolerance(absolute = 1.0E-8, relative = 0.0),
// stepSafety = 1.0,
// extrapolation = 0.0,
// primalResidualScale = 215.6,
// dualResidualScale = 1.0,
// algorithm = LimitedMemory(
// historySize = 10,
// c1 = 1.0E-4,
// c2 = 0.9,
// maxLineSearch = 40,
// maximumStep = 1.0E20
// ),
// maxEvaluations = 2147483647
// ),
// primalResolution = 0.0,
// dualResolution = 0.0,
// boundPrimal = Some(gale.linalg.DMat@1ef68887),
// boundDual = None
// ),
// evaluations = EvaluationCounts(
// callbacks = 47,
// values = 47,
// gradients = 47,
// proximals = 0,
// projections = 0,
// forwards = 0,
// adjoints = 0,
// ...
(optUnconstrained.status, optUnconstrained.primal(0, 0), optUnconstrained.primal(1, 0))
// res35: Tuple3[FirstOrderStoppingStatus, Double, Double] = (
// Converged,
// 1.0000000000091538,
// 1.000000000023191
// )
val optBox = MatrixBoxBounds.uniform(2, -2.0, 0.8).toOption.get
val optBounded = LBFGSB
.minimize(optObjective, optBox, DMat.zeros(2, 1), LBFGSBConfig(tolerance = optTolerance))
.toOption.get
// optBounded: FirstOrderSolution = FirstOrderSolution(
// primal = gale.linalg.DMat@2a423f6c,
// dual = None,
// objective = 0.03999999999999998,
// status = Converged,
// certificate = FirstOrderCertificate(
// primal = ValueSummary(
// rows = 2,
// columns = 1,
// sum = 1.4400000000000002,
// squaredNorm = 1.0496000000000003,
// maxAbs = 0.8
// ),
// dual = None,
// objective = 0.03999999999999998,
// primalResidual = 0.0,
// dualResidual = 0.0,
// objectiveChange = 0.0,
// iterations = 13,
// settings = FirstOrderSettings(
// method = LBFGSB,
// maxIterations = 1000,
// tolerance = FirstOrderTolerance(absolute = 1.0E-8, relative = 0.0),
// stepSafety = 1.0,
// extrapolation = 0.0,
// primalResidualScale = 1.0,
// dualResidualScale = 1.0,
// algorithm = BoundedLimitedMemory(
// historySize = 10,
// c1 = 1.0E-4,
// c2 = 0.9,
// maxLineSearch = 40
// ),
// maxEvaluations = 2147483647
// ),
// primalResolution = 0.0,
// dualResolution = 0.0,
// boundPrimal = Some(gale.linalg.DMat@2a423f6c),
// boundDual = None
// ),
// evaluations = EvaluationCounts(
// callbacks = 18,
// values = 18,
// gradients = 18,
// proximals = 0,
// projections = 0,
// forwards = 0,
// adjoints = 0,
// residuals = 0,
// ...
(optBounded.status, optBounded.primal(0, 0), optBounded.primal(1, 0))
// res36: Tuple3[FirstOrderStoppingStatus, Double, Double] = (
// Converged,
// 0.8,
// 0.6400000000000001
// )

OptimizerParitySuite in the parity/ module runs both libraries with this shared rule (τ = 1e-8, history 10) on quadratics with condition numbers up to 1e6, chained Rosenbrock up to n = 100, L2-regularized logistic regression, and box-constrained quadratics and logistic regression. On every problem, both libraries reach τ. The returned points agree within the bound implied by τ and the strong convexity constant, and the values and active sets also agree. The suite records these differences:

  • Default accuracy. Default-configured Breeze can stop far from the minimizer. On a quadratic with n = 100 and κ = 1e4, new LBFGS() stopped with ‖x − x*‖₂ ≈ 9e-3. On a box quadratic of the same size, new LBFGSB(l, u) reached its 100-iteration limit with ‖x − x*‖₂ ≈ 1.8. Under the shared rule, both libraries returned points within 4e-9 of each other.
  • Evaluation counts. These are informational, not a benchmark. In the unconstrained cases, the two libraries used similar numbers of callbacks. In the box-constrained cases, Breeze LBFGSB used about three times as many callbacks as Gale.
  • Infeasible starts. Both libraries reject them. Gale returns Left(FirstOrderError.InvalidConfiguration(...)). Breeze throws IllegalArgumentException. Project the start onto the box before calling either solver.
  • A start at the minimizer returns after one evaluation in both libraries.
  • Roundoff limit. A strong-Wolfe line search must detect a decrease in f of about ‖∇f‖² / L. When |f*| is large, such as 1e2, that decrease can fall below eps · |f| before ‖∇f‖∞ reaches 1e-8. Either library may then stop on a failed line search: Gale reports LineSearchFailed, and Breeze reports line search failed!. Whether a given problem stalls differs between the libraries. In the suite, Gale reached τ on one of three such problems and Breeze on another. Neither reports Converged with a residual above τ. Subtract a known constant from the objective, or loosen the tolerance, when this happens.

Gale does not provide:

  • Breeze collections, generic scalar operators, broadcasting, or compatible :: slicing syntax;
  • probability distributions, Breeze’s other breeze.optimize solvers (for example OWLQN, SGD variants, and projected quasi-Newton), statistics, signal processing, plotting, machine learning, tensors, or other non-linear-algebra modules;
  • general complex matrix storage and arithmetic;
  • sparse direct factorization;
  • negative-stride Gale views;
  • source or binary compatibility with Breeze;
  • identical exception classes, pivots, factor signs, eigenvector signs, or bit-identical floating-point results; or
  • a guarantee that Gale is faster than a native-enabled Breeze installation.

Continue with Worked examples for more complete programs. Read Advanced topics when allocation control, sparse structure reuse, backend selection, or matrix-free generalized eigensolving affects the application. The current portable / backend-only / deferred split is tabulated in Shipped vs deferred.