Skip to content
Two sparsity patterns. Left, the 217 nonzeros of the five-point Laplacian on a 7 by 7 grid. Right, its Cholesky factor, in which elimination has filled the band with 216 new entries.

Gale

Linear algebra for Scala 3, on the JVM and Scala.js. Vectors and matrices, dense and sparse; linear solvers; eigenvalues and the SVD; and optimization.

Make a matrix and a vector, read an entry and a row, and multiply. This code is taken from Get started; the documentation build runs it, and each comment shows the value it printed.

FirstProgram.scala
import gale.linalg.*
val a = Matrix(3, 3)(
2.0, 1.0, 0.0,
1.0, 3.0, 1.0,
0.0, 1.0, 4.0
)
val x = Vec(1.0, 2.0, 3.0)
a(1, 2)
// res0: Double = 1.0
a.row(1).toSeq
// res1: Seq[Double] = Vector(1.0, 3.0, 1.0)
(a * x).toSeq
// res2: Seq[Double] = Vector(4.0, 10.0, 14.0)
(a.t * a + Matrix.eye(3)).valuesRowMajor
// res3: Seq[Double] = Vector(6.0, 5.0, 1.0, 5.0, 12.0, 7.0, 1.0, 7.0, 18.0)

Matrix(3, 3) takes its values row by row, so the code reads like the matrix on paper. Indices start at zero.

* is the matrix product, a.t is the transpose, and + adds entry by entry. A product of the wrong shapes throws a LinAlgError at the line that made it.

Vectors and matrices never change once made. Rows, columns, slices, and transposes share the original’s storage instead of copying it.

Solve.scala
val b = a * x
val solved = a.solve(b).orThrow
solved.toSeq
// res4: Seq[Double] = Vector(1.0, 2.0, 3.0)
val singular = Matrix(2, 2)(
1.0, 2.0,
2.0, 4.0
)
singular.solve(Vec(1.0, 1.0)).isLeft
// res6: Boolean = true

a.solve(b) returns an Either. A singular matrix has no unique solution, so the result is a Left that says so, not a vector of meaningless numbers.

.orThrow turns a failure into an exception, which suits a script or a test. Library code can keep the Either and decide what to do.

Iterative solvers work the same way. When one runs out of iterations it still returns its last answer, marked converged = false.

The same code runs on the JVM and under Scala.js. The published core needs no native library and no JVM flags.

On the JVM you can also import an optional backend, the Vector API or BLAS and LAPACK, to speed up the operations it supports. Results keep the same types and meaning, though the last few bits may differ, because a backend can add numbers in a different order. The numerical contract says exactly what is guaranteed.

Gale is built with Scala 3.7.4 and needs JDK 21 on the JVM. Add the core to build.sbt:

scalaVersion := "3.7.4"
libraryDependencies += "io.github.canardlapin" %% "gale-core" % "0.1.0-M1"

For Scala.js or a cross-project, use %%% instead of %%. Modules and platforms lists every module and what it needs.