R3BROOT
R3B analysis software
Loading...
Searching...
No Matches
R3BNeulandMillepede.cxx
Go to the documentation of this file.
1/******************************************************************************
2 * Copyright (C) 2019 GSI Helmholtzzentrum für Schwerionenforschung GmbH *
3 * Copyright (C) 2019-2023 Members of R3B Collaboration *
4 * *
5 * This software is distributed under the terms of the *
6 * GNU General Public Licence (GPL) version 3, *
7 * copied verbatim in the file "LICENSE". *
8 * *
9 * In applying this license GSI does not waive the privileges and immunities *
10 * granted to it by virtue of its status as an Intergovernmental Organization *
11 * or submit itself to any jurisdiction. *
12 ******************************************************************************/
13
14#include "R3BNeulandMillepede.h"
15#include "Mille.h"
16#include "ParResultReader.h"
17#include "R3BDataMonitor.h"
18#include "R3BNeulandCalData2.h"
21#include <R3BException.h>
23#include <R3BNeulandCommon.h>
24#include <SteerWriter.h>
25
26#include <TGraphErrors.h>
27#include <TH1.h>
28#include <algorithm>
29#include <array>
30#include <cstdlib>
31#include <fairlogger/Logger.h>
32#include <filesystem>
33#include <fmt/core.h>
34#include <iterator>
35#include <memory>
36#include <numeric>
37#include <optional>
38#include <range/v3/algorithm/all_of.hpp>
39#include <range/v3/iterator/operations.hpp>
40#include <range/v3/numeric/accumulate.hpp>
41#include <range/v3/view/all.hpp>
42#include <range/v3/view/filter.hpp>
43#include <range/v3/view/sliding.hpp>
44#include <range/v3/view/transform.hpp>
45#include <stdexcept>
46#include <string>
47#include <string_view>
48#include <utility>
49#include <vector>
50
51namespace rng = ranges;
52
53constexpr auto DEFAULT_RES_FILENAME = "millepede.res";
54constexpr auto SCALE_FACTOR = 10.F;
55// constexpr auto REFERENCE_BAR_NUM = 25;
56constexpr auto MILLE_BUFFER_SIZE = std::size_t{ 100000 };
57constexpr auto DEFAULT_T_ERROR = 2; // ns
58
59namespace
60{
61 void calculate_time_offset(R3B::Neuland::Cal2HitPar& cal_to_hit_par)
62 {
63 auto& module_pars = cal_to_hit_par.GetListOfModuleParRef();
64 for (auto& [module_num, module_par] : module_pars)
65 {
66 if (module_par.effective_speed.value != 0)
67 {
68 module_par.t_diff = module_par.t_diff / module_par.effective_speed;
69 }
70 }
71 }
72
73 void change_time_offset(R3B::Neuland::Cal2HitPar& cal_to_hit_par)
74 {
75 auto& module_pars = cal_to_hit_par.GetListOfModuleParRef();
76 for (auto& [module_num, module_par] : module_pars)
77 {
78 module_par.t_diff = module_par.t_diff * module_par.effective_speed;
79 }
80 }
81} // namespace
82
84{
86 {
88 fs::create_directories(fs::path(working_dir_));
89 cal_to_hit_par_ = GetTask()->GetCal2HitPar();
90
91 par_result_.set_filename((fs::path(working_dir_) / DEFAULT_RES_FILENAME).string());
92 pede_launcher_.set_steer_filename(pede_steer_filename_);
93 pede_launcher_.set_parameter_filename(parameter_filename_);
94 if (const auto* r3b_dir = std::getenv("R3BROOTPATH"); r3b_dir != nullptr)
95 {
96 pede_launcher_.set_binary_dir(fmt::format("{}/bin", r3b_dir));
97 // TODO: make subdir configurable
98 pede_launcher_.set_working_dir(fs::absolute(fs::path{ working_dir_ }).string());
99 }
100 else
101 {
102 throw R3B::runtime_error(
103 "Environment variable R3BROOTPATH is not defined! Did you forget to source the \"config.sh\" file?");
104 }
105 binary_data_writer_ = std::make_unique<Mille>((fs::path{ working_dir_ } / input_data_filename_).string());
106 binary_data_writer_->set_buffer_size(MILLE_BUFFER_SIZE);
107 data_preprocessor_ = std::make_unique<MilleDataProcessor>(GetModuleSize());
108 data_preprocessor_->set_p_value_cut(p_value_cut_);
109
112 }
113
115 {
116 auto filename = FairRun::Instance()->GetSink()->GetFileName();
117 auto output_dir_str = filename.View();
118 auto output_path = fs::path{ output_dir_str };
119 auto output_dir = output_path.parent_path();
120 auto output_filename = output_path.filename();
121 working_dir_ = (output_dir / DEFAULT_SUB_DIR / output_filename);
122 LOGP(debug, "Working dir has set to be: {}", working_dir_);
123 }
124
125 // output: module_num & global label
126 inline auto MillepedeEngine::to_module_num_label(int par_num) -> std::pair<int, GlobalLabel>
127 {
128 const auto num_of_module = GetModuleSize();
129 auto res = std::pair<int, GlobalLabel>{};
130 const auto factor = (par_num - 1) / num_of_module;
131 res.first = (par_num - 1) % num_of_module + 1;
132
133 switch (factor)
134 {
135 // case 0:
136 // res.second = GlobalLabel::tsync;
137 // break;
138 // case 1:
139 // res.second = GlobalLabel::offset_effective_c;
140 // break;
141 // case 2:
142 // res.second = GlobalLabel::effective_c;
143 // break;
144 case 0:
146 break;
147 case 1:
148 res.second = GlobalLabel::effective_c;
149 break;
150 default:
151 throw R3B::logic_error(fmt::format("An error occured with unrecognized global par id: {}", par_num));
152 }
153
154 return res;
155 }
156
157 inline auto MillepedeEngine::get_global_label_id(int module_num, GlobalLabel label) -> int
158 {
159 const auto num_of_module = GetModuleSize();
160 switch (label)
161 {
162 // case GlobalLabel::tsync:
163 // return module_num;
164 // case GlobalLabel::offset_effective_c:
165 // return module_num + num_of_module;
166 // case GlobalLabel::effective_c:
167 // return module_num + (2 * num_of_module);
169 return module_num;
171 return module_num + num_of_module;
172 default:
173 throw R3B::logic_error("An error occured with unrecognized global tag");
174 }
175 }
176
178 Neuland::Cal2HitPar& cal_to_hit_par)
179 {
180 change_time_offset(cal_to_hit_par);
181 const auto& pars = result.get_pars();
182 for (const auto& [par_id, par] : pars)
183 {
184 const auto [module_num, global_label] = to_module_num_label(par_id);
185 auto& module_pars = cal_to_hit_par.GetListOfModuleParRef();
186
187 auto& par_ref = module_pars.emplace(module_num, HitModulePar{}).first->second;
188 switch (global_label)
189 {
191 par_ref.t_sync.value = par.value * SCALE_FACTOR;
192 par_ref.t_sync.error = par.error * SCALE_FACTOR;
193 break;
195 // The value here is the product of tDiff and effectiveSped. Real tDiff will be calculated later
196 par_ref.t_diff.value += par.value * SCALE_FACTOR;
197 par_ref.t_diff.error += par.error * SCALE_FACTOR;
198 break;
200 par_ref.effective_speed.value += par.value;
201 par_ref.effective_speed.error += par.error;
202 break;
203 default:
204 throw std::runtime_error("An error occured with unrecognized global tag");
205 }
206 }
207
208 calculate_time_offset(cal_to_hit_par);
209 }
210
211 auto MillepedeEngine::set_minimum_values(const std::vector<R3B::Neuland::BarCalData>& signals) -> bool
212 {
213 // make sure only one hit exists in one bar
214 auto filtered_signals = rng::filter_view(
215 signals | rng::views::all,
216 [](const auto& bar_signal) { return bar_signal.left.size() == 1 and bar_signal.right.size() == 1; });
217 if (filtered_signals.empty())
218 {
219 return false;
220 }
221
222 if (not average_t_sum_.has_value())
223 {
224 auto t_sum_view = filtered_signals | rng::views::transform(
225 [](const auto& bar_signal)
226 {
227 const auto& left_signal = bar_signal.left.front();
228 const auto& right_signal = bar_signal.right.front();
229 return (left_signal.leading_time - left_signal.trigger_time +
230 right_signal.leading_time - right_signal.trigger_time)
231 .value;
232 });
233 auto sum = rng::accumulate(t_sum_view, 0.F);
234 average_t_sum_ = sum / static_cast<float>(rng::distance(t_sum_view.begin(), t_sum_view.end()));
235 LOGP(info, "Average t_sum is calculated to be {}", average_t_sum_.value());
236 }
237 return true;
238 }
239
240 auto MillepedeEngine::SignalFilter(const std::vector<BarCalData>& signals) -> bool
241 {
242 // select out rays with few hits
243 if (signals.size() < minimum_hit_)
244 {
245 return false;
246 }
247
248 // select out vertical cosmic rays
249 if (rng::all_of(signals |
250 rng::views::transform([](const auto& bar_signal)
251 { return ModuleID2PlaneID(bar_signal.module_num - 1); }) |
252 rng::views::sliding(2),
253 [](const auto& pair) { return pair.front() == pair.back(); }))
254 {
255 return false;
256 }
257
258 if (not set_minimum_values(signals))
259 {
260 return false;
261 }
262
263 return true;
264 }
265
267 {
268 buffer_clear();
269 const auto module_num = static_cast<int>(signal.module_num);
270 const auto pos_z = ModuleNum2ZPos<float>(static_cast<int>(module_num));
271
272 auto init_effective_c = cal_to_hit_par_->GetModuleParAt(module_num).effective_speed.value;
273
274 const auto& left_signal = signal.left;
275 const auto& right_signal = signal.right;
276 const auto t_sum = (left_signal.leading_time - left_signal.trigger_time) +
277 (right_signal.leading_time - right_signal.trigger_time) - average_t_sum_.value_or(0.F);
278
279 input_data_buffer_.measurement =
280 static_cast<float>((t_sum.value / SCALE_FACTOR / 2.F) - (BarLength / SCALE_FACTOR / init_effective_c));
281 input_data_buffer_.sigma = static_cast<float>(t_sum.error / SCALE_FACTOR / 2. * error_scale_factor_);
282 // input_data_buffer_.sigma = static_cast<float>(DEFAULT_MEAS_ERROR);
283 const auto local_derivs_t = std::array{ 0.F, 0.F, pos_z / SCALE_FACTOR, 0.F, 0.F, 1.F };
284 std::copy(local_derivs_t.begin(), local_derivs_t.end(), std::back_inserter(input_data_buffer_.locals));
285 input_data_buffer_.globals.emplace_back(get_global_label_id(module_num, GlobalLabel::tsync), 1.F);
286 input_data_buffer_.globals.emplace_back(get_global_label_id(module_num, GlobalLabel::effective_c),
287 -BarLength / SCALE_FACTOR / 2.F / init_effective_c / init_effective_c);
288
290 }
291
292 void MillepedeEngine::add_spacial_local_constraint(int plane_id, const std::vector<MilleCalData>& plane_signals)
293 {
294 buffer_clear();
295 const auto pos_z = PlaneID2ZPos<float>(plane_id);
296 const auto is_horizontal = IsPlaneIDHorizontal(plane_id);
297 // const auto pos_bar_vert_disp = GetBarVerticalDisplacement(module_num);
298 const auto pos_bar_vert_disp = std::accumulate(plane_signals.begin(),
299 plane_signals.end(),
300 0.,
301 [](double sum, const auto& signal) {
302 return sum + GetBarVerticalDisplacement(signal.module_num);
303 }) /
304 static_cast<double>(plane_signals.size());
305 const auto local_derivs = is_horizontal ? std::array{ 0.F, pos_z / SCALE_FACTOR, 0.F, 1.F }
306 : std::array{ pos_z / SCALE_FACTOR, 0.F, 1.F, 0.F };
307 // const auto local_derivs = is_horizontal ? std::array{ 0.F, pos_z / SCALE_FACTOR, 0.F, 0.F, 1.F, 0.F }
308 // : std::array{ pos_z / SCALE_FACTOR, 0.F, 0.F, 1.F, 0.F, 0.F };
309
310 input_data_buffer_.measurement = static_cast<float>(pos_bar_vert_disp / SCALE_FACTOR);
311 input_data_buffer_.sigma = static_cast<float>(BarSize_XY / SQRT_12 / SCALE_FACTOR * error_scale_factor_);
312
313 // if (not is_horizontal)
314 // {
315 // fmt::println("c_value_1.append({})\na_value_1.append({})\nb_value_1.append({})",
316 // pos_bar_vert_disp / SCALE_FACTOR,
317 // pos_z / SCALE_FACTOR,
318 // 1.);
319 // }
320 std::copy(local_derivs.begin(), local_derivs.end(), std::back_inserter(input_data_buffer_.locals));
322 }
323
325 {
326 buffer_clear();
327 const auto module_num = static_cast<int>(signal.module_num);
328 const auto plane_id = ModuleID2PlaneID(static_cast<int>(module_num) - 1);
329 const auto is_horizontal = IsPlaneIDHorizontal(plane_id);
330 const auto& module_par = cal_to_hit_par_->GetModuleParAt(module_num);
331 auto init_effective_c = module_par.effective_speed.value;
332 auto init_t_offset = module_par.t_diff.value;
333 const auto pos_z = static_cast<float>(PlaneID2ZPos(plane_id));
334
335 const auto& left_signal = signal.left;
336 const auto& right_signal = signal.right;
337 const auto t_diff = (right_signal.leading_time - right_signal.trigger_time) -
338 (left_signal.leading_time - left_signal.trigger_time);
339
340 const auto t_error = t_diff.error == 0 ? DEFAULT_T_ERROR : t_diff.error;
341 input_data_buffer_.measurement = static_cast<float>((init_effective_c * init_t_offset / 2. / SCALE_FACTOR) -
342 (init_effective_c * t_diff.value / SCALE_FACTOR / 2.));
343 input_data_buffer_.sigma =
344 static_cast<float>(t_error / SCALE_FACTOR / 2. * std::abs(init_effective_c) * error_scale_factor_);
345 const auto local_derivs = is_horizontal ? std::array{ pos_z / SCALE_FACTOR, 0.F, 1.F, 0.F }
346 : std::array{ 0.F, pos_z / SCALE_FACTOR, 0.F, 1.F };
347 // const auto local_derivs = is_horizontal ? std::array{ pos_z / SCALE_FACTOR, 0.F, 0.F, 1.F, 0.F, 0.F }
348 // : std::array{ 0.F, pos_z / SCALE_FACTOR, 0.F, 0.F, 1.F, 0.F };
349 std::copy(local_derivs.begin(), local_derivs.end(), std::back_inserter(input_data_buffer_.locals));
350 // fmt::println("Adding global: {}", get_global_label_id(module_num, GlobalLabel::offset_effective_c));
352 -0.5F);
353 input_data_buffer_.globals.emplace_back(get_global_label_id(module_num, GlobalLabel::effective_c),
354 static_cast<float>(t_diff.value / SCALE_FACTOR / 2.));
355
356 // if (is_horizontal)
357 // {
358 // const auto c_val = (0.5 * (module_par.t_diff * module_par.effective_speed).value / SCALE_FACTOR) -
359 // (module_par.effective_speed.value * t_diff.value / SCALE_FACTOR / 2.);
360 // fmt::println(
361 // "c_value_2.append({})\na_value_2.append({})\nb_value_2.append({})", c_val, pos_z / SCALE_FACTOR, 1.);
362 // }
364 LOGP(debug,
365 "Writting Mille data to binary file with meas = {} and z = {}",
366 input_data_buffer_.measurement,
367 pos_z);
368 }
369
370 auto MillepedeEngine::select_t_diff_signal(const std::vector<MilleCalData>& plane_data)
371 {
372 if (plane_data.empty())
373 {
374 return plane_data.end();
375 }
376 auto calculate_residual = [this](const MilleCalData& signal) -> double
377 {
378 const auto t_diff = (signal.right.leading_time - signal.right.trigger_time) -
379 (signal.left.leading_time - signal.left.trigger_time);
380 const auto& module_par = cal_to_hit_par_->GetModuleParAt(signal.module_num);
381 const auto position = (-t_diff + module_par.t_diff) / 2 * module_par.effective_speed;
382 const auto res =
383 data_preprocessor_->calculate_residual(position.value, static_cast<int>(signal.module_num));
384 return res;
385 };
386 auto iter = std::min_element(plane_data.begin(),
387 plane_data.end(),
388 [calculate_residual](const auto& first, const auto& second)
389 { return calculate_residual(first) < calculate_residual(second); });
390 if (iter != plane_data.end())
391 {
392 auto residual = calculate_residual(*iter);
393 hist_t_offset_residual_->Fill(residual);
394 if (residual > t_diff_residual_cut_)
395 {
396 return plane_data.end();
397 }
398 // fmt::println("selected signal residual: {}", residual);
399 }
400 return iter;
401 }
402
403 void MillepedeEngine::AddSignals(const std::vector<BarCalData>& signals)
404 {
405
406 // fmt::println("==================new event===============\n");
407 if (not data_preprocessor_->filter(signals))
408 {
409 return;
410 }
411 const auto& processed_data = data_preprocessor_->get_data();
412 for (const auto& [plane_id, plane_signals] :
413 processed_data |
414 rng::views::filter([](const auto& planeid_signals) { return not planeid_signals.second.empty(); }))
415 {
416 // fmt::println("\n--------------------\n");
417 auto iter = select_t_diff_signal(plane_signals);
418 if (iter == plane_signals.end())
419 {
420 continue;
421 }
422 // fmt::println("selected signal: {}", *iter);
423 // for (const auto& signal : plane_signals)
424 // {
425 // // add_signal_t_sum(signal);
426 add_signal_t_diff(*iter);
427 add_spacial_local_constraint(plane_id, plane_signals);
428 // }
429 }
430 }
431
433 {
434 binary_data_writer_->close();
435 LOGP(info, "Launching pede algorithm..");
436 pede_launcher_.launch();
437 pede_launcher_.end();
438
439 par_result_.read();
441 fill_data_to_figure(hit_par);
442 }
443
445 {
446 const auto& pars = hit_par.GetListOfModulePar();
447 for (const auto& [module_num, par] : pars)
448 {
449 graph_time_offset_->SetPoint(static_cast<int>(module_num), module_num, par.t_diff.value);
450 graph_time_offset_->SetPointError(static_cast<int>(module_num), 0., par.t_diff.error);
451 graph_time_sync_->SetPoint(static_cast<int>(module_num), module_num, par.t_sync.value);
452 graph_time_sync_->SetPointError(static_cast<int>(module_num), 0., par.t_sync.error);
453 graph_effective_c_->SetPoint(static_cast<int>(module_num), module_num, par.effective_speed.value);
454 graph_effective_c_->SetPointError(static_cast<int>(module_num), 0., par.effective_speed.error);
455 }
456 }
457
458 void MillepedeEngine::EndOfEvent(unsigned int /*event_num*/)
459 {
460 // TODO: could be an empty event
461 binary_data_writer_->end();
462 data_preprocessor_->reset();
463 }
464
466
468 {
469 const auto module_size = GetModuleSize();
470
471 graph_time_offset_ = histograms.add_graph("time_offset", std::make_unique<TGraphErrors>(module_size));
472 graph_time_offset_->SetTitle("Time offset vs BarNum");
473
474 graph_time_sync_ = histograms.add_graph("time_sync", std::make_unique<TGraphErrors>(module_size));
475 graph_time_sync_->SetTitle("Time sync vs BarNum");
476
477 graph_effective_c_ = histograms.add_graph("effective_c", std::make_unique<TGraphErrors>(module_size));
478 graph_effective_c_->SetTitle("Effective c vs BarNum");
479
480 static constexpr auto RESIDUAL_BIN_NUM = 500;
481 hist_t_offset_residual_ = histograms.add_hist<TH1D>(
482 "t_diff_residual", "Residual values of the positios calculated from t_dff", RESIDUAL_BIN_NUM, 0., 1000.);
483 }
484
486 {
487 input_data_buffer_.locals.clear();
488 input_data_buffer_.globals.clear();
489 input_data_buffer_.measurement = 0.F;
490 input_data_buffer_.sigma = 0.F;
491 }
492
494
496 {
497 average_t_sum_.reset();
498 buffer_clear();
499 }
500
502 {
503 if (cal_to_hit_par_ == nullptr)
504 {
505 throw R3B::runtime_error("Pointer to cal_to_hit_par is nullptr!");
506 }
507 }
508
510 {
511 auto steer_writer = SteerWriter{};
512 steer_writer.set_working_dir(working_dir_);
513 steer_writer.set_filepath(pede_steer_filename_);
514 steer_writer.set_parameter_file(parameter_filename_);
515 steer_writer.set_data_filepath(input_data_filename_);
516 static constexpr auto NUMBER_OF_ITERARTION = 3.F;
517 static constexpr auto CONVERGENCE_RECOGNITION = 0.001F;
518 steer_writer.add_method(SteerWriter::Method::inversion,
519 std::make_pair(NUMBER_OF_ITERARTION, CONVERGENCE_RECOGNITION));
520 steer_writer.add_other_options(std::vector<std::string>{ "hugecut", "50000" });
521 steer_writer.add_other_options(std::vector<std::string>{ "outlierdownweighting", "4" });
522
523 // const auto module_size = GetModuleSize();
524 // for (int module_num{ 1 }; module_num <= module_size; ++module_num)
525 // {
526 // const auto& module_par = cal_to_hit_par_->GetModuleParAt(module_num);
527 // steer_writer.add_parameter_default(
528 // get_global_label_id(module_num, GlobalLabel::effective_c),
529 // // std::make_pair(module_par.effective_speed.value, module_par.effective_speed.error));
530 // std::make_pair(DEFAULT_EFFECTIVE_C, module_par.effective_speed.error));
531
532 // const auto offset_effective_c = module_par.t_diff * module_par.effective_speed;
533 // steer_writer.add_parameter_default(
534 // get_global_label_id(module_num, GlobalLabel::offset_effective_c),
535 // std::make_pair(offset_effective_c.value / SCALE_FACTOR, offset_effective_c.error / SCALE_FACTOR));
536 // }
537 // steer_writer.add_parameter_default(get_global_label_id(REFERENCE_BAR_NUM, GlobalLabel::tsync),
538 // std::make_pair(0.F, -1.F));
539 steer_writer.write();
540 }
541} // namespace R3B::Neuland::Calibration
constexpr auto SCALE_FACTOR
constexpr auto DEFAULT_T_ERROR
constexpr auto DEFAULT_RES_FILENAME
constexpr auto MILLE_BUFFER_SIZE
auto add_hist(std::unique_ptr< TH1 > hist) -> TH1 *
auto add_graph(std::string_view graph_name, std::unique_ptr< GraphType > graph) -> GraphType *
auto get_pars() const -> const auto &
auto GetListOfModulePar() const -> const std::unordered_map< int, ::R3B::Neuland::HitModulePar > &
auto to_module_num_label(int par_num) -> std::pair< int, GlobalLabel >
void Calibrate(Cal2HitPar &hit_par) override
void add_spacial_local_constraint(int plane_id, const std::vector< MilleCalData > &plane_signals)
auto set_minimum_values(const std::vector< R3B::Neuland::BarCalData > &signals) -> bool
void EndOfEvent(unsigned int event_num=0) override
auto select_t_diff_signal(const std::vector< MilleCalData > &plane_data)
static constexpr std::string_view DEFAULT_SUB_DIR
void fill_module_parameters(const Millepede::ResultReader &result, Neuland::Cal2HitPar &cal_to_hit_par)
std::unique_ptr< MilleDataProcessor > data_preprocessor_
void add_signal_t_sum(const MilleCalData &signal)
void add_signal_t_diff(const MilleCalData &signal)
auto SignalFilter(const std::vector< BarCalData > &signals) -> bool override
void AddSignals(const std::vector< BarCalData > &signals) override
auto get_global_label_id(int module_num, GlobalLabel label) -> int
void HistInit(DataMonitor &histograms) override
void set_working_dir(std::string_view dir)
Definition SteerWriter.h:51
STL class.
constexpr auto ModuleID2PlaneID(int moduleID) -> int
constexpr auto SQRT_12
constexpr auto BarLength
constexpr auto BarSize_XY
constexpr auto ModuleNum2ZPos(int module_num) -> T
constexpr auto IsPlaneIDHorizontal(int plane_id) -> bool
constexpr auto PlaneID2ZPos(int plane_id) -> T