/* * Demo: exercise libflame compiled to WebAssembly. * * 1. Native FLAME/C API: Cholesky factorization of an SPD matrix. * 2. LAPACK compatibility layer (lapack2flame): solve A x = b with dgesv_. */ #include #include #include "FLAME.h" /* LAPACK-style prototype provided by the lapack2flame layer. */ extern int dgesv_( int* n, int* nrhs, double* a, int* lda, int* ipiv, double* b, int* ldb, int* info ); static int test_flame_cholesky( void ) { int n = 4, i, j; FLA_Obj A; double* buf; /* SPD matrix: A = M^T M + n*I built by hand (column-major). */ double A0[16] = { 4.16, -3.12, 0.56, -0.10, -3.12, 5.03, -0.83, 1.18, 0.56, -0.83, 0.76, 0.34, -0.10, 1.18, 0.34, 1.18 }; FLA_Obj_create( FLA_DOUBLE, n, n, 0, 0, &A ); buf = (double*) FLA_Obj_buffer_at_view( A ); for ( j = 0; j < n; j++ ) for ( i = 0; i < n; i++ ) buf[ j * n + i ] = A0[ j * n + i ]; if ( FLA_Chol( FLA_LOWER_TRIANGULAR, A ) != FLA_SUCCESS ) { printf( "FLA_Chol: FAILED (matrix not SPD?)\n" ); FLA_Obj_free( &A ); return 1; } /* Check L(0,0) = sqrt(4.16) */ double expect = sqrt( 4.16 ); double got = buf[0]; printf( "FLA_Chol: L(0,0) = %.6f (expected %.6f) %s\n", got, expect, fabs( got - expect ) < 1e-12 ? "OK" : "MISMATCH" ); FLA_Obj_free( &A ); return fabs( got - expect ) >= 1e-12; } static int test_lapack_dgesv( void ) { /* Solve A x = b where A = [[2,1],[1,3]], b = [3,5] -> x = [0.8, 1.4] */ int n = 2, nrhs = 1, lda = 2, ldb = 2, info = 0; int ipiv[2]; double A[4] = { 2.0, 1.0, /* column 0 */ 1.0, 3.0 }; /* column 1 */ double b[2] = { 3.0, 5.0 }; dgesv_( &n, &nrhs, A, &lda, ipiv, b, &ldb, &info ); printf( "dgesv_: info = %d, x = [%.6f, %.6f] (expected [0.8, 1.4]) %s\n", info, b[0], b[1], ( info == 0 && fabs( b[0] - 0.8 ) < 1e-12 && fabs( b[1] - 1.4 ) < 1e-12 ) ? "OK" : "MISMATCH" ); return !( info == 0 && fabs( b[0] - 0.8 ) < 1e-12 && fabs( b[1] - 1.4 ) < 1e-12 ); } int main( void ) { int failures = 0; FLA_Init(); printf( "libflame WASM demo\n" ); failures += test_flame_cholesky(); failures += test_lapack_dgesv(); FLA_Finalize(); printf( failures == 0 ? "ALL TESTS PASSED\n" : "%d TEST(S) FAILED\n", failures ); return failures; }