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 "PedeLauncher.h"
18#include "R3BDataMonitor.h"
19#include "R3BNeulandCalData2.h"
22#include <R3BException.h>
24#include <R3BNeulandCommon.h>
26#include <SteerWriter.h>
27
28#include <TGraphErrors.h>
29#include <TH1.h>
30#include <algorithm>
31#include <array>
32#include <chrono>
33#include <cmath>
34#include <cstdint>
35#include <cstdlib>
36#include <fairlogger/Logger.h>
37#include <filesystem>
38#include <fmt/core.h>
39#include <fmt/format.h>
40#include <functional>
41#include <iterator>
42#include <magic_enum/magic_enum.hpp>
43#include <memory>
44#include <numeric>
45#include <optional>
46#include <range/v3/algorithm/all_of.hpp>
47#include <range/v3/algorithm/copy.hpp>
48#include <range/v3/algorithm/max.hpp>
49#include <range/v3/algorithm/min_element.hpp>
50#include <range/v3/iterator/operations.hpp>
51#include <range/v3/numeric/accumulate.hpp>
52#include <range/v3/view/all.hpp>
53#include <range/v3/view/drop.hpp>
54#include <range/v3/view/filter.hpp>
55#include <range/v3/view/iota.hpp>
56#include <range/v3/view/join.hpp>
57#include <range/v3/view/map.hpp>
58#include <range/v3/view/repeat.hpp>
59#include <range/v3/view/sliding.hpp>
60#include <range/v3/view/take.hpp>
61#include <range/v3/view/transform.hpp>
62#include <stdexcept>
63#include <string>
64#include <string_view>
65#include <utility>
66#include <vector>
67
68// #define TWO_PAR
69
70namespace rng = ranges;
71
72constexpr auto DEFAULT_RES_FILENAME = "millepede.res";
73constexpr auto DEFAULT_RES_JSON_FILENAME = "millepede.res.json";
74constexpr auto SCALE_FACTOR = 10.F;
75// constexpr auto REFERENCE_BAR_NUM = 25;
76constexpr auto MILLE_BUFFER_SIZE = std::size_t{ 100000 };
77constexpr auto DEFAULT_T_ERROR = 2; // ns
78
79namespace
80{
81 enum class FilterEvent : uint8_t
82 {
83 after_trigger,
84 n_plane_filter,
85 };
86 void calculate_time_offset(R3B::Neuland::Cal2HitPar& cal_to_hit_par)
87 {
88 auto& module_pars = cal_to_hit_par.GetListOfModuleParRef();
89 for (auto& [module_num, module_par] : module_pars)
90 {
91 if (module_par.effective_speed.value != 0)
92 {
93 module_par.t_diff = module_par.t_diff / module_par.effective_speed;
94 }
95 }
96 }
97
98 void change_time_offset(R3B::Neuland::Cal2HitPar& cal_to_hit_par)
99 {
100 auto& module_pars = cal_to_hit_par.GetListOfModuleParRef();
101 for (auto& [module_num, module_par] : module_pars)
102 {
103 module_par.t_diff = module_par.t_diff * module_par.effective_speed;
104 }
105 }
106
107 template <typename T, typename U>
108 void vector_zip_action(const T& data, U&& unitary_action)
109 {
110 namespace sr = ranges;
111 namespace sv = ranges::views;
112 const auto max_size = sr::max(data | sv::transform([](const auto& vec) -> auto { return vec.size(); }));
113 static constexpr auto nth_element = [](auto& vec, const int n) -> auto
114 { return sv::repeat(vec) | sv::join | sv::drop(n) | sv::take(1); };
115
116 for (const auto index : sv::iota(std::size_t{ 0 }, max_size))
117 {
118 auto zip_view = data | sv::filter([](const auto& vec) -> auto { return not vec.empty(); }) |
119 sv::transform([index](auto&& vec) -> auto { return nth_element(vec, index); }) | sv::join;
120 std::forward<U>(unitary_action)(zip_view);
121 }
122 }
123
124 namespace sv = ranges::views;
125} // namespace
126
128{
129 void MillepedeEngine::set_options(const MillepedeOptions& options) { config_ = options; }
130
132 {
135 {
136 output_mille_data_.init();
139 }
140 fs::create_directories(fs::path(working_dir_));
141 cal_to_hit_par_ = GetTask()->GetCal2HitPar();
142
146 if (const auto* r3b_dir = std::getenv("R3BROOTPATH"); r3b_dir != nullptr)
147 {
148 pede_launcher_.set_binary_dir(fmt::format("{}/bin", r3b_dir));
149 // TODO: make subdir configurable
150 pede_launcher_.set_working_dir(fs::absolute(fs::path{ working_dir_ }).string());
151 }
152 else
153 {
154 throw R3B::runtime_error(
155 "Environment variable R3BROOTPATH is not defined! Did you forget to source the \"config.sh\" file?");
156 }
158 std::make_unique<Mille>((fs::path{ working_dir_ } / config_.mille_data_filename).string());
159 binary_data_writer_->set_buffer_size(MILLE_BUFFER_SIZE);
160 data_preprocessor_ = std::make_unique<MilleDataProcessor>(GetModuleSize());
161 data_preprocessor_->set_p_value_cut(config_.p_value_cut);
162
165 }
166
168 {
169 const auto filename = FairRun::Instance()->GetSink()->GetFileName();
170 const auto output_dir = fs::path{ filename.View() }.parent_path();
171 const auto time_now = std::chrono::time_point_cast<std::chrono::seconds>(std::chrono::system_clock::now());
172 const auto output_folder_name =
173 config_.outdir_has_timestamp ? fmt::format("{:%Y-%m-%d_%H-%M-%S}", time_now) : "output";
174
175 working_dir_ = (output_dir / DEFAULT_SUB_DIR / output_folder_name);
176 LOGP(debug, "Working dir has set to be: {}", working_dir_);
177 }
178
179 // output: module_num & global label
180 inline auto MillepedeEngine::to_module_num_label(int par_num) -> std::pair<int, GlobalLabel>
181 {
182 const auto num_of_module = GetModuleSize();
183 auto res = std::pair<int, GlobalLabel>{};
184 res.first = ((par_num - 1) % num_of_module) + 1;
185
187 {
188 res.second = GlobalLabel::tsync;
189 }
191 {
192 const auto factor = (par_num - 1) / num_of_module;
193 switch (factor)
194 {
195 case 0:
197 break;
198 case 1:
199 res.second = GlobalLabel::effective_c;
200 break;
201 default:
202 throw R3B::logic_error(
203 fmt::format("An error occurred with unrecognized global par id: {}", par_num));
204 }
205 }
206 else
207 {
208 throw R3B::logic_error(
209 fmt::format("cal mode {} is not implemented!", magic_enum::enum_name(config_.cal_mode)));
210 }
211
212 return res;
213 }
214
215 inline auto MillepedeEngine::get_global_label_id(int module_num, GlobalLabel label) -> int
216 {
217 const auto num_of_module = GetModuleSize();
218
220 {
221 return module_num;
222 }
224 {
225 switch (label)
226 {
228 return module_num;
230 return module_num + num_of_module;
231 default:
232 return -1;
233 }
234 }
235 throw R3B::logic_error(fmt::format("cal mode {} is not implemented!", magic_enum::enum_name(config_.cal_mode)));
236 }
237
239 Neuland::Cal2HitPar& cal_to_hit_par)
240 {
241 // this changes the t_diff value to the product of t_diff and speed.
243 {
244 change_time_offset(cal_to_hit_par);
245 }
246
247 const auto& pars = result.get_pars();
248 for (const auto& [par_id, par] : pars)
249 {
250 const auto [module_num, global_label] = to_module_num_label(par_id);
251 auto& module_pars = cal_to_hit_par.GetListOfModuleParRef();
252
253 auto& par_ref = module_pars.emplace(module_num, HitModulePar{}).first->second;
255 {
256 if (module_num == DEFAULT_TSYNC_REFERENCE_BAR_NUM)
257 {
258 par_ref.t_sync.value = DEFAULT_TSYNC_REFERENCE_BAR_VALUE;
259 par_ref.t_sync.error = 0.;
260 }
261 else
262 {
263 par_ref.t_sync.value += par.value * SCALE_FACTOR;
264 par_ref.t_sync.error = par.error * SCALE_FACTOR;
265 }
266 }
268 {
269 switch (global_label)
270 {
272 // NOTE: The value here is the product of tDiff and effectiveSped. Real tDiff will be calculated
273 // later
274 par_ref.t_diff.value += par.value * SCALE_FACTOR;
275 par_ref.t_diff.error = par.error * SCALE_FACTOR;
276 break;
278 par_ref.effective_speed.value += par.value;
279 par_ref.effective_speed.error = par.error;
280 break;
281 default:
282 throw std::runtime_error("An error occurred with unrecognized global tag");
283 }
284 }
285 else
286 {
287 throw R3B::logic_error(
288 fmt::format("cal mode {} is not implemented!", magic_enum::enum_name(config_.cal_mode)));
289 }
290 }
291
293 {
294 calculate_time_offset(cal_to_hit_par);
295 }
296 }
297
298 auto MillepedeEngine::set_minimum_values(const std::vector<R3B::Neuland::BarCalData>& signals) -> bool
299 {
300 // make sure only one hit exists in one bar
301 auto filtered_signals =
302 rng::filter_view(signals | rng::views::all,
303 [](const auto& bar_signal) -> auto
304 { return bar_signal.left.size() == 1 and bar_signal.right.size() == 1; });
305 if (filtered_signals.empty())
306 {
307 return false;
308 }
309
310 if (not average_t_sum_.has_value())
311 {
312 auto t_sum_view = filtered_signals | rng::views::transform(
313 [](const auto& bar_signal) -> auto
314 {
315 const auto& left_signal = bar_signal.left.front();
316 const auto& right_signal = bar_signal.right.front();
317 return (left_signal.leading_time - left_signal.trigger_time +
318 right_signal.leading_time - right_signal.trigger_time)
319 .value;
320 });
321 auto sum = rng::accumulate(t_sum_view, 0.F);
322 average_t_sum_ = sum / static_cast<float>(rng::distance(t_sum_view.begin(), t_sum_view.end()));
323 LOGP(info, "Average t_sum is calculated to be {}", average_t_sum_.value());
324 }
325 return true;
326 }
327
328 auto MillepedeEngine::SignalFilter(const std::vector<BarCalData>& signals) -> bool
329 {
330 const auto n_plane = GetTask()->GetBasePar()->get_num_of_planes();
331 plane_counter_.clear();
332 plane_counter_.resize(n_plane, 0);
333
334 // select out events with less plane hits
335 for (const auto& bar_data : signals)
336 {
337 if (bar_data.left.size() != bar_data.right.size())
338 {
339 continue;
340 }
341 if (bar_data.left.size() != 1)
342 {
343 continue;
344 }
345 const auto module_num = bar_data.module_num;
346 const auto plane_id = Common::ModuleID2PlaneID(module_num - 1);
347 ++plane_counter_.at(plane_id);
348 }
349 const auto n_hit_plane = std::ranges::count_if(plane_counter_, [](auto val) -> bool { return val != 0; });
350 hist_plane_hit_num_->Fill(static_cast<double>(n_hit_plane));
351 if (n_hit_plane < config_.min_plane_num)
352 {
353 return false;
354 }
355
356 if (not set_minimum_values(signals))
357 {
358 return false;
359 }
360
361 return true;
362 }
363
364 auto MillepedeEngine::add_signal_t_sum(const MilleCalData& signal, const TrackFitResult& fit_coeff) -> float
365 {
366 buffer_clear();
367
368 const auto x_z_slope = fit_coeff.x_z.slope;
369 const auto y_z_slope = fit_coeff.y_z.slope;
370 const auto a_z = std::sqrt(1 + (x_z_slope * x_z_slope) + (y_z_slope * y_z_slope)) / CLight;
371 const auto sign_factor = (y_z_slope > 0.) ? 1. : -1.;
372
373 const auto module_num = static_cast<int>(signal.module_num);
374 const auto pos_z = ModuleNum2ZPos<float>(static_cast<int>(module_num));
375
376 const auto init_effective_c = cal_to_hit_par_->GetModuleParAt(module_num).effective_speed.value;
377 const auto init_t_sync = (module_num == DEFAULT_TSYNC_REFERENCE_BAR_NUM)
379 : cal_to_hit_par_->GetModuleParAt(module_num).t_sync.value;
380
381 const auto& left_signal = signal.left;
382 const auto& right_signal = signal.right;
383 const auto t_sum = (left_signal.leading_time - left_signal.trigger_time) +
384 (right_signal.leading_time - right_signal.trigger_time) - average_t_sum_.value_or(0.F);
385
386 auto meas = static_cast<float>((t_sum.value / 2.F) + (sign_factor * pos_z * a_z) -
387 (BarLength / init_effective_c / 2.F) - init_t_sync) /
389 // auto meas = static_cast<float>((t_sum.value / 2.F) + (sign_factor * pos_z * a_z) +
390 // (BarLength / init_effective_c) - init_t_sync) /
391 // SCALE_FACTOR;
392 input_data_buffer_.measurement = meas;
393 input_data_buffer_.sigma = static_cast<float>(t_sum.error / SCALE_FACTOR / 2. * config_.scale_factor);
394
395 const auto local_derivs_t = std::array{ 1.F };
396#ifdef HAS_CPP_STANDARD_17
397 std::copy(local_derivs_t.begin(), local_derivs_t.end(), std::back_inserter(input_data_buffer_.locals));
398#else
399 ranges::copy(local_derivs_t, std::back_inserter(input_data_buffer_.locals));
400#endif
401 input_data_buffer_.globals.emplace_back(get_global_label_id(module_num, GlobalLabel::tsync), 1.F);
402
404 return meas;
405 }
406
407 void MillepedeEngine::add_spacial_local_constraint(int plane_id, const std::vector<MilleCalData>& plane_signals)
408 {
409 buffer_clear();
410 const auto pos_z = PlaneID2ZPos<float>(plane_id);
411 const auto is_horizontal = IsPlaneIDHorizontal(plane_id);
412 // const auto pos_bar_vert_disp = GetBarVerticalDisplacement(module_num);
413 auto n_not_outlier = 0;
414 auto pos_bar_vert_disp = std::accumulate(plane_signals.begin(),
415 plane_signals.end(),
416 0.,
417 [this, &n_not_outlier](double sum, const auto& signal) -> double
418 {
419 if (data_preprocessor_->check_is_outlier(signal.module_num))
420 {
421 return 0.;
422 }
423 ++n_not_outlier;
424 return sum + GetBarVerticalDisplacement(signal.module_num);
425 });
426 if (n_not_outlier == 0)
427 {
428 LOGP(debug, "no valid constraint found in event id: {}", GetTask()->GetEventHeader()->GetEventno());
429 return;
430 }
431 pos_bar_vert_disp /= n_not_outlier;
432 const auto local_derivs = std::array{ pos_z / SCALE_FACTOR, 1.F };
433
434 input_data_buffer_.measurement = static_cast<float>(pos_bar_vert_disp / SCALE_FACTOR);
435 input_data_buffer_.sigma = static_cast<float>(BarSize_XY / SQRT_12 / SCALE_FACTOR * n_not_outlier);
436
437#ifdef HAS_CPP_STANDARD_17
438 std::copy(local_derivs.begin(), local_derivs.end(), std::back_inserter(input_data_buffer_.locals));
439#else
440 ranges::copy(local_derivs, std::back_inserter(input_data_buffer_.locals));
441#endif
442 write_to_buffer();
443 }
444
446 {
447 buffer_clear();
448 const auto module_num = static_cast<int>(signal.module_num);
449 const auto plane_id = ModuleID2PlaneID(static_cast<int>(module_num) - 1);
450 const auto is_horizontal = IsPlaneIDHorizontal(plane_id);
451 const auto& module_par = cal_to_hit_par_->GetModuleParAt(module_num);
452 const auto init_effective_c = module_par.effective_speed.value;
453 const auto init_t_offset = module_par.t_diff.value;
454 const auto pos_z = static_cast<float>(PlaneID2ZPos(plane_id));
455
456 const auto& left_signal = signal.left;
457 const auto& right_signal = signal.right;
458 const auto t_diff = (right_signal.leading_time - right_signal.trigger_time) -
459 (left_signal.leading_time - left_signal.trigger_time);
460
461 const auto t_error = t_diff.error == 0 ? DEFAULT_T_ERROR : t_diff.error;
462 input_data_buffer_.measurement = static_cast<float>((init_effective_c * init_t_offset / 2. / SCALE_FACTOR) -
463 (init_effective_c * t_diff.value / SCALE_FACTOR / 2.));
464 input_data_buffer_.sigma =
465 static_cast<float>(t_error / SCALE_FACTOR / 2. * std::abs(init_effective_c) * config_.scale_factor);
466 const auto local_derivs = std::array{ pos_z / SCALE_FACTOR, 1.F };
467 ranges::copy(local_derivs, std::back_inserter(input_data_buffer_.locals));
469 -0.5F);
470 input_data_buffer_.globals.emplace_back(get_global_label_id(module_num, GlobalLabel::effective_c),
471 static_cast<float>(t_diff.value / SCALE_FACTOR / 2.));
472
474 LOGP(debug,
475 "Writing Mille data to binary file with meas = {} and z = {}",
476 input_data_buffer_.measurement,
477 pos_z);
478 }
479
480 auto MillepedeEngine::select_t_sync_signal(const std::vector<MilleCalData>& plane_data)
481 {
482 auto iter = ranges::min_element(plane_data, std::less{}, &MilleCalData::residual);
483 if (iter != plane_data.end())
484 {
485 auto residual = iter->residual;
486 hist_t_offset_residual_->Fill(residual);
487 if (residual > config_.t_diff_residual_cut)
488 {
489 return plane_data.end();
490 }
491 // fmt::println("selected signal residual: {}", residual);
492 }
493 return iter;
494 }
495
496 template <>
498 const DataBufferType& processed_data,
499 const TrackFitResult& fit_coeff)
500 {
501 const auto is_xz_flat = std::abs(fit_coeff.x_z.slope) < std::abs(config_.max_abs_a_xz);
502 const auto is_yz_flat = std::abs(fit_coeff.y_z.slope) < std::abs(config_.max_abs_a_yz);
503 auto add_to_constraints = [this, &processed_data](bool is_x_z) -> void
504 {
505 for (const auto& [plane_id, plane_signals] :
506 processed_data | rng::views::filter(
507 [is_x_z](const auto& planeid_signals) -> auto
508 {
509 return (not planeid_signals.second.empty()) and
510 (IsPlaneIDHorizontal(planeid_signals.first) != is_x_z);
511 }))
512 {
513 add_spacial_local_constraint(plane_id, plane_signals);
514 }
515 };
516 for (const auto& [plane_id, plane_signals] :
517 processed_data | rng::views::filter([](const auto& planeid_signals) -> auto
518 { return not planeid_signals.second.empty(); }))
519 {
520 const auto is_horizontal = IsPlaneIDHorizontal(plane_id);
521 if (not(is_horizontal ? is_xz_flat : is_yz_flat))
522 {
523 continue;
524 }
525 for (const auto& signal : plane_signals)
526 {
527 add_signal_t_diff(signal);
528 add_to_constraints(is_horizontal);
529 binary_data_writer_->end();
530 }
531 }
532 if (config_.enable_data_write)
533 {
534 for (const auto& bar_signal : processed_data | sv::values | sv::join)
535 {
536 output_mille_data_.get().push_back(bar_signal);
537 }
538 }
539 }
540
541 template <>
543 const TrackFitResult& fit_coeff)
544 {
545 for (const auto& [plane_id, plane_signals] :
546 processed_data | rng::views::filter([](const auto& planeid_signals) -> auto
547 { return not planeid_signals.second.empty(); }))
548 {
549 auto iter = select_t_sync_signal(plane_signals);
550 if (iter == plane_signals.end())
551 {
552 continue;
553 }
554 auto mille_data = *iter;
555 mille_data.tsync_meas = add_signal_t_sum(mille_data, fit_coeff);
556 if (config_.enable_data_write)
557 {
558 output_tsync_mille_data_.get().push_back(mille_data);
559 }
560 }
561
562 binary_data_writer_->end();
563 }
564
565 void MillepedeEngine::AddSignals(const std::vector<BarCalData>& signals)
566 {
567 auto* task = GetTask();
568 if (not data_preprocessor_->process(signals, *cal_to_hit_par_))
569 {
570 task->ConditionFillToHist("preprocess_fail");
571 return;
572 }
573 task->ConditionFillToHist("preprocess_success");
574 const auto& processed_data = data_preprocessor_->get_data();
575 if (config_.enable_data_write)
576 {
578 }
579 const auto& fit_coeff = data_preprocessor_->get_track_info().bar_disp_data;
580
581 const auto is_xz_flat = std::abs(fit_coeff.x_z.slope) < std::abs(config_.max_abs_a_xz);
582 const auto is_yz_flat = std::abs(fit_coeff.y_z.slope) < std::abs(config_.max_abs_a_yz);
583
584 if (not(is_xz_flat or is_yz_flat))
585 {
586 return;
587 }
588
589 switch (config_.cal_mode)
590 {
593 break;
595 add_signals<MillepedeCalibrationMode::tsync>(processed_data, fit_coeff);
596 break;
597 default:
598 throw R3B::logic_error(
599 fmt::format("Unrecognized calibration mode: {}", magic_enum::enum_name(config_.cal_mode)));
600 }
601
602 add_fit_result_hist(fit_coeff);
603 }
604
606 {
607 binary_data_writer_->close();
608 LOGP(info, "Launching pede algorithm..");
609 pede_launcher_.launch();
610 pede_launcher_.end();
611
612 par_result_.read();
614 fill_data_to_figure(hit_par);
615 }
616
618 {
619 const auto& pars = hit_par.GetListOfModulePar();
620 for (const auto& [module_num, par] : pars)
621 {
622 graph_time_offset_->SetPoint(static_cast<int>(module_num), module_num, par.t_diff.value);
623 graph_time_offset_->SetPointError(static_cast<int>(module_num), 0., par.t_diff.error);
624 graph_time_sync_->SetPoint(static_cast<int>(module_num), module_num, par.t_sync.value);
625 graph_time_sync_->SetPointError(static_cast<int>(module_num), 0., par.t_sync.error);
626 graph_effective_c_->SetPoint(static_cast<int>(module_num), module_num, par.effective_speed.value);
627 graph_effective_c_->SetPointError(static_cast<int>(module_num), 0., par.effective_speed.error);
628 }
629 }
630
631 void MillepedeEngine::EndOfEvent([[maybe_unused]] unsigned int event_num)
632 {
633 // TODO: could be an empty event
634 binary_data_writer_->end();
635 data_preprocessor_->reset();
636 // fmt::println("<<<<<<<<<<<<<<<< End of the event {}", event_num);
637 }
638
640
642 {
643 const auto module_size = GetModuleSize();
644
645 graph_time_offset_ = histograms.add_graph("time_offset", std::make_unique<TGraphErrors>(module_size));
646 graph_time_offset_->SetTitle("Time offset vs BarNum");
647
648 graph_time_sync_ = histograms.add_graph("time_sync", std::make_unique<TGraphErrors>(module_size));
649 graph_time_sync_->SetTitle("Time sync vs BarNum");
650
651 graph_effective_c_ = histograms.add_graph("effective_c", std::make_unique<TGraphErrors>(module_size));
652 graph_effective_c_->SetTitle("Effective c vs BarNum");
653
654 static constexpr auto RESIDUAL_BIN_NUM = 500;
655 static constexpr auto PAR_BIN_NUM = 400;
656 static const auto SLOPE_MAX = 10.;
657 static const auto OFFSET_MAX = 200.;
658
659 auto set_x_title = [](auto* hist, std::string_view title) -> void { hist->GetXaxis()->SetTitle(title.data()); };
660 auto set_y_title = [](auto* hist, std::string_view title) -> void { hist->GetYaxis()->SetTitle(title.data()); };
661
662 hist_t_offset_residual_ = histograms.add_hist<TH1D>(
663 "t_diff_residual", "Residual values of the positions calculated from t_dff", RESIDUAL_BIN_NUM, 0., 1000.);
664
665 hist_p_value_xz_ = histograms.add_hist<TH1D>(
666 "p_value_xz", "p values from the fitting of the muon track in xz plane", RESIDUAL_BIN_NUM, 0., 1.);
667 hist_p_value_yz_ = histograms.add_hist<TH1D>(
668 "p_value_yz", "p values from the fitting of the muon track in yz plane", RESIDUAL_BIN_NUM, 0., 1.);
669 hist_a_xz_ = histograms.add_hist<TH1D>("a_xz", "slope of the xz plane", PAR_BIN_NUM, 0., SLOPE_MAX);
670 set_x_title(hist_a_xz_, "abs(a_xz)");
671 set_y_title(hist_a_xz_, fmt::format("counts per {}", SLOPE_MAX / PAR_BIN_NUM));
672
673 hist_b_xz_ = histograms.add_hist<TH1D>("b_xz", "offset of the xz plane", PAR_BIN_NUM, 0., OFFSET_MAX);
674 set_x_title(hist_b_xz_, "abs(b_xz)");
675 set_y_title(hist_b_xz_, fmt::format("counts per {}", OFFSET_MAX / PAR_BIN_NUM));
676
677 hist_a_yz_ = histograms.add_hist<TH1D>("a_yz", "slope of the yz plane", PAR_BIN_NUM, 0., SLOPE_MAX);
678 set_x_title(hist_a_yz_, "abs(a_yz)");
679 set_y_title(hist_a_yz_, fmt::format("counts per {}", SLOPE_MAX / PAR_BIN_NUM));
680
681 hist_b_yz_ = histograms.add_hist<TH1D>("b_yz", "offset of the yz plane", PAR_BIN_NUM, 0., OFFSET_MAX);
682 set_x_title(hist_b_yz_, "abs(b_yz)");
683 set_y_title(hist_b_yz_, fmt::format("counts per {}", OFFSET_MAX / PAR_BIN_NUM));
684
685 barplot_filter_counts_ = histograms.add_hist<TH1L>("filter_counts", "Counts after filters", 1, 0., 0.);
686
687 const auto n_plane = module_size / R3B::Neuland::BarsPerPlane;
689 histograms.add_hist<TH1D>("plane_hit_num", "Number of hit planes", n_plane + 1, -0.5, 0.5 + n_plane);
690 hist_plane_hit_num_->GetXaxis()->SetTitle("Number of planes hit");
691 hist_plane_hit_num_->GetYaxis()->SetTitle("Counts");
692
693 static constexpr auto residual_bin_num = 1000;
694 static constexpr auto max_residual = 300.;
695 static constexpr auto max_diff = 50;
696 }
697
699 {
700 input_data_buffer_.locals.clear();
701 input_data_buffer_.globals.clear();
702 input_data_buffer_.measurement = 0.F;
703 input_data_buffer_.sigma = 0.F;
704 }
705
707 {
709 // output_mille_data_point_->push_back(input_data_buffer_);
710 }
711
713 {
714 average_t_sum_.reset();
715 buffer_clear();
716 }
717
719 {
720 if (cal_to_hit_par_ == nullptr)
721 {
722 throw R3B::runtime_error("Pointer to cal_to_hit_par is nullptr!");
723 }
724
726 {
727 auto& module_pars = cal_to_hit_par_->GetListOfModuleParRef();
728 auto reference_bar_value = module_pars.at(DEFAULT_TSYNC_REFERENCE_BAR_NUM).t_sync.value;
729 if (reference_bar_value != DEFAULT_TSYNC_REFERENCE_BAR_VALUE)
730 {
731 LOGP(info,
732 "The reference bar (bar_num {}) from the input tsync parameter has the wrong value ({}, should be "
733 "{}). Offsetting the input parameters ...",
735 reference_bar_value,
737 for (auto& [module_num, module_par] : module_pars)
738 {
739 module_par.t_sync.value -= reference_bar_value;
740 }
741 }
742 }
743 }
744
746 {
747 hist_p_value_xz_->Fill(fit_result.x_z.p_value);
748 hist_p_value_yz_->Fill(fit_result.y_z.p_value);
749 hist_a_xz_->Fill(std::abs(fit_result.x_z.slope));
750 hist_b_xz_->Fill(std::abs(fit_result.x_z.offset));
751 hist_a_yz_->Fill(std::abs(fit_result.y_z.slope));
752 hist_b_yz_->Fill(std::abs(fit_result.y_z.offset));
753 }
754
756 {
757 auto steer_writer = SteerWriter{};
758 steer_writer.set_working_dir(working_dir_);
759 steer_writer.set_filepath(pede_steer_filename_);
760 steer_writer.set_parameter_file(input_parameter_filename_);
761 steer_writer.set_data_filepath(config_.mille_data_filename);
762 static constexpr auto NUMBER_OF_ITERATION = 3.F;
763 static constexpr auto CONVERGENCE_RECOGNITION = 0.001F;
764 steer_writer.add_method(SteerWriter::Method::inversion,
765 std::make_pair(NUMBER_OF_ITERATION, CONVERGENCE_RECOGNITION));
766 steer_writer.add_other_options(std::vector<std::string>{ "hugecut", "50000" });
767
769 {
770
772 std::make_pair(DEFAULT_TSYNC_REFERENCE_BAR_VALUE / SCALE_FACTOR, -1.F));
773 }
774 else
775 {
776 steer_writer.add_other_options(std::vector<std::string>{ "outlierdownweighting", "2" });
777 }
778
779 if (config_.num_of_threads > 0)
780 {
781 steer_writer.add_other_options(std::vector<std::string>{
782 "threads", fmt::format("{}", config_.num_of_threads), fmt::format("{}", config_.num_of_threads) });
783 }
784 steer_writer.write();
785 }
786} // namespace R3B::Neuland::Calibration
constexpr auto SCALE_FACTOR
constexpr auto DEFAULT_T_ERROR
constexpr auto DEFAULT_RES_FILENAME
constexpr auto DEFAULT_RES_JSON_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 *
void set_binary_dir(std::string_view dir)
void set_steer_filename(std::string_view filename)
void set_working_dir(std::string_view dir)
void set_parameter_filename(std::string_view filename)
auto get_pars() const -> const auto &
void set_filename(std::string_view filename)
auto GetListOfModulePar() const -> const std::unordered_map< int, ::R3B::Neuland::HitModulePar > &
auto to_module_num_label(int par_num) -> std::pair< int, GlobalLabel >
R3B::OutputVectorConnector< MilleCalData > output_tsync_mille_data_
R3B::OutputConnector< NeulandTrackInfo > output_mille_track_info_
void add_fit_result_hist(const MilleDataProcessor::FitResult &fit_result)
auto select_t_sync_signal(const std::vector< MilleCalData > &plane_data)
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
static constexpr std::string_view DEFAULT_SUB_DIR
void fill_module_parameters(const Millepede::ResultReader &result, Neuland::Cal2HitPar &cal_to_hit_par)
void set_options(const MillepedeOptions &options)
std::unique_ptr< MilleDataProcessor > data_preprocessor_
auto add_signal_t_sum(const MilleCalData &signal, const TrackFitResult &fit_coeff) -> float
void add_signal_t_diff(const MilleCalData &signal)
auto SignalFilter(const std::vector< BarCalData > &signals) -> bool override
void add_signals(const DataBufferType &processed_data, const TrackFitResult &fit_coeff)
void AddSignals(const std::vector< BarCalData > &signals) override
auto get_global_label_id(int module_num, GlobalLabel label) -> int
void HistInit(DataMonitor &histograms) override
R3B::OutputVectorConnector< MilleCalData > output_mille_data_
static constexpr auto ModuleID2PlaneID(int moduleID) -> int
void set_working_dir(std::string_view dir)
Definition SteerWriter.h:51
constexpr auto DEFAULT_TSYNC_REFERENCE_BAR_VALUE
constexpr auto DEFAULT_TSYNC_REFERENCE_BAR_NUM
std::unordered_map< int, std::vector< MilleCalData > > DataBufferType
constexpr auto BarsPerPlane
constexpr auto ModuleID2PlaneID(int moduleID) -> int
constexpr auto GetBarVerticalDisplacement(int module_num) -> double
constexpr auto SQRT_12
constexpr auto BarLength
constexpr auto CLight
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
Data structure to store the cal level data for the data preprocessing.
float residual
residual value against the fitted line