Hyperiso 1.0.3
Modular flavour-physics calculations, Wilson coefficients and statistical inference
Loading...
Searching...
No Matches
CsvWriter.cpp
Go to the documentation of this file.
1#include "CsvWriter.h"
2
3void CsvWriter::write(const DataSet& ds, const OutputSpec& spec) {
4 std::ofstream out(path_);
5 if (!out) throw std::runtime_error("Cannot open CSV file: " + path_);
6
7 const char sep = spec.csv_sep;
8
9 std::vector<std::string> header;
10 header.reserve(ds.vars.size() + ds.outputs_schema.size());
11 for (const auto& v : ds.vars) header.push_back(v.name);
12
13 std::vector<std::string> outCols = ds.outputs_schema;
14 if (outCols.empty()) {
15 std::unordered_set<std::string> uniq;
16 for (const auto& p : ds.points)
17 for (const auto& kv : p.y) uniq.insert(kv.first);
18
19 outCols.assign(uniq.begin(), uniq.end());
20 std::sort(outCols.begin(), outCols.end());
21 }
22
23 if (!spec.keys.empty()) {
24 std::unordered_set<std::string> wanted(spec.keys.begin(), spec.keys.end());
25 std::vector<std::string> filtered;
26 filtered.reserve(outCols.size());
27 for (auto& k : outCols) if (wanted.count(k)) filtered.push_back(k);
28 outCols = std::move(filtered);
29 }
30
31 header.insert(header.end(), outCols.begin(), outCols.end());
32
33 if (spec.csv_write_header) {
34 write_row(out, header, sep);
35 }
36
37 for (const auto& p : ds.points) {
38 std::vector<std::string> row;
39 row.reserve(header.size());
40
41 for (size_t i = 0; i < ds.vars.size(); ++i) {
42 double val = (i < p.x.size()) ? p.x[i] : 0.0;
43 row.push_back(double_to_string(val));
44 }
45
46 for (const auto& col : outCols) {
47 auto it = p.y.find(col);
48 if (it == p.y.end()) row.push_back("");
49 else row.push_back(escape_csv(to_string_value(it->second), sep));
50 }
51
52 write_row(out, row, sep);
53 }
54}
55
56std::string CsvWriter::double_to_string(double x) {
57 std::ostringstream oss;
58 oss << std::setprecision(17) << x;
59 return oss.str();
60}
61
62void CsvWriter::write_row(std::ostream& os,
63 const std::vector<std::string>& cells,
64 char sep)
65{
66 for (size_t i = 0; i < cells.size(); ++i) {
67 if (i) os << sep;
68 os << cells[i];
69 }
70 os << "\n";
71}
72
73std::string CsvWriter::escape_csv(std::string s, char sep) {
74 // RFC4180 (simplified)
75 bool need = false;
76 for (char c : s) {
77 if (c == sep || c == '"' || c == '\n' || c == '\r') { need = true; break; }
78 }
79 if (!need) return s;
80
81 std::string out;
82 out.reserve(s.size() + 2);
83 out.push_back('"');
84 for (char c : s) {
85 if (c == '"') out += "\"\"";
86 else out.push_back(c);
87 }
88 out.push_back('"');
89 return out;
90}
std::string to_string_value(const Value &v)
Definition UtilOutput.h:7
void write(const DataSet &ds, const OutputSpec &spec) override
Definition CsvWriter.cpp:3
std::vector< DataPoint > points
std::vector< std::string > outputs_schema
std::vector< ScanVar > vars
bool csv_write_header
std::vector< std::string > keys