-
Notifications
You must be signed in to change notification settings - Fork 297
/
PlotWindow.cpp
2319 lines (2190 loc) · 82.3 KB
/
PlotWindow.cpp
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of OpenModelica.
*
* Copyright (c) 1998-CurrentYear, Open Source Modelica Consortium (OSMC),
* c/o Linköpings universitet, Department of Computer and Information Science,
* SE-58183 Linköping, Sweden.
*
* All rights reserved.
*
* THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 LICENSE OR
* THIS OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3,
* ACCORDING TO RECIPIENTS CHOICE.
*
* The OpenModelica software and the Open Source Modelica
* Consortium (OSMC) Public License (OSMC-PL) are obtained
* from OSMC, either from the above address,
* from the URLs: http://www.ida.liu.se/projects/OpenModelica or
* http://www.openmodelica.org, and in the OpenModelica distribution.
* GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html.
*
* This program is distributed WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
* IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL.
*
* See the full OSMC Public License conditions for more details.
*
*/
#include <iostream>
#include <memory>
#include "PlotWindow.h"
#include "LogScaleEngine.h"
#include "LinearScaleEngine.h"
#include "qwt_plot_layout.h"
#if QWT_VERSION >= 0x060000
#include "qwt_plot_renderer.h"
#endif
#include "qwt_scale_draw.h"
#include "qwt_scale_widget.h"
#include "qwt_text_label.h"
#include "qwt_abstract_legend.h"
#include <QtSvg/QSvgGenerator>
#include <QToolBar>
#include <QFileInfo>
#include <QLayout>
#include <QCloseEvent>
#include <QDir>
#include <QMessageBox>
#include <QFileDialog>
#include <QPrinter>
#include <QPrintDialog>
#include <QLineEdit>
#include <QColorDialog>
using namespace OMPlot;
PlotWindow::PlotWindow(QStringList arguments, QWidget *parent, bool isInteractiveSimulation)
: QMainWindow(parent), mIsInteractiveSimulation(isInteractiveSimulation)
{
/* set the widget background white. so that the plot is more useable in books and publications. */
QPalette p(palette());
p.setColor(QPalette::Window, Qt::white);
setAutoFillBackground(true);
setPalette(p);
// setup the main window widget
setUpWidget();
// Keep default legend font since greek-mu for micro is not displayed correctly with monospaced font.
setLegendFont(mpPlot->legend()->font());
// initialize plot by reading all parameters passed to it
if (arguments.size() > 1) {
initializePlot(arguments);
mpPlot->getPlotZoomer()->setZoomBase(false);
}
// set qwtplot the central widget
setCentralWidget(getPlot());
}
PlotWindow::~PlotWindow()
{
}
void PlotWindow::setUpWidget()
{
// create an instance of qwt plot
mpPlot = new Plot(this);
// set up the toolbar
setupToolbar();
// set the default values
// set the plot title
setTitle(tr("Plot by OpenModelica"));
// set the plot grid
setGrid("simple");
}
void PlotWindow::initializePlot(QStringList arguments)
{
// open the file
initializeFile(QString(arguments[1]));
//Set up arguments
setTitle(QString(arguments[2]));
setGrid(QString(arguments[3]));
QString plotType = arguments[4];
if (QString(arguments[5]) == "true") {
setLogX(true);
} else if (QString(arguments[5]) == "false") {
setLogX(false);
} else {
throw PlotException("Invalid input" + arguments[5]);
}
if (QString(arguments[6]) == "true") {
setLogY(true);
} else if (QString(arguments[6]) == "false") {
setLogY(false);
} else {
throw PlotException("Invalid input" + arguments[6]);
}
setXLabel(QString(arguments[7]));
setYLabel(QString(arguments[8]));
setXCustomLabel(getXLabel());
setYCustomLabel(getYLabel());
setXUnit("");
setXDisplayUnit("");
setYUnit("");
setYDisplayUnit("");
setXRange(QString(arguments[9]).toDouble(), QString(arguments[10]).toDouble());
setYRange(QString(arguments[11]).toDouble(), QString(arguments[12]).toDouble());
setCurveWidth(QString(arguments[13]).toDouble());
setCurveStyle(QString(arguments[14]).toInt());
setLegendPosition(QString(arguments[15]));
setFooter(QString(arguments[16]));
if (QString(arguments[17]) == "true") {
setAutoScale(true);
} else if (QString(arguments[17]) == "false") {
setAutoScale(false);
} else {
throw PlotException("Invalid input" + arguments[17]);
}
setTimeUnit("");
setPrefixUnits(true);
setCanUseXPrefixUnits(false);
setCanUseYPrefixUnits(false);
/* read variables */
QStringList variablesToRead;
for(int i = 18; i < arguments.length(); i++)
variablesToRead.append(QString(arguments[i]));
setVariablesList(variablesToRead);
//Plot
if(plotType.toLower().compare("plot") == 0)
{
setPlotType(PlotWindow::PLOT);
plot();
}
else if(plotType.toLower().compare("plotall") == 0)
{
setPlotType(PlotWindow::PLOTALL);
plot();
}
else if(plotType.toLower().compare("plotparametric") == 0)
{
setPlotType(PlotWindow::PLOTPARAMETRIC);
plotParametric();
}
else if (plotType.toLower().compare("plotinteractive") == 0)
{
setPlotType(PlotWindow::PLOTINTERACTIVE);
plotInteractive();
}
}
void PlotWindow::setVariablesList(QStringList variables)
{
mVariablesList = variables;
}
void PlotWindow::setPlotType(PlotType type)
{
mPlotType = type;
}
PlotWindow::PlotType PlotWindow::getPlotType()
{
return mPlotType;
}
void PlotWindow::initializeFile(QString file)
{
mFile.setFileName(file);
if (!mFile.exists()) {
throw NoFileException(QString("File not found : ").append(file).toStdString().c_str());
}
}
void PlotWindow::getStartStopTime(double &start, double &stop){
//PLOT PLT
if (mFile.fileName().endsWith("plt"))
{
QString currentLine;
// open the file
mFile.open(QIODevice::ReadOnly);
mpTextStream = new QTextStream(&mFile);
// read the interval size from the file
int intervalSize = 0;
while (!mpTextStream->atEnd())
{
currentLine = mpTextStream->readLine();
if (currentLine.startsWith("#IntervalSize"))
{
intervalSize = static_cast<QString>(currentLine.split("=").last()).toInt();
break;
}
}
// Read start and stop time
while (!mpTextStream->atEnd())
{
currentLine = mpTextStream->readLine();
QString currentVariable;
if (currentLine.contains("DataSet:"))
{
currentVariable = currentLine.remove("DataSet: ");
if (currentVariable == "time")
{
// read the variable values now
currentLine = mpTextStream->readLine();
QStringList values = currentLine.split(",");
start = QString(values[0]).toDouble();
for(int j = 0; j < intervalSize-1; j++)
{
currentLine = mpTextStream->readLine();
}
values = currentLine.split(",");
stop = QString(values[0]).toDouble();
break;
}
}
}
if(mpTextStream->atEnd()) throw NoVariableException("Variable doesnt exist: time");
// close the file
mFile.close();
}
//PLOT CSV
else if (mFile.fileName().endsWith("csv"))
{
/* open the file */
struct csv_data *csvReader;
csvReader = read_csv(mFile.fileName().toStdString().c_str());
if (csvReader == NULL) {
throw NoVariableException("Variable doesnt exist: time");
}
//Read in timevector
double *timeVals = read_csv_dataset(csvReader, "time");
if (timeVals == NULL) {
omc_free_csv_reader(csvReader);
throw NoVariableException("Variable doesnt exist: time");
}
start = timeVals[0];
stop = timeVals[csvReader->numsteps-1];
// close the file
omc_free_csv_reader(csvReader);
}
//PLOT MAT
else if(mFile.fileName().endsWith("mat"))
{
ModelicaMatReader reader;
const char *msg = "";
//Read in mat file
if(0 != (msg = omc_new_matlab4_reader(mFile.fileName().toStdString().c_str(), &reader))) {
throw PlotException(msg);
}
//Read in timevector
start = omc_matlab4_startTime(&reader);
stop = omc_matlab4_stopTime(&reader);
// close the file
omc_free_matlab4_reader(&reader);
} else {throw PlotException(tr("Failed to open simulation result file %1").arg(mFile.fileName()));}
}
void PlotWindow::setupToolbar()
{
QToolBar *toolBar = new QToolBar(this);
setContextMenuPolicy(Qt::NoContextMenu);
// Interactive Simulation
if (mIsInteractiveSimulation) {
//start tool button
mpStartSimulationToolButton = new QToolButton;
mpStartSimulationToolButton->setText(tr("Start"));
mpStartSimulationToolButton->setIcon(QIcon(":/Resources/icons/play_animation.svg"));
mpStartSimulationToolButton->setToolTip(tr("Start"));
mpStartSimulationToolButton->setAutoRaise(true);
connect(mpStartSimulationToolButton, SIGNAL(clicked(bool)), SLOT(interactiveSimulationStarted()));
// pause tool button
mpPauseSimulationToolButton = new QToolButton;
mpPauseSimulationToolButton->setEnabled(false);
mpPauseSimulationToolButton->setText(tr("Pause"));
mpPauseSimulationToolButton->setIcon(QIcon(":/Resources/icons/pause.svg"));
mpPauseSimulationToolButton->setToolTip(tr("Pause"));
mpPauseSimulationToolButton->setAutoRaise(true);
connect(mpPauseSimulationToolButton, SIGNAL(clicked(bool)), SLOT(interactiveSimulationPaused()));
// speed label and combo box
mpSimulationSpeedLabel = new QLabel(tr("Speed:"));
QDoubleValidator *pDoubleValidator = new QDoubleValidator(this);
pDoubleValidator->setBottom(0.01);
pDoubleValidator->setTop(100);
mpSimulationSpeedComboBox = new QComboBox;
mpSimulationSpeedComboBox->setEditable(true);
mpSimulationSpeedComboBox->addItems(QStringList() << "10" << "5" << "2" << "1" << "0.5" << "0.2" << "0.1");
mpSimulationSpeedComboBox->setCurrentIndex(3);
mpSimulationSpeedComboBox->setCompleter(0);
mpSimulationSpeedComboBox->setValidator(pDoubleValidator);
// add the interactive controls
toolBar->addWidget(mpStartSimulationToolButton);
toolBar->addSeparator();
toolBar->addWidget(mpPauseSimulationToolButton);
toolBar->addSeparator();
toolBar->addWidget(mpSimulationSpeedLabel);
toolBar->addWidget(mpSimulationSpeedComboBox);
toolBar->addSeparator();
}
// Auto scale
mpAutoScaleButton = new QToolButton(toolBar);
QString autoScale(tr("Auto Scale"));
mpAutoScaleButton->setText(autoScale);
mpAutoScaleButton->setToolTip(autoScale);
mpAutoScaleButton->setStatusTip(autoScale);
mpAutoScaleButton->setIcon(QIcon(":/Resources/icons/auto_scale.svg"));
mpAutoScaleButton->setCheckable(true);
connect(mpAutoScaleButton, SIGNAL(toggled(bool)), SLOT(setAutoScale(bool)));
toolBar->addWidget(mpAutoScaleButton);
toolBar->addSeparator();
//Fit in View
QToolButton *fitInViewButton = new QToolButton(toolBar);
QString fitInView(tr("Fit in View"));
fitInViewButton->setText(fitInView);
fitInViewButton->setToolTip(fitInView);
fitInViewButton->setStatusTip(fitInView);
fitInViewButton->setIcon(QIcon(":/Resources/icons/fit-to-diagram.svg"));
connect(fitInViewButton, SIGNAL(clicked()), SLOT(fitInView()));
toolBar->addWidget(fitInViewButton);
toolBar->addSeparator();
//GRID
mpGridComboBox = new QComboBox;
mpGridComboBox->addItems(QStringList() << tr("Grid") << tr("Detailed Grid") << tr("No Grid"));
connect(mpGridComboBox, SIGNAL(currentIndexChanged(int)), SLOT(setGrid(int)));
toolBar->addWidget(mpGridComboBox);
toolBar->addSeparator();
//LOG x LOG y
mpLogXCheckBox = new QCheckBox(tr("Log X"), this);
connect(mpLogXCheckBox, SIGNAL(toggled(bool)), SLOT(setLogX(bool)));
toolBar->addWidget(mpLogXCheckBox);
toolBar->addSeparator();
mpLogYCheckBox = new QCheckBox(tr("Log Y"), this);
connect(mpLogYCheckBox, SIGNAL(toggled(bool)), SLOT(setLogY(bool)));
toolBar->addWidget(mpLogYCheckBox);
toolBar->addSeparator();
// setup
mpSetupButton = new QToolButton(toolBar);
QString setup(tr("Setup"));
mpSetupButton->setText(setup);
mpSetupButton->setToolTip(setup);
mpSetupButton->setStatusTip(setup);
mpSetupButton->setIcon(QIcon(":/Resources/icons/options.svg"));
connect(mpSetupButton, SIGNAL(clicked()), SLOT(showSetupDialog()));
toolBar->addWidget(mpSetupButton);
toolBar->addSeparator();
//EXPORT
QToolButton *btnExport = new QToolButton(toolBar);
QString save(tr("Save"));
btnExport->setText(save);
btnExport->setToolTip(save);
btnExport->setStatusTip(save);
btnExport->setIcon(QIcon(":/Resources/icons/save.svg"));
connect(btnExport, SIGNAL(clicked()), SLOT(exportDocument()));
toolBar->addWidget(btnExport);
toolBar->addSeparator();
//PRINT
QToolButton *btnPrint = new QToolButton(toolBar);
QString print(tr("Print"));
btnPrint->setText(print);
btnPrint->setToolTip(print);
btnPrint->setStatusTip(print);
btnPrint->setIcon(QIcon(":/Resources/icons/print.svg"));
connect(btnPrint, SIGNAL(clicked()), SLOT(printPlot()));
toolBar->addWidget(btnPrint);
// finally add the tool bar to the mainwindow
addToolBar(toolBar);
}
void PlotWindow::plot(PlotCurve *pPlotCurve)
{
QString currentLine;
if (mVariablesList.isEmpty() && getPlotType() == PlotWindow::PLOT)
throw NoVariableException(QString("No variables specified!").toStdString().c_str());
bool editCase = pPlotCurve ? true : false;
//PLOT PLT
if (mFile.fileName().endsWith("plt"))
{
// open the file
mFile.open(QIODevice::ReadOnly);
mpTextStream = new QTextStream(&mFile);
// read the interval size from the file
int intervalSize = 0;
while (!mpTextStream->atEnd())
{
currentLine = mpTextStream->readLine();
if (currentLine.startsWith("#IntervalSize"))
{
intervalSize = static_cast<QString>(currentLine.split("=").last()).toInt();
break;
}
}
QStringList variablesPlotted;
// Read variable values and plot them
while (!mpTextStream->atEnd())
{
currentLine = mpTextStream->readLine();
QString currentVariable;
if (currentLine.contains("DataSet:"))
{
currentVariable = currentLine.remove("DataSet: ");
if (mVariablesList.contains(currentVariable) || getPlotType() == PlotWindow::PLOTALL)
{
variablesPlotted.append(currentVariable);
if (!editCase) {
QFileInfo fileInfo(mFile);
pPlotCurve = new PlotCurve(fileInfo.fileName(), fileInfo.absoluteFilePath(), "time", getXUnit(), getXDisplayUnit(), currentVariable, getYUnit(), getYDisplayUnit(), mpPlot);
mpPlot->addPlotCurve(pPlotCurve);
}
// clear previous curve data
pPlotCurve->clearXAxisVector();
pPlotCurve->clearYAxisVector();
// read the variable values now
currentLine = mpTextStream->readLine();
for(int j = 0; j < intervalSize; j++)
{
QStringList values = currentLine.split(",");
pPlotCurve->addXAxisValue(QString(values[0]).toDouble());
pPlotCurve->addYAxisValue(QString(values[1]).toDouble());
currentLine = mpTextStream->readLine();
}
pPlotCurve->setData(pPlotCurve->getXAxisVector(), pPlotCurve->getYAxisVector(), pPlotCurve->getSize());
pPlotCurve->attach(mpPlot);
mpPlot->replot();
}
// if plottype is PLOT and we have read all the variable we need to plot then simply break the loop
if (getPlotType() == PlotWindow::PLOT)
if (mVariablesList.size() == variablesPlotted.size())
break;
}
}
// if plottype is PLOT then check which requested variables are not found in the file
if (getPlotType() == PlotWindow::PLOT)
checkForErrors(mVariablesList, variablesPlotted);
// close the file
mFile.close();
}
//PLOT CSV
else if (mFile.fileName().endsWith("csv"))
{
/* open the file */
QStringList variablesPlotted;
struct csv_data *csvReader;
csvReader = read_csv(mFile.fileName().toStdString().c_str());
if (csvReader == NULL)
throw PlotException(tr("Failed to open simulation result file %1").arg(mFile.fileName()));
//Read in timevector
double *timeVals = read_csv_dataset(csvReader, "time");
if (timeVals == NULL)
{
timeVals = read_csv_dataset(csvReader, "lambda");
if (timeVals == NULL)
{
omc_free_csv_reader(csvReader);
throw NoVariableException(tr("Variable doesnt exist: %1").arg("time or lambda").toStdString().c_str());
}
setXLabel("lambda");
}
// read in all values
for (int i = 0; i < csvReader->numvars; i++)
{
if (mVariablesList.contains(csvReader->variables[i]) || getPlotType() == PlotWindow::PLOTALL)
{
variablesPlotted.append(csvReader->variables[i]);
double *vals = read_csv_dataset(csvReader, csvReader->variables[i]);
if (vals == NULL)
{
omc_free_csv_reader(csvReader);
throw NoVariableException(tr("Variable doesnt exist: %1").arg(csvReader->variables[i]).toStdString().c_str());
}
if (!editCase) {
QFileInfo fileInfo(mFile);
pPlotCurve = new PlotCurve(fileInfo.fileName(), fileInfo.absoluteFilePath(), "time", getXUnit(), getXDisplayUnit(), csvReader->variables[i], getYUnit(), getYDisplayUnit(), mpPlot);
mpPlot->addPlotCurve(pPlotCurve);
}
// clear previous curve data
pPlotCurve->clearXAxisVector();
pPlotCurve->clearYAxisVector();
for (int i = 0 ; i < csvReader->numsteps ; i++)
{
pPlotCurve->addXAxisValue(timeVals[i]);
pPlotCurve->addYAxisValue(vals[i]);
}
pPlotCurve->setData(pPlotCurve->getXAxisVector(), pPlotCurve->getYAxisVector(), pPlotCurve->getSize());
pPlotCurve->attach(mpPlot);
mpPlot->replot();
}
}
// if plottype is PLOT then check which requested variables are not found in the file
if (getPlotType() == PlotWindow::PLOT)
checkForErrors(mVariablesList, variablesPlotted);
// close the file
omc_free_csv_reader(csvReader);
}
//PLOT MAT
else if(mFile.fileName().endsWith("mat"))
{
ModelicaMatReader reader;
ModelicaMatVariable_t *var;
const char *msg = "";
QStringList variablesPlotted;
//Read in mat file
if(0 != (msg = omc_new_matlab4_reader(mFile.fileName().toStdString().c_str(), &reader))) {
throw PlotException(msg);
}
if (reader.nvar < 1) {
omc_free_matlab4_reader(&reader);
throw NoVariableException("Variable doesnt exist: time");
}
double startTime = omc_matlab4_startTime(&reader);
double stopTime = omc_matlab4_stopTime(&reader);
//Read in timevector
double *timeVals = omc_matlab4_read_vals(&reader,1);
if (!timeVals) {
omc_free_matlab4_reader(&reader);
throw NoVariableException(QString("Corrupt file. nvar %1").arg(reader.nvar).toStdString().c_str());
}
// read in all values
for (uint32_t i = 0; i < reader.nall; i++) {
if (mVariablesList.contains(reader.allInfo[i].name) || getPlotType() == PlotWindow::PLOTALL) {
variablesPlotted.append(reader.allInfo[i].name);
// create the plot curve for variable
if (!editCase) {
QFileInfo fileInfo(mFile);
pPlotCurve = new PlotCurve(fileInfo.fileName(), fileInfo.absoluteFilePath(), "time", getXUnit(), getXDisplayUnit(), reader.allInfo[i].name, getYUnit(), getYDisplayUnit(), mpPlot);
mpPlot->addPlotCurve(pPlotCurve);
}
// read the variable values
var = omc_matlab4_find_var(&reader, reader.allInfo[i].name);
if (!var) {
omc_free_matlab4_reader(&reader);
throw NoVariableException(QString("Variable doesn't exist : ").append(reader.allInfo[i].name).toStdString().c_str());
}
// clear previous curve data
pPlotCurve->clearXAxisVector();
pPlotCurve->clearYAxisVector();
// if variable is not a parameter then
if (!var->isParam) {
double *vals = omc_matlab4_read_vals(&reader,var->index);
if (!vals) {
omc_free_matlab4_reader(&reader);
throw NoVariableException(QString("Corrupt file. nvar %1").arg(reader.nvar).toStdString().c_str());
}
// set plot curve data and attach it to plot
for (uint32_t i = 0 ; i < reader.nrows ; i++) {
pPlotCurve->addXAxisValue(timeVals[i]);
pPlotCurve->addYAxisValue(vals[i]);
}
pPlotCurve->setData(pPlotCurve->getXAxisVector(), pPlotCurve->getYAxisVector(), pPlotCurve->getSize());
pPlotCurve->attach(mpPlot);
mpPlot->replot();
} else { // if variable is a parameter then
double val;
if (omc_matlab4_val(&val,&reader,var,0.0)) {
omc_free_matlab4_reader(&reader);
throw NoVariableException(QString("Parameter doesn't have a value : ").append(reader.allInfo[i].name).toStdString().c_str());
}
pPlotCurve->addXAxisValue(startTime);
pPlotCurve->addYAxisValue(val);
pPlotCurve->addXAxisValue(stopTime);
pPlotCurve->addYAxisValue(val);
pPlotCurve->setData(pPlotCurve->getXAxisVector(), pPlotCurve->getYAxisVector(), pPlotCurve->getSize());
pPlotCurve->attach(mpPlot);
mpPlot->replot();
}
}
}
// if plottype is PLOT then check which requested variables are not found in the file
if (getPlotType() == PlotWindow::PLOT)
checkForErrors(mVariablesList, variablesPlotted);
// close the file
omc_free_matlab4_reader(&reader);
}
}
void PlotWindow::plotParametric(PlotCurve *pPlotCurve)
{
QString xVariable, yVariable, xTitle, yTitle;
int pair = 0;
if (mVariablesList.isEmpty())
throw NoVariableException(QString("No variables specified!").toStdString().c_str());
else if (mVariablesList.size()%2 != 0)
throw NoVariableException(QString("Please specify variable pairs for plotParametric.").toStdString().c_str());
bool editCase = pPlotCurve ? true : false;
for (pair = 0; pair < mVariablesList.size(); pair += 2)
{
xVariable = mVariablesList.at(pair);
yVariable = mVariablesList.at(pair+1);
if (pair==0) {
xTitle = xVariable;
yTitle = yVariable;
} else {
xTitle += ", "+xVariable;
yTitle += ", "+yVariable;
}
setXLabel(xTitle);
setYLabel(yTitle);
//PLOT PLT
if (mFile.fileName().endsWith("plt"))
{
QString currentLine;
// open the file
mFile.open(QIODevice::ReadOnly);
mpTextStream = new QTextStream(&mFile);
// read the interval size from the file
int intervalSize;
while (!mpTextStream->atEnd())
{
currentLine = mpTextStream->readLine();
if (currentLine.startsWith("#IntervalSize"))
{
intervalSize = static_cast<QString>(currentLine.split("=").last()).toInt();
break;
}
}
QStringList variablesPlotted;
// Read variable values and plot them
while (!mpTextStream->atEnd())
{
currentLine = mpTextStream->readLine();
QString currentVariable;
if (currentLine.contains("DataSet:"))
{
currentVariable = currentLine.remove("DataSet: ");
if (mVariablesList.contains(currentVariable))
{
variablesPlotted.append(currentVariable);
if (variablesPlotted.size() == 1)
{
if (!editCase) {
QFileInfo fileInfo(mFile);
pPlotCurve = new PlotCurve(fileInfo.fileName(), fileInfo.absoluteFilePath(), xVariable, getXUnit(), getXDisplayUnit(), yVariable, getYUnit(), getYDisplayUnit(), mpPlot);
mpPlot->addPlotCurve(pPlotCurve);
}
// clear previous curve data
pPlotCurve->clearXAxisVector();
pPlotCurve->clearYAxisVector();
}
// read the variable values now
currentLine = mpTextStream->readLine();
for(int j = 0; j < intervalSize; j++)
{
// add first variable to the xaxis vector and 2nd to yaxis vector
QStringList values = currentLine.split(",");
if (variablesPlotted.size() == 1)
pPlotCurve->addXAxisValue(QString(values[1]).toDouble());
else if (variablesPlotted.size() == 2)
pPlotCurve->addYAxisValue(QString(values[1]).toDouble());
currentLine = mpTextStream->readLine();
}
// when two variables are found plot then plot them
if (variablesPlotted.size() == 2)
{
pPlotCurve->setData(pPlotCurve->getXAxisVector(), pPlotCurve->getYAxisVector(), pPlotCurve->getSize());
pPlotCurve->attach(mpPlot);
mpPlot->replot();
}
}
// if we have read all the variable we need to plot then simply break the loop
if (mVariablesList.size() == variablesPlotted.size())
break;
}
}
// check which requested variables are not found in the file
checkForErrors(mVariablesList, variablesPlotted);
// close the file
mFile.close();
}
//PLOT CSV
else if (mFile.fileName().endsWith("csv"))
{
/* open the file */
QStringList variablesPlotted;
struct csv_data *csvReader;
csvReader = read_csv(mFile.fileName().toStdString().c_str());
if (csvReader == NULL)
throw PlotException(tr("Failed to open simulation result file %1").arg(mFile.fileName()));
double *xVals = NULL, *yVals = NULL;
// read in all values
for (int i = 0; i < csvReader->numvars; i++)
{
if ((xVariable.compare(csvReader->variables[i]) == 0))
{
variablesPlotted.append(csvReader->variables[i]);
xVals = read_csv_dataset(csvReader, csvReader->variables[i]);
if (xVals == NULL) {
omc_free_csv_reader(csvReader);
throw NoVariableException(tr("Variable doesnt exist: %1").arg(csvReader->variables[i]).toStdString().c_str());
}
}
if ((yVariable.compare(csvReader->variables[i]) == 0))
{
variablesPlotted.append(csvReader->variables[i]);
yVals = read_csv_dataset(csvReader, csvReader->variables[i]);
if (yVals == NULL) {
omc_free_csv_reader(csvReader);
throw NoVariableException(tr("Variable doesnt exist: %1").arg(csvReader->variables[i]).toStdString().c_str());
}
}
}
if (!editCase) {
QFileInfo fileInfo(mFile);
pPlotCurve = new PlotCurve(fileInfo.fileName(), fileInfo.absoluteFilePath(), xVariable, getXUnit(), getXDisplayUnit(), yVariable, getYUnit(), getYDisplayUnit(), mpPlot);
mpPlot->addPlotCurve(pPlotCurve);
}
// clear previous curve data
pPlotCurve->clearXAxisVector();
pPlotCurve->clearYAxisVector();
for (int i = 0 ; i < csvReader->numsteps ; i++)
{
pPlotCurve->addXAxisValue(xVals[i]);
pPlotCurve->addYAxisValue(yVals[i]);
}
pPlotCurve->setData(pPlotCurve->getXAxisVector(), pPlotCurve->getYAxisVector(), pPlotCurve->getSize());
pPlotCurve->attach(mpPlot);
mpPlot->replot();
// check which requested variables are not found in the file
checkForErrors(mVariablesList, variablesPlotted);
// close the file
omc_free_csv_reader(csvReader);
}
//PLOT MAT
else if(mFile.fileName().endsWith("mat"))
{
//Declare variables
ModelicaMatReader reader;
ModelicaMatVariable_t *var;
const char *msg = "";
//Read the .mat file
if(0 != (msg = omc_new_matlab4_reader(mFile.fileName().toStdString().c_str(), &reader)))
throw PlotException(msg);
if (!editCase) {
QFileInfo fileInfo(mFile);
pPlotCurve = new PlotCurve(fileInfo.fileName(), fileInfo.absoluteFilePath(), xVariable, getXUnit(), getXDisplayUnit(), yVariable, getYUnit(), getYDisplayUnit(), mpPlot);
mpPlot->addPlotCurve(pPlotCurve);
}
//Fill variable x with data
var = omc_matlab4_find_var(&reader, xVariable.toStdString().c_str());
if (!var) {
omc_free_matlab4_reader(&reader);
throw NoVariableException(QString("Variable doesn't exist : ").append(xVariable).toStdString().c_str());
}
// clear previous curve data
pPlotCurve->clearXAxisVector();
pPlotCurve->clearYAxisVector();
// if variable is not a parameter then
if (!var->isParam)
{
double *xVals = omc_matlab4_read_vals(&reader,var->index);
if (!xVals) {
omc_free_matlab4_reader(&reader);
throw NoVariableException(QString("Corrupt file. nvar %1").arg(reader.nvar).toStdString().c_str());
}
for (uint32_t i = 0 ; i < reader.nrows ; i++)
pPlotCurve->addXAxisValue(xVals[i]);
}
// if variable is a parameter then
else
{
double xval;
if (omc_matlab4_val(&xval,&reader,var,0.0)) {
omc_free_matlab4_reader(&reader);
throw NoVariableException(QString("Parameter doesn't have a value : ").append(xVariable).toStdString().c_str());
}
pPlotCurve->addXAxisValue(xval);
}
//Fill variable y with data
var = omc_matlab4_find_var(&reader, yVariable.toStdString().c_str());
if (!var) {
omc_free_matlab4_reader(&reader);
throw NoVariableException(QString("Variable doesn't exist : ").append(yVariable).toStdString().c_str());
}
// if variable is not a parameter then
if (!var->isParam)
{
double *yVals = omc_matlab4_read_vals(&reader,var->index);
if (!yVals) {
omc_free_matlab4_reader(&reader);
throw NoVariableException(QString("Corrupt file. nvar %1").arg(reader.nvar).toStdString().c_str());
}
for (uint32_t i = 0 ; i < reader.nrows ; i++)
pPlotCurve->addYAxisValue(yVals[i]);
}
// if variable is a parameter then
else
{
double yval;
if (omc_matlab4_val(&yval,&reader,var,0.0)) {
omc_free_matlab4_reader(&reader);
throw NoVariableException(QString("Parameter doesn't have a value : ").append(yVariable).toStdString().c_str());
}
pPlotCurve->addYAxisValue(yval);
}
pPlotCurve->setData(pPlotCurve->getXAxisVector(), pPlotCurve->getYAxisVector(), pPlotCurve->getSize());
pPlotCurve->attach(mpPlot);
mpPlot->replot();
omc_free_matlab4_reader(&reader);
}
}
}
int setupInterp(double *vals, double val, int N, double &alpha){
//given sorted values array of length N and val, returns pointer to i-th element so that
//vals[i-1] < val <= vals[i] and sets an interpolation coefficient alpha
//if val is out of the array range, returns NULL
double *p;
if (val < vals[0] || vals[N-1] < val) return -1;
p = std::lower_bound(vals, vals+N, val);
if (p == vals) //first element
alpha = 0;
else
alpha = (val - *(p-1))/(*p-*(p-1));
return p-vals;
}
int readPLTDataset(QTextStream *mpTextStream, QString variable, int N, double* valsOut){
bool resetDone = false;
QString currentLine;
do { //find start of dataset of the varible
currentLine = mpTextStream->readLine();
if (currentLine.contains("DataSet:"))
{
currentLine.remove("DataSet: ");
if (currentLine == variable) break;
}
if (mpTextStream->atEnd() && !resetDone){
mpTextStream->seek(0);
resetDone = true;
//Reset is done for each last index+1, so that the file is searched once again.
//May be optimized.
}
} while (!mpTextStream->atEnd());
if (mpTextStream->atEnd())
return -1;
for (int i = 0; i < N; i++ ){
currentLine = mpTextStream->readLine();
QStringList values = currentLine.split(",");
if (values.count()!=2) throw PlotException("Faild to load the " + variable + "variable.");
valsOut[i] = QString(values[1]).toDouble();
}
return 0;
}
void readPLTArray(QTextStream *mpTextStream, QString variable, double alpha, int intervalSize, int it, QList<double> &arrLstOut){
int index = 1;
auto vals = std::make_unique<double[]>(intervalSize);
do //loop over all indexes
{
//read the values
QString variableWithInd = variable;
if (QRegExp("der\\(\\D(\\w)*\\)").exactMatch(variableWithInd)){
variableWithInd.chop(1);
variableWithInd.append("["+QString::number(index)+"])");
} else {
variableWithInd.append("["+QString::number(index)+"]");
}
if (readPLTDataset(mpTextStream, variableWithInd, intervalSize, vals.get())){
if (index == 1)
throw NoVariableException(QObject::tr("Array variable doesnt exist: %1").arg(variable).toStdString().c_str());
else
break;
}
if (it == 0)
arrLstOut.push_back(vals[0]);
else
arrLstOut.push_back(alpha*vals[it-1] + (1-alpha)*vals[it]);
index++;
} while(true);
return;
}
double getTimeUnitFactor(QString timeUnit)
{
if (timeUnit == "ms") return 1000.0;
else if (timeUnit == "s") return 1.0;
else if (timeUnit == "min") return 1.0/6.0;
else if (timeUnit == "h") return 1.0/3600.0;
else if (timeUnit == "d") return 1.0/86400.0;
else throw PlotException(QObject::tr("Unknown unit in plotArray(Parametric)."));
}
void PlotWindow::updateTimeText()
{
QString unit = getTimeUnit();
double timeUnitFactor = getTimeUnitFactor(unit);
mpPlot->setFooter(QString("t = %1 " + unit).arg(getTime()*timeUnitFactor,0,'g',3));
mpPlot->replot();
}
void PlotWindow::plotArray(double time, PlotCurve *pPlotCurve)
{
double *res;
QString currentLine;
setTime(time);
if (mVariablesList.isEmpty() && getPlotType() == PlotWindow::PLOTARRAY)
throw NoVariableException(QString("No variables specified!").toStdString().c_str());
bool editCase = pPlotCurve ? true : false;
//PLOT PLT
//we presume time is the first dataset and array elements datasets are consequent
if (mFile.fileName().endsWith("plt"))
{
/* open the file */
if (!mFile.open(QIODevice::ReadOnly))
throw PlotException(tr("Failed to open simulation result file %1").arg(mFile.fileName()));
mpTextStream = new QTextStream(&mFile);
// read the interval size from the file
int intervalSize = -1;
while (!mpTextStream->atEnd())
{
currentLine = mpTextStream->readLine();
if (currentLine.startsWith("#IntervalSize"))
{
intervalSize = static_cast<QString>(currentLine.split("=").last()).toInt();
break;
}
}
if (intervalSize == -1) {
mFile.close();
throw PlotException(tr("Interval size not specified.").toStdString().c_str());
}
// double vals[intervalSize];
//Read in timevector
auto timeVals = std::make_unique<double[]>(intervalSize);
readPLTDataset(mpTextStream, "time", intervalSize, timeVals.get());
//Find indexes and alpha to interpolate data in particular time
double alpha;
int it = setupInterp(timeVals.get(), time, intervalSize, alpha);
if (it < 0) {
mFile.close();
throw PlotException("Time out of bounds.");
}
QString currentVariable; //without index part
// Read variable values and plot them
for (QStringList::Iterator itVarList = mVariablesList.begin(); itVarList != mVariablesList.end(); itVarList++){ //loop over all variables to be plotted
currentVariable = *(itVarList);
if (editCase)
{
// clear previous curve data
pPlotCurve->clearXAxisVector();
pPlotCurve->clearYAxisVector();
} else {
QFileInfo fileInfo(mFile);
pPlotCurve = new PlotCurve(fileInfo.fileName(), fileInfo.absoluteFilePath(), "array index", getXUnit(), getXDisplayUnit(), currentVariable, getYUnit(), getYDisplayUnit(), mpPlot);
mpPlot->addPlotCurve(pPlotCurve);
}
QList<double> arrLst;
readPLTArray(mpTextStream, currentVariable, alpha, intervalSize, it, arrLst);
for (int i = 0; i < arrLst.length(); i++)
{
pPlotCurve->addXAxisValue(i+1);
pPlotCurve->addYAxisValue(arrLst[i]);
}
pPlotCurve->setData(pPlotCurve->getXAxisVector(), pPlotCurve->getYAxisVector(), pPlotCurve->getSize());
pPlotCurve->attach(mpPlot);