Bug Summary

File:OMCompiler/Compiler/runtime/SimulationResults_omc.c
Warning:line 170, column 18
Potential leak of memory pointed to by 'strToFind'

Annotated Source Code

[?] Use j/k keys for keyboard navigation

SimulationResults_omc.c

1/*
2 * This file is part of OpenModelica.
3 *
4 * Copyright (c) 1998-2010, Linköpings University,
5 * Department of Computer and Information Science,
6 * SE-58183 Linköping, Sweden.
7 *
8 * All rights reserved.
9 *
10 * THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THIS OSMC PUBLIC
11 * LICENSE (OSMC-PL). ANY USE, REPRODUCTION OR DISTRIBUTION OF
12 * THIS PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THE OSMC
13 * PUBLIC LICENSE.
14 *
15 * The OpenModelica software and the Open Source Modelica
16 * Consortium (OSMC) Public License (OSMC-PL) are obtained
17 * from Linköpings University, either from the above address,
18 * from the URL: http://www.ida.liu.se/projects/OpenModelica
19 * and in the OpenModelica distribution.
20 *
21 * This program is distributed WITHOUT ANY WARRANTY; without
22 * even the implied warranty of MERCHANTABILITY or FITNESS
23 * FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
24 * IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS
25 * OF OSMC-PL.
26 *
27 * See the full OSMC Public License conditions for more details.
28 *
29 */
30
31#if defined(_MSC_VER) || defined(__MINGW32__)
32 #define WIN32_LEAN_AND_MEAN
33 #include <windows.h>
34#endif
35
36#include <stdio.h>
37#include <stdlib.h>
38
39
40#include "meta_modelica.h"
41#define ADD_METARECORD_DEFINITIONSstatic static
42#include "OpenModelicaBootstrappingHeader.h"
43
44#include "SimulationResults.c"
45#include "SimulationResultsCmp.c"
46
47void* SimulationResults_readVariables(const char *filename, int readParameters, int omcStyle)
48{
49 return SimulationResultsImpl__readVars(filename, readParameters, omcStyle, &simresglob);
50}
51
52extern void* _ValuesUtil_reverseMatrix(void*);
53void* SimulationResults_readDataset(const char *filename, void *vars, int datasize)
54{
55 void *res = SimulationResultsImpl__readDataset(filename,vars,datasize,0,&simresglob,0);
56 if (res == NULL((void*)0)) MMC_THROW(){longjmp(*((threadData_t*)pthread_getspecific(mmc_thread_data_key
))->mmc_jumper,1);}
;
57 return res;
58}
59
60int SimulationResults_readSimulationResultSize(const char *filename)
61{
62 return SimulationResultsImpl__readSimulationResultSize(filename,&simresglob);
63}
64
65double SimulationResults_val(const char *filename, const char *varname, double timeStamp)
66{
67 return SimulationResultsImpl__val(filename,varname,timeStamp,&simresglob);
1
Calling 'SimulationResultsImpl__val'
68}
69
70void* SimulationResults_cmpSimulationResults(int runningTestsuite, const char *filename,const char *reffilename,const char *logfilename, double refTol, double absTol, void *vars)
71{
72 return SimulationResultsCmp_compareResults(1,runningTestsuite,filename,reffilename,logfilename,refTol,absTol,0,0,vars,0,NULL((void*)0),0,NULL((void*)0));
73}
74
75double SimulationResults_deltaSimulationResults(const char *filename,const char *reffilename, const char *methodname, void *vars)
76{
77 double res = SimulationResultsCmp_deltaResults(filename,reffilename,methodname,vars);
78 return res;
79}
80
81void* SimulationResults_diffSimulationResults(int runningTestsuite, const char *filename,const char *reffilename,const char *logfilename, double refTol, double reltolDiffMaxMin, double rangeDelta, void *vars, int keepEqualResults, int *success)
82{
83 return SimulationResultsCmp_compareResults(0,runningTestsuite,filename,reffilename,logfilename,refTol,0,reltolDiffMaxMin,rangeDelta,vars,keepEqualResults,success,0,NULL((void*)0));
84}
85
86const char* SimulationResults_diffSimulationResultsHtml(int runningTestsuite, const char *var, const char *filename,const char *reffilename, double refTol, double reltolDiffMaxMin, double rangeDelta)
87{
88 char *res = "";
89 SimulationResultsCmp_compareResults(0,runningTestsuite,filename,reffilename,"",0,refTol,reltolDiffMaxMin,rangeDelta,mmc_mk_cons(mmc_mk_scon(var),mmc_mk_nil()((void*)((char*)(&(mmc_nil).header) + 3))),0,NULL((void*)0),1,&res);
90 return res;
91}
92
93void SimulationResults_close()
94{
95 SimulationResultsImpl__close(&simresglob);
96}

./SimulationResults.c

1#include "read_matlab4.h"
2#include "write_matlab4.h"
3#include <stdint.h>
4#include <string.h>
5#include "errorext.h"
6#include "systemimpl.h"
7#include "ptolemyio.h"
8#include "read_csv.h"
9#include <math.h>
10#include <gc.h>
11#include "omc_file.h"
12#include "omc_msvc.h" /* For INFINITY and NAN */
13#include <time.h>
14#include <sys/types.h>
15#include <sys/stat.h>
16
17#if defined(__MINGW32__) || defined(_MSC_VER)
18#define stat _stat
19#endif
20
21#if defined(_MSC_VER)
22#define fmax(x, y) ((x>y)?x:y)
23#define fmin(x, y) ((x<y)?x:y)
24#define snprintf sprintf_s
25#endif
26
27typedef enum {
28 UNKNOWN_PLOT=0,
29 MATLAB4,
30 PLT,
31 CSV
32} PlotFormat;
33const char *PlotFormatStr[] = {"Unknown","MATLAB4","PLT","CSV"};
34
35typedef struct {
36 PlotFormat curFormat;
37 char *curFileName;
38 time_t mtime;
39 ModelicaMatReader matReader;
40 FILE *pltReader;
41 struct csv_data *csvReader;
42} SimulationResult_Globals;
43
44static SimulationResult_Globals simresglob = {
45 UNKNOWN_PLOT,
46 0
47};
48
49static void SimulationResultsImpl__close(SimulationResult_Globals* simresglob)
50{
51 switch (simresglob->curFormat) {
52 case MATLAB4: omc_free_matlab4_reader(&simresglob->matReader); break;
53 case PLT: fclose(simresglob->pltReader); break;
54 case CSV: omc_free_csv_reader(simresglob->csvReader); simresglob->csvReader=NULL((void*)0); break;
55 default: break;
56 }
57 simresglob->curFormat = UNKNOWN_PLOT;
58 if (simresglob->curFileName) free(simresglob->curFileName);
59 simresglob->curFileName = NULL((void*)0);
60}
61
62static PlotFormat SimulationResultsImpl__openFile(const char *filename, SimulationResult_Globals* simresglob)
63{
64 PlotFormat format;
65 int len = strlen(filename);
66 const char *msg[] = {"",""};
67#if defined(__MINGW32__) || defined(_MSC_VER)
68 struct _stat buf;
69#else
70 struct stat buf = {0} /* Zero this or valgrind complains */;
71#endif
72
73 if (simresglob->curFileName && 0==strcmp(filename,simresglob->curFileName)) {
74 /* Also check that the file was not modified */
75 if (omc_stat(filename, &buf)==0 && difftime(buf.st_mtimest_mtim.tv_sec,simresglob->mtime)==0.0) {
76 return simresglob->curFormat; // Super cache :)
77 }
78 }
79 // Start by closing the old file...
80 SimulationResultsImpl__close(simresglob);
81
82 if (len < 5) format = UNKNOWN_PLOT;
83 else if (0 == strcmp(filename+len-4, ".mat")) format = MATLAB4;
84 else if (0 == strcmp(filename+len-4, ".plt")) format = PLT;
85 else if (0 == strcmp(filename+len-4, ".csv")) format = CSV;
86 else {
87 msg[0] = filename;
88 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("Unknown result-file suffix of file '%s'")dcgettext (((void*)0), "Unknown result-file suffix of file '%s'"
, 5)
, msg, 1);
89 format = UNKNOWN_PLOT;
90 }
91 switch (format) {
92 case MATLAB4:
93 if (0!=(msg[0]=omc_new_matlab4_reader(filename,&simresglob->matReader))) {
94 msg[1] = filename;
95 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("Failed to open simulation result %s: %s")dcgettext (((void*)0), "Failed to open simulation result %s: %s"
, 5)
, msg, 2);
96 return UNKNOWN_PLOT;
97 }
98 break;
99 case PLT:
100 simresglob->pltReader = omc_fopen(filename, "r");
101 if (simresglob->pltReader==NULL((void*)0)) {
102 msg[1] = filename;
103 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("Failed to open simulation result %s: %s")dcgettext (((void*)0), "Failed to open simulation result %s: %s"
, 5)
, msg, 2);
104 return UNKNOWN_PLOT;
105 }
106 break;
107 case CSV:
108 simresglob->csvReader = read_csv(filename);
109 if (simresglob->csvReader==NULL((void*)0)) {
110 msg[1] = filename;
111 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("Failed to open simulation result %s: %s")dcgettext (((void*)0), "Failed to open simulation result %s: %s"
, 5)
, msg, 2);
112 return UNKNOWN_PLOT;
113 }
114 break;
115 default:
116 msg[0] = filename;
117 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("Failed to open simulation result %s")dcgettext (((void*)0), "Failed to open simulation result %s",
5)
, msg, 1);
118 return UNKNOWN_PLOT;
119 }
120
121 simresglob->curFormat = format;
122 simresglob->curFileName = strdup(filename);
123#if !defined(__MINGW32__) && !defined(_MSC_VER)
124 stat(filename, &buf);
125 simresglob->mtime = buf.st_mtimest_mtim.tv_sec;
126#endif
127 // fprintf(stderr, "SimulationResultsImpl__openFile(%s) => %s\n", filename, PlotFormatStr[curFormat]);
128 return simresglob->curFormat;
129}
130
131static double SimulationResultsImpl__val(const char *filename, const char *varname, double timeStamp, SimulationResult_Globals* simresglob)
132{
133 double res;
134 const char *msg[4] = {"","","",""};
135 if (UNKNOWN_PLOT == SimulationResultsImpl__openFile(filename,simresglob)) {
2
Assuming the condition is false
3
Taking false branch
136 return NAN(__builtin_nanf (""));
137 }
138 switch (simresglob->curFormat) {
4
Control jumps to 'case PLT:' at line 161
139 case MATLAB4: {
140 ModelicaMatVariable_t *var;
141 if (0 == (var=omc_matlab4_find_var(&simresglob->matReader,varname))) {
142 msg[1] = varname;
143 msg[0] = filename;
144 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("%s not found in %s\n")dcgettext (((void*)0), "%s not found in %s\n", 5), msg, 2);
145 return NAN(__builtin_nanf (""));
146 }
147 if (omc_matlab4_val(&res,&simresglob->matReader,var,timeStamp)) {
148 char buf[64],buf2[64],buf3[64];
149 snprintf(buf,60,"%g",timeStamp);
150 snprintf(buf2,60,"%g",omc_matlab4_startTime(&simresglob->matReader));
151 snprintf(buf3,60,"%g",omc_matlab4_stopTime(&simresglob->matReader));
152 msg[3] = varname;
153 msg[2] = buf;
154 msg[1] = buf2;
155 msg[0] = buf3;
156 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("%s not defined at time %s (startTime=%s, stopTime=%s).")dcgettext (((void*)0), "%s not defined at time %s (startTime=%s, stopTime=%s)."
, 5)
, msg, 4);
157 return NAN(__builtin_nanf (""));
158 }
159 return res;
160 }
161 case PLT: {
162 char *strToFind = (char*) malloc(strlen(varname)+30);
5
Memory is allocated
163 char line[255];
164 double pt,t,pv,v,w1,w2;
165 int nread=0;
166 sprintf(strToFind,"DataSet: %s\n",varname);
167 fseek(simresglob->pltReader,0,SEEK_SET0);
168 do {
169 if (NULL((void*)0)==fgets(line,255,simresglob->pltReader)) {
6
Taking true branch
170 msg[1] = varname;
7
Potential leak of memory pointed to by 'strToFind'
171 msg[0] = filename;
172 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("%s not found in %s\n")dcgettext (((void*)0), "%s not found in %s\n", 5), msg, 2);
173 return NAN(__builtin_nanf (""));
174 }
175 } while (strcmp(strToFind,line));
176 free(strToFind);
177 while (fscanf(simresglob->pltReader,"%lg, %lg\n",&t,&v) == 2) {
178 nread++;
179 if (t > timeStamp) break;
180 pt = t;
181 pv = v;
182 };
183 if (nread == 0 || nread == 1 || t < timeStamp) {
184 char buf[64];
185 snprintf(buf,60,"%g",timeStamp);
186 msg[1] = varname;
187 msg[0] = buf;
188 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("%s not defined at time %s\n")dcgettext (((void*)0), "%s not defined at time %s\n", 5), msg, 2);
189 return NAN(__builtin_nanf (""));
190 } else {
191 /* Linear interpolation */
192 if ((t-pt) == 0.0) return v;
193 w1 = (timeStamp - pt) / (t-pt);
194 w2 = 1.0 - w1;
195 return pv*w2 + v*w1;
196 }
197 }
198 default:
199 msg[0] = PlotFormatStr[simresglob->curFormat];
200 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("val() not implemented for plot format: %s\n")dcgettext (((void*)0), "val() not implemented for plot format: %s\n"
, 5)
, msg, 1);
201 return NAN(__builtin_nanf (""));
202 }
203}
204
205static int SimulationResultsImpl__readSimulationResultSize(const char *filename, SimulationResult_Globals* simresglob)
206{
207 const char *msg[2] = {"",""};
208 int size;
209 if (UNKNOWN_PLOT == SimulationResultsImpl__openFile(filename,simresglob)) {
210 return -1;
211 }
212 switch (simresglob->curFormat) {
213 case MATLAB4: {
214 return simresglob->matReader.nrows;
215 }
216 case PLT: {
217 size = read_ptolemy_dataset_size(filename);
218 msg[0] = filename;
219 if (size == -1) c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("Failed to read readSimulationResultSize from file: %s\n")dcgettext (((void*)0), "Failed to read readSimulationResultSize from file: %s\n"
, 5)
, msg, 1);
220 return size;
221 }
222 case CSV: {
223 size = simresglob->csvReader ? simresglob->csvReader->numsteps : -1;
224 msg[0] = filename;
225 if (size == -1) c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("Failed to read readSimulationResultSize from file: %s\n")dcgettext (((void*)0), "Failed to read readSimulationResultSize from file: %s\n"
, 5)
, msg, 1);
226 return size;
227 }
228 default:
229 msg[0] = PlotFormatStr[simresglob->curFormat];
230 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("readSimulationResultSize() not implemented for plot format: %s\n")dcgettext (((void*)0), "readSimulationResultSize() not implemented for plot format: %s\n"
, 5)
, msg, 1);
231 return -1;
232 }
233}
234
235static void* makeOMCStyle(const char *var, int omcStyle)
236{
237 char *res1 = NULL((void*)0);
238 const char *res2 = NULL((void*)0);
239 if (!omcStyle) {
240 return mmc_mk_scon(var);
241 }
242 res1 = openmodelicaStyleVariableName(var);
243 res2 = _replace(res1 ? res1 : var, " ", "");
244 if (res1 == NULL((void*)0)) {
245 free(res1);
246 }
247 return mmc_mk_scon(res2);
248}
249
250static void* SimulationResultsImpl__readVars(const char *filename, int readParameters, int omcStyle, SimulationResult_Globals* simresglob)
251{
252 const char *msg[2] = {"",""};
253 void *res;
254 if (UNKNOWN_PLOT == SimulationResultsImpl__openFile(filename,simresglob)) {
255 return mmc_mk_nil()((void*)((char*)(&(mmc_nil).header) + 3));
256 }
257 res = mmc_mk_nil()((void*)((char*)(&(mmc_nil).header) + 3));
258 switch (simresglob->curFormat) {
259 case MATLAB4: {
260 int i;
261 for (i=simresglob->matReader.nall-1; i>=0; i--) {
262 if (readParameters || !simresglob->matReader.allInfo[i].isParam) {
263 res = mmc_mk_cons(makeOMCStyle(simresglob->matReader.allInfo[i].name, omcStyle),res);
264 }
265 }
266 return res;
267 }
268 case PLT: {
269 return read_ptolemy_variables(filename /* Assume it is in OMC style */);
270 }
271 case CSV: {
272 if (simresglob->csvReader && simresglob->csvReader->variables) {
273 char **variables = simresglob->csvReader->variables;
274 int i;
275 for (i=simresglob->csvReader->numvars-1; i>=0; i--) {
276 if (variables[i][0] != '\0') {
277 res = mmc_mk_cons(makeOMCStyle(variables[i], omcStyle),res);
278 }
279 }
280 }
281 return res;
282 }
283 default:
284 msg[0] = PlotFormatStr[simresglob->curFormat];
285 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("readSimulationResultSize() not implemented for plot format: %s")dcgettext (((void*)0), "readSimulationResultSize() not implemented for plot format: %s"
, 5)
, msg, 1);
286 return mmc_mk_nil()((void*)((char*)(&(mmc_nil).header) + 3));
287 }
288}
289
290static void* SimulationResultsImpl__readVarsFilterAliases(const char *filename, SimulationResult_Globals* simresglob)
291{
292 if (UNKNOWN_PLOT == SimulationResultsImpl__openFile(filename,simresglob)) {
293 return mmc_mk_nil()((void*)((char*)(&(mmc_nil).header) + 3));
294 }
295 switch (simresglob->curFormat) {
296 case MATLAB4: {
297 void *res = mmc_mk_nil()((void*)((char*)(&(mmc_nil).header) + 3));
298 int i;
299 int *params = (int*) calloc(simresglob->matReader.nparam+1,sizeof(int));
300 int *vars = (int*) calloc(simresglob->matReader.nvar+1,sizeof(int));
301 for (i=simresglob->matReader.nall-1; i>=0; i--) {
302 if (0 >= simresglob->matReader.allInfo[i].index) continue; /* Negated aliases always have a real variable, so skip it */
303 if (simresglob->matReader.allInfo[i].isParam && params[simresglob->matReader.allInfo[i].index]) continue;
304 if (!simresglob->matReader.allInfo[i].isParam && vars[simresglob->matReader.allInfo[i].index]) continue;
305 if (simresglob->matReader.allInfo[i].isParam) {
306 params[simresglob->matReader.allInfo[i].index] = 1;
307 } else {
308 vars[simresglob->matReader.allInfo[i].index] = 1;
309 }
310 res = mmc_mk_cons(mmc_mk_scon(simresglob->matReader.allInfo[i].name),res);
311 }
312 free(params);
313 free(vars);
314 return res;
315 }
316 default: return SimulationResultsImpl__readVars(filename, 0, 0, simresglob);
317 }
318}
319
320static void* SimulationResultsImpl__readDataset(const char *filename, void *vars, int dimsize, int suggestReadAllVars, SimulationResult_Globals* simresglob, int runningTestsuite)
321{
322 const char *msg[2] = {"",""};
323 void *res,*col;
324 char *var;
325 double *vals;
326 int i;
327 if (UNKNOWN_PLOT == SimulationResultsImpl__openFile(filename,simresglob)) {
328 return NULL((void*)0);
329 }
330 res = mmc_mk_nil()((void*)((char*)(&(mmc_nil).header) + 3));
331 switch (simresglob->curFormat) {
332 case MATLAB4: {
333 ModelicaMatVariable_t *mat_var;
334 if (dimsize == 0) {
335 dimsize = simresglob->matReader.nrows;
336 } else if (simresglob->matReader.nrows != dimsize) {
337 fprintf(stderrstderr, "dimsize: %d, rows %d\n", dimsize, simresglob->matReader.nrows);
338 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("readDataset(...): Expected and actual dimension sizes do not match.")dcgettext (((void*)0), "readDataset(...): Expected and actual dimension sizes do not match."
, 5)
, NULL((void*)0), 0);
339 return NULL((void*)0);
340 }
341 if (suggestReadAllVars) {
342 omc_matlab4_read_all_vals(&simresglob->matReader);
343 }
344 while (MMC_NILHDR(((0) << 10) + (((0) & 255) << 2)) != MMC_GETHDR(vars)(*(mmc_uint_t*)((void*)((char*)(vars) - 3)))) {
345 var = MMC_STRINGDATA(MMC_CAR(vars))(((struct mmc_string*)((void*)((char*)((*(void**)(((void*)((void
**)(((void*)((char*)(vars) - 3))) + (1)))))) - 3)))->data)
;
346 vars = MMC_CDR(vars)(*(void**)(((void*)((void**)(((void*)((char*)(vars) - 3))) + (
2)))))
;
347 mat_var = omc_matlab4_find_var(&simresglob->matReader,var);
348 if (mat_var == NULL((void*)0)) {
349 msg[0] = runningTestsuite ? SystemImpl__basename(filename) : filename;
350 msg[1] = var;
351 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("Could not read variable %s in file %s.")dcgettext (((void*)0), "Could not read variable %s in file %s."
, 5)
, msg, 2);
352 return NULL((void*)0);
353 } else if (mat_var->isParam) {
354 col=mmc_mk_nil()((void*)((char*)(&(mmc_nil).header) + 3));
355 for (i=0;i<dimsize;i++) col=mmc_mk_cons(mmc_mk_rcon((mat_var->index<0)?-simresglob->matReader.params[abs(mat_var->index)-1]:simresglob->matReader.params[abs(mat_var->index)-1]),col);
356 res = mmc_mk_cons(col,res);
357 } else {
358 vals = omc_matlab4_read_vals(&simresglob->matReader,mat_var->index);
359 col=mmc_mk_nil()((void*)((char*)(&(mmc_nil).header) + 3));
360 for (i=0;i<dimsize;i++) col=mmc_mk_cons(mmc_mk_rcon(vals[i]),col);
361 res = mmc_mk_cons(col,res);
362 }
363 }
364 return res;
365 }
366 case PLT: {
367 return read_ptolemy_dataset(filename,vars,dimsize);
368 }
369 case CSV: {
370 while (MMC_NILHDR(((0) << 10) + (((0) & 255) << 2)) != MMC_GETHDR(vars)(*(mmc_uint_t*)((void*)((char*)(vars) - 3)))) {
371 var = MMC_STRINGDATA(MMC_CAR(vars))(((struct mmc_string*)((void*)((char*)((*(void**)(((void*)((void
**)(((void*)((char*)(vars) - 3))) + (1)))))) - 3)))->data)
;
372 vars = MMC_CDR(vars)(*(void**)(((void*)((void**)(((void*)((char*)(vars) - 3))) + (
2)))))
;
373 vals = simresglob->csvReader ? read_csv_dataset(simresglob->csvReader,var) : NULL((void*)0);
374 if (vals == NULL((void*)0)) {
375 msg[0] = runningTestsuite ? SystemImpl__basename(filename) : filename;
376 msg[1] = var;
377 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("Could not read variable %s in file %s.")dcgettext (((void*)0), "Could not read variable %s in file %s."
, 5)
, msg, 2);
378 return NULL((void*)0);
379 } else {
380 col=mmc_mk_nil()((void*)((char*)(&(mmc_nil).header) + 3));
381 for (i=0;i<dimsize;i++) {
382 col=mmc_mk_cons(mmc_mk_rcon(vals[i]),col);
383 }
384 res = mmc_mk_cons(col,res);
385 }
386 }
387 return res;
388 }
389 default:
390 msg[0] = PlotFormatStr[simresglob->curFormat];
391 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("readDataSet() not implemented for plot format: %s\n")dcgettext (((void*)0), "readDataSet() not implemented for plot format: %s\n"
, 5)
, msg, 1);
392 return NULL((void*)0);
393 }
394}
395
396static inline__inline__ int failedToWriteToFileImpl(const char *file, const char *sourceFile, const char *line)
397{
398 const char *msg[3] = {file,line,sourceFile};
399 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("%s:%s: Failed to write to file %s.")dcgettext (((void*)0), "%s:%s: Failed to write to file %s.", 5
)
, msg, 3);
400 return 0;
401}
402
403#define STR_HELPER(x)"x" #x
404#define STR(x)"x" STR_HELPER(x)"x"
405#define failedToWriteToFile(file)failedToWriteToFileImpl(file, "./SimulationResults.c", "405") failedToWriteToFileImpl(file, __FILE__"./SimulationResults.c", STR(__LINE__)"405")
406
407
408static inline__inline__ int intMax(int a, int b)
409{
410 return a>b ? a : b;
411}
412
413static int endsWith(const char *s, const char *suffix)
414{
415 s = strrchr(s, *suffix);
416 if (s != NULL((void*)0)) {
417 return 0==strcmp(s, suffix);
418 } else {
419 return 0;
420 }
421}
422int SimulationResults_filterSimulationResults(const char *inFile, const char *outFile, void *vars, int numberOfIntervals, int removeDescription)
423{
424 const char *msg[5] = {"","","","",""};
425 void *tmp;
426 if (UNKNOWN_PLOT == SimulationResultsImpl__openFile(inFile, &simresglob)) {
427 return 0;
428 }
429 vars = mmc_mk_cons(mmc_mk_scon("time"),vars);
430 switch (simresglob.curFormat) {
431 case MATLAB4: {
432 int numToFilter = listLength(vars);
433 int i, j;
434 int numUnique = 0;
435 int numUniqueParam = 1;
436 int longestName = 0;
437 int longestDesc = 0;
438 ModelicaMatVariable_t **mat_var = omc_alloc_interface.malloc(numToFilter*sizeof(ModelicaMatVariable_t*));
439 int *indexes = (int*) omc_alloc_interface.malloc(simresglob.matReader.nvar*sizeof(int)); /* Need it to be zeros; note that the actual number of indexes is smaller */
440 int *parameter_indexes = (int*) omc_alloc_interface.malloc(simresglob.matReader.nparam*sizeof(int)); /* Need it to be zeros; note that the actual number of indexes is smaller */
441 int *indexesToOutput = NULL((void*)0);
442 int *parameter_indexesToOutput = NULL((void*)0);
443 FILE *fout = NULL((void*)0);
444 char *tmp;
445 double start = omc_matlab4_startTime(&simresglob.matReader);
446 double stop = omc_matlab4_stopTime(&simresglob.matReader);
447 double start_stop[2] = {start, stop};
448 parameter_indexes[0] = 1; /* time */
449 omc_matlab4_read_all_vals(&simresglob.matReader);
450 if (endsWith(outFile,".csv")) {
451 double **vals = omc_alloc_interface.malloc(sizeof(double*)*numToFilter);
452 FILE *fout = NULL((void*)0);
453 for (i=0; i<numToFilter; i++) {
454 const char *var = MMC_STRINGDATA(MMC_CAR(vars))(((struct mmc_string*)((void*)((char*)((*(void**)(((void*)((void
**)(((void*)((char*)(vars) - 3))) + (1)))))) - 3)))->data)
;
455 vars = MMC_CDR(vars)(*(void**)(((void*)((void**)(((void*)((char*)(vars) - 3))) + (
2)))))
;
456 mat_var[i] = omc_matlab4_find_var(&simresglob.matReader, var);
457 if (mat_var[i] == NULL((void*)0)) {
458 msg[0] = SystemImpl__basename(inFile);
459 msg[1] = var;
460 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("Could not read variable %s in file %s.")dcgettext (((void*)0), "Could not read variable %s in file %s."
, 5)
, msg, 2);
461 return 0;
462 }
463 if (mat_var[i]->isParam) {
464 msg[0] = var;
465 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("Could not filter parameter %s since the output format is CSV (only variables are allowed).")dcgettext (((void*)0), "Could not filter parameter %s since the output format is CSV (only variables are allowed)."
, 5)
, msg, 1);
466 return 0;
467 } else {
468 vals[i] = omc_matlab4_read_vals(&simresglob.matReader, mat_var[i]->index);
469 }
470 }
471 fout = fopen(outFile, "w");
472 fprintf(fout, "time");
473 for (i=1; i<numToFilter; i++) {
474 fprintf(fout, ",\"%s\"", mat_var[i]->name);
475 }
476 fprintf(fout, ",nrows=%d\n", simresglob.matReader.nrows);
477 for (i=0; i<simresglob.matReader.nrows; i++) {
478 fprintf(fout, "%.15g", vals[0][i]);
479 for (j=1; j<numToFilter; j++) {
480 fprintf(fout, ",%.15g", vals[j][i]);
481 }
482 fprintf(fout, "\n");
483 }
484 fclose(fout);
485 return 1;
486 } /* Not CSV */
487
488 for (i=0; i<numToFilter; i++) {
489 const char *var = MMC_STRINGDATA(MMC_CAR(vars))(((struct mmc_string*)((void*)((char*)((*(void**)(((void*)((void
**)(((void*)((char*)(vars) - 3))) + (1)))))) - 3)))->data)
;
490 vars = MMC_CDR(vars)(*(void**)(((void*)((void**)(((void*)((char*)(vars) - 3))) + (
2)))))
;
491 mat_var[i] = omc_matlab4_find_var(&simresglob.matReader,var);
492 if (mat_var[i] == NULL((void*)0)) {
493 msg[0] = SystemImpl__basename(inFile);
494 msg[1] = var;
495 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("Could not read variable %s in file %s.")dcgettext (((void*)0), "Could not read variable %s in file %s."
, 5)
, msg, 2);
496 return 0;
497 }
498 if (mat_var[i]->isParam) {
499 /* Store the old index in the array */
500 if (0==parameter_indexes[abs(mat_var[i]->index)-1]++) {
501 numUniqueParam++;
502 }
503 } else {
504 /* Store the old index in the array */
505 if (0==indexes[abs(mat_var[i]->index)-1]++) {
506 numUnique++;
507 }
508 }
509 longestName = intMax(longestName, strlen(mat_var[i]->name));
510 longestDesc = intMax(longestDesc, strlen(mat_var[i]->descr));
511 }
512 /* Create the list of variable indexes to output */
513 indexesToOutput = omc_alloc_interface.malloc_atomic(numUnique * sizeof(int));
514 parameter_indexesToOutput = omc_alloc_interface.malloc_atomic(numUniqueParam * sizeof(int));
515 j=0;
516 for (i=0; i<simresglob.matReader.nvar; i++) {
517 if (indexes[i]) {
518 indexesToOutput[j++] = i+1;
519 }
520 /* indexes becomes the lookup table from old index to new index */
521 indexes[i] = j;
522 }
523 j=0;
524 for (i=0; i<simresglob.matReader.nparam; i++) {
525 if (parameter_indexes[i]) {
526 parameter_indexesToOutput[j++] = i+1;
527 }
528 /* indexes becomes the lookup table from old index to new index */
529 parameter_indexes[i] = j;
530 }
531 fout = fopen(outFile, "wb");
532 if (fout == NULL((void*)0)) {
533 return failedToWriteToFile(outFile)failedToWriteToFileImpl(outFile, "./SimulationResults.c", "533"
)
;
534 }
535 /* Matrix list: "Aclass" "name" "description" "dataInfo" "data_1" "data_2" */
536 if (writeMatVer4AclassNormal(fout)) {
537 return failedToWriteToFile(outFile)failedToWriteToFileImpl(outFile, "./SimulationResults.c", "537"
)
;
538 }
539 if (writeMatVer4MatrixHeader(fout, "name", numToFilter, longestName, sizeof(int8_t))) {
540 return failedToWriteToFile(outFile)failedToWriteToFileImpl(outFile, "./SimulationResults.c", "540"
)
;
541 }
542
543 tmp = omc_alloc_interface.malloc(numToFilter*longestName);
544 for (i=0; i<numToFilter; i++) {
545 int len = strlen(mat_var[i]->name);
546 for (j=0; j<len; j++) {
547 tmp[numToFilter*j+i] = mat_var[i]->name[j];
548 }
549 }
550 if (1 != fwrite(tmp, numToFilter*longestName, 1, fout)) {
551 return failedToWriteToFile(outFile)failedToWriteToFileImpl(outFile, "./SimulationResults.c", "551"
)
;
552 }
553 GC_free(tmp);
554
555 if (removeDescription) {
556 if (writeMatVer4MatrixHeader(fout, "description", numToFilter, 0, sizeof(int8_t))) {
557 return failedToWriteToFile(outFile)failedToWriteToFileImpl(outFile, "./SimulationResults.c", "557"
)
;
558 }
559 } else {
560 if (writeMatVer4MatrixHeader(fout, "description", numToFilter, longestDesc, sizeof(int8_t))) {
561 return failedToWriteToFile(outFile)failedToWriteToFileImpl(outFile, "./SimulationResults.c", "561"
)
;
562 }
563
564 tmp = omc_alloc_interface.malloc(numToFilter*longestDesc);
565 for (i=0; i<numToFilter; i++) {
566 int len = strlen(mat_var[i]->descr);
567 for (j=0; j<len; j++) {
568 tmp[numToFilter*j+i] = mat_var[i]->descr[j];
569 }
570 }
571 if (1 != fwrite(tmp, numToFilter*longestDesc, 1, fout)) {
572 return failedToWriteToFile(outFile)failedToWriteToFileImpl(outFile, "./SimulationResults.c", "572"
)
;
573 }
574 GC_free(tmp);
575 }
576
577 if (writeMatVer4MatrixHeader(fout, "dataInfo", numToFilter, 4, sizeof(int32_t))) {
578 return failedToWriteToFile(outFile)failedToWriteToFileImpl(outFile, "./SimulationResults.c", "578"
)
;
579 }
580 for (i=0; i<numToFilter; i++) {
581 int32_t x = mat_var[i]->isParam ? 1 : 2; /* data_1 or data_2 */
582 if (1 != fwrite(&x, sizeof(int32_t), 1, fout)) {
583 return failedToWriteToFile(outFile)failedToWriteToFileImpl(outFile, "./SimulationResults.c", "583"
)
;
584 }
585 }
586 for (i=0; i<numToFilter; i++) {
587 int32_t x = (mat_var[i]->index < 0 ? -1 : 1) * (mat_var[i]->isParam ? parameter_indexes[abs(mat_var[i]->index)-1] : indexes[abs(mat_var[i]->index)-1]);
588 if (1 != fwrite(&x, sizeof(int32_t), 1, fout)) {
589 return failedToWriteToFile(outFile)failedToWriteToFileImpl(outFile, "./SimulationResults.c", "589"
)
;
590 }
591 }
592 for (i=0; i<numToFilter; i++) {
593 int32_t x = 0; /* linear interpolation */
594 if (1 != fwrite(&x, sizeof(int32_t), 1, fout)) {
595 return failedToWriteToFile(outFile)failedToWriteToFileImpl(outFile, "./SimulationResults.c", "595"
)
;
596 }
597 }
598 for (i=0; i<numToFilter; i++) {
599 int32_t x = -1; /* not defined outside the time interval */
600 if (1 != fwrite(&x, sizeof(int32_t), 1, fout)) {
601 return failedToWriteToFile(outFile)failedToWriteToFileImpl(outFile, "./SimulationResults.c", "601"
)
;
602 }
603 }
604
605 if (writeMatVer4MatrixHeader(fout, "data_1", 2, numUniqueParam, sizeof(double))) {
606 return failedToWriteToFile(outFile)failedToWriteToFileImpl(outFile, "./SimulationResults.c", "606"
)
;
607 }
608
609 if (1 != fwrite(start_stop, sizeof(double)*2, 1, fout)) {
610 return failedToWriteToFile(outFile)failedToWriteToFileImpl(outFile, "./SimulationResults.c", "610"
)
;
611 }
612
613 for (i=1; i<numUniqueParam; i++) {
614 int paramIndex = parameter_indexesToOutput[i];
615 double d[2] = {simresglob.matReader.params[abs(paramIndex)-1],0};
616 d[1] = d[0];
617 if (1!=fwrite(d, sizeof(double)*2, 1, fout)) {
618 return failedToWriteToFile(outFile)failedToWriteToFileImpl(outFile, "./SimulationResults.c", "618"
)
;
619 }
620 }
621
622 if (numberOfIntervals) {
623 double *timevals = omc_matlab4_read_vals(&simresglob.matReader, 1);
624 int last_found=0;
625 int nevents=0, neventpoints=0;
626 for (i=1; i<numberOfIntervals; i++) {
627 double t = start + (stop-start)*((double)i)/numberOfIntervals;
628 while (timevals[j]<=t) {
629 if (timevals[j]==timevals[j+1]) {
630 while (timevals[j]==timevals[j+1]) {
631 j++;
632 neventpoints++;
633 }
634 nevents++;
635 }
636 j++;
637 }
638 }
639 msg[4] = inFile;
640 GC_asprintf(msg+3, "%d", simresglob.matReader.nrows);
641 GC_asprintf(msg+2, "%d", numberOfIntervals);
642 GC_asprintf(msg+1, "%d", nevents);
643 GC_asprintf(msg+0, "%d", neventpoints);
644 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_notification, gettext("Resampling %s from %s points to %s points, removing %s events stored in %s points.\n")dcgettext (((void*)0), "Resampling %s from %s points to %s points, removing %s events stored in %s points.\n"
, 5)
, msg, 5);
645 }
646
647 if (writeMatVer4MatrixHeader(fout, "data_2", numberOfIntervals ? numberOfIntervals+1 : simresglob.matReader.nrows, numUnique, sizeof(double))) {
648 return failedToWriteToFile(outFile)failedToWriteToFileImpl(outFile, "./SimulationResults.c", "648"
)
;
649 }
650 for (i=0; i<numUnique; i++) {
651 double *vals = NULL((void*)0);
652 int nrows;
653 if (numberOfIntervals) {
654 omc_matlab4_read_all_vals(&simresglob.matReader);
655 nrows = numberOfIntervals+1;
656 vals = omc_alloc_interface.malloc_atomic(sizeof(double)*nrows);
657 for (j=0; j<=numberOfIntervals; j++) {
658 double t = j==numberOfIntervals ? stop : start + (stop-start)*((double)j)/numberOfIntervals;
659 ModelicaMatVariable_t var = {0};
660 var.name="";
661 var.descr="";
662 var.isParam=0;
663 var.index=indexesToOutput[i];
664 if (omc_matlab4_val(vals+j, &simresglob.matReader, &var, t)) {
665 msg[2] = inFile;
666 GC_asprintf(msg+1, "%d", indexesToOutput[i]);
667 GC_asprintf(msg+0, "%.15g", t);
668 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("Resampling %s failed to get variable %s at time %s.\n")dcgettext (((void*)0), "Resampling %s failed to get variable %s at time %s.\n"
, 5)
, msg, 3);
669 return 0;
670 }
671 }
672 } else {
673 vals = omc_matlab4_read_vals(&simresglob.matReader, indexesToOutput[i]);
674 nrows = simresglob.matReader.nrows;
675 }
676 if (nrows > 0) {
677 if (1!=fwrite(vals, sizeof(double)*nrows, 1, fout)) {
678 fprintf(stderrstderr, "nrows=%d\n", nrows);
679 return failedToWriteToFile(outFile)failedToWriteToFileImpl(outFile, "./SimulationResults.c", "679"
)
;
680 }
681 }
682 if (numberOfIntervals) {
683 GC_free(vals);
684 }
685 }
686 fclose(fout);
687 return 1;
688 }
689 default:
690 msg[0] = PlotFormatStr[simresglob.curFormat];
691 c_add_message(NULL((void*)0),-1, ErrorType_scripting, ErrorLevel_error, gettext("filterSimulationResults not implemented for plot format: %s\n")dcgettext (((void*)0), "filterSimulationResults not implemented for plot format: %s\n"
, 5)
, msg, 1);
692 return 0;
693 }
694}