complete first draft of package
[epclust.git] / old_C_code / stage1 / src / TimeSeries / deserialize.c
1 #include "TimeSeries/deserialize.h"
2 #include <stdio.h>
3 #include "Util/utils.h"
4
5 // Deserialize a portion of a binary file into an array of PowerCurve, or a file
6 // WARNING: NO start bytes, NO date times (all series have the same length, at same times).
7 PowerCurve* deserialize(const char* ifileName, const char* ofileName,
8 uint32_t* ranks, uint32_t nbRanks)
9 {
10 // Read tsLength at the beginning of the file
11 uint32_t tsLength = get_tsLength(ifileName);
12
13 uint32_t valuesPerSerie = (tsLength - 4) / 4; //remove 4 bytes of ID
14
15 FILE* ifile = fopen(ifileName, "rb");
16 FILE* ofile = NULL;
17 if (ofileName)
18 ofile = fopen(ofileName, "w");
19
20 if (!ranks || nbRanks <= 0)
21 {
22 nbRanks = get_nbSeries(ifileName);
23 ranks = NULL;
24 }
25
26 PowerCurve* powerCurves = NULL;
27 if (!ofile)
28 powerCurves = (PowerCurve*) malloc(nbRanks * sizeof(PowerCurve));
29
30 for (uint32_t i = 0; i < nbRanks; i++)
31 {
32 // position to the beginning of current (binarized) time-series
33 // NOTE: shift by 8 bytes, because data size and series length are written first
34 fseek(ifile, 8 + (ranks ? ranks[i] : i) * tsLength, SEEK_SET);
35
36 PowerCurve* powerCurve;
37 if (!ofile)
38 {
39 powerCurve = powerCurves + i;
40 powerCurve->values = (float*) malloc(valuesPerSerie * sizeof(float));
41 }
42
43 // translate 4-bytes binary integer into integer ID
44 void* binaryID = malloc(4);
45 size_t lengthRead = fread(binaryID, 4, 1, ifile);
46 if (lengthRead != 1)
47 fprintf(stderr,"Warning: deserializing truncated binary file.\n");
48 uint32_t ID = bInt_to_uint((Byte*) binaryID);
49 free(binaryID);
50 if (ofile)
51 fprintf(ofile, "%u,", ID);
52 else
53 powerCurve->ID = ID;
54
55 // translate 4-bytes binary integers into float
56 Byte* binarySerie = (Byte*) malloc(4 * valuesPerSerie);
57 lengthRead = fread(binarySerie, 1, 4*valuesPerSerie, ifile);
58 //TODO: assert that lengthRead == 4*valuesPerSerie (...)
59 for (uint32_t i = 0; i < valuesPerSerie; i++)
60 {
61 float power = bReal_to_float(binarySerie + 4 * i);
62 if (ofile)
63 {
64 fprintf(ofile, "%g", power);
65 if (i < valuesPerSerie-1)
66 fprintf(ofile, ",");
67 }
68 else
69 powerCurve->values[i] = power;
70 }
71 free(binarySerie);
72 if (ofile)
73 fprintf(ofile, "\n");
74 }
75
76 fclose(ifile);
77 if (ofile)
78 fclose(ofile);
79
80 return powerCurves;
81 }