- read_csv.hpp: replace std::exit(1) with std::runtime_error throw - read_csv.hpp: remove duplicate #pragma once - RNG.cc: wrap JSON load in try-catch to prevent crash on missing config - Generator.cc: fix comments to reflect actual 3-pass structure
67 lines
1.7 KiB
C++
67 lines
1.7 KiB
C++
#pragma once
|
|
#include <fstream>
|
|
#include <iostream>
|
|
#include <sstream>
|
|
#include <stdexcept>
|
|
#include <string>
|
|
#include <type_traits>
|
|
#include <vector>
|
|
namespace ReadCSV {
|
|
using std::string;
|
|
using std::vector;
|
|
const string dir_root = "/users/dsc/code/TestProject/data_files";
|
|
template <typename T>
|
|
struct ReadCSV {
|
|
vector<vector<T>> operator()(string file_name) {
|
|
vector<vector<T>> res;
|
|
string file_dir = dir_root + "/" + file_name;
|
|
std::ifstream infile(file_dir, std::ios::in);
|
|
string line;
|
|
string word;
|
|
using std::is_same_v;
|
|
if (!infile.is_open()) {
|
|
throw std::runtime_error("Cannot open CSV file: " + file_dir);
|
|
}
|
|
while (std::getline(infile, line)) {
|
|
std::istringstream sin;
|
|
sin.str(line);
|
|
vector<T> line_data;
|
|
while (std::getline(sin, word, ',')) {
|
|
if constexpr (is_same_v<T, double>) {
|
|
line_data.push_back(std::stod(word));
|
|
} else if constexpr (is_same_v<T, int>) {
|
|
line_data.push_back(std::stoi(word));
|
|
}
|
|
}
|
|
res.push_back(line_data);
|
|
}
|
|
return res;
|
|
}
|
|
};
|
|
using ReadCSVF = ReadCSV<double>;
|
|
using ReadCSVI = ReadCSV<int>;
|
|
|
|
template <typename T>
|
|
struct FlowData {
|
|
ReadCSVF readf;
|
|
ReadCSVI readi;
|
|
vector<vector<T>> data;
|
|
int length;
|
|
int cols;
|
|
FlowData(string file_name = "D102-1#酸槽数据.csv") {
|
|
if constexpr (is_same_v<T, double>) {
|
|
data = readf(file_name);
|
|
} else if constexpr (is_same_v<T, int>) {
|
|
data = readi(file_name);
|
|
}
|
|
length = data.size();
|
|
cols = data[0].size();
|
|
}
|
|
double operator()(int index, int col) {
|
|
return data[index % length][col % cols];
|
|
}
|
|
};
|
|
|
|
using DoubleData = FlowData<double>;
|
|
using IntData = FlowData<int>;
|
|
}; // namespace ReadCSV
|