/ concept-collection / libflame2wasm
Sign in
concept-collection / libflame2wasm
libflame2wasm / demo / demo.c
86 lines · 2.4 KBBlameHistoryRaw
1/*
2 * Demo: exercise libflame compiled to WebAssembly.
3 *
4 * 1. Native FLAME/C API: Cholesky factorization of an SPD matrix.
5 * 2. LAPACK compatibility layer (lapack2flame): solve A x = b with dgesv_.
6 */
7#include <stdio.h>
8#include <math.h>
9#include "FLAME.h"
11/* LAPACK-style prototype provided by the lapack2flame layer. */
12extern int dgesv_( int* n, int* nrhs, double* a, int* lda,
13 int* ipiv, double* b, int* ldb, int* info );
15static int test_flame_cholesky( void )
17 int n = 4, i, j;
18 FLA_Obj A;
19 double* buf;
21 /* SPD matrix: A = M^T M + n*I built by hand (column-major). */
22 double A0[16] = {
23 4.16, -3.12, 0.56, -0.10,
24 -3.12, 5.03, -0.83, 1.18,
25 0.56, -0.83, 0.76, 0.34,
26 -0.10, 1.18, 0.34, 1.18
27 };
29 FLA_Obj_create( FLA_DOUBLE, n, n, 0, 0, &A );
30 buf = (double*) FLA_Obj_buffer_at_view( A );
31 for ( j = 0; j < n; j++ )
32 for ( i = 0; i < n; i++ )
33 buf[ j * n + i ] = A0[ j * n + i ];
35 if ( FLA_Chol( FLA_LOWER_TRIANGULAR, A ) != FLA_SUCCESS ) {
36 printf( "FLA_Chol: FAILED (matrix not SPD?)\n" );
37 FLA_Obj_free( &A );
38 return 1;
39 }
41 /* Check L(0,0) = sqrt(4.16) */
42 double expect = sqrt( 4.16 );
43 double got = buf[0];
44 printf( "FLA_Chol: L(0,0) = %.6f (expected %.6f) %s\n",
45 got, expect, fabs( got - expect ) < 1e-12 ? "OK" : "MISMATCH" );
47 FLA_Obj_free( &A );
48 return fabs( got - expect ) >= 1e-12;
51static int test_lapack_dgesv( void )
53 /* Solve A x = b where A = [[2,1],[1,3]], b = [3,5] -> x = [0.8, 1.4] */
54 int n = 2, nrhs = 1, lda = 2, ldb = 2, info = 0;
55 int ipiv[2];
56 double A[4] = { 2.0, 1.0, /* column 0 */
57 1.0, 3.0 }; /* column 1 */
58 double b[2] = { 3.0, 5.0 };
60 dgesv_( &n, &nrhs, A, &lda, ipiv, b, &ldb, &info );
62 printf( "dgesv_: info = %d, x = [%.6f, %.6f] (expected [0.8, 1.4]) %s\n",
63 info, b[0], b[1],
64 ( info == 0 && fabs( b[0] - 0.8 ) < 1e-12
65 && fabs( b[1] - 1.4 ) < 1e-12 ) ? "OK" : "MISMATCH" );
67 return !( info == 0 && fabs( b[0] - 0.8 ) < 1e-12
68 && fabs( b[1] - 1.4 ) < 1e-12 );
71int main( void )
73 int failures = 0;
75 FLA_Init();
76 printf( "libflame WASM demo\n" );
78 failures += test_flame_cholesky();
79 failures += test_lapack_dgesv();
81 FLA_Finalize();
83 printf( failures == 0 ? "ALL TESTS PASSED\n" : "%d TEST(S) FAILED\n",
84 failures );
85 return failures;
moveopenescclose