Source
tests/purrc/app_matrix_test.cpp
1
// Copyright (c) 2026 BigBrain LLC. MIT-licensed (see LICENSE).2
// Original work; see ACKNOWLEDGMENTS.md for the open-source ideas we build upon.3
// System-level "application" test: a small linear-algebra solver written in4
// cheatah that only passes if FOUR stdlib modules cooperate end to end —5
// * ndarray : array / reshape / sub (data construction + elementwise)6
// * linalg : solve / matmul / det / trace / norm (the numerical core)7
// * math : sqrt (scalar check on a linalg result)8
// * io : print (deterministic reporting)9
//10
// The program solves A x = b for a 3x3 system engineered to have the exact11
// integer solution x = [1, 2, 3] (so to_string is byte-stable), then verifies12
// the answer independently: it reconstructs A·x via linalg.matmul, forms the13
// residual r = A·x − b with ndarray.sub, and confirms ||r|| ≈ 0. det and trace14
// are printed as integer-valued cross-checks. The whole pipeline runs as a15
// compiled .purr module under the cheatah runtime; this test just compiles it16
// with purrc, runs it, and asserts the exact stdout (verified by hand-running17
// the program before hard-coding the expectation).19
#include "e2e_harness.hpp"21
TEST(SystemApps, LinearSolve) {22
e2e::expect_e2e("app_matrix", R"PURR(import io23
import ndarray24
import linalg25
import math27
# A small linear-algebra "solver app": solve A x = b for a 3x3 system whose28
# exact solution is the integer vector x = [1, 2, 3], then independently verify29
# the result via det / trace and a residual norm computed by hand.30
let A = ndarray.reshape(ndarray.array([2.0, 1.0, 1.0, 1.0, 3.0, 2.0, 1.0, 0.0, 0.0]), [3, 3])31
let b = ndarray.reshape(ndarray.array([7.0, 13.0, 1.0]), [3, 1])33
# Solve, then reshape the solution to a column vector for matmul.34
let x = linalg.solve(A, b)35
let xcol = ndarray.reshape(x, [3, 1])37
# Residual r = A x - b; ||r|| should be ~0 if everything cooperated.38
let resid = ndarray.sub(linalg.matmul(A, xcol), b)39
let rnorm = linalg.norm(resid)41
# math.sqrt(rnorm*rnorm) == |rnorm|, exercising math on a linalg scalar.42
io.print("solution", ndarray.to_string(x))43
io.print("det", linalg.det(A))44
io.print("trace", linalg.trace(A))45
io.print("residual_ok", math.sqrt(rnorm * rnorm) < 0.000001)46
)PURR",47
"solution [1, 2, 3]\n"48
"det -1\n"49
"trace 5\n"50
"residual_ok True\n");51
}