cheatah
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 in
4// 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 exact
11// integer solution x = [1, 2, 3] (so to_string is byte-stable), then verifies
12// the answer independently: it reconstructs A·x via linalg.matmul, forms the
13// residual r = A·x − b with ndarray.sub, and confirms ||r|| ≈ 0. det and trace
14// are printed as integer-valued cross-checks. The whole pipeline runs as a
15// compiled .purr module under the cheatah runtime; this test just compiles it
16// with purrc, runs it, and asserts the exact stdout (verified by hand-running
17// the program before hard-coding the expectation).
19#include "e2e_harness.hpp"
21TEST(SystemApps, LinearSolve) {
22 e2e::expect_e2e("app_matrix", R"PURR(import io
23import ndarray
24import linalg
25import math
27# A small linear-algebra "solver app": solve A x = b for a 3x3 system whose
28# exact solution is the integer vector x = [1, 2, 3], then independently verify
29# the result via det / trace and a residual norm computed by hand.
30let 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])
31let 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.
34let x = linalg.solve(A, b)
35let xcol = ndarray.reshape(x, [3, 1])
37# Residual r = A x - b; ||r|| should be ~0 if everything cooperated.
38let resid = ndarray.sub(linalg.matmul(A, xcol), b)
39let rnorm = linalg.norm(resid)
41# math.sqrt(rnorm*rnorm) == |rnorm|, exercising math on a linalg scalar.
42io.print("solution", ndarray.to_string(x))
43io.print("det", linalg.det(A))
44io.print("trace", linalg.trace(A))
45io.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");