fix generateRunSave_EMGLLF, simplify arrays readings
[valse.git] / src / test / utils.c
CommitLineData
2d22ed81
BA
1#include <stdlib.h>
2#include <stdio.h>
3#include <math.h>
4#include <string.h>
5
6// Check if array == refArray
7void compareArray(const char* ID, const void* array, const void* refArray, int size,
8 int isinteger)
9{
10 float EPS = 1e-5; //precision
11 printf("Checking %s\n",ID);
12 float maxError = 0.0;
13 for (int i=0; i<size; i++)
14 {
15 float error = isinteger
16 ? fabs(((int*)array)[i] - ((int*)refArray)[i])
17 : fabs(((float*)array)[i] - ((float*)refArray)[i]);
18 if (error >= maxError)
19 maxError = error;
20 }
21 if (maxError >= EPS)
22 printf(" Inaccuracy: max(abs(error)) = %g >= %g\n",maxError,EPS);
23 else
24 printf(" OK\n");
25}
26
27void compareArray_real(const char* ID, const void* array, const void* refArray, int size)
28{
29 return compareArray(ID, array, refArray, size, 0);
30}
31
32void compareArray_int(const char* ID, const void* array, const void* refArray, int size)
33{
34 return compareArray(ID, array, refArray, size, 1);
35}
36
37// Read array by columns (as in MATLAB) and return by-rows encoding
38void* readArray(const char* fileName, int isinteger)
39{
e8bb4764 40 // need to prepend 'data/' (not really nice code...)
2d22ed81
BA
41 char* fullFileName = (char*)calloc(5+strlen(fileName)+1, sizeof(char));
42 strcat(fullFileName, "data/");
43 strcat(fullFileName, fileName);
44
45 // first pass to know how many elements to allocate
46 char* command = (char*)calloc(12+strlen(fullFileName)+8+1, sizeof(char));
e8bb4764 47 strcat(command, "wc -l ");
2d22ed81 48 strcat(command, fullFileName);
e8bb4764
BA
49 FILE *arraySize = popen(command, "r");
50 char* bufferNum = (char*)calloc(64, sizeof(char));
51 fgets(bufferNum, sizeof(bufferNum), arraySize);
52 int n = atoi(bufferNum);
53 pclose(arraySize);
2d22ed81
BA
54
55 // open file for reading
e8bb4764 56 FILE* arrayFile = fopen(fullFileName, "r");
2d22ed81
BA
57 free(fullFileName);
58
2d22ed81 59 // read all values, and convert them to by-rows matrices format
e8bb4764 60 size_t elementSize = isinteger ? sizeof(int) : sizeof(float);
2d22ed81 61 void* array = malloc(n*elementSize);
e8bb4764 62 for (int i=0; i<n; i++)
2d22ed81 63 {
e8bb4764 64 // transform buffer content into float or int, and store it at appropriate location
2d22ed81 65 if (isinteger)
e8bb4764 66 ((int*)array)[i] = atoi(bufferNum);
2d22ed81 67 else
e8bb4764 68 ((float*)array)[i] = atof(bufferNum);
2d22ed81 69 }
e8bb4764
BA
70 fclose(arrayFile);
71 free(bufferNum);
2d22ed81
BA
72
73 return array;
74}
75
76int* readArray_int(const char* fileName)
77{
78 return (int*)readArray(fileName, 1);
79}
80
81float* readArray_real(const char* fileName)
82{
83 return (float*)readArray(fileName, 0);
84}
85
86int read_int(const char* fileName)
87{
88 return readArray_int(fileName)[0];
89}
90
91float read_real(const char* fileName)
92{
93 return readArray_real(fileName)[0];
94}