Belle II Software development
IO_csv.h
1/**************************************************************************
2 * basf2 (Belle II Analysis Software Framework) *
3 * Author: The Belle II Collaboration *
4 * *
5 * See git log for contributors and copyright holders. *
6 * This file is licensed under LGPL-3.0, see LICENSE.md. *
7 **************************************************************************/
8#pragma once
9
10#include <iostream>
11#include <fstream>
12#include <vector>
13#include <map>
14#include <string>
15#include <optional>
16#include <string>
17#include <vector>
18#include <map>
19#include "trg/klm/modules/klmtrigger/ntuples_full.h"
20
21
22template <int N = 0>
23auto & get_IO_csv_handle()
24{
25 struct data {
26 int event_nr = 0;
27 std::string dump_path;
28 std::map<std::string, std::optional<std::ofstream>> files;
29 bool do_dump = false;
30 };
31 static data m_data{};
32 return m_data;
33
34}
35
36
37
38template <typename T>
39void save(std::string filename, T&& content)
40{
41 if (content.empty()) {
42 return;
43 }
44 auto& o_file = get_IO_csv_handle().files[filename];
45
46 if (!o_file) {
47 std::ofstream ofs;
48 // Open the file
49 ofs.open(filename);
50
51 // Check if the file is successfully opened
52 if (!ofs.is_open()) {
53 throw std::runtime_error("unable to open file: " + filename);
54 }
55 o_file = std::move(ofs);
56
57 *o_file << "gevent_number";
58 const auto& row = content[0];
59
60 nt::ntuple_for_each(row,
61 [&](auto & ele) {
62 *o_file << "," << ele.get_name();
63 }
64 );
65
66 *o_file << '\n';
67
68 }
69
70
71
72 for (const auto& row : content) {
73 *o_file << get_IO_csv_handle().event_nr;
74 nt::ntuple_for_each(row,
75 [&](auto & ele) {
76 *o_file << ',' << ele.v;
77 }
78 );
79
80 *o_file << '\n';
81 }
82
83}
84
85
86template <typename T>
87void save_internal(std::string source_file, int lineno, std::string variable_name, T&& content)
88{
89 if (!get_IO_csv_handle().do_dump) {
90 return;
91 }
92 auto itterA = source_file.find_last_of("\\");
93 auto itterB = source_file.find_last_of("/");
94 itterB = itterB < source_file.size() ? itterB : 0;
95 itterA = itterA < source_file.size() ? itterA : 0;
96 auto itter = std::max(itterA, itterB);
97
98 auto file = source_file.substr(itter + 1);
99
100 file = get_IO_csv_handle().dump_path + file + "_" + std::to_string(lineno) + "_" + variable_name + ".csv";
101 //std::cout << source_file << " " << variable_name << " " << file << "\n";
102 save(file, content);
103}
104
105
106#define __CSV__WRITE_W_lINE__(x) save_internal(__FILE__, __LINE__, #x, x)
107#define __CSV__WRITE__(x) save_internal(__FILE__, 0, #x, x)
108
109