ECF 1.5
fileparser.cpp
1#include <ECF_macro.h>
2#include <iostream>
3#include <boost/algorithm/string.hpp>
4#include <set>
5#include <map>
6#include "fileparser.h"
7
8
9namespace utility{
10 std::vector<std::string> parseCSVFromFile(const std::string& file_name)
11 {
12 std::vector<std::string> parsed;
13 std::ifstream in_file(file_name.c_str());
14 if(!in_file) {
15 std::cerr << "Parser could not load a .csv file named: " << file_name << '\n';
16 exit(-1);
17 }
18 for(std::string line; getline(in_file,line);) {
19 parsed.push_back(line);
20 }
21 in_file.close();
22 return parsed;
23 }
24
25
26 PairAllFeaturesAllLabels parseStringIntoFeaturesAndLabels(const std::vector<std::string>& csv, bool leadsWithID)
27 {
28 std::vector<std::vector<double> > allFeatures;
29 std::vector<uint> allLabels;
30 std::set<int> distinct;
31 std::map<std::string,int> keyLabelMap;
32 uint generalClassLabel = 0;
33 for(uint i = 0; i < csv.size(); i++) {
34 std::vector<std::string> splitsContainer;
35 boost::split(splitsContainer, csv[i], boost::is_any_of(","));
36 std::vector<double> features;
37 for(uint j = leadsWithID ? 1 : 0; j < splitsContainer.size() - 1; j++) {
38 features.push_back(str2dbl(splitsContainer[j]));
39 }
40 allFeatures.push_back(features);
41 std::string last = splitsContainer[splitsContainer.size() -1];
42 if(keyLabelMap.find(last) == keyLabelMap.end()) {
43 keyLabelMap.insert(std::make_pair(last,generalClassLabel));
44 allLabels.push_back(generalClassLabel);
45 distinct.insert(generalClassLabel);
46 generalClassLabel++;
47 }
48 else {
49 allLabels.push_back(keyLabelMap[last]);
50 }
51
52 }
53 return std::make_pair(allFeatures,allLabels);
54 }
55
56 std::pair<std::vector<double>,double> parseArgumentsAndFunctionValues(const std::string& line)
57 {
58 std::vector<std::string> splitsContainer;
59 boost::split(splitsContainer,line,boost::algorithm::is_space());
60 std::vector<double> arguments;
61 double functionValue;
62 for(uint i = 0; i < splitsContainer.size() - 1; i++) {
63 try{
64 arguments.push_back(str2dbl(splitsContainer[i]));
65 }catch(std::exception& ex) {
66 std::cerr << "An error occurred while converting a string into a double: " << splitsContainer[i] << '\n';
67 }
68 }
69 try{
70 functionValue = str2dbl(splitsContainer[splitsContainer.size() -1]);
71 }catch(std::exception& ex) {
72 std::cerr << "An error occured while converting a string into a double: " << splitsContainer[splitsContainer.size() - 1] << '\n';
73 }
74// for(uint i = 0; i < arguments.size(); i++) {
75// std::cout << i << " " << arguments[i] << '\n';
76// }
77 return std::make_pair(arguments,functionValue);
78 }
79}