-
Notifications
You must be signed in to change notification settings - Fork 23
/
ResultsPelicun.cpp
1504 lines (1198 loc) · 47 KB
/
ResultsPelicun.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
/* *****************************************************************************
Copyright (c) 2016-2017, The Regents of the University of California (Regents).
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS
PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*************************************************************************** */
// Written: fmckenna
#include <ResultsPelicun.h>
#include <QProcess>
#include <QStringList>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QApplication>
#include <QTabWidget>
#include <QTextEdit>
#include <MyTableWidget.h>
#include <QDebug>
#include <QHBoxLayout>
#include <QColor>
#include <QDir>
#include <QFile>
#include <QProcess>
#include <QFileInfo>
#include <QScrollArea>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <QMessageBox>
#include <QVBoxLayout>
#include <QLineEdit>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QtCharts/QChart>
#include <QtCharts/QChartView>
#include <QtCharts/QLineSeries>
#include <QtCharts/QScatterSeries>
#include <QtCharts/QVXYModelMapper>
#include <math.h>
#include <QValueAxis>
#include <QXYSeries>
#include <QBarSeries>
#include <QBarSet>
#include <QBarCategoryAxis>
#include <QLabel>
#include <QSettings>
#include <SimCenterPreferences.h>
#define NUM_DIVISIONS 10
ResultsPelicun::ResultsPelicun(QWidget *parent)
: SimCenterWidget(parent)
{
// title & add button
tabWidget = new QTabWidget(this);
QHBoxLayout *layout = new QHBoxLayout();
layout->addWidget(tabWidget,1);
mLeft = true;
col1 = 0;
col2 = 0;
this->setLayout(layout);
}
ResultsPelicun::~ResultsPelicun()
{
}
void ResultsPelicun::clear(void)
{
//
// get the tab widgets and delete them
//
QWidget *res=tabWidget->widget(0);
QWidget *dat=tabWidget->widget(1);
if (res != NULL)
delete res;
if (dat != NULL)
delete dat;
tabWidget->clear();
//
// clear any data we have stored
//
theHeadings.clear();
theNames.clear();
theMeans.clear();
theStdDevs.clear();
}
bool
ResultsPelicun::outputToJSON(QJsonObject &jsonObject)
{
bool result = true;
int numEDP = theNames.count();
// quick return .. noEDP -> no analysis done -> no results out
if (numEDP == 0)
return true;
jsonObject["resultType"]=QString(tr("ResultsPelicun"));
//
// add summary data
//
QJsonArray resultsData;
for (int i=0; i<numEDP; i++) {
QJsonObject edpData;
edpData["name"]=theNames.at(i);
edpData["mean"]=theMeans.at(i);
edpData["stdDev"]=theStdDevs.at(i);
resultsData.append(edpData);
}
jsonObject["summary"]=resultsData;
jsonObject["dataType"]=dataType;
// add general data
jsonObject["general"]=dakotaText->toPlainText();
//
// add spreadsheet data
//
QJsonObject spreadsheetData;
int numCol = spreadsheet->columnCount();
int numRow = spreadsheet->rowCount();
spreadsheetData["numRow"]=numRow;
spreadsheetData["numCol"]=numCol;
QJsonArray headingsArray;
for (int i = 0; i <theHeadings.size(); ++i) {
headingsArray.append(QJsonValue(theHeadings.at(i)));
}
spreadsheetData["headings"]=headingsArray;
QJsonArray dataArray;
QApplication::setOverrideCursor(Qt::WaitCursor);
for (int row = 0; row < numRow; ++row) {
for (int column = 0; column < numCol; ++column) {
QTableWidgetItem *theItem = spreadsheet->item(row,column);
QString textData = theItem->text();
dataArray.append(textData.toDouble());
}
}
QApplication::restoreOverrideCursor();
spreadsheetData["data"]=dataArray;
jsonObject["spreadsheet"] = spreadsheetData;
return result;
}
bool
ResultsPelicun::inputFromJSON(QJsonObject &jsonObject)
{
bool result = true;
this->clear();
//
// create a summary widget in which place basic output (name, mean, stdDev)
//
QWidget *summaryWidget = new QWidget();
QVBoxLayout *summaryLayout = new QVBoxLayout();
summaryWidget->setLayout(summaryLayout);
QJsonArray edpArray = jsonObject["summary"].toArray();
QJsonValue type = jsonObject["dataType"];
if (!type.isNull()) {
dataType = type.toInt();
} else
dataType = 0;
foreach (const QJsonValue &edpValue, edpArray) {
QString name;
double mean, stdDev;
QJsonObject edpObject = edpValue.toObject();
QJsonValue theNameValue = edpObject["name"];
name = theNameValue.toString();
QJsonValue theMeanValue = edpObject["mean"];
mean = theMeanValue.toDouble();
QJsonValue theStdDevValue = edpObject["stdDev"];
stdDev = theStdDevValue.toDouble();
}
summaryLayout->addStretch();
//
// place widget in scrollable area
//
QScrollArea *summary = new QScrollArea;
summary->setWidgetResizable(true);
summary->setLineWidth(0);
summary->setFrameShape(QFrame::NoFrame);
summary->setWidget(summaryWidget);
//
// into a QTextEdit place more detailed Dakota text
//
dakotaText = new QTextEdit();
dakotaText->setReadOnly(true); // make it so user cannot edit the contents
QJsonValue theValue = jsonObject["general"];
dakotaText->setText(theValue.toString());
//
// into a spreadsheet place all the data returned
//
spreadsheet = new MyTableWidget();
QJsonObject spreadsheetData = jsonObject["spreadsheet"].toObject();
int numRow = spreadsheetData["numRow"].toInt();
int numCol = spreadsheetData["numCol"].toInt();
spreadsheet->setColumnCount(numCol);
spreadsheet->setRowCount(numRow);
QJsonArray headingData= spreadsheetData["headings"].toArray();
for (int i=0; i<numCol; i++) {
theHeadings << headingData.at(i).toString();
}
spreadsheet->setHorizontalHeaderLabels(theHeadings);
QJsonArray dataData= spreadsheetData["data"].toArray();
int dataCount =0;
for (int row =0; row<numRow; row++) {
for (int col=0; col<numCol; col++) {
QModelIndex index = spreadsheet->model()->index(row, col);
spreadsheet->model()->setData(index, dataData.at(dataCount).toDouble());
dataCount++;
}
}
spreadsheet->setEditTriggers(QAbstractItemView::NoEditTriggers);
connect(spreadsheet,SIGNAL(cellPressed(int,int)),this,SLOT(onSpreadsheetCellClicked(int,int)));
//
// create a chart, setting data points from first and last col of spreadsheet
//
chart = new QChart();
chart->setAnimationOptions(QChart::AllAnimations);
QScatterSeries *series = new QScatterSeries;
col1 = 0;
col2 = numCol-3;
mLeft = true;
this->onSpreadsheetCellClicked(0,numCol-3);
QChartView *chartView = new QChartView(chart);
chartView->setRenderHint(QPainter::Antialiasing);
chartView->chart()->legend()->hide();
//
// create a widget into which we place the chart and the spreadsheet
//
QWidget *widget = new QWidget();
QVBoxLayout *layout = new QVBoxLayout(widget);
layout->addWidget(chartView, 1);
// layout->addWidget(spreadsheet, 1);
QScrollArea *tableScroll = new QScrollArea;
tableScroll->setWidgetResizable(true);
tableScroll->setLineWidth(0);
tableScroll->setFrameShape(QFrame::NoFrame);
tableScroll->setWidget(spreadsheet);
layout->addWidget(tableScroll);
//
// add 3 Widgets to TabWidget
//
tabWidget->addTab(summary,tr("Summmary"));
tabWidget->addTab(widget, tr("Data Values"));
tabWidget->adjustSize();
return result;
}
static void merge_helper(double *input, int left, int right, double *scratch)
{
// if one element: done else: recursive call and then merge
if(right == left + 1) {
return;
} else {
int length = right - left;
int midpoint_distance = length/2;
/* l and r are to the positions in the left and right subarrays */
int l = left, r = left + midpoint_distance;
// sort each subarray
merge_helper(input, left, left + midpoint_distance, scratch);
merge_helper(input, left + midpoint_distance, right, scratch);
// merge the arrays together using scratch for temporary storage
for(int i = 0; i < length; i++) {
/* Check to see if any elements remain in the left array; if so,
* we check if there are any elements left in the right array; if
* so, we compare them. Otherwise, we know that the merge must
* use take the element from the left array */
if(l < left + midpoint_distance &&
(r == right || fmin(input[l], input[r]) == input[l])) {
scratch[i] = input[l];
l++;
} else {
scratch[i] = input[r];
r++;
}
}
// Copy the sorted subarray back to the input
for(int i = left; i < right; i++) {
input[i] = scratch[i - left];
}
}
}
static int mergesort(double *input, int size)
{
double *scratch = new double[size];
if(scratch != NULL) {
merge_helper(input, 0, size, scratch);
delete [] scratch;
return 1;
} else {
return 0;
}
}
int ResultsPelicun::runPelicunAfterHPC(QString &resultsDirName,
QString &runDirName,
QString &appDirName){
//
// create workdir & copy dakotaTab.out & scInput there
//
if (!QDir(runDirName).exists()) {
QDir().mkdir(runDirName);
}
QDir runDir(runDirName);
QDir resultsDir(resultsDirName);
QDir downloadDir(resultsDirName); downloadDir.cdUp(); // templateDir.cd("templatedir");
QString downloadedTemplateDir = downloadDir.absoluteFilePath("templatedir");
QString runTemplateDir = runDir.absoluteFilePath("templatedir");
QDir templateDir(runTemplateDir);
runDir.rename(downloadedTemplateDir, runTemplateDir);
QFile::copy(resultsDir.absoluteFilePath("dakotaTab.out"),
runDir.absoluteFilePath("dakotaTab.out"));
QDir tmpDir(runTemplateDir);
QFile::copy(templateDir.absoluteFilePath("scInput.json"),
runDir.absoluteFilePath("scInput.json"));
//
// run the loss assessment
//
QDir scriptDir(appDirName);
scriptDir.cd("applications");
scriptDir.cd("Workflow");
QString pySCRIPT = scriptDir.absoluteFilePath("sWHALE.py");
QString createResponseCSV = scriptDir.absoluteFilePath("createResponseCSV.py");
QString registryFile = scriptDir.absoluteFilePath("WorkflowApplications.json");
QString inputFileName = runDir.absoluteFilePath("scInput.json");
QProcess *proc = new QProcess();
SimCenterPreferences *preferences = SimCenterPreferences::getInstance();
QString python = preferences->getPython();
QFileInfo pythonFile(python);
if (pythonFile.exists()) {
QString pythonPath = pythonFile.absolutePath();
} else {
errorMessage("No python found, see the manual");
return 0;
}
errorMessage("Now Running Pelicun to deremine losses");
#ifdef Q_OS_WIN
python = QString("\"") + python + QString("\"");
QStringList argsCSV{createResponseCSV,"--inputFile",inputFileName};
proc->execute(python, argsCSV);
QStringList args{pySCRIPT, "loss_only",inputFileName,registryFile};
proc->execute(python, args);
#else
// note the above not working under linux because basrc not being called so no env variables!!
QString sourceBash("");
QDir homeDir(QDir::homePath());
if (homeDir.exists(".bash_profile")) {
sourceBash = QString("source $HOME/.bash_profile; \"");
} else if (homeDir.exists(".bashrc")) {
sourceBash = QString("source $HOME/.bashrc; \"");
} else if (homeDir.exists(".zprofile")) {
sourceBash = QString("source $HOME/.zprofile; \"");
} else if (homeDir.exists(".zshrc")) {
sourceBash = QString("source $HOME/.zshrc; \"");
} else
this->errorMessage( "No .bash_profile, .bashrc, .zprofile or .zshrc file found. This may not find Dakota or OpenSees");
QString command = sourceBash + python + QString("\" \"") +
createResponseCSV + QString("\" --inputFile \"") + inputFileName +
QString("\" > /Users/fmckenna/output.log 2>&1; \"") + python + QString("\" \"") +
pySCRIPT + QString("\" \"loss_only\" \"") + inputFileName + QString("\" \"") +
registryFile + QString("\"");
qDebug() << "PYTHON COMMAND: " << command;
proc->execute("bash", QStringList() << "-c" << command);
#endif
proc->waitForStarted();
return 0;
}
int ResultsPelicun::processResults(QString &inputFileName,
QString &resultsDirName) {
QDir rDir(resultsDirName);
QFile inputFile(inputFileName);
inputFile.open(QFile::ReadOnly | QFile::Text);
QString val;
val=inputFile.readAll();
QJsonDocument doc = QJsonDocument::fromJson(val.toUtf8());
QJsonObject inputData = doc.object();
inputFile.close();
// If the runType is HPC, then we need to do additional operations
QString runType = inputData["runType"].toString();
qDebug() << "inputFile: " << inputFileName;
qDebug() << "resultsDIR: " << resultsDirName;
qDebug() << "runTYPE: " << runType;
if (runType == "HPC" || runType == "runningRemote"){
qDebug() << "Loaded response data from HPC, running performance assessment locally.";
QString runDirName = inputData["runDir"].toString();
QString appDirName = SimCenterPreferences::getInstance()->getAppDir();
this->runPelicunAfterHPC(resultsDirName, runDirName, appDirName);
// move the resultsDir to the runDir
resultsDirName = runDirName;
qDebug() << "Performance assessment finished successfully.";
}
qDebug() << "Loading performance assessment results";
this->clear();
mLeft = true;
col1 = 0;
col2 = 0;
//
// get a Qwidget ready to place summary data, the EDP name, mean, stdDev into
//
QWidget *summaryWidget = new QWidget();
summaryLayout = new QVBoxLayout();
summaryWidget->setLayout(summaryLayout);
//
// place contents of Dakota more detailed output into a QTextEdit
//
dakotaText = new QTextEdit();
dakotaText->setReadOnly(true); // make it so user cannot edit the contents
dakotaText->setText("\n");
// check if the main DL result file is available
QString resultsStatsFile = resultsDirName + "/DL_summary_stats.csv";
std::ifstream fileResultsStats(resultsStatsFile.toStdString().c_str());
if (!fileResultsStats.is_open()) {
// Now we know that something is wrong...
/*
// skip all of the dakota messages because they are confusing users
//
// check dakota actually ran the FE simulations so that blame may
// be properly assessed .. i.e. not always the fault of pelicun.
//
QString filenameTab = resultsDirName + QDir::separator() + "dakotaTab.out";
QFileInfo fileTabInfo(filenameTab);
QString filenameErrorString = fileTabInfo.absolutePath() + QDir::separator() + QString("dakota.err");
QFileInfo filenameErrorInfo(filenameErrorString);
if (!filenameErrorInfo.exists()) {
errorMessage("No dakota.err file - dakota did not run - problem with dakota setup or the applicatins failed with inputs provided");
return 0;
}
QFile fileError(filenameErrorString);
QString line("");
if (fileError.open(QIODevice::ReadOnly)) {
QTextStream in(&fileError);
while (!in.atEnd()) {
line = in.readLine();
}
fileError.close();
}
if (line.length() != 0) {
qDebug() << line.length() << " " << line;
errorMessage(QString(QString("Error Running Dakota: ") + line));
return 0;
}
QFileInfo filenameTabInfo(filenameTab);
if (!filenameTabInfo.exists()) {
errorMessage("No dakotaTab.out file - dakota failed .. possibly no QoI");
return 0;
}
*/
errorMessage(
QString("Could not open file: ") + resultsStatsFile +
QString(".<br>Damage and loss results are not available. See the "
"log (above) for more information on the error."));
return -1;
}
// If we get until this point, then the DL_summary_stats file is available.
//
// first 4 lines contain summary data
//
std::string summaryDummy;
std::string summaryName, summaryMean, summaryStdDev, summaryLogStdDev;
std::string summaryMin, summary10, summary50, summary90, summaryMax;
std::string tokenName, tokenMean, tokenStd, tokenLogStd;
std::string tokenMin, token10, token50, token90, tokenMax;
std::getline(fileResultsStats, summaryName);
std::getline(fileResultsStats, summaryDummy);
std::getline(fileResultsStats, summaryMean);
std::getline(fileResultsStats, summaryStdDev);
std::getline(fileResultsStats, summaryLogStdDev);
std::getline(fileResultsStats, summaryMin);
std::getline(fileResultsStats, summaryDummy);
std::getline(fileResultsStats, summaryDummy);
std::getline(fileResultsStats, summary10);
std::getline(fileResultsStats, summaryDummy);
std::getline(fileResultsStats, summary50);
std::getline(fileResultsStats, summaryDummy);
std::getline(fileResultsStats, summary90);
std::getline(fileResultsStats, summaryDummy);
std::getline(fileResultsStats, summaryDummy);
std::getline(fileResultsStats, summaryMax);
std::istringstream ssName(summaryName);
std::istringstream ssMean(summaryMean);
std::istringstream ssStd(summaryStdDev);
std::istringstream ssLogStd(summaryLogStdDev);
std::istringstream ssMin(summaryMin);
std::istringstream ss10(summary10);
std::istringstream ss50(summary50);
std::istringstream ss90(summary90);
std::istringstream ssMax(summaryMax);
std::getline(ssName, tokenName, ',');
std::getline(ssMean, tokenMean, ',');
std::getline(ssStd, tokenStd, ',');
std::getline(ssLogStd, tokenLogStd, ',');
std::getline(ssMin, tokenMin, ',');
std::getline(ss10, token10, ',');
std::getline(ss50, token50, ',');
std::getline(ss90, token90, ',');
std::getline(ssMax, tokenMax, ',');
// ignore first
int colCount = 1;
//theHeadings << "Percent";
theHeadings << "Realization";
QWidget *theSummaryHeader = this->createSummaryHeader();
summaryLayout->addWidget(theSummaryHeader);
summaryLayout->addSpacing(10);
QFrame *sepLine = new QFrame;
sepLine->setFrameShape(QFrame::HLine);
sepLine->setFrameShadow(QFrame::Sunken);
summaryLayout->addWidget(sepLine);
resultsToShow.clear();
//resultsToShow.insert("inhabitants/","inhabitants");
//resultsToShow.insert("red_tagged/","red tagged?");
resultsToShow.insert("collapse","Collapsed?");
resultsToShow.insert("irreparable","Irreparable?");
resultsToShow.insert("repair_cost","Repair Cost");
resultsToShow.insert("repair_cost-","Repair Cost");
resultsToShow.insert("repair_time","Repair Time");
resultsToShow.insert("repair_time-","Repair Time");
resultsToShow.insert("repair_time-sequential","Repair Time - sequential");
resultsToShow.insert("repair_time-parallel","Repair Time - parallel");
resultsToShow.insert("repair_carbon","Embodied Carbon in Repairs");
resultsToShow.insert("repair_carbon-","Embodied Carbon in Repairs");
resultsToShow.insert("repair_energy","Embodied Energy in Repairs");
resultsToShow.insert("repair_energy-","Embodied Energy in Repairs");
//resultsToShow.insert("injuries/sev1","injuries-1");
//resultsToShow.insert("injuries/sev2","injuries-2");
//resultsToShow.insert("injuries/sev3","injuries-3");
//resultsToShow.insert("injuries/sev4","injuries-4");
//resultsToShow.insert("highest_damage_state/S","top DS S");
//resultsToShow.insert("highest_damage_state/NSA","top DS NSA");
//resultsToShow.insert("highest_damage_state/NSD","top DS NSD");
// go along the column names in the header
while(std::getline(ssName, tokenName, ',')) {
std::getline(ssMean, tokenMean, ',');
std::getline(ssStd, tokenStd, ',');
std::getline(ssLogStd, tokenLogStd, ',');
std::getline(ssMin, tokenMin, ',');
std::getline(ss10, token10, ',');
std::getline(ss50, token50, ',');
std::getline(ss90, token90, ',');
std::getline(ssMax, tokenMax, ',');
QString DV_name(tokenName.c_str());
std::string::size_type sz;
double DV_mean = std::stod(tokenMean.c_str(), &sz);
double DV_stdDev = std::stod(tokenStd.c_str(), &sz);
double DV_logStdDev;
try{
DV_logStdDev = std::stod(tokenLogStd.c_str(), &sz);
}
catch(...){
DV_logStdDev = -1;
}
double DV_min = std::stod(tokenMin.c_str(), &sz);
double DV_10 = std::stod(token10.c_str(), &sz);
double DV_50 = std::stod(token50.c_str(), &sz);
double DV_90 = std::stod(token90.c_str(), &sz);
double DV_max = std::stod(tokenMax.c_str(), &sz);
theHeadings << DV_name;
if (resultsToShow.contains(DV_name)) {
QString DV_DisplayName = resultsToShow.value(DV_name);
QWidget *theWidget = this->createSummaryItem2(DV_DisplayName,
DV_mean, DV_stdDev, DV_logStdDev, DV_min, DV_10, DV_50, DV_90, DV_max);
summaryLayout->addWidget(theWidget);
// add a separator line after the row
QFrame *sepLine = new QFrame;
sepLine->setFrameShape(QFrame::HLine);
sepLine->setFrameShadow(QFrame::Sunken);
summaryLayout->addWidget(sepLine);
}
colCount++;
}
summaryLayout->addStretch();
//
// place summary widget in scrollable area
//
QScrollArea *summary = new QScrollArea;
summary->setWidgetResizable(true);
summary->setLineWidth(0);
summary->setFrameShape(QFrame::NoFrame);
summary->setWidget(summaryWidget);
tabWidget->addTab(summary,"Summary");
qDebug() << "Summary statistics successfully loaded.";
//
// now parse the file with all realizations
//
spreadsheet = new MyTableWidget();
std::string inputLine;
// std::getline(fileResults, inputLine);
// std::istringstream iss(inputLine);
resultsToShow.insert("#","#");
//resultsToShow.insert("Realization","#");
//resultsToShow.insert("event_time/month","month");
//resultsToShow.insert("event_time/weekday?","weekday?");
//resultsToShow.insert("event_time/hour","hour");
//resultsToShow.insert("collapses/mode","collapse mode");
QStringList modHeadings = QStringList();
for (const auto& colHeader: theHeadings){
modHeadings << resultsToShow.value(colHeader);
}
colCount = modHeadings.count();
spreadsheet->setColumnCount(colCount);
spreadsheet->setHorizontalHeaderLabels(modHeadings);
// now read the file with the detailed results
//DL_Summary
QString resultsFile = resultsDirName + "/DL_summary.csv";
std::ifstream fileResults(resultsFile.toStdString().c_str());
if (!fileResults.is_open()) {
errorMessage(
QString("Could not open file: ") + resultsFile +
QString(" . Damage and loss results are not available."));
return -1;
}
std::getline(fileResults, summaryName);
// now until end of file, read lines and place data into spreadsheet
// (do not read more than 20000 lines to avoid visualization issues)
int rowCount = 0;
while ((std::getline(fileResults, inputLine)) && (rowCount <= 20000)) {
spreadsheet->insertRow(rowCount);
std::istringstream line(inputLine);
std::string value;
int col=0;
while (std::getline(line, value, ',')) {
QModelIndex index = spreadsheet->model()->index(rowCount, col);
if (col != 0)
spreadsheet->model()->setData(index, value.c_str());
else
spreadsheet->model()->setData(index, rowCount);
col++;
}
rowCount++;
}
if (rowCount == 0) {
errorMessage("Damage and loss result file is empty.");
return -2;
}
// rowCount;
spreadsheet->setEditTriggers(QAbstractItemView::NoEditTriggers);
connect(spreadsheet,SIGNAL(cellPressed(int,int)),this,SLOT(onSpreadsheetCellClicked(int,int)));
//
// create a chart, setting data points from first and last col of spreadsheet
//
chart = new QChart();
chart->setAnimationOptions(QChart::AllAnimations);
this->onSpreadsheetCellClicked(0,colCount-3);
QChartView *chartView = new QChartView(chart);
chartView->setRenderHint(QPainter::Antialiasing);
chartView->chart()->legend()->hide();
//
// into QWidget place chart and spreadsheet
//
QWidget *widget = new QWidget();
QVBoxLayout *layout = new QVBoxLayout(widget);
layout->addWidget(chartView, 3);
layout->addWidget(spreadsheet, 1);
//
// add summary, detained info and spreadsheet with chart to the tabed widget
//
// tabWidget->addTab(summary,tr("Summmary"));
// tabWidget->addTab(dakotaText, tr("General"));
tabWidget->addTab(widget, tr("Data Values"));
tabWidget->adjustSize();
tabWidget->setCurrentIndex(0);
fileResultsStats.close();
fileResults.close();
// close input file
// clear messages
errorMessage("");
return 0;
}
int ResultsPelicun::processREDiResults(QString &inputFileName,
QString &resultsDirName) {
if(summaryLayout == nullptr)
return 0;
QDir rDir(resultsDirName);
QFile inputFile(inputFileName);
inputFile.open(QFile::ReadOnly | QFile::Text);
QString val;
val=inputFile.readAll();
QJsonDocument doc = QJsonDocument::fromJson(val.toUtf8());
QJsonObject inputData = doc.object();
inputFile.close();
auto redi_res_path = resultsDirName + QDir::separator() + "REDi_output" + QDir::separator() + "redi_summary_stats.json";
QFile resultsSummaryFile(redi_res_path);
if(!resultsSummaryFile.exists())
return 0;
resultsSummaryFile.open(QFile::ReadOnly | QFile::Text);
QString val2;
val2=resultsSummaryFile.readAll();
QJsonDocument res_doc = QJsonDocument::fromJson(val2.toUtf8());
QJsonObject resData = res_doc.object();
resultsSummaryFile.close();
if(resData.isEmpty())
this->errorMessage("Error, the REDi results file "+redi_res_path+" is empty or failed to load as json");
summaryLayout->addWidget(new QLabel("<b>REDi Recovery</b>"), 0, Qt::AlignCenter);
// add a separator line after the row
QFrame *sepLine = new QFrame;
sepLine->setFrameShape(QFrame::HLine);
sepLine->setFrameShadow(QFrame::Raised);
summaryLayout->addWidget(sepLine);
QJsonObject::const_iterator it;
for (it = resData.constBegin(); it != resData.constEnd(); ++it) {
QString key = it.key();
QJsonValue value = it.value().toObject();
auto DV_DisplayName = key;
double DV_min = value["min"].toDouble();
double DV_10 = value["0.10%"].toDouble();
double DV_50 = value["50%"].toDouble();
double DV_90 = value["90%"].toDouble();
double DV_max = value["max"].toDouble();
double DV_mean = value["mean"].toDouble();
double DV_stdDev = value["std"].toDouble();
double DV_logStdDev;
if (value["log_std"] != "") {
DV_logStdDev = value["log_std"].toDouble();
} else {
DV_logStdDev = -1;
}
QWidget *theWidget = this->createSummaryItem2(DV_DisplayName,
DV_mean, DV_stdDev, DV_logStdDev, DV_min, DV_10, DV_50, DV_90, DV_max);
summaryLayout->addWidget(theWidget);
// add a separator line after the row
QFrame *sepLine = new QFrame;
sepLine->setFrameShape(QFrame::HLine);
sepLine->setFrameShadow(QFrame::Sunken);
summaryLayout->addWidget(sepLine);
}
return 0;
}
void
ResultsPelicun::getColData(QVector<double> &data, int numRow, int col) {
bool ok;
double data0 = spreadsheet->item(0,col)->text().toDouble(&ok);
if (ok == true) {
for (int i=0; i<numRow; i++) {
QTableWidgetItem *item = spreadsheet->item(i,col);
data.append(item->text().toDouble());
}
} else { // it's a string create a map
QMap<QString, int> map;
int numDifferent = 1;
for (int i=0; i<numRow; i++) {
QTableWidgetItem *item = spreadsheet->item(i,col);
QString text = item->text();
if (map.contains(text))
data.append(map.value(text));
else {
data.append(numDifferent);
map[text] = numDifferent++;
}
}
}
return;
}
void
ResultsPelicun::getColDataExt(QList<QPointF> &dataXY, int numRow, int colX,
int colY, bool doMap) {
if (doMap == true) {
//If doMap is set to True, then we assume a list of strings and create
// a map of the results.
if (colY != colX) {
QMap<QString, int> mapX, mapY;
int numDifferentX = 0, numDifferentY = 0;
for (int i=0; i<numRow; i++) {
QString textX = spreadsheet->item(i,colX)->text();
if (mapX.contains(textX) == 0) mapX[textX] = numDifferentX++;
QString textY = spreadsheet->item(i,colY)->text();
if (mapY.contains(textY) == 0) mapY[textY] = numDifferentY++;
QPointF dataP;
dataP.setX(mapX.value(textX));