25#include <fairlogger/Logger.h>
39constexpr Double_t MSE_SLOW_THRESHOLD{2.0};
40constexpr Int_t MIN_TRACKS_PER_THREAD{1000};
41constexpr Double_t MIN_HITS_PORTION{0.01};
43constexpr Double_t MAX_ELEMENT_Z_SPREAD{1.0};
45constexpr Double_t OUTLIER_FACTOR{3.0};
47constexpr Int_t OUTLIER_MIN_SAMPLE{100};
48constexpr Double_t VERTEX_OUTLIER_FACTOR{
51constexpr Double_t MAD_TO_SIGMA{1.4826};
54constexpr Int_t Z0_MAX_STEPS{10};
55constexpr Double_t Z0_TOLERANCE{1.0E-4};
57constexpr Int_t Z0_MIN_TERMS{100};
60constexpr Double_t REL_PROGRESS_FAIL{-1.0};
61constexpr Double_t MIN_PROGRESS_STEP{1
E-3};
62constexpr Double_t MIN_REL_PROGRESS{0.001};
63constexpr Double_t REL_PROGRESS_GOOD{0.05};
64constexpr Int_t MIN_REGULAR_ITERS{2};
65constexpr Int_t MAX_REGULAR_RETRY{0};
70constexpr Double_t STEP_TOLERANCE_1D{0.01};
71constexpr Int_t BRENT_GRID_SIZE{4};
72constexpr Int_t LM_ITERATIONS_MIN{3};
73constexpr Int_t LM_ITERATIONS_MAX{8};
76static_assert(LM_ITERATIONS_MIN >= 2,
"Levenberg-Marquardt needs at least two iterations");
77static_assert(LM_ITERATIONS_MAX > LM_ITERATIONS_MIN,
"Levenberg-Marquardt maximum must exceed the minimum");
97 const auto mid{buffer.begin() + buffer.size() / 2};
98 std::nth_element(buffer.begin(), mid, buffer.end());
101 x = std::abs(x - median);
102 std::nth_element(buffer.begin(), mid, buffer.end());
103 return {median, MAD_TO_SIGMA * *mid};
113 const char* filesListPath,
114 const char* constraintsPath,
115 const char* presigmaPath,
125 LOG(state) <<
" > BmnAligner : initialization started";
129 fBrent.SetNpx(BRENT_GRID_SIZE);
134 LOG(error) <<
"<!> detector model is not initialized: call Init() on it"
135 " right after construction (see BmnDetectorModel)";
136 LOG(state) <<
" < BmnAligner : initialization terminated";
139 LOG(info) <<
" --- TASK CONFIG ---------------------------------------------------";
140 LOG(info) <<
" measure model: " << measureModel->
Description();
141 LOG(info) <<
" detector model: " << modelDetector->
Description();
142 LOG(info) <<
" -------------------------------------------------------------------";
145 LOG(info) <<
" " << filesListPath <<
" : .root files list";
153 LOG(error) <<
"<!> ROOT iterator initialization failed";
161 LOG(state) <<
" < BmnAligner : initialization terminated";
185 LOG(info) <<
Form(
" %.1f GB of RAM required",
221 LOG(state) <<
" > BmnAligner : data preparation started";
228 TFile* dumpFile{
nullptr};
229 TTree* dumpTree{
nullptr};
233 auto CleanupDump = [&]() {
242 dumpFile =
new TFile(dumpPath,
"RECREATE");
244 LOG(error) <<
" <!> PrepareData: failed to create dump file " << dumpPath;
263 LOG(info) <<
" " << dumpPath <<
" : dumping compacted input data to this file";
266 LOG(info) <<
" loading data from ROOT files into RAM...";
278 Int_t detID, iTrack{0}, iHit{0},
306 LOG(error) <<
" <!> Unknown detector module encoding:"
307 <<
"\n iterator::HitDetectorID() = " << detID
308 <<
"\n DetectorModel::DecodeID() = " <<
fpDetModel->DecodeID(detID)
309 <<
"\n FairHit::GetDetectorID() = " << hit->GetDetectorID()
310 <<
"\n CbmStsHit::GetSystemId() = " << hit->
GetSystemId()
311 <<
"\n CbmStsHit::GetStationNr() = " << hit->
GetStationNr()
312 <<
"\n CbmStsHit::GetSectorNr() = " << hit->
GetSectorNr()
313 <<
"\n CbmStsHit::GetSensorNr() = " << hit->
GetSensorNr();
333 if (dumpPath && srcHit) {
334 Int_t newHitIdx{dumpHits->GetEntriesFast()};
335 new ((*dumpHits)[newHitIdx])
CbmStsHit(*srcHit);
336 dumpHitArr[dumpArrIdx++] = newHitIdx;
352 Dx += srcHit->GetDx();
353 Dy += srcHit->GetDy();
387 LOG(info) <<
" " << dumpPath <<
" : compacted data successfully created";
398 LOG(error) <<
" <!> PrepareData: detector element " << ID <<
" (" <<
fpDetModel->DecodeID(ID)
402 LOG(warning) <<
Form(
" ! detector element %d (%s) has only %d hits of %d expected", ID,
406 LOG(error) <<
" <!> PrepareData: " << emptyCount <<
" detector element(s) without hits, alignment stopped";
410 LOG(info) <<
" " << iTrack <<
" tracks loaded into RAM";
411 LOG(info) <<
" " << iHit <<
" hits loaded into RAM";
412 LOG(info) <<
Form(
" (%.1e, %.1e) : average STS hit position errors in loaded data", Dx / stsHits, Dy / stsHits);
415 LOG(info) <<
Form(
" %d (%.1f%%) tracks take the vertex hit", vertexHits, 100.0 * vertexHits / iTrack);
426 if (spread > maxZspread)
428 if (spread <= MAX_ELEMENT_Z_SPREAD)
430 LOG_IF(warning, !wideCount++)
431 <<
" ! these elements span more z than one plane would, so their pivot is a compromise:";
432 LOG(warning) <<
Form(
" det %2d (id %9d, %s) : z = %.3f cm, spread %.3f cm",
i,
fpDetModel->EncodedID(
i),
435 LOG(info) <<
Form(
" %.2e cm : largest hit z spread within a detector element", maxZspread);
440 const std::vector<BmnDetectorModel::Composite> modelNodes{
fpDetModel->Composites()};
442 if (!
fHierarchy.AddComposite(node.name, node.parent, node.leaves,
nullptr))
444 LOG(info) << (modelNodes.empty()
445 ?
" flat parametrization: the detector model declares no composite nodes"
446 :
Form(
" %zu composite node(s) declared by the detector model", modelNodes.size()));
448 LOG(error) <<
"<!> failed to build the detector hierarchy";
473 Form(
"%+.3f cm : target moved in the detector model, now from %.3f to %.3f cm%s; reading the data again",
475 LOG_IF(warning, beyond) <<
" ! " << moved;
476 LOG_IF(info, !beyond) <<
" " << moved;
486 LOG(state) <<
" > BmnAligner : loading solution from file";
489 if (jsonPath[0] ==
'\0') {
490 LOG(info) <<
" filename is empty, adding blank solution";
497 LOG(info) <<
" " << jsonPath <<
" : file to load solution from";
506 if (!solution.
leaves.empty()) {
518 params(p.full) = comp.
values(p.prm);
576 const Double_t sigma{(*pStdDevComp)[p.prm]};
578 dP[p.full] =
gRandom->Gaus(0.0, sigma);
589 const Double_t sigma{(*pStdDevLeaf)[p.prm]};
591 dP[p.full] +=
gRandom->Gaus(0.0, sigma);
592 trueMeans(p.prm) += dP[p.full];
605 solution.
A(
i) -= trueMeans;
620 LOG(state) <<
" > BmnAligner : iterative alignment started";
624 LOG(error) <<
" <!> BmnAligner::Align: maxRounds " << maxRounds <<
" is less than 1";
631 if (zeroRand > 0.0) {
636 LOG(info) <<
" zero approximation randomized with StdDev = " << zeroRand;
638 LOG(info) <<
" zero approximation randomization skipped";
645 LOG_IF(info, OUTLIER_FACTOR <= 0.0) <<
" outlier rejection skipped by setup";
646 LOG_IF(warning, OUTLIER_FACTOR > 0.0 && !outlierOn)
647 <<
" ! " <<
fTracksUsableCnt <<
" tracks available only, outlier rejection skipped";
653 Bool_t outlierTest{outlierOn}, vertexTest{vertexOn};
687 LOG(info) <<
Form(
" --- round %d of %d at most",
round, maxRounds);
690 Int_t regularRetries{MAX_REGULAR_RETRY}, retriesLast;
691 Double_t progressAbs{0.0}, progressRel{MIN_REL_PROGRESS}, progressStep{MIN_PROGRESS_STEP};
692 while (
TMath::Abs(progressRel) >= MIN_REL_PROGRESS || regularRetries > 0 || progressStep >= MIN_PROGRESS_STEP)
695 if (progressAbs < 0.0) {
699 if (progressRel <= REL_PROGRESS_FAIL) {
701 "quasi-Newton iteration made very poor step - "
702 "reverting to previous approximation";
706 LOG(error) <<
" <!> BmnAligner::Align : algorithm is diverging";
714 LOG(error) <<
" <!> BmnAligner::Align : iteration failed";
718 progressRel = progressAbs /
fpResultPrev->GetValueMSE();
725 progressStep = std::sqrt((prev.
GetSub(0, nLeaf - 1) - curr.GetSub(0, nLeaf - 1)).Norm2Sqr());
726 LOG(info) <<
Form(
" = %+.3f%% relative progress, MSE change : %.3e -> %.3e\n", progressRel * 100.0,
729 retriesLast = regularRetries;
732 if (progressRel >= REL_PROGRESS_GOOD)
738 if (progressRel < MIN_REL_PROGRESS && regularRetries > 0)
742 LOG_IF(info, retriesLast != regularRetries) <<
" " << regularRetries <<
" regularization retries left";
744 if (progressAbs <= 0.0)
761 progressStep = MIN_PROGRESS_STEP;
764 if (
round >= maxRounds)
768 LOG(info) <<
" " << changed <<
" tracks or vertex hits changed state: the track set has settled";
776 LOG(info) <<
" " <<
fIterationResults.size() - 1 <<
" iterations until algorithm convergence criteria reached";
808 LOG(state) <<
" > #" <<
fIteration + 1 <<
" iteration started";
816 TMatrixD mC_dash(LeafParamsCnt, LeafParamsCnt);
819 LOG(info) <<
" " <<
fThreadsCnt <<
" threads started to perform dimension reduction (Millepede)";
823 LOG(info) <<
Form(
" %.1fs (REAL) / %.1fs (CPU) took to complete dimension reduction", timerMille.
RealTime(),
835 fHierarchy.PromoteSystem(vB_dash, mC_dash, vB_h, mC_h);
842 LOG_IF(info,
fPriors.presigmaCount) <<
" " <<
fPriors.presigmaCount <<
" parameter priors (presigmas) applied";
869 mCL.
ResizeTo(HierParamsCnt + kept, HierParamsCnt + kept);
886 vBL[HierParamsCnt +
i] = vRhs[
fPriors.Kept()[
i]];
887 mCL.
SetSub(HierParamsCnt, 0, rows);
889 LOG(info) <<
" " << kept <<
" parameter constraints applied";
894 LOG(info) <<
" solving non-regularized system for global parameters...";
898 LOG(warning) <<
" ! iteration failed to improve MSE";
900 }
else if (!successNR) {
912 LOG(info) <<
" starting Levenberg-Marquardt regularization...";
915 Int_t LMiterarion{0};
917 while ((LMworking || LMiterarion < LM_ITERATIONS_MIN) && LMiterarion < LM_ITERATIONS_MAX) {
920 for (
Int_t i = 0;
i < HierParamsCnt;
i++)
921 mCL(
i,
i) = mC_h(
i,
i) * LMfactor;
925 if (1.0 -
fpResultLast->GetValueMSE() / valueMSEbest >= REL_PROGRESS_GOOD) {
935 LMfactorBest = LMfactor;
939 LOG(warning) <<
Form(
" ! LM regularization failed for F=%.3e", LMfactor);
941 LMfactor *= LM_MULT_STEP;
948 for (
Int_t i = 0;
i < HierParamsCnt;
i++)
949 mCLcopy(
i,
i) = mC_h(
i,
i) * factor;
951 throw std::runtime_error(
Form(
"Levenberg-Marquardt failed (F=%.3e)", factor));
959 " regularization cancelled : sufficient %+.1f%% progress achieved using non-regularized method",
962 }
else if (LMfactorBest < 1.0) {
963 LOG(warning) <<
" ! iteration failed to improve MSE";
966 }
else if (LMfactorBest == 1.0 || LMworking) {
970 <<
Form(
" F = %.3e : LM regularization approached gradient descent", LMfactorBest);
973 <<
" F = 1.0 : LM regularization did not improve results, using simple step regularization";
981 brent.
SetNpx(BRENT_GRID_SIZE);
982 brent.
SetFunction(fnLM, LMfactorBest, LMfactorBest * LM_MULT_STEP);
983 Bool_t success{brent.
Minimize(
static_cast<Int_t>(0.1 / STEP_TOLERANCE_1D), STEP_TOLERANCE_1D * 10.0,
986 LOG(info) <<
Form(
" F = %.3e : optimal LM factor value", brent.
XMinimum());
988 LOG(warning) <<
Form(
" ! F = %.3e : rough LM factor value used, 1D optimization failed",
990 fnLM(success ? brent.
XMinimum() : LMfactorBest);
998 LOG(info) <<
Form(
" %d MSE value calculations performed during iteration",
fMSEclcCounter);
999 LOG(info) <<
Form(
" %.1fs (REAL) / %.1fs (CPU) took to complete parameters estimation", timerGlobal.
RealTime(),
1033 LOG(warning) <<
" ! SVD decomposition failed";
1053 TMatrixD mCLinv(mCL.GetNrows(), mCL.GetNcols());
1055 mCLinv = mLU.
Invert(success);
1057 const Bool_t invertFailed{!success};
1058 TVectorD vAL{success ? mCLinv * vBL : mSVD.
Solve(vBL, success)};
1060 LOG(warning) <<
" ! global matrix inversion failed";
1068 if (activeConstCnt) {
1094 fHierarchy.ToEffectiveCov(mCLinv.
GetSub(0, HierParamsCnt - 1, 0, HierParamsCnt - 1), covEff);
1100 aCorr(p.full) = 1.0;
1102 aErr(p.full) = std::sqrt(errSq);
1109 const Double_t prod{errSq * mCL(p.full, p.full)};
1110 aCorr(p.full) = prod > 1.0 ? std::sqrt(1.0 - 1.0 / prod) : 0.0;
1117 if (s.full > r.full)
1121 Cov(r.full, s.full) = Cov(s.full, r.full) = newValue;
1127 LOG(info) <<
" updating local parameters...";
1135 LOG(warning) <<
" ! Step optimization requested while Alpha is not ready yet - check the code";
1138 }
else if (optimStep) {
1145 Double_t valueMSE, stepMin{0.0}, stepMax{1.0};
1146 valueMSE = fnMSE(stepMax);
1147 while (valueMSE < fpResultPrev->GetValueMSE()) {
1150 valueMSE = fnMSE(stepMax);
1153 constexpr static const Int_t iterations{
static_cast<Int_t>(1.0 / STEP_TOLERANCE_1D)};
1154 fBrent.SetFunction(fnMSE, stepMin, stepMax);
1155 success =
fBrent.Minimize(iterations, STEP_TOLERANCE_1D, STEP_TOLERANCE_1D * 0.1);
1157 LOG(warning) <<
" ! Brent method failed to calculate step size";
1167 const Double_t cnstrFactor{std::fabs(1.0 - stepBest)};
1168 LOG_IF(warning,
fPriors.inhomogeneous && cnstrFactor >= 1.0)
1169 <<
" ! Brent step = " << stepBest <<
": inhomogeneous-constraint residual will "
1170 << (cnstrFactor > 1.0 ?
"grow" :
"not decay") <<
" this iteration";
1245 static const auto zStart = zeroes.begin();
1255 std::vector<SMatrGP> mG;
1257 TMatrixD mC_part(LeafParamsCnt, LeafParamsCnt);
1267 const auto TensorProdSelf = [](
const SVectLC&
v) {
1270 for (
Int_t j{0}; j <=
i; j++)
1271 m(
i, j) =
v[
i] *
v[j];
1315 mGamma += wx * TensorProdSelf(vGradLx);
1316 mGamma += wy * TensorProdSelf(vGradLy);
1317 vBeta += wDx * vGradLx + wDy * vGradLy;
1321 hitIdx.push_back(iHit);
1332 TMatrixDSub(mC_part, lower, upper, lower, upper) += amCdelta;
1335 vB_part[lower + k] += wDx * vGradGx[k] + wDy * vGradGy[k];
1342 throw std::runtime_error(
"matrix inversion failed while calculating local parameters");
1343 const SMatrLC& mGammaInv{mGamma};
1344 vDelta = mGammaInv * vBeta;
1364 const Int_t globalHits{
static_cast<Int_t>(hitIdx.size())};
1365 for (
Int_t i{0};
i < globalHits;
i++) {
1377 for (
Int_t j{0}; j < globalHits; j++) {
1379 if (iLower > jLower)
1382 TMatrixDSub(mC_part, iLower, iUpper, jLower, jUpper) += amCdelta;
1385 const SVectGL vBdelta{mG[
i] * vDelta};
1387 vB_part[iLower + k] -= vBdelta[k];
1393 for (
Int_t r{1}; r < LeafParamsCnt; r++)
1394 for (
Int_t c{0}; c < r; c++)
1395 mC_part(r, c) = mC_part(c, r);
1399 *pmC_dash += mC_part;
1400 *pvB_dash += vB_part;
1408 tempSolution.
A() = solution;
1409 tempSolution.SeparateA();
1420 if (withResiduals) {
1432 std::cout <<
" " <<
fMSEclcCounter <<
" MSE calculations\r" << std::flush;
1438 Double_t delta, omega, valueMSE{0.0};
1439 TH1D *pResX{
nullptr}, *pResY{
nullptr};
1440 TH2D *pResSX{
nullptr}, *pResSY{
nullptr};
1442 if (withResiduals) {
1448 pResX =
new TH1D(
Form(
"residualsX_%lu",
fpResultLast->GetHistCounter()),
"Partial residuals by X",
1450 pResY =
new TH1D(
Form(
"residualsY_%lu",
fpResultLast->GetHistCounter()),
"Partial residuals by Y",
1452 pResSX =
new TH2D(
Form(
"residualsSX_%lu",
fpResultLast->GetHistCounter()),
"Partial synthetic X residuals",
1455 pResSY =
new TH2D(
Form(
"residualsSY_%lu",
fpResultLast->GetHistCounter()),
"Partial synthetic Y residuals",
1475 omega = pItr->
HitWx();
1477 valueMSE += omega * delta * delta;
1478 if (withResiduals && omega > 0.0) {
1480 pResSX->
Fill(z + pItr->
HitX() * 0.1, delta);
1483 omega = pItr->
HitWy();
1485 valueMSE += omega * delta * delta;
1486 if (withResiduals && omega > 0.0) {
1488 pResSY->Fill(z + pItr->
HitY() * 0.1, delta);
1496 if (withResiduals) {
1522 LOG(info) <<
" vertex hit residuals calculation";
1528 static_cast<Int_t>(std::count_if(rx.begin(), rx.end(), [](
Double_t r) { return !std::isnan(r); }))};
1529 if (tested < OUTLIER_MIN_SAMPLE) {
1530 LOG(warning) <<
" ! " << tested <<
" vertex hits available only, their test skipped";
1534 buffer.reserve(tested);
1535 const auto [cx, sx]{MedianAndSigma(rx, buffer)};
1536 const auto [cy, sy]{MedianAndSigma(ry, buffer)};
1537 LOG(info) <<
Form(
" %.2e, %.2e : median vertex hit residual in X, Y", cx, cy);
1538 LOG(info) <<
Form(
" %.2e, %.2e : MAD-sigma of vertex hit residuals in X, Y", sx, sy);
1540 Int_t rejected{0}, changed{0};
1542 if (std::isnan(rx[iTrack]))
1544 const Bool_t accept{std::abs(rx[iTrack] - cx) <= VERTEX_OUTLIER_FACTOR * sx
1545 && std::abs(ry[iTrack] - cy) <= VERTEX_OUTLIER_FACTOR * sy};
1547 rejected += !accept;
1551 LOG(info) <<
Form(
" %d (%.1f%%) vertex hits rejected as outliers, their tracks kept; %d changed state", rejected,
1552 100.0 * rejected / tested, changed);
1570 (*pRx)[iTrack] = hits.front().rx;
1571 (*pRy)[iTrack] = hits.front().ry;
1629 LOG(error) <<
" <!> BmnAligner::FitTargetZ: the detector model has no target element";
1633 LOG(error) <<
" <!> BmnAligner::FitTargetZ: no parameter layout, PrepareData() must run first";
1644 std::vector<VertexTerm_t> terms;
1652 || itr.
HitWy() <= 0.0)
1662 if (lineX.
Det() <= 0.0 || lineY.
Det() <= 0.0)
1664 terms.push_back({{vertex(
iX) - lineX.
At(vertex(
iZ)), vertex(
iY) - lineY.
At(vertex(
iZ))},
1666 {lineX.
Var(vertex(
iZ)), lineY.
Var(vertex(
iZ))}});
1671 LOG(info) <<
Form(
" %zu vertex tracks in the target z fit", terms.size());
1675 constexpr Int_t iDZ{4};
1676 auto Offset = [](
Int_t p,
Double_t s) {
return 2 * p + (s >= 0.0 ? 1 : 0); };
1677 auto Residual = [&](
const VertexTerm_t& t,
Int_t p,
const SVectZ0& th) {
1678 return t.r[p] - th(Offset(p, t.s[p])) - th(iDZ) * t.s[p];
1685 Int_t used{0}, usedPrev{-1}, steps{0};
1688 pulls.reserve(terms.size());
1689 for (; steps < Z0_MAX_STEPS && !converged; steps++) {
1693 for (
const VertexTerm_t& t : terms)
1694 for (
Int_t p = 0; p < 2; p++) {
1695 const Double_t sigma{scale[p] * std::sqrt(t.var[p])};
1696 if (std::fabs(Residual(t, p, theta)) > window * sigma)
1698 const Double_t w{1.0 / (sigma * sigma)};
1699 const Int_t k{Offset(p, t.s[p])};
1702 normal(k, iDZ) += w * t.s[p];
1703 normal(iDZ, iDZ) += w * t.s[p] * t.s[p];
1704 rhs(k) += w * t.r[p];
1705 rhs(iDZ) += w * t.s[p] * t.r[p];
1709 fitted = used >= Z0_MIN_TERMS && cov.InvertChol();
1717 converged = std::fabs(theta(iDZ) - dzPrev) < Z0_TOLERANCE && used == usedPrev && steps > 0;
1719 for (
Int_t p = 0; p < 2; p++) {
1721 for (
const VertexTerm_t& t : terms)
1722 pulls.push_back(std::fabs(Residual(t, p, theta)) / std::sqrt(t.var[p]));
1723 const auto mid{pulls.begin() + pulls.size() / 2};
1724 std::nth_element(pulls.begin(), mid, pulls.end());
1725 scale[p] = MAD_TO_SIGMA * *mid;
1730 LOG(error) <<
" <!> BmnAligner::FitTargetZ: " << used
1731 <<
" vertex track terms only, or a singular fit: z0 is undetermined";
1735 z0 = zC + theta(iDZ);
1736 z0Err = std::sqrt(cov(iDZ, iDZ));
1737 LOG(info) <<
Form(
" %.3f +- %.3f cm : z0, where the tracks meet the beam; target from %.3f to %.3f cm", z0,
1739 LOG(info) <<
Form(
" beam - track offsets at z_c (cm), slope < 0 / >= 0 : x %+.3f / %+.3f, y %+.3f / %+.3f",
1740 theta(0), theta(1), theta(2), theta(3));
1741 LOG(info) <<
Form(
" %d of %zu terms used, pull width x %.2f, y %.2f, %d fit(s)", used, 2 * terms.size(),
1742 scale[0], scale[1], steps);
1743 LOG_IF(warning, !converged) <<
" ! the z0 fit did not settle in " << Z0_MAX_STEPS
1744 <<
" fits: terms near the window edge keep changing";
1746 LOG_IF(warning, (z0 < target.zStart || z0 > target.
zEnd)) <<
" ! z0 lies outside the target of the geometry file";
1769 auto Aligned = [
this, pItr]() {
1777 const SVect3 hit{Aligned()};
1782 const SVect3 hit{Aligned()};
1786 restY.Remove(hit(
iZ), hit(
iY), wy);
1787 LooHit_t& loo{hits.emplace_back()};
1789 if (restX.
Det() <= 0.0 || restY.Det() <= 0.0) {
1793 const SVectLC lc{restX.
At0(), restX.
Slope(), restY.At0(), restY.Slope()};
1823 LOG(info) <<
" hit pulls calculation";
1830 const auto [cx, sx]{MedianAndSigma(px, buffer)};
1831 const auto [cy, sy]{MedianAndSigma(py, buffer)};
1832 LOG(info) <<
Form(
" %.2e, %.2e : median hit pull in X, Y", cx, cy);
1833 LOG(info) <<
Form(
" %.2e, %.2e : MAD-sigma of hit pulls in X, Y", sx, sy);
1835 Int_t rejected{0}, changed{0};
1840 std::isnan(px[iHit]) || std::isnan(py[iHit])
1841 || (std::abs(px[iHit] - cx) <= OUTLIER_FACTOR * sx && std::abs(py[iHit] - cy) <= OUTLIER_FACTOR * sy);
1842 rejected += !accept;
1847 LOG(info) <<
Form(
" %d (%.1f%%) tracks with outlier rejected; %d changed state", rejected,
1866 for (
size_t k{0}; k < hits.size(); k++) {
1867 if (hits[k].detID == targetID)
1878 LOG(info) <<
" " <<
fThreadsCnt <<
" threads requested";
1883 LOG(warning) <<
" ! too many threads requested for the size of dataset, using " << max_threads
1887 LOG(info) <<
" " <<
fThreadsCnt <<
" threads approved";
1900 : tracksPerThread));
std::vector< Double_t > VecDouble_t
std::vector< Bool_t > VecBool_t
RM::SVector< Double_t, 3 > SVect3
RM::SVector< Double_t, BMN_LOCAL_PARAMS_PT > SVectLC
RM::SVector< Double_t, BMN_GLOBAL_PARAMS_PD > SVectGL
std::vector< Int_t > VecInt_t
RM::SMatrix< Double_t, BMN_GLOBAL_PARAMS_PD, BMN_GLOBAL_PARAMS_PD > SMatrGL
RM::SMatrix< Double_t, BMN_GLOBAL_PARAMS_PD, BMN_LOCAL_PARAMS_PT > SMatrGP
RM::SMatrix< Double_t, BMN_LOCAL_PARAMS_PT, BMN_LOCAL_PARAMS_PT, RM::MatRepSym< Double_t, BMN_LOCAL_PARAMS_PT > > SMatrLC
#define BMN_LOCAL_PARAMS_PT
#define BMN_GLOBAL_PARAMS_PD
TrackFilter_t BmnDefaultTrackFilter(Bool_t wholeTrackOnly=kTRUE)
constexpr const char * BMN_VERTEX_CUT_STR
HitFilter_t BmnDefaultHitFilter(const BmnDetectorModel &model)
constexpr const char * BMN_HITS_CUT_STR
constexpr const char * BMN_TRACKS_CUT_STR
#define BMN_BEAM_BRANCH_NAME
#define BMN_TRACKS_BRANCH_NAME
#define BMN_HITS_BRANCH_NAME
TMatrixTSym< Double_t > TMatrixDSym
TMatrixTSub< Double_t > TMatrixDSub
TMatrixT< Double_t > TMatrixD
R__EXTERN TRandom * gRandom
char * Form(const char *fmt,...)
TVectorT< Double_t > TVectorD
static Bool_t LoadConstraints(const char *jsonPath, const BmnAlignHierarchy &hierarchy, BmnAlignPriors &priors)
static Bool_t WriteSolution(const char *jsonPath, const BmnAlignHierarchy &hierarchy, const BmnAlignResult &result, Int_t totalTracks, Bool_t withAlpha)
static Bool_t LoadPresigmas(const char *jsonPath, const BmnAlignHierarchy &hierarchy, BmnAlignPriors &priors)
static Bool_t ReadSolution(const char *jsonPath, const BmnAlignHierarchy &hierarchy, Solution &solution)
SVectGL & A(Int_t index) noexcept
VecHitRecs_t fHits
indexed by hit, the same way as fHits
void LeaveOneOut(BmnRamIterator *pItr, VecLooHits_t &hits) const
void DoneInTime(TStopwatch &timer, const char *stage)
BmnAlignResult * fpResultPrev
VecBool_t * fpTrackUsable
BmnRamIterator * fpRamIterator
void VertexResidualsPart(VecDouble_t *pRx, VecDouble_t *pRy, Int_t threadNum)
BmnAligner(const BmnMeasureModel *measureModel, BmnDetectorModel *modelDetector, const char *filesListPath, const char *constraintsPath=nullptr, const char *presigmaPath=nullptr, Int_t nThreads=1, Bool_t withProgressBar=kTRUE)
Double_t CalculateMSE(const TVectorD &solution)
RM::BrentMinimizer1D fBrent
std::vector< BmnRamIterator * > fpIterators
void CalculateMSEpart(Bool_t withResiduals, Int_t threadNum)
BmnDetectorModel * fpDetModel
const BmnAlignResult & ResultLast() const
Bool_t SolveGlobal(const TMatrixD &mCL, const TVectorD &vBL, Bool_t optimStep=kFALSE)
BmnSimpleProgressBar * fpProgressBar
const char * fpPresigmaPath
const BmnMeasureModel * fpMeasureModel
void HitPullsPart(VecDouble_t *pPx, VecDouble_t *pPy, Int_t threadNum)
VecInt_t fHitsPerDetector
Bool_t IterateAlignment()
BmnRootIterator * fpRootIterator
Results_t fIterationResults
Bool_t CheckInit(const char *stage)
Bool_t LoadSolution(const char *jsonPath)
std::vector< LooHit_t > VecLooHits_t
BmnAlignResult * fpResultLast
BmnAlignHierarchy fHierarchy
void SelectIterator(Int_t threadNum, Int_t &trackIdx, BmnRamIterator *&pItr)
Int_t Elements() const noexcept
Bool_t Align(Double_t zeroRand=0.0, Int_t maxRounds=3)
Bool_t PrepareData(const char *dumpPath=nullptr, Bool_t fitTargetZ=kTRUE)
void RunThreads(Method method, Args... args)
void CalculateLocals(TVectorD *pvDA, Int_t threadNum)
void ProcessTracks(TVectorD *pvB_dash, TMatrixD *pmC_dash, Int_t threadNum)
VecAlphaRecs_t fAlphaRecs
const char * fpConstraintsPath
void RandomizeSolution(BmnAlignResult &solution, TVectorD *pStdDevLeaf, TVectorD *pStdDevComp)
Bool_t SaveSolution(const char *jsonPath, Bool_t withAlpha=kFALSE)
VecInt_t fFirstHits
hits of all tracks, stored track by track
Bool_t FitTargetZ(Double_t &z0, Double_t &z0Err)
void LinRegressionAlphaPart(Int_t threadNum)
Bool_t EndOfTracks() const noexcept
Bool_t EndOfHits() const noexcept
Bool_t Initialized() const
const std::string & Description() const
Bool_t IsEnabled() const noexcept
void SetEnabled(Bool_t enabled) noexcept
virtual const char * Description() const noexcept=0
virtual void NextHit() override
const BmnHitRecord & GetHit() const noexcept
virtual void ResetAll() override
virtual Double_t HitY() const override
virtual Double_t HitX() const override
virtual Int_t HitDetectorID() const override
virtual Double_t HitWy() const override
virtual void ResetHits() override
virtual Double_t HitWx() const override
virtual void NextTrack() override
virtual Double_t HitZ() const override
Double_t Det() const noexcept
Double_t At0() const noexcept
Double_t Var(Double_t z) const noexcept
Double_t At(Double_t z) const noexcept
void Add(Double_t z, Double_t v, Double_t w=1.0) noexcept
Double_t Slope() const noexcept
void Remove(Double_t z, Double_t v, Double_t w=1.0) noexcept
Int_t GetSensorNr() const
virtual Int_t GetStationNr() const
Int_t GetSectorNr() const
Int_t GetSystemId() const
Accessors.
void SetStsHits(TArrayI &hitsArr)
void SetFunction(const ROOT::Math::IGenFunction &f, double xlow, double xup)
bool Minimize(int maxIter, double absTol=1.E-8, double relTol=1.E-10) override
double XMinimum() const override
void SetElements(InputIterator begin, InputIterator end, bool triang=false, bool lower=true)
void SetElements(InputIterator begin, InputIterator end)
void Set(Int_t n) override
void Delete(Option_t *option="") override
Bool_t Decompose() override
const TVectorD & GetSig()
Bool_t Decompose() override
TVectorD Solve(const TVectorD &b, Bool_t &ok) override
Int_t Write(const char *name=nullptr, Int_t opt=0, Int_t bufsize=0) const override
void Close(Option_t *option="") override
static void StatOverflows(Bool_t flag=kTRUE)
virtual Int_t GetNbinsY() const
static void AddDirectory(Bool_t add=kTRUE)
virtual Int_t GetNbinsX() const
virtual Int_t Fill(const char *name, Double_t w)
virtual Int_t Fill(const char *namex, const char *namey, Double_t w)
TMatrixT< Element > GetSub(Int_t row_lwb, Int_t row_upb, Int_t col_lwb, Int_t col_upb, Option_t *option="S") const
const TMatrixT< Element > & Use(const TMatrixT< Element > &a) const
TMatrixTBase< Element > & ResizeTo(const TMatrixT< Element > &m)
TMatrixTBase< Element > & SetSub(Int_t row_lwb, Int_t col_lwb, const TMatrixTBase< Element > &source) override
Int_t GetEntriesFast() const
TObject * At(Int_t idx) const override
R__ALWAYS_INLINE Bool_t IsZombie() const
void Start(Bool_t reset=kTRUE)
const char * Data() const
static TString Format(const char *fmt,...)
virtual void SetDirectory(TDirectory *dir)
virtual Int_t Branch(const char *folder, Int_t bufsize=32000, Int_t splitlevel=99)
TVectorT< Element > & SetSub(Int_t row_lwb, const TVectorT< Element > &source)
TVectorT< Element > & ResizeTo(const TVectorT< Element > &v)
Element * GetMatrixArray()
TVectorT< Element > GetSub(Int_t row_lwb, Int_t row_upb, Option_t *option="S") const
Expr< TensorMulOp< SVector< T, D1 >, SVector< T, D2 > >, T, D1, D2 > TensorProd(const SVector< T, D1 > &lhs, const SVector< T, D2 > &rhs)
RVec< PromoteType< T > > round(const RVec< T > &v)
Expr< TransposeOp< Expr< A, T, D1, D2, R >, T, D1, D2 >, T, D2, D1, typename TranspPolicy< T, D1, D2, R >::RepType > Transpose(const Expr< A, T, D1, D2, R > &rhs)
std::vector< NodeValues > composites
std::vector< NodeValues > leaves