/
experimentFunctions.cpp
795 lines (729 loc) · 20.3 KB
/
experimentFunctions.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
#include "Header.h"
using namespace std;
using namespace datans;
// default constructor for Experiment objects
Experiment::Experiment(std::string name, std::vector<std::string> v) : name_(name)
{
for (auto iter = v.begin(); iter != v.end(); ++iter)
{
headings_.push_back(*iter);
}
}
// rvalue move constructor for efficient moving of Experiment objects
Experiment::Experiment(Experiment&& e)
{
// copy all types
headings_ = e.headings_;
measurementContainer_ = std::move(e.measurementContainer_);
dataHeadings_ = e.dataHeadings_;
name_ = e.name_;
// now cleanup the original
e.headings_.clear();
e.dataHeadings_.clear();
e.measurementContainer_.clear();
e.name_.clear();
}
// error calculation for experiment objects
vector<double> Experiment::errorCalc()
{
double rowCount{ 0 };
int colCount{ 0 };
vector<double> errors(headings_.size());
// iterate over rows in experiment
for (auto vec_iter = measurementContainer_.begin(); vec_iter != measurementContainer_.end(); ++vec_iter)
{
rowCount++;
// now iterate over the measurements within each row>
for (auto meas_it = (*vec_iter).begin(); meas_it != (*vec_iter).end(); ++meas_it)
{
// we need to sum error / value for the COLUMN - so for each element of the row
// we will add to the vector error in the same row format
colCount = std::distance((*vec_iter).begin(), meas_it);
if ((*meas_it)->getValue() != 0)
{
// use fabs to find absolute value for error calc
errors[colCount] += ((*meas_it)->getError() / fabs((*meas_it)->getValue()));
}
}
}
// divide by rowcount to get average error
for_each(errors.begin(), errors.end(), [rowCount](double val)
{
val = val / rowCount;
});
return errors;
}
// add measurement based on a temporary measurement
std::shared_ptr<Measurement> datans::addMeasurement(std::vector<std::string> v)
{
int vectorSize = v.size();
std::shared_ptr<Measurement> ptr; // base class pointer
std::string buf;
int checkIfNum;
switch (vectorSize)
{
// size 4 = double type
case 4:
{
double tempVal, tempErr, tempSyst;
try {
// convert to double
tempVal = stod(v[0]);
tempErr = stod(v[1]);
tempSyst = stod(v[2]);
}
catch (const std::invalid_argument& ia) {
std::cin.clear();
cerr << ia.what() << ": ";
throw "Numerical format should have numerical values only\n";
}
// date validation
istringstream ss(v[3]);
while (getline(ss, buf, '/'))
{
try {
checkIfNum = stoi(buf);
}
catch (const std::invalid_argument& ia) {
std::cin.clear();
cerr << ia.what() << ": ";
throw "Date in invalid format\n";
}
}
// create the measurement
ptr.reset(new NumMeasure(tempVal, tempErr, tempSyst, v[3]));
break;
}
// size 2 = string type
case 2:
{
// date validation
istringstream ss(v[1]);
while (getline(ss, buf, '/'))
{
try {
checkIfNum = stoi(buf);
}
catch (const std::invalid_argument& ia) {
std::cin.clear();
cerr << ia.what() << ": ";
throw "Date in invalid format\n";
}
}
ptr.reset(new StringMeasure(v[0], v[1]));
break;
}
default:
{
throw "Invalid data type! Format should be (numerical value, error, systematic error, date) or (textual value, date)\n";
break;
}
break;
}
return ptr;
}
// read experiment in either from file or from default data folder
void datans::readExperiment(std::string n, std::map<std::string, Experiment> &u, char readFlag)
{
std::ifstream dataFile;
std::string tempLine, tempLine2, buf; // one for the total line, one for in between tabs
std::vector<std::string> tempHeadings, tempDataHeadings, tempMeasurement;
std::vector<shared_ptr<Measurement>> rowMeasurement;
std::string filePath;
// reading from data folder
if (readFlag == 'r')
{
dataFile.open(".//data//" + n);
n.erase(n.end()-4, n.end());
}
// filepath parsed from openFileDialogue
else if (readFlag == 'f')
{
dataFile.open(n);
// reassign n to be just the name
filePath = n;
n = fileNameFromPath(n);
}
if (dataFile.is_open())
{
// read the first line which will be headings
std::getline(dataFile, tempLine);
std::stringstream ss(tempLine);
while (ss >> buf)
{
tempHeadings.push_back(buf);
}
// create temporary object
Experiment tempExp(n, tempHeadings);
tempDataHeadings.resize(tempHeadings.size());
static int counter{ 0 };
// position should now be on the second line
while (std::getline(dataFile, tempLine))
{
int colCount{ 0 };
try {
// we read the whole line, then each measurement is tab delineated, so split into n strings (each string is a measurement)
// then create each measurement and push that back into a row. row is then pushed back into the measurement container
std::stringstream ss(tempLine);
while (std::getline(ss, tempLine2, '\t'))
{
std::stringstream ss2(tempLine2);
while (ss2 >> buf)
{
tempMeasurement.push_back(buf);
}
// can only be size 4 or 2
if (tempMeasurement.size() != 4 || tempMeasurement.size() != 2)
{
throw("Measurement should be in one of the specified formats");
}
// only execute once to set dataheadings
if (counter == 0)
{
if (tempMeasurement.size() == 4)
{
tempDataHeadings[colCount] = "Val Err SEerr Date ";
}
else if (tempMeasurement.size() == 2)
{
tempDataHeadings[colCount] = "Val Date ";
}
else
{
perror("Data should be in format specified");
}
}
else
// compare other measurements to the first to ensure same type down columns
// by the size of measurement compared to the length of dataheadings
{
if ((tempDataHeadings[colCount].length() < 13 && tempMeasurement.size() == 4) || (tempDataHeadings[colCount].length() > 13 && tempMeasurement.size() == 2))
{
throw("Measurements in a column should be of the same type");
}
}
colCount++;
// try catch to find invalid input; no recovery (user must fix their file)
try {
rowMeasurement.push_back(std::move(addMeasurement(tempMeasurement)));
}
catch (const char* msg) {
cerr << msg;
cerr << "Check format of file " << n << " and try again." << endl;
std::cin.clear();
return;
}
tempMeasurement.clear();
}
tempExp.measurementContainer_.emplace_back(std::move(rowMeasurement));
}
catch (const char* msg) {
cerr << msg << endl;
std::cin.clear();
}
}
tempHeadings.clear();
// if file is from openFileDialogue, save the experiment locally to data folder
if (readFlag == 'f')
{
// for checking file exists and can be wrote to
int check = tempExp.saveExperiment('s');
if (check != 1)
{
return;
}
}
// move object to the map
u[n] = std::move(tempExp);
u[n].dataHeadings_ = tempDataHeadings;
dataFile.close();
std::cout << "Experiment " << n << " loaded successfully\n";
return;
}
else
{
perror("Could not find or read file\n");
return;
}
}
// add experiment by hand
void datans::addExperiment(std::map<std::string, Experiment> &u)
{
std::string tempName, tempStr, buf;
std::vector<std::string> tempHeadings, tempDataHeadings;
char existsFlag;
std::cout << "Enter experiment name (q to quit): ";
std::getline(std::cin, tempName);
if (tempName == "q")
{
cout << "Aborting...\n";
return;
}
// check if the experiment exists, if so can overwrite, if not exit
std::map<std::string, Experiment>::iterator ptr;
ptr = u.find(tempName);
if (ptr != u.end())
{
cout << "Experiment with this name already exists! Overwrite? (Y/N): ";
cin >> existsFlag;
cin.ignore();
if (tolower(existsFlag) == 'n')
{
cout << "Aborting...\n";
return;
}
}
std::cout << "\nEnter headings, space delimited - units in () i.e. Voltage(V) (q to quit): ";
std::getline(std::cin, tempStr);
if (tempStr == "q")
{
cout << "Aborting...\n";
return;
}
std::stringstream ss(tempStr);
while (ss >> buf)
{
tempHeadings.push_back(buf);
}
// create temporary object
Experiment tempExp(tempName, tempHeadings);
tempDataHeadings.resize(tempHeadings.size());
char loopFlag('y'); // for do-while loop
char isGood('y'); // for retrying of try-catch loop
std::vector<string> tempMeasurement;
std::vector<std::shared_ptr<Measurement>> rowMeasurement;
static int counter{ 0 };
do
{
for (unsigned int i = 0; i < tempHeadings.size(); ++i)
{
do {
try {
std::cout << "Enter data " << counter + 1 << " for " << tempHeadings[i] << " (space delimited).";
std::cout << " Example formats: \"10 2 2 2016/05/03\" or \"Red 2016/05/03\" (q to quit):\n";
std::getline(std::cin, tempStr);
if (tempName == "q")
{
cout << "Aborting...\n";
return;
}
std::stringstream ss(tempStr);
while (ss >> buf)
{
tempMeasurement.push_back(buf);
}
if (tempMeasurement.size() != 4 || tempMeasurement.size() != 2)
{
throw("Measurement should be in one of the specified formats");
}
// only need to execute this code once to set dataheadings
if (counter == 0)
{
if (tempMeasurement.size() == 4)
{
tempDataHeadings[i] = "Value Err Systerr Date";
}
else if (tempMeasurement.size() == 2)
{
tempDataHeadings[i] = "Value Date";
}
else
{
cerr << "Data of invalid size";
}
}
else
// now we compare other measurements to the first to ensure same type down columns
{
if ((tempDataHeadings[i].length() < 13 && tempMeasurement.size() == 4) || (tempDataHeadings[i].length() > 13 && tempMeasurement.size() == 2))
{
throw("Measurements in a column should be of the same type");
}
}
rowMeasurement.push_back(std::move(addMeasurement(tempMeasurement)));
tempMeasurement.clear();
isGood = 'y'; // flag set if no error is caught
}
// if the data is in an invalid format (throw from addMeasurement)
catch (const char* msg) {
cerr << msg << endl;
std::cin.clear();
isGood = 'n'; // set flag so that try-catch loop will retry
}
if (isGood != 'n') // we only push back the row if data has been added successfully
{
tempExp.measurementContainer_.emplace_back(std::move(rowMeasurement));
rowMeasurement.clear();
break;
}
else
{
rowMeasurement.clear();
tempMeasurement.clear();
}
} while (isGood == 'n');
}
counter++;
std::cout << "Continue to add data? (Current rows: " << counter << ") (Y/N): ";
std::cin >> loopFlag;
std::cin.ignore();
} while (loopFlag == 'Y' || loopFlag == 'y');
// save the experiment locally
int check = tempExp.saveExperiment('s');
if (check != 1)
{
std::cout << "Could not save experiment to file.\n";
return;
}
// move object to map
u[tempName] = std::move(tempExp);
u[tempName].dataHeadings_ = tempDataHeadings;
}
// print experiment to console
int Experiment::printExperiment()
{
const char seperator = ' ';
const int width = WIDTH;
// extra spacing to offset the row numbers
std::cout << endl;
std::cout << " ";
// print out header numbers
for (unsigned int i = 0; i < headings_.size(); ++i)
{
std::cout << std::left << std::setw(width) << setfill(seperator) << i+1;
}
std::cout << endl;
std::cout << " ";
// print out the headings
for_each(headings_.begin(), headings_.end(), [width, seperator](std::string h)
{
std::cout << std::left << std::setw(width) << setfill(seperator) << h;
});
std::cout << endl;
std::cout << " ";
// print out column titles
for_each(dataHeadings_.begin(), dataHeadings_.end(), [width, seperator](std::string h)
{
std::cout << std::left << std::setw(width) << setfill(seperator) << h;
});
std::cout << endl;
// print measurements
int rowcount{ 1 };
// iterating over the container
for (auto vec_iter = measurementContainer_.begin(); vec_iter != measurementContainer_.end(); ++vec_iter)
{
std::cout << rowcount << " ";
// iterating over the measurements in the row
for (vector<std::shared_ptr<Measurement>>::iterator meas_it = (*vec_iter).begin(); meas_it != (*vec_iter).end(); ++meas_it)
{
(*meas_it)->printInfo(seperator);
}
rowcount++;
std::cout << endl;
}
// print out % error
std::vector<double> errors = errorCalc();
std::cout << " ";
for_each(errors.begin(), errors.end(), [width, seperator](double e)
{
std::cout << std::left << std::setw(width/4) << "% error: ";
if (e != 0)
{
std::cout << std::setw(width-10) << e << std::setfill(seperator);
}
else
{
std::cout << std::setw(width-10) << "N/A" << std::setfill(seperator);
}
});
std::cout << endl;
return 1;
}
int Experiment::editExperiment()
{
// print the experiment first for user reference
cout << endl;
printExperiment();
vector<int> coordinates; // [0] = row [1] = col
std::string tempCoord;
std::string tempStr, buf;
std::vector<std::string> tempMeasurement;
char continueFlag = ('y');
const char seperator = ' ';
const int width = WIDTH;
// for checking whether operations completed successfully
int check{ 0 };
int checkSave{ 0 };
int checkInputType{ 0 };
do {
cout << "\nEdit which measurement? (Row, column) (q to quit): ";
std::getline(cin, tempCoord);
if (tempCoord == "q")
{
cout << "Aborting...\n";
return -1;
}
// need to sanitise coordinate input - check for comma somewhere in string
if (tempCoord.find(',') != std::string::npos)
{
// read string, split the string by comma and push back
std::stringstream ss(tempCoord);
while (ss.good())
{
std::string substr;
getline(ss, substr, ',');
// check input is numerical
if (!substr.empty() && substr.find_first_not_of("123456789") == std::string::npos)
{
// check range is valid
if (stoi(substr) - 1 < static_cast<int>(headings_.size()))
{
// -1 as user inputs starting from 1 for readability
coordinates.push_back(stoi(substr) - 1);
}
}
else
{
cout << "\nColumn out of range\n";
return -1;
}
}
}
else
{
cout << "\nIncorrect row/column format.\n";
return -1;
}
measurementContainer_[coordinates[0]][coordinates[1]]->printInfo(seperator);
cout << endl << "\nEnter new data, space delimited (date will update automatically).";
cout << "Example format: \"20 23 3\" or \"Red\" (q to quit): ";
std::getline(std::cin, tempStr);
if (tempStr == "q")
{
cout << "Aborting...\n";
return -1;
}
std::stringstream ss2(tempStr);
while (ss2 >> buf)
{
tempMeasurement.push_back(buf);
}
// check if operation completed successfully
check = measurementContainer_[coordinates[0]][coordinates[1]]->updateInfo(tempMeasurement);
tempMeasurement.clear();
coordinates.clear();
// we will only print the experiment if any data has changed; updateInfo returns -1 if invalid
if (check == 1)
{
cout << "Measurement edited successfully" << endl;
printExperiment();
}
cout << "\nContinue editing experiment? (Y/N): ";
std::cin >> continueFlag;
std::cin.ignore();
} while (tolower(continueFlag) == 'y');
// update the experiment file in /data
if (check == 1)
{
checkSave = saveExperiment('s');
}
if (checkSave == 1)
{
return 1;
}
else
{
cout << "No changes made to experiment " << name_ << ".\n";
return -1;
}
}
int Experiment::saveExperiment(char saveFlag)
{
char typeFlag;
std::string filename;
if (saveFlag == 'e')
{
// check how we are saving the file
cout << "Save to which format? [T]ext / [C]SV / [L]atex (q to quit): ";
cin >> typeFlag;
switch (tolower(typeFlag))
{
case 't':
filename = name_ + ".txt";
break;
case 'c':
filename = name_ + ".csv";
break;
case 'l':
filename = name_ + ".tex";
break;
case 'q':
cout << "Aborting...\n";
return -1;
default:
cout << "Command not recognised\n";
return -1;
}
}
else if (saveFlag == 's')
{
filename = name_ + ".txt";
typeFlag = 't';
}
if (isFileExist(filename) == true)
{
char saveFlag;
std::cout << "File " << filename << " already exists. Overwrite? (Y/N): ";
std::cin >> saveFlag;
if (saveFlag == 'N' || saveFlag == 'n')
{
std::cout << "\nSave operation aborted.\n";
return -1;
}
}
// if file doesn't exist (or user chooses to overwrite)
ofstream dataFile(".//data//" + filename);
if (dataFile.is_open())
{
switch (typeFlag)
{
case 't':
// save headings
for (auto vec_iter = headings_.begin(); vec_iter != headings_.end(); ++vec_iter)
{
dataFile << (*vec_iter) << "\t";
}
dataFile << std::endl;
// passed by reference so we can access the info properly
// iterate over container rows
for (auto& vec_iter = measurementContainer_.begin(); vec_iter != measurementContainer_.end(); ++vec_iter)
{
// iterate over individual rows
for (auto& meas_it = (*vec_iter).begin(); meas_it != (*vec_iter).end(); ++meas_it)
{
dataFile << (*meas_it)->saveInfo(typeFlag); // flag determines how file is saved
}
dataFile << endl;
}
break;
case 'c':
// save headings
for (auto vec_iter = headings_.begin(); vec_iter != headings_.end(); ++vec_iter)
{
dataFile << (*vec_iter) << "\t";
}
dataFile << std::endl;
for (auto& vec_iter = measurementContainer_.begin(); vec_iter != measurementContainer_.end(); ++vec_iter)
{
for (auto& meas_it = (*vec_iter).begin(); meas_it != (*vec_iter).end(); ++meas_it)
{
dataFile << (*meas_it)->saveInfo(typeFlag);
}
dataFile << endl;
}
break;
case 'l':
std::string buf;
std::string tempStr;
// latex formatting has some requirements for the document
dataFile << "\\documentclass{article}" << endl;
dataFile << "\\newcommand\\tab[1][0.8cm]{\\hspace*{#1}}" << endl;
dataFile << "\\begin{document}" << endl;
dataFile << "\\title{" << name_ << "}" << endl;
dataFile << "\\begin{center}" << endl;
dataFile << "\\begin{tabular}{";
for (size_t i = 0; i < headings_.size(); ++i)
{
dataFile << "|c";
}
dataFile << "|}" << endl;
dataFile << "\\hline" << endl;
int counter{ 0 }; // to make sure & not at the end of line
for (auto vec_iter = headings_.begin(); vec_iter != headings_.end(); ++vec_iter)
{
dataFile << (*vec_iter);
if (counter != (distance(headings_.begin(), headings_.end()))-1)
{
dataFile << " & ";
}
++counter;
}
dataFile << "\\\\ [0.5ex]" << std::endl;
dataFile << "\\hline" << endl;
counter = 0; // to make sure & not at the end of line
for (auto vec_iter = dataHeadings_.begin(); vec_iter != dataHeadings_.end(); ++vec_iter)
{
// open stringstream on (*vec_iter)
istringstream ss(*vec_iter);
while (ss >> buf)
{
dataFile << buf;
dataFile << "\\tab ";
}
if (counter != (distance(dataHeadings_.begin(), dataHeadings_.end())) - 1)
{
dataFile << " & ";
}
++counter;
}
dataFile << "\\\\ [0.5ex]" << std::endl;
dataFile << "\\hline\\hline" << endl;
for (auto& vec_iter = measurementContainer_.begin(); vec_iter != measurementContainer_.end(); ++vec_iter)
{
counter = 0; // to make sure & not at the end of line
for (auto& meas_it = (*vec_iter).begin(); meas_it != (*vec_iter).end(); ++meas_it)
{
dataFile << (*meas_it)->saveInfo(typeFlag);
if (counter != (distance((*vec_iter).begin(), (*vec_iter).end())) - 1)
{
dataFile << " & ";
}
++counter;
}
dataFile << "\\\\" << endl;
dataFile << "\\hline" << endl;
}
dataFile << "\\end{tabular}" << endl;
dataFile << "\\end{center}" << endl;
dataFile << "\\end{document}" << endl;
break;
}
dataFile.close();
cout << "File " << filename << " saved successfully" << endl;
return 1;
}
else
{
perror("Could not open file\n");
return -1;
}
}
int Experiment::deleteExperiment(std::map<std::string, Experiment> &u)
{
char deleteFlag;
std::cout << "Confirm deletion of experiment " << (*this).name_ << " (Y/N): " << endl;
cin >> deleteFlag;
if (tolower(deleteFlag) == 'y')
{
// create a string to filepath then pass this as a const char * to remove
std::string filePath = ".//data//" + name_ + ".txt";
if (remove(filePath.c_str()) != 0)
{
// print error file not found
perror("Error deleting data file");
return -1;
}
else
{
// delete the pair from the map
u.erase(name_);
std::cout << "Experiment deleted successfully" << endl;
return 1;
}
}
else
{
std::cout << "Aborting deletion" << endl;
return -1;
}
}