exp-rs 0.2.0

no_std expression parser, compiler, and evaluation engine for math expressions designed for embedded, with qemu examples
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "exp_rs.h"

#define EPSILON 1e-10

// Helper function to check if two doubles are approximately equal
int approx_equal(double a, double b) {
    return fabs(a - b) < EPSILON;
}

void test_basic_batch_eval() {
    printf("Test 1: Basic batch evaluation\n");
    
    // Create a context
    void* ctx = exp_rs_context_new();
    
    // Test expressions
    const char* expressions[] = {
        "x + y",
        "x * y",
        "x - y",
        "x / y"
    };
    size_t expr_count = 4;
    
    // Parameter names
    const char* param_names[] = {"x", "y"};
    size_t param_count = 2;
    
    // Parameter values: param_values[param_idx][batch_idx]
    double x_values[] = {2.0, 5.0, 1.0};  // x values for batch 0, 1, 2
    double y_values[] = {3.0, 10.0, 4.0}; // y values for batch 0, 1, 2
    const double* param_values[] = {x_values, y_values};
    size_t batch_size = 3;
    
    // Expected results
    double expected[4][3] = {
        {5.0, 15.0, 5.0},    // x + y
        {6.0, 50.0, 4.0},    // x * y
        {-1.0, -5.0, -3.0},  // x - y
        {2.0/3.0, 0.5, 0.25} // x / y
    };
    
    // Pre-allocate result buffers
    double** results = (double**)calloc(expr_count, sizeof(double*));
    for (size_t i = 0; i < expr_count; i++) {
        results[i] = (double*)calloc(batch_size, sizeof(double));
    }
    BatchStatus* statuses = (BatchStatus*)calloc(expr_count * batch_size, sizeof(BatchStatus));
    
    BatchEvalRequest request = {
        .expressions = expressions,
        .expression_count = expr_count,
        .param_names = param_names,
        .param_count = param_count,
        .param_values = param_values,
        .batch_size = batch_size,
        .results = results,
        .stop_on_error = 0,
        .statuses = statuses
    };
    
    int result = exp_rs_batch_eval(&request, ctx);
    
    if (result != 0) {
        printf("  FAIL: batch_eval returned error code %d\n", result);
        goto cleanup1;
    }
    
    // Check all results
    int all_passed = 1;
    for (size_t i = 0; i < expr_count; i++) {
        for (size_t j = 0; j < batch_size; j++) {
            BatchStatus* status = &statuses[i * batch_size + j];
            if (status->code != 0) {
                printf("  FAIL: Expression %zu, batch %zu failed with code %d\n", 
                       i, j, status->code);
                all_passed = 0;
                continue;
            }
            
            double actual = results[i][j];
            double expect = expected[i][j];
            if (!approx_equal(actual, expect)) {
                printf("  FAIL: Expression %zu (%s), batch %zu: expected %.6f, got %.6f\n",
                       i, expressions[i], j, expect, actual);
                all_passed = 0;
            }
        }
    }
    
    if (all_passed) {
        printf("  PASS: All results match expected values\n");
    }
    
cleanup1:
    // Free allocated results
    for (size_t i = 0; i < expr_count; i++) {
        if (results[i]) free(results[i]);
    }
    free(results);
    free(statuses);
    exp_rs_context_free(ctx);
    printf("\n");
}

void test_with_context() {
    printf("Test 2: Batch evaluation with pre-set parameters\n");
    
    // Create a context
    void* ctx = exp_rs_context_new();
    
    // Test expressions with different parameter sets
    const char* expressions[] = {
        "x * 3.14159",
        "10.0 + x",
        "20.0 * y"
    };
    size_t expr_count = 3;
    
    const char* param_names[] = {"x", "y"};
    size_t param_count = 2;
    
    // Parameter values: param_values[param_idx][batch_idx]
    double x_values2[] = {1.0, 2.0};  // x values for batch 0, 1
    double y_values2[] = {2.0, 3.0};  // y values for batch 0, 1
    const double* param_values[] = {x_values2, y_values2};
    size_t batch_size = 2;
    
    double expected[3][2] = {
        {3.14159, 6.28318},     // x * 3.14159
        {11.0, 12.0},           // 10.0 + x
        {40.0, 60.0}            // 20.0 * y
    };
    
    double** results = (double**)calloc(expr_count, sizeof(double*));
    for (size_t i = 0; i < expr_count; i++) {
        results[i] = (double*)calloc(batch_size, sizeof(double));
    }
    BatchStatus* statuses = (BatchStatus*)calloc(expr_count * batch_size, sizeof(BatchStatus));
    
    BatchEvalRequest request = {
        .expressions = expressions,
        .expression_count = expr_count,
        .param_names = param_names,
        .param_count = param_count,
        .param_values = param_values,
        .batch_size = batch_size,
        .results = results,
        .stop_on_error = 0,
        .statuses = statuses
    };
    
    // Use batch eval with context
    int result = exp_rs_batch_eval_with_context(&request, ctx);
    
    if (result != 0) {
        printf("  FAIL: batch_eval_with_context returned error code %d\n", result);
        goto cleanup2;
    }
    
    // Check all results
    int all_passed = 1;
    for (size_t i = 0; i < expr_count; i++) {
        for (size_t j = 0; j < batch_size; j++) {
            BatchStatus* status = &statuses[i * batch_size + j];
            if (status->code != 0) {
                printf("  FAIL: Expression %zu, batch %zu failed with code %d\n", 
                       i, j, status->code);
                all_passed = 0;
                continue;
            }
            
            double actual = results[i][j];
            double expect = expected[i][j];
            if (!approx_equal(actual, expect)) {
                printf("  FAIL: Expression %zu (%s), batch %zu: expected %.6f, got %.6f\n",
                       i, expressions[i], j, expect, actual);
                all_passed = 0;
            }
        }
    }
    
    if (all_passed) {
        printf("  PASS: All results match expected values\n");
    }
    
cleanup2:
    for (size_t i = 0; i < expr_count; i++) {
        if (results[i]) free(results[i]);
    }
    free(results);
    free(statuses);
    exp_rs_context_free(ctx);
    printf("\n");
}

void test_error_handling() {
    printf("Test 3: Error handling in batch evaluation\n");
    
    // Test expressions with errors
    const char* expressions[] = {
        "x + y",          // Valid
        "x / 0",          // Division by zero
        "undefined_var",  // Undefined variable
        "x * y"           // Valid
    };
    size_t expr_count = 4;
    
    const char* param_names[] = {"x", "y"};
    size_t param_count = 2;
    
    // Parameter values: param_values[param_idx][batch_idx]
    double x_values3[] = {2.0};
    double y_values3[] = {3.0};
    const double* param_values[] = {x_values3, y_values3};
    size_t batch_size = 1;
    
    double** results = (double**)calloc(expr_count, sizeof(double*));
    for (size_t i = 0; i < expr_count; i++) {
        results[i] = (double*)calloc(batch_size, sizeof(double));
    }
    BatchStatus* statuses = (BatchStatus*)calloc(expr_count * batch_size, sizeof(BatchStatus));
    
    // Create a context
    void* ctx = exp_rs_context_new();
    
    // Test without stop_on_error
    BatchEvalRequest request = {
        .expressions = expressions,
        .expression_count = expr_count,
        .param_names = param_names,
        .param_count = param_count,
        .param_values = param_values,
        .batch_size = batch_size,
        .results = results,
        .stop_on_error = 0,
        .statuses = statuses
    };
    
    int result = exp_rs_batch_eval(&request, ctx);
    
    // With stop_on_error=0, it should continue processing despite errors
    // The return code indicates if any errors occurred
    if (result != 0) {
        printf("  PASS: Got expected error code %d (some expressions failed)\n", result);
    } else {
        printf("  INFO: All expressions processed (check individual statuses)\n");
    }
    
    // Check individual statuses
    if (statuses[0].code == 0 && approx_equal(results[0][0], 5.0)) {
        printf("  PASS: First valid expression evaluated correctly\n");
    } else {
        printf("  FAIL: First valid expression failed\n");
    }
    
    if (statuses[1].code == 0 && isinf(results[1][0])) {
        printf("  PASS: Division by zero returned infinity\n");
    } else if (statuses[1].code != 0) {
        printf("  PASS: Division by zero reported error code %d\n", statuses[1].code);
    } else {
        printf("  FAIL: Division by zero handling incorrect\n");
    }
    
    if (statuses[2].code != 0) {
        printf("  PASS: Undefined variable reported error code %d\n", statuses[2].code);
    } else {
        printf("  FAIL: Undefined variable did not report error\n");
    }
    
    if (statuses[3].code == 0 && approx_equal(results[3][0], 6.0)) {
        printf("  PASS: Last valid expression evaluated correctly\n");
    } else {
        printf("  FAIL: Last valid expression failed\n");
    }
    
    // Cleanup
    for (size_t i = 0; i < expr_count; i++) {
        if (results[i]) free(results[i]);
    }
    free(results);
    free(statuses);
    exp_rs_context_free(ctx);
    printf("\n");
}

void test_batch_builder() {
    printf("Test 4: BatchBuilder API\n");
    
    // Create a BatchBuilder
    struct BatchBuilderOpaque* builder = exp_rs_batch_builder_new();
    if (!builder) {
        printf("  FAIL: Failed to create BatchBuilder\n");
        return;
    }
    
    // Add expressions
    const char* expressions[] = {
        "x + y",
        "x * y",
        "x * x + y * y"
    };
    
    for (size_t i = 0; i < 3; i++) {
        printf("  Adding expression %zu: '%s'\n", i, expressions[i]);
        int32_t result = exp_rs_batch_builder_add_expression(builder, expressions[i]);
        if (result < 0) {
            printf("  FAIL: Failed to add expression %zu ('%s') with error code %d\n", i, expressions[i], result);
            exp_rs_batch_builder_free(builder);
            return;
        }
        if (result != (int32_t)i) {
            printf("  WARN: Expected index %zu but got %d\n", i, result);
        }
    }
    
    // Add parameters
    exp_rs_batch_builder_add_parameter(builder, "x", 2.0);
    exp_rs_batch_builder_add_parameter(builder, "y", 3.0);
    
    // Create context for evaluation
    void* ctx = exp_rs_context_new();
    if (!ctx) {
        printf("  FAIL: Failed to create context\n");
        exp_rs_batch_builder_free(builder);
        return;
    }
    
    // Evaluate
    int32_t eval_result = exp_rs_batch_builder_eval(builder, ctx);
    if (eval_result != 0) {
        printf("  FAIL: Evaluation failed with code %d\n", eval_result);
        exp_rs_batch_builder_free(builder);
        return;
    }
    
    // Check results
    double expected[] = {5.0, 6.0, 13.0};
    int all_passed = 1;
    
    for (size_t i = 0; i < 3; i++) {
        double actual = exp_rs_batch_builder_get_result(builder, i);
        if (!approx_equal(actual, expected[i])) {
            printf("  FAIL: Expression %zu (%s): expected %.6f, got %.6f\n",
                   i, expressions[i], expected[i], actual);
            all_passed = 0;
        }
    }
    
    if (all_passed) {
        printf("  PASS: All BatchBuilder results correct\n");
    }
    
    // Test parameter update
    exp_rs_batch_builder_set_param_by_name(builder, "x", 4.0);
    exp_rs_batch_builder_set_param_by_name(builder, "y", 5.0);
    
    eval_result = exp_rs_batch_builder_eval(builder, ctx);
    if (eval_result != 0) {
        printf("  FAIL: Re-evaluation failed\n");
    } else {
        double expected2[] = {9.0, 20.0, 41.0};
        all_passed = 1;
        
        for (size_t i = 0; i < 3; i++) {
            double actual = exp_rs_batch_builder_get_result(builder, i);
            if (!approx_equal(actual, expected2[i])) {
                printf("  FAIL: After update, expression %zu: expected %.6f, got %.6f\n",
                       i, expected2[i], actual);
                all_passed = 0;
            }
        }
        
        if (all_passed) {
            printf("  PASS: Parameter updates work correctly\n");
        }
    }
    
    exp_rs_batch_builder_free(builder);
    exp_rs_context_free(ctx);
    printf("\n");
}

void test_performance_comparison() {
    printf("Test 5: Performance comparison (batch vs individual)\n");
    
    // Larger batch for performance testing
    const char* expressions[] = {
        "x * y + z",
        "sin(x) * cos(y)",
        "sqrt(x*x + y*y)",
        "exp(x) + log(y)"
    };
    size_t expr_count = 4;
    
    const char* param_names[] = {"x", "y", "z"};
    size_t param_count = 3;
    
    // Generate 100 batches of data
    size_t batch_size = 100;
    // Create param_values[param_idx][batch_idx]
    double* x_values_perf = (double*)malloc(batch_size * sizeof(double));
    double* y_values_perf = (double*)malloc(batch_size * sizeof(double));
    double* z_values_perf = (double*)malloc(batch_size * sizeof(double));
    
    for (size_t i = 0; i < batch_size; i++) {
        x_values_perf[i] = (double)(i + 1) / 10.0;  // x
        y_values_perf[i] = (double)(i + 2) / 10.0;  // y  
        z_values_perf[i] = (double)(i + 3) / 10.0;  // z
    }
    
    const double* param_values_perf[] = {x_values_perf, y_values_perf, z_values_perf};
    
    // Test batch evaluation
    double** results = (double**)calloc(expr_count, sizeof(double*));
    for (size_t i = 0; i < expr_count; i++) {
        results[i] = (double*)calloc(batch_size, sizeof(double));
    }
    BatchStatus* statuses = (BatchStatus*)calloc(expr_count * batch_size, sizeof(BatchStatus));
    
    // Create a context
    void* ctx = exp_rs_context_new();
    
    BatchEvalRequest request = {
        .expressions = expressions,
        .expression_count = expr_count,
        .param_names = param_names,
        .param_count = param_count,
        .param_values = param_values_perf,
        .batch_size = batch_size,
        .results = results,
        .stop_on_error = 0,
        .statuses = statuses
    };
    
    int batch_result = exp_rs_batch_eval(&request, ctx);
    
    if (batch_result == 0) {
        printf("  PASS: Batch evaluation completed successfully\n");
        
        // Verify a few results by computing them individually
        void* ctx = exp_rs_context_new();
        
        for (size_t i = 0; i < 3; i++) {  // Check first 3 batches
            exp_rs_context_set_parameter(ctx, "x", x_values_perf[i]);
            exp_rs_context_set_parameter(ctx, "y", y_values_perf[i]);
            exp_rs_context_set_parameter(ctx, "z", z_values_perf[i]);
            
            for (size_t j = 0; j < expr_count; j++) {
                struct EvalResult eval_result = exp_rs_context_eval(expressions[j], ctx);
                double individual_result = eval_result.value;
                double batch_result_val = results[j][i];
                
                if (!approx_equal(individual_result, batch_result_val)) {
                    printf("  FAIL: Mismatch at expr %zu, batch %zu: %.6f vs %.6f\n",
                           j, i, individual_result, batch_result_val);
                }
            }
        }
        
        printf("  PASS: Batch results match individual evaluations\n");
    } else {
        printf("  FAIL: Batch evaluation failed with code %d\n", batch_result);
    }
    
    // Cleanup
    for (size_t i = 0; i < expr_count; i++) {
        if (results[i]) free(results[i]);
    }
    free(results);
    free(statuses);
    
    free(x_values_perf);
    free(y_values_perf);
    free(z_values_perf);
    exp_rs_context_free(ctx);
    printf("\n");
}

int main() {
    printf("=== Batch Evaluation Tests ===\n\n");
    
    test_basic_batch_eval();
    test_with_context();
    test_error_handling();
    test_batch_builder();
    test_performance_comparison();
    
    printf("=== Tests Complete ===\n");
    return 0;
}