fix accent (TODO: fix gitweb...)
[ppam-mpi.git] / code / 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) / 3; //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 = (Real*) malloc(valuesPerSerie * sizeof(Real));
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, 4);
49 free(binaryID);
50 if (ofile)
51 fprintf(ofile, "%u,", ID);
52 else
53 powerCurve->ID = ID;
54
55 // translate 3-bytes binary integers into Real
56 Byte* binarySerie = (Byte*) malloc(3 * valuesPerSerie);
57 lengthRead = fread(binarySerie, 1, 3*valuesPerSerie, ifile);
58 if (lengthRead != 3*valuesPerSerie)
59 fprintf(stderr,"Warning: deserializing truncated binary file.\n");
60 for (uint32_t i = 0; i < valuesPerSerie; i++)
61 {
62 uint32_t powerInt = bInt_to_uint(binarySerie + 3 * i, 3);
63 if (ofile)
64 {
65 fprintf(ofile, "%g", powerInt / 10.0 - 0.0);
66 if (i < valuesPerSerie-1)
67 fprintf(ofile, ",");
68 }
69 else
70 powerCurve->values[i] = powerInt / 10.0 - 0.0;
71 }
72 free(binarySerie);
73 if (ofile)
74 fprintf(ofile, "\n");
75 }
76
77 fclose(ifile);
78 if (ofile)
79 fclose(ofile);
80
81 return powerCurves;
82 }