-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmainwindow.cpp
1337 lines (1045 loc) · 47 KB
/
mainwindow.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
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <functional>
#include "sshInterface.h"
#include "sqlhandler/serialization.h"
#include <fstream>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
std::ifstream usernamefile;
usernamefile.open("lastusername.txt");
if(usernamefile)
{
std::string username;
usernamefile >> username;
ui->lineEditUsername->setText(QString::fromStdString(username));
usernamefile.close();
}
else
{
ui->lineEditUsername->setText("username");
}
std::ifstream workingdirfile;
workingdirfile.open("last_working_directory.txt");
if(workingdirfile)
{
std::string workingdir;
workingdirfile >> workingdir;
lastWorkingDirectory_ = QString::fromStdString(workingdir);
workingdirfile.close();
}
qDebug() << "Last working directory was " << lastWorkingDirectory_;
treeParameters_ = nullptr;
treeResults_ = nullptr;
treeInputs_ = nullptr;
parameterModel_ = nullptr;
ui->radioButtonDaily->click();
setWeExpectToBeConnected(false);
QObject::connect(ui->radioButtonDaily, &QRadioButton::clicked, this, &MainWindow::updateGraphsAndResultSummary);
QObject::connect(ui->radioButtonDailyNormalized, &QRadioButton::clicked, this, &MainWindow::updateGraphsAndResultSummary);
QObject::connect(ui->radioButtonMonthlyAverages, &QRadioButton::clicked, this, &MainWindow::updateGraphsAndResultSummary);
QObject::connect(ui->radioButtonYearlyAverages, &QRadioButton::clicked, this, &MainWindow::updateGraphsAndResultSummary);
QObject::connect(ui->radioButtonErrors, &QRadioButton::clicked, this, &MainWindow::updateGraphsAndResultSummary);
QObject::connect(ui->radioButtonErrorHistogram, &QRadioButton::clicked, this, &MainWindow::updateGraphsAndResultSummary);
QObject::connect(ui->radioButtonErrorNormalProbability, &QRadioButton::clicked, this, &MainWindow::updateGraphsAndResultSummary);
QObject::connect(ui->checkBoxScatterInputs, &QCheckBox::clicked, this, &MainWindow::updateGraphsAndResultSummary);
QObject::connect(ui->checkBoxLogarithmicPlot, &QCheckBox::clicked, this, &MainWindow::updateGraphsAndResultSummary);
//NOTE: the lineeditdelegate is used by the tableviewparameters to provide an input widget when editing parameter values.
lineEditDelegate = new ParameterEditDelegate();
ui->tableViewParameters->setItemDelegateForColumn(1, lineEditDelegate);
ui->tableViewParameters->verticalHeader()->hide();
ui->tableViewParameters->setEditTriggers(QAbstractItemView::AllEditTriggers);
ui->pushSaveParameters->setEnabled(false);
ui->pushExportParameters->setEnabled(false);
//ui->pushCreateDatabase->setEnabled(false);
//ui->pushUploadInputs->setEnabled(false);
ui->treeViewResults->setSelectionMode(QTreeView::ExtendedSelection); // Allows to ctrl-select multiple items.
ui->treeViewInputs->setSelectionMode(QTreeView::ExtendedSelection); // Allows to ctrl-select multiple items.
//NOTE: we override the ctrl-c functionality in order to copy the table view correctly.
//So anything that should be copyable to the clipboard has to be explicitly handled in MainWindow::copyToClipboard.
QAction *ctrlc = new QAction("copy");
ctrlc->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_C));
QObject::connect(ctrlc, &QAction::triggered, this, &MainWindow::copyToClipboard);
ui->centralWidget->addAction(ctrlc);
QAction *ctrlz = new QAction("undo");
ctrlz->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Z));
QObject::connect(ctrlz, &QAction::triggered, this, &MainWindow::undo);
ui->centralWidget->addAction(ctrlz);
QLocale::setDefault(QLocale::English);
ui->widgetPlotResults->setLocale(QLocale::English);
ui->widgetPlotResults->setInteraction(QCP::iRangeDrag, true);
ui->widgetPlotResults->setInteraction(QCP::iRangeZoom, true);
ui->widgetPlotResults->axisRect(0)->setRangeDrag(Qt::Horizontal);
ui->widgetPlotResults->axisRect(0)->setRangeZoom(Qt::Horizontal);
//NOTE: If we want a rectangle zoom for the plot, look at http://www.qcustomplot.com/index.php/support/forum/227
QObject::connect(ui->widgetPlotResults, &QCustomPlot::mouseMove, this, &MainWindow::updateGraphToolTip);
QObject::connect(ui->widgetPlotResults, &QCustomPlot::mouseWheel, this, &MainWindow::getCurrentRange);
//TODO: We have to think about whether the login info for the hub should be hard coded.
//NOTE: The hub ssh keys have to be distributed with the exe and be placed in the same folder as the exe.
sshInterface_ = new SSHInterface("35.198.76.72", "magnus", "hubkey");
QObject::connect(sshInterface_, &SSHInterface::log, this, &MainWindow::log);
QObject::connect(sshInterface_, &SSHInterface::logError, this, &MainWindow::logSSHError);
plotter_ = new Plotter(ui->widgetPlotResults, ui->textResultsInfo);
}
MainWindow::~MainWindow()
{
delete ui;
delete plotter_;
delete sshInterface_;
}
void MainWindow::log(const QString& Message)
{
QScrollBar *bar = ui->textLog->verticalScrollBar();
bool isatbottom = (bar->value() == bar->maximum());
ui->textLog->append(QTime::currentTime().toString("hh:mm: ") + Message);
if(isatbottom) bar->setValue(bar->maximum()); //If it was at the bottom, scroll it down to the new bottom.
QApplication::processEvents();
}
void MainWindow::logError(const QString& Message)
{
ui->tabWidget->setCurrentIndex(1);
log("<font color=red>" + Message + "</font>");
}
void MainWindow::logSSHError(const QString& message)
{
logError(message);
//TODO: We may want to do this regularly in some other way instead. It is not too reliable to do it here.. Maybe put it on a regular timer that is called once in a while.
if(weExpectToBeConnected_ && !sshInterface_->isInstanceConnected())
{
const char *disconnectionMessage = sshInterface_->getDisconnectionMessage();
logError(QString("SSH Disconnected:") + disconnectionMessage);
handleInvoluntarySSHDisconnect();
}
}
void MainWindow::resetWindowTitle()
{
QString dbState = selectedParameterDbPath_;
if(parametersHaveBeenEditedSinceLastSave_) dbState = "*" + dbState;
QString loginState = "";
QString username = ui->lineEditUsername->text();
if(weExpectToBeConnected_) loginState = " - " + username;
QString title = QString("%1%2 INCAView").arg(dbState).arg(loginState);
setWindowTitle(title);
}
void MainWindow::on_pushConnect_clicked()
{
//NOTE: Even if the disabling of these elements are handled by toggleWeExpectToBeConnected below, we want to do them here too since
// we don't want them to be enabled for the half second the connection takes.
ui->pushConnect->setEnabled(false);
ui->lineEditUsername->setEnabled(false);
QByteArray username = ui->lineEditUsername->text().toLatin1();
std::ofstream usernamefile;
usernamefile.open("lastusername.txt");
if(usernamefile)
{
usernamefile.write(username.data(), username.size());
usernamefile.close();
}
//TODO: Check that username is a single word in lower caps or with '-'. If that is not always possible, we should generate the instance name in a different way
QString instancename = QString("incaview-") + username.data();
QByteArray instancename2 = instancename.toLatin1();
log(QString("Attempting to get a google compute instance for ") + username.data());
//bool success = sshInterface_->connectSession(name.data(), ip.data(), keyPath_);
bool success = sshInterface_->createInstance(username.data(), instancename2.data());
if(success)
{
log("Connection successful");
setWeExpectToBeConnected(true);
}
else
{
//NOTE: SSH errors are reported to the log elsewhere.
setWeExpectToBeConnected(false);
}
}
void MainWindow::on_pushLoadProject_clicked()
{
//TODO: Should probably check that lastWorkingDirectory_ is a valid directory??
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open project database"), lastWorkingDirectory_, tr("Database files (*.db)"));
if(!fileName.isEmpty() && !fileName.isNull()) //NOTE: in case the user clicked cancel.
{
loadParameterDatabase(fileName);
}
}
void MainWindow::loadParameterDatabase(QString fileName)
{
if(parameterDbWasSelected_) //NOTE: If a database is already selected we have to do some cleanup.
{
if(parametersHaveBeenEditedSinceLastSave_)
{
//NOTE: Alternatively we could just save the parameters without asking?
QMessageBox::StandardButton resBtn = QMessageBox::question( this, tr("Loading a new database without saving."),
tr("If you load a new database without saving the parameters or running the model, your changes to the parameters will not be stored. Do you still want to load a new database?\n"),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::Yes);
if (resBtn != QMessageBox::Yes) return;
}
if(treeResults_) delete treeResults_;
if(treeInputs_) delete treeInputs_;
treeResults_ = nullptr;
treeInputs_ = nullptr;
clearGraphsAndResultSummary();
}
bool success = projectDb_.setDatabase(fileName);
if(success)
{
parameterDbWasSelected_ = true;
selectedParameterDbPath_ = fileName;
QFileInfo fileinfo(selectedParameterDbPath_);
projectDirectory_ = fileinfo.absolutePath();
lastWorkingDirectory_ = projectDirectory_.path();
QByteArray workdirstr = lastWorkingDirectory_.toLatin1();
std::ofstream dirfile;
dirfile.open("last_working_directory.txt");
if(dirfile)
{
dirfile.write(workdirstr.data(), workdirstr.size());
dirfile.close();
}
loadParameterData();
ui->treeViewParameters->expandToDepth(3);
ui->treeViewParameters->resizeColumnToContents(0);
ui->treeViewParameters->setColumnHidden(1, true);
ui->treeViewParameters->setColumnHidden(2, true);
ui->pushExportParameters->setEnabled(true);
updateRunButtonState();
setParametersHaveBeenEditedSinceLastSave(false);
resetWindowTitle();
}
else
{
updateRunButtonState();
ui->pushExportParameters->setEnabled(false);
//TODO: additional error handling?
}
}
void MainWindow::on_pushCreateDatabase_clicked()
{
//TODO: This entire thing needs to be rethought. Button is removed for now.
if(!weExpectToBeConnected_)
{
//NOTE: This should not be possible. The button should not be active in that case.
return;
}
if(!sshInterface_->isInstanceConnected())
{
handleInvoluntarySSHDisconnect();
return;
}
QString fileName = QFileDialog::getOpenFileName(this,
tr("Select parameter file to convert"), "", tr("Data files (*.dat)")); //TODO: should not restrict it to .dat
if(fileName.isEmpty() || fileName.isNull()) //NOTE: In case the user clicked cancel etc.
{
return;
}
const char *remoteParameterFileName = "parameters.dat";
const char *remoteParameterDbName = "parameters.db";
//TODO: This means that they have to have a parameter database loaded, which is weird since what they are doing here is trying to create one.
// We should instead query a selection list of models that can be loaded from the server.
QString exename;
projectDb_.setDatabase(selectedParameterDbPath_);
projectDb_.getExenameFromParameterInfo(exename);
qDebug() << "exe name was: " << exename;
QByteArray exename2 = exename.toLatin1();
QByteArray filename2 = fileName.toLatin1();
bool success = sshInterface_->uploadEntireFile(filename2.data(), "~/", remoteParameterFileName);
if(!success) return;
success = sshInterface_->createParameterDatabase(exename2.data(), remoteParameterFileName, remoteParameterDbName);
if(!success) return;
QString saveFileName = QFileDialog::getSaveFileName(this,
tr("Select location to store database file"), "", tr("Database files (*.db)"));
if(fileName.isEmpty() || fileName.isNull()) //NOTE: In case the user clicked cancel etc.
{
return;
}
QByteArray saveFileName2 = saveFileName.toLatin1();
//TODO: Don't hard code the location of the remote parameter database file?
success = sshInterface_->downloadEntireFile(saveFileName2.data(), remoteParameterDbName);
if(!success) return;
loadParameterDatabase(saveFileName);
}
void MainWindow::on_pushExportParameters_clicked()
{
if(!parameterDbWasSelected_)
{
return; //NOTE: Just in case. This should not be possible due to handling of button states
}
QString exportParametersPath = QFileDialog::getSaveFileName(this,
tr("Select file to export parameters"), "", tr("Data files (*.dat)"));
if(exportParametersPath.isEmpty() || exportParametersPath.isNull()) return; //NOTE: In case the user clicked cancel or closed the dialog.
on_pushSaveParameters_clicked(); //NOTE: save any changes to the database.
QString exename;
projectDb_.setDatabase(selectedParameterDbPath_);
projectDb_.getExenameFromParameterInfo(exename);
if(weExpectToBeConnected_)
{
if(!sshInterface_->isInstanceConnected())
{
handleInvoluntarySSHDisconnect();
return;
}
const char *remoteParameterFileName = "parameters.dat";
const char *remoteParameterDbName = "parameters.db";
QByteArray dbfilename2 = selectedParameterDbPath_.toLatin1();
bool success = sshInterface_->uploadEntireFile(dbfilename2.data(), "~/", remoteParameterDbName);
if(!success) return;
QByteArray exename2 = exename.toLatin1();
success = sshInterface_->exportParameters(exename2.data(), remoteParameterDbName, remoteParameterFileName);
if(!success) return;
QByteArray saveFileName2 = exportParametersPath.toLatin1();
success = sshInterface_->downloadEntireFile(saveFileName2.data(), remoteParameterFileName);
}
else
{
//For now, assume the exe is in the same directory as the parameter database.
QString program = projectDirectory_.absoluteFilePath(exename);
qDebug() << "trying to run program " << program;
QStringList arguments;
arguments << "convert_parameters" << selectedParameterDbPath_ << exportParametersPath;
runModelProcessLocally(program, arguments);
}
}
void MainWindow::on_pushUploadInputs_clicked()
{
selectedInputFilePath_ = QFileDialog::getOpenFileName(this,
tr("Select input file"), "", tr("Data files (*.dat)")); //TODO: should not restrict it to .dat
if(selectedInputFilePath_.isEmpty() || selectedInputFilePath_.isNull()) //NOTE: In case the user clicked cancel etc.
{
return;
}
inputFileWasSelected_ = true;
updateRunButtonState();
if(!weExpectToBeConnected_)
{
return;
}
if(!sshInterface_->isInstanceConnected())
{
handleInvoluntarySSHDisconnect();
return;
}
const char *remoteInputFileName = "uploadedinputs.dat";
QByteArray filename2 = selectedInputFilePath_.toLatin1();
bool success = sshInterface_->uploadEntireFile(filename2.data(), "~/", remoteInputFileName);
if(success) inputFileWasUploaded_ = true;
}
void MainWindow::loadParameterData()
{
if(parameterDbWasSelected_)
{
projectDb_.setDatabase(selectedParameterDbPath_);
log("Loading parameter structure...");
parameterModel_ = new ParameterModel();
treeParameters_ = new TreeModel("Parameter Structure");
std::map<uint32_t, parameter_min_max_val_serial_entry> IDtoParam;
projectDb_.getParameterValuesMinMax(IDtoParam);
QVector<TreeData> structuredata;
projectDb_.getParameterStructure(structuredata);
for(TreeData& data : structuredata)
{
auto parref = IDtoParam.find(data.ID); //NOTE: See if there is a parameter with this ID.
if(parref == IDtoParam.end())
{
//This ID corresponds to something that is not a parameter (i.e. an indexer, and index or a root node), and so we add it to the tree structure.
treeParameters_->addItem(data);
}
else
{
//This ID corresponds to a parameter, and so we add it to the parameter model.
parameter_min_max_val_serial_entry& par = parref->second;
parameterModel_->addParameter(data.name, data.unit, data.description, data.ID, data.parentID, par);
}
}
ui->tableViewParameters->setModel(parameterModel_);
ui->treeViewParameters->setModel(treeParameters_);
QObject::connect(parameterModel_, &ParameterModel::parameterWasEdited, this, &MainWindow::parameterWasEdited);
QObject::connect(ui->treeViewParameters->selectionModel(), &QItemSelectionModel::selectionChanged, this, &MainWindow::updateParameterView);
QObject::connect(ui->tableViewParameters, &QTableView::clicked, parameterModel_, &ParameterModel::handleClick);
log("Loading complete");
}
else
{
logError("Tried to load parameter data without having a valid project database.");
}
}
void MainWindow::loadResultAndInputStructure(const char *ResultDb, const char *InputDb)
{
log("Attempting to load result and input structure.");
bool success = false;
QVector<TreeData> resultstreedata;
QVector<TreeData> inputtreedata;
if(weExpectToBeConnected_)
{
success = sshInterface_->getStructureData(ResultDb, "ResultsStructure", resultstreedata);
success = success && sshInterface_->getStructureData(InputDb, "InputsStructure", inputtreedata);
}
else
{
QString resultdbpath = projectDirectory_.absoluteFilePath(ResultDb);
projectDb_.setDatabase(resultdbpath);
success = projectDb_.getResultOrInputStructure(resultstreedata, "ResultsStructure");
QString inputdbpath = projectDirectory_.absoluteFilePath(InputDb);
projectDb_.setDatabase(inputdbpath);
success = success && projectDb_.getResultOrInputStructure(inputtreedata, "InputsStructure");
}
if(resultstreedata.empty())
{
logError("The result structure is empty. A results database may not have been created, maybe due to an error.");
return;
}
if(!success) return;
// Setup result structure
if(treeResults_) delete treeResults_;
treeResults_ = new TreeModel("Results structure");
maxresultID_ = 0;
for(TreeData& item : resultstreedata)
{
treeResults_->addItem(item);
maxresultID_ = item.ID > maxresultID_ ? item.ID : maxresultID_;
}
ui->treeViewResults->setModel(treeResults_);
QObject::connect(ui->treeViewResults->selectionModel(), &QItemSelectionModel::selectionChanged, this, &MainWindow::updateGraphsAndResultSummary);
// Setup input structure
if(treeInputs_) delete treeInputs_;
treeInputs_ = new TreeModel("Input structure");
for(TreeData &item : inputtreedata)
{
//NOTE: We remap the input IDs so that they don't overlap with the result IDs. This makes every timeseries have a unique internal ID in INCAView, and simplifies the Plotter a bit.
item.ID += maxresultID_;
if(item.parentID != 0) item.parentID += maxresultID_; //NOTE: parentID=0 just signifies that it does not have a parent, so that should stay 0.
treeInputs_->addItem(item);
}
ui->treeViewInputs->setModel(treeInputs_);
QObject::connect(ui->treeViewInputs->selectionModel(), &QItemSelectionModel::selectionChanged, this, &MainWindow::updateGraphsAndResultSummary);
//TODO: The following should be done somewhere else?
ui->radioButtonDaily->setEnabled(true);
ui->radioButtonDailyNormalized->setEnabled(true);
ui->radioButtonMonthlyAverages->setEnabled(true);
ui->radioButtonYearlyAverages->setEnabled(true);
ui->radioButtonErrors->setEnabled(true);
ui->radioButtonErrorHistogram->setEnabled(true);
ui->radioButtonErrorNormalProbability->setEnabled(true);
ui->treeViewResults->expandToDepth(3);
ui->treeViewResults->resizeColumnToContents(0);
ui->treeViewResults->setColumnHidden(1, true);
ui->treeViewResults->setColumnHidden(2, true);
ui->treeViewInputs->expandToDepth(3);
ui->treeViewInputs->resizeColumnToContents(0);
ui->treeViewInputs->setColumnHidden(1, true);
ui->treeViewInputs->setColumnHidden(2, true);
log("Loading complete.");
}
void MainWindow::updateRunButtonState()
{
if(parameterDbWasSelected_ &&
inputFileWasSelected_
)
{
ui->pushRun->setEnabled(true);
ui->pushRunOptimizer->setEnabled(true);
}
else
{
ui->pushRun->setEnabled(false);
ui->pushRunOptimizer->setEnabled(false);
}
}
void MainWindow::setWeExpectToBeConnected(bool connected)
{
weExpectToBeConnected_ = connected;
//updateRunButtonState();
if(connected)
{
ui->pushConnect->setEnabled(false);
ui->lineEditUsername->setEnabled(false);
ui->pushDisconnect->setEnabled(true);
//ui->pushCreateDatabase->setEnabled(true);
}
else
{
ui->pushConnect->setEnabled(true);
ui->lineEditUsername->setEnabled(true);
ui->pushDisconnect->setEnabled(false);
ui->pushRun->setEnabled(false);
ui->pushRunOptimizer->setEnabled(false);
//ui->pushCreateDatabase->setEnabled(false);
ui->radioButtonDaily->setEnabled(false);
ui->radioButtonDailyNormalized->setEnabled(false);
ui->radioButtonMonthlyAverages->setEnabled(false);
ui->radioButtonYearlyAverages->setEnabled(false);
ui->radioButtonErrors->setEnabled(false);
ui->radioButtonErrorHistogram->setEnabled(false);
ui->radioButtonErrorNormalProbability->setEnabled(false);
}
resetWindowTitle();
}
void MainWindow::on_pushDisconnect_clicked()
{
bool success = sshInterface_->destroyInstance();
//TODO: If we were not successful destroying the instance, what do we do?
setWeExpectToBeConnected(false);
if(treeResults_) delete treeResults_; //NOTE: The destructor of the QAbstractItemModel automatically disconnects it from it's view.
treeResults_ = nullptr;
if(treeInputs_) delete treeInputs_;
treeInputs_ = nullptr;
clearGraphsAndResultSummary();
}
void MainWindow::handleInvoluntarySSHDisconnect()
{
//TODO: Should we attempt to destroy the compute instance?
// OR it would probably be better to attempt to reconnect to it?
setWeExpectToBeConnected(false);
if(treeResults_) delete treeResults_; //NOTE: The destructor of the QAbstractItemModel automatically disconnects it from it's view.
treeResults_ = nullptr;
if(treeInputs_) delete treeInputs_;
treeInputs_ = nullptr;
clearGraphsAndResultSummary();
logError("We were disconnected from the SSH connection.");
}
void MainWindow::on_pushSaveParameters_clicked()
{
if(parametersHaveBeenEditedSinceLastSave_)
{
log("Saving parameters...");
//NOTE: Serialize parameter values and send them to the remote database
QVector<parameter_serial_entry> parameterdata;
//TODO: we should probably only save the parameters that have been changed instead of all of them.. However this operation is very fast, so it doesn't seem to matter.
parameterModel_->serializeParameterData(parameterdata);
projectDb_.setDatabase(selectedParameterDbPath_);
bool success = projectDb_.writeParameterValues(parameterdata);
if(success)
{
setParametersHaveBeenEditedSinceLastSave(false);
editUndoStack_.clear();
log("Saving parameters complete.");
}
}
}
void MainWindow::on_pushRun_clicked()
{
QVector<Parameter *> parametersNotInRange;
if(parameterModel_->areAllParametersInRange(parametersNotInRange))
{
runModel();
}
else
{
QString msg = "Not all parameter values are in the suggested [Min, Max] range:";
for(Parameter *param : parametersNotInRange)
{
msg += "\n" + param->name;
//TODO: This does not work, I don't know why:
//int ID = param->ID;
//qDebug() << "ID of param out of range: " << ID;
//QString parentName = treeParameters_->getParentName(ID);
//msg += "\n" + param->name + " (" + parentName + ")";
}
msg += "\nThis may cause the model to behave unexpectedly. Run the model anyway?";
QMessageBox msgBox(QMessageBox::Warning, tr("Invalid parameters"), msg);
QPushButton *runButton = msgBox.addButton(tr("Run model"), QMessageBox::ActionRole);
QPushButton *abortButton = msgBox.addButton(QMessageBox::Cancel);
msgBox.exec();
if (msgBox.clickedButton() == runButton) {
runModel();
} else if (msgBox.clickedButton() == abortButton) {
// NOTE: Do nothing.
}
}
}
void MainWindow::on_pushRunOptimizer_clicked()
{
ui->pushRunOptimizer->setEnabled(false);
QString setupScriptPath = QFileDialog::getOpenFileName(this,
tr("Select optimization script"), "", tr("Data files (*.dat)"));
if(setupScriptPath.isEmpty() || setupScriptPath.isNull()) //NOTE: in case the user clicked cancel.
{
return;
}
log("Attempting to run optimization...");
on_pushSaveParameters_clicked(); //NOTE: Save the parameters to the database.
if(weExpectToBeConnected_ && inputFileWasSelected_ && !inputFileWasUploaded_) //NOTE: If the input file was selected before we connected it has not been uploaded yet, so we have to do it now.
{
//TODO: This is repeated code from RunModel.
const char *remoteInputFileName = "uploadedinputs.dat";
QByteArray filename2 = selectedInputFilePath_.toLatin1();
bool success = sshInterface_->uploadEntireFile(filename2.data(), "~/", remoteInputFileName);
if(success) inputFileWasUploaded_ = true;
}
QString exename;
projectDb_.setDatabase(selectedParameterDbPath_);
projectDb_.getExenameFromParameterInfo(exename);
qDebug() << "exe name was: " << exename;
if(weExpectToBeConnected_)
{
//TODO: Not implemented
}
else
{
//For now, assume the exe is in the same directory as the parameter database.
QString program = projectDirectory_.absoluteFilePath(exename);
qDebug() << "trying to run program with optimization " << program;
QStringList arguments;
arguments << "run_optimizer" << selectedInputFilePath_ << selectedParameterDbPath_ << setupScriptPath << "optimized_parameters.db";
runModelProcessLocally(program, arguments);
}
log("Optimizer process completed.");
//NOTE: Load in the optimized parameters and run the model one more time to see the results.
QString dbpath = projectDirectory_.filePath("optimized_parameters.db");
loadParameterDatabase(dbpath);
runModel();
ui->pushRunOptimizer->setEnabled(true);
}
bool MainWindow::runModelProcessLocally(const QString& program, const QStringList& arguments)
{
QProcess modelrun;
modelrun.setWorkingDirectory(projectDirectory_.path());
modelrun.start(program, arguments);
if(!modelrun.waitForStarted())
{
logError("Model exe process did not start.");
ui->pushRun->setEnabled(true);
return false;
}
bool correct = true;
connect(&modelrun, &QProcess::readyReadStandardOutput, [&](){log(modelrun.readAllStandardOutput());});
connect(&modelrun, &QProcess::readyReadStandardError, [&](){logError(modelrun.readAllStandardError()); correct=false;});
connect(&modelrun, &QProcess::errorOccurred, [&]()
{
logError("An error occurred while running the model exe.");
correct = false;
}
);
if(!modelrun.waitForFinished(-1)) //TODO: We could maybe have a timeout, but it is hard to predict what it should be (some models could potentially take a minute or two to run?).
{
logError("Model exe process finished incorrectly.");
ui->pushRun->setEnabled(true);
return false;
}
return correct;
}
void MainWindow::runModel()
{
if(!parameterDbWasSelected_)
{
//it should not be possible to reach this state since the button should be disabled
return;
}
ui->pushRun->setEnabled(false);
log("Attempting to run Model...");
on_pushSaveParameters_clicked(); //NOTE: Save the parameters to the database.
if(weExpectToBeConnected_ && inputFileWasSelected_ && !inputFileWasUploaded_) //NOTE: If the input file was selected before we connected it has not been uploaded yet, so we have to do it now.
{
const char *remoteInputFileName = "uploadedinputs.dat";
QByteArray filename2 = selectedInputFilePath_.toLatin1();
bool success = sshInterface_->uploadEntireFile(filename2.data(), "~/", remoteInputFileName);
if(success) inputFileWasUploaded_ = true;
}
const char *ResultDb = "results.db";
const char *InputDb = "inputs.db";
QString exename;
projectDb_.setDatabase(selectedParameterDbPath_);
projectDb_.getExenameFromParameterInfo(exename);
qDebug() << "exe name was: " << exename;
bool success = true;
if(weExpectToBeConnected_)
{
if(!sshInterface_->isInstanceConnected())
{
handleInvoluntarySSHDisconnect();
return;
}
//TODO: Upload the entire parameter database to the instance!
const char *remoteParameterDbName = "parameters.db";
QByteArray dbpath = selectedParameterDbPath_.toLatin1();
sshInterface_->uploadEntireFile(dbpath.data(), "~/", remoteParameterDbName);
QByteArray exename2 = exename.toLatin1();
const char *remoteInputFile = "uploadedinputs.dat";
sshInterface_->runModel(exename2.data(), remoteInputFile, remoteParameterDbName); //TODO: This one should also report success/error?
}
else
{
//For now, assume the exe is in the same directory as the parameter database.
QString program = projectDirectory_.absoluteFilePath(exename);
//TODO: Deleting the previous inputs and results db may not be that clean, but we don't have any system for managing it properly yet, so not deleting them causes errors.
QString resultpath = projectDirectory_.absoluteFilePath(ResultDb);
QFile::remove(resultpath);
QString inputpath = projectDirectory_.absoluteFilePath(InputDb);
QFile::remove(inputpath);
qDebug() << "trying to run program " << program;
QStringList arguments;
arguments << "run" << selectedInputFilePath_ << selectedParameterDbPath_;
success = runModelProcessLocally(program, arguments);
}
//log("Model run process completed."); //NOTE: This one was just confusing, since it was also printed if there was an error.
if(success)
{
//TODO: We should do a more rigorous check here. If e.g. the user has switched out the input file between runs then the tree structure may no longer be valid and should be recreated.
if(!treeResults_)
loadResultAndInputStructure(ResultDb, InputDb);
plotter_->clearCache();
updateGraphsAndResultSummary(); //In case somebody had a graph selected, it is updated with a plot of the data generated from the last run.
}
ui->pushRun->setEnabled(true);
}
void MainWindow::closeEvent (QCloseEvent *event)
{
if(parametersHaveBeenEditedSinceLastSave_)
{
//NOTE: Alternatively we could just save the parameters without asking?
QMessageBox::StandardButton resBtn = QMessageBox::question( this, tr("Closing INCAView without saving."),
tr("If you exit INCAView without saving the parameters or running the model, your changes to the parameters will not be stored. Do you still want to exit?\n"),
QMessageBox::Yes | QMessageBox::No ,
QMessageBox::Yes);
if (resBtn != QMessageBox::Yes) {
event->ignore();
} else {
bool success = sshInterface_->destroyInstance(); //TODO: If we were not successful destroying the instance, what do we do?
event->accept();
}
}
else
{
bool success = sshInterface_->destroyInstance(); //TODO: If we were not successful destroying the instance, what do we do?
}
}
void MainWindow::updateParameterView(const QItemSelection& selected, const QItemSelection& deselected)
{
parameterModel_->clearVisibleParameters();
QModelIndexList indexes = selected.indexes();
if(indexes.count() >= 1)
{
// NOTE: The selection mode for this view is configured so that we can only select one row at the time.
// The first item in indexes points to the name, the second to the ID.
QModelIndex index = indexes[1];
int ID = treeParameters_->data(index).toInt();
parameterModel_->setChildrenVisible(ID);
}
}
bool MainWindow::getDataSets(const char *dbname, const QVector<int> &IDs, const char *table, QVector<QVector<double>> &seriesout, QVector<int64_t> &startdatesout)
{
if(weExpectToBeConnected_)
{
if(!sshInterface_->isInstanceConnected())
{
handleInvoluntarySSHDisconnect();
return false;
}
return sshInterface_->getDataSets(dbname, IDs, table, seriesout, startdatesout);
}
else
{
QString dbpath = projectDirectory_.absoluteFilePath(dbname);
projectDb_.setDatabase(dbpath);
return projectDb_.getResultOrInputValues(table, IDs, seriesout, startdatesout);
}
}
void MainWindow::updateGraphsAndResultSummary()
{
if(!treeResults_ || !treeInputs_)
{
clearGraphsAndResultSummary();
return;
}
QModelIndexList resultindexes = ui->treeViewResults->selectionModel()->selectedIndexes();
QVector<QString> names;
QVector<int> resultIDs;
for(auto index : resultindexes)
{
if(index.column() == 0)
{
auto idx = index.model()->index(index.row(),index.column() + 1, index.parent());
int ID = (treeResults_->itemData(idx))[0].toInt();
if( ID != 0 && treeResults_->childCount(ID) == 0) //NOTE: If it has children in the tree, it is an indexer or index, not a result series.
{
resultIDs.push_back(ID);
QString name = treeResults_->getName(ID);
QString parentName = treeResults_->getParentName(ID);
QString unit = treeResults_->getUnit(ID);
names.push_back(name + " (" + parentName + ") " + unit);
}
}
}
QModelIndexList inputindexes = ui->treeViewInputs->selectionModel()->selectedIndexes();
QVector<int> inputIDs;
for(auto index : inputindexes)
{
auto idx = index.model()->index(index.row(), index.column() + 1, index.parent());