cpp/io.cpp
2024-08-20 17:51:49 +02:00

127 lines
3.4 KiB
C++

//
// Created by dominik on 8/14/24.
//
#include "io.h"
#include <sstream>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <unordered_map>
#include <map>
#include <string>
#include <filesystem>
Arguments parse_args(const int argc, char **argv) {
if (argc < 2) {
throw std::runtime_error("Not enough arguments: missing parameter file");
}
Arguments args;
for (int i=1; i<argc; i++) {
if (std::string arg = argv[i]; arg[0] == '-') {
if (arg == "-ste") {
args.ste = true;
} else if (arg == "-spectrum") {
args.spectrum = true;
} else {
throw std::runtime_error("Unrecognized option: " + arg);
}
} else if (args.parameter_file.empty()) {
args.parameter_file = arg;
} else {
throw std::runtime_error("Too many options for parameter file");
}
}
if (args.parameter_file.empty()) {
throw std::runtime_error("Missing parameter file");
}
return args;
}
std::unordered_map<std::string, double> read_parameter(const std::filesystem::path& infile) {
if (!std::filesystem::exists(infile)) {
std::cerr << "File " << infile << " does not exist" << std::endl;
exit(1);
}
std::ifstream instream(infile);
std::unordered_map<std::string, double> parameter;
std::string line;
std::string delim = "=";
std::string key;
std::string value;
size_t delim_pos;
while (std::getline(instream, line)) {
if (line[0] == '#' || line.length() == 1) continue;
line.erase(std::remove(line.begin(), line.end(), ' '), line.end());
delim_pos = line.find('=');
key = line.substr(0, delim_pos);
value = line.substr(delim_pos+1);
parameter[key] = std::stod(value);
}
std::cout << "Found parameter\n";
for (const auto& [key, value]: parameter) {
std::cout << " " << key << ": " << std::to_string(value) << "\n";
}
std::cout << std::endl;
return parameter;
}
void fid_write_out(const std::string& filename, const std::vector<double>& x, const std::vector<double>& y, const double tau, const double t_evo) {
auto size = x.size();
std::ostringstream sfile;
sfile << filename << "_";
sfile << std::setprecision(6) << std::scientific;
sfile << "tau=" << tau << "_tevo=" << t_evo << ".dat";
{
std::string outfile = sfile.str();
std::ofstream fid_file(outfile, std::ios::out);
for (unsigned int i = 0; i < size; i++) {
fid_file << x[i] << "\t" << y[i] << "\n";
}
}
}
void fid_write_out(const std::string& filename, const std::vector<double>& x, const std::map<double, std::vector<double>>& y, const double tau) {
auto size = x.size();
std::ostringstream sfile;
sfile << filename << "_";
sfile << std::setprecision(6) << std::scientific;
sfile << "tau=" << tau << ".dat";
{
std::string outfile = sfile.str();
std::ofstream fid_file(outfile, std::ios::out);
fid_file << "#";
for (const auto& [t_echo_j, _] : y) {
fid_file << t_echo_j << "\t";
}
fid_file << std::endl;
for (unsigned int i = 0; i < size; i++) {
fid_file << x[i];
for (const auto& [_, fid_j] : y) {
fid_file << "\t" << fid_j[i];
}
fid_file << "\n";
}
}
}