diff --git a/Detectors/TPC/calibration/src/TPCFastSpaceChargeCorrectionHelper.cxx b/Detectors/TPC/calibration/src/TPCFastSpaceChargeCorrectionHelper.cxx index 494d8059707ea..6bda08d7c8544 100644 --- a/Detectors/TPC/calibration/src/TPCFastSpaceChargeCorrectionHelper.cxx +++ b/Detectors/TPC/calibration/src/TPCFastSpaceChargeCorrectionHelper.cxx @@ -28,6 +28,7 @@ #include "Spline2DHelper.h" #include "Riostream.h" #include +#include #include #include "TStopwatch.h" #include "TTreeReader.h" @@ -1057,7 +1058,24 @@ void TPCFastSpaceChargeCorrectionHelper::initInverse(o2::gpu::TPCFastSpaceCharge void TPCFastSpaceChargeCorrectionHelper::initInverse(std::vector& corrections, const std::vector& scaling, bool prn) { - /// initialise inverse transformation + /// Initialise the inverse correction splines from the direct ones. + /// + /// Convention: the direct correction d maps a measured cluster position m (y, z in a pad row) to the real one, r = m + d(m). The inverse + /// splines are a function of the REAL position and hold the same correction d, evaluated at the measured position that belongs to r: + /// d_inv(r) = d(m(r)), with m(r) the solution of m + d(m) = r. + /// The tracker uses them to go back from a real (track) position to the measured one: m = r - d_inv(r). + /// + /// Method, per sector and pad row: + /// 1. fit points on a regular grid of REAL positions r, 10 per knot interval in u and v, so every knot cell gets points; + /// 2. at each r, solve m + d(m) = r for m and take d(m) as the fit value (exact inverse up to the solver tolerance); + /// 3. points whose solve does not converge (e.g. close to a fold of the direct map) take the value and weight of a nearby converged + /// point of the row (if no point of the row converges: the direct correction at r, with a warning); + /// 4. least-squares spline fit of the points (Spline2DHelper::approximateDataPoints). + /// Where the direct map folds (two measured positions map onto the same r) there is no unique inverse. This is not detected: the solve + /// usually still converges there, to one of the solutions, and such points are not counted as not converged. + /// The former scheme took the measured grid points moved by the correction as fit points. Wherever the correction pushes clusters away + /// from a region (e.g. narrow knot cells at the sector edges), knot cells there got no point at all and were held only by the spline + /// helper's tiny smoothness term, which gave arbitrary inverse values (up to 1e7 cm). TStopwatch watch; LOG(info) << "fast space charge correction helper: init inverse"; @@ -1074,11 +1092,41 @@ void TPCFastSpaceChargeCorrectionHelper::initInverse(std::vector nNewton(mNthreads, 0); // fit points that needed the Newton solve, per thread + std::vector nFailed(mNthreads, 0); // fit points whose solve did not converge, per thread + std::vector nRowsFailed(mNthreads, 0); // sector rows without any converged fit point, per thread + + // positions along one spline axis: 10 per knot interval (knot included, next knot excluded) and the last knot + auto samplePositions = [](const auto& grid) { + std::vector positions; + for (int i = 0; i < grid.getNumberOfKnots(); i++) { + if (i == grid.getNumberOfKnots() - 1) { + positions.push_back(grid.getKnot(i).u); + break; + } + for (int k = 0; k < 10; ++k) { // integer loop: a floating-point step would add an 11th point at the next knot + positions.push_back(grid.getKnot(i).u + 0.1 * k * (grid.getKnot(i + 1).u - grid.getKnot(i).u)); + } + } + return positions; + }; + for (int sector = 0; sector < mGeo.getNumberOfSectors(); sector++) { // LOG(info) << "inverse transform for sector " << sector ; @@ -1092,64 +1140,220 @@ void TPCFastSpaceChargeCorrectionHelper::initInverse(std::vector gridU; - { - const auto& grid = spline.getGridX1(); - for (int i = 0; i < grid.getNumberOfKnots(); i++) { - if (i == grid.getNumberOfKnots() - 1) { - gridU.push_back(grid.getKnot(i).u); - break; + // the summed (scaled) direct correction d at a measured position y, z of this sector and row + auto directCorrection = [&](double y, double z, double& dx, double& dy, double& dz) { + dx = 0.; + dy = 0.; + dz = 0.; + for (int i = 0; i < corrections.size(); ++i) { + if (scaling[i] == 0.f) { + continue; // not part of the sum; also keeps a non-finite value of an unused map out of it (0 * NaN = NaN) } - for (double s = 1.; s > 0.; s -= 0.1) { - gridU.push_back(s * grid.getKnot(i).u + (1. - s) * grid.getKnot(i + 1).u); + float dxTmp = 0.f; + float dyTmp = 0.f; + float dzTmp = 0.f; + corrections[i]->getCorrectionLocal(sector, row, y, z, dxTmp, dyTmp, dzTmp); + dx += dxTmp * scaling[i]; + dy += dyTmp * scaling[i]; + dz += dzTmp * scaling[i]; + } + }; + + // Solve m + d(m) = r for the measured position m = (y, z) of the real position r = (yReal, zReal); on return dx, dy, dz = d(m). + // Outside the measured grid d is the edge value (beyond the grid's z end times the spline scale s(z)), so a solution exists there too. + // Returns false if neither stage converges, e.g. close to a fold of the direct map (two measured positions map onto the same r, + // no unique inverse). It is no test for a fold: inside one the iteration usually converges, to one of the solutions. + auto solveMeasured = [&](double yReal, double zReal, double& y, double& z, double& dx, double& dy, double& dz) { + // residual of a candidate m: m + d(m) - r, and d(m) + auto residual = [&](double yM, double zM, double& ry, double& rz, double& cx, double& cy, double& cz) { + directCorrection(yM, zM, cx, cy, cz); + ry = yM + cy - yReal; + rz = zM + cz - zReal; + }; + double ry = 0.; + double rz = 0.; + // stage 1, fixed-point iteration m <- r - d(m): cheap, converges wherever d changes by less than the distance (|dd/dm| < 1) + y = yReal; + z = zReal; + double bestY = y; + double bestZ = z; + double bestNorm = 1.e30; + for (int it = 0; it < kMaxIterations; ++it) { + residual(y, z, ry, rz, dx, dy, dz); + const double norm = std::hypot(ry, rz); + if (norm < kTolerance) { + return true; } + if (norm < bestNorm) { + bestNorm = norm; + bestY = y; + bestZ = z; + } + y = yReal - dy; + z = zReal - dz; } - } - std::vector gridV; - { - const auto& grid = spline.getGridX2(); - for (int i = 0; i < grid.getNumberOfKnots(); i++) { - if (i == grid.getNumberOfKnots() - 1) { - gridV.push_back(grid.getKnot(i).u); - break; + // stage 2, Newton with a numerical Jacobian and step halving: for strong gradients of d (e.g. at the sector edges), where the + // fixed-point iteration may diverge; it starts from the stage-1 point with the smallest residual + nNewton[iThread]++; + y = bestY; + z = bestZ; + for (int it = 0; it < kMaxIterations; ++it) { + constexpr double kStep = 1.e-2; // cm, finite-difference step of the Jacobian + double r1y = 0.; + double r1z = 0.; + double r2y = 0.; + double r2z = 0.; + double tx = 0.; + double ty = 0.; + double tz = 0.; + residual(y, z, ry, rz, dx, dy, dz); + const double norm0 = std::hypot(ry, rz); + if (norm0 < kTolerance) { + return true; + } + residual(y + kStep, z, r1y, r1z, tx, ty, tz); + residual(y, z + kStep, r2y, r2z, tx, ty, tz); + const double jyy = (r1y - ry) / kStep; + const double jyz = (r2y - ry) / kStep; + const double jzy = (r1z - rz) / kStep; + const double jzz = (r2z - rz) / kStep; + const double det = jyy * jzz - jyz * jzy; + if (std::abs(det) < 1.e-6) { + return false; // singular Jacobian: the map folds here + } + // Newton step -J^-1 (ry, rz), halved until the residual decreases; no decrease: give up (fold or close to it) + const double stepY = -(jzz * ry - jyz * rz) / det; + const double stepZ = -(-jzy * ry + jyy * rz) / det; + double lambda = 1.; + bool decreased = false; + for (int k = 0; k < 10 && !decreased; ++k) { + double qy = 0.; + double qz = 0.; + residual(y + lambda * stepY, z + lambda * stepZ, qy, qz, tx, ty, tz); + decreased = std::hypot(qy, qz) < norm0; + if (!decreased) { + lambda *= 0.5; + } } - for (double s = 1.; s > 0.; s -= 0.1) { - gridV.push_back(s * grid.getKnot(i).u + (1. - s) * grid.getKnot(i + 1).u); + if (!decreased) { + return false; } + y += lambda * stepY; + z += lambda * stepZ; } - } + // the point reached with the last step + residual(y, z, ry, rz, dx, dy, dz); + return std::hypot(ry, rz) < kTolerance; + }; + + // 1. sample positions: a regular grid in (u, v) of the real-position grid + const std::vector gridU = samplePositions(spline.getGridX1()); + const std::vector gridV = samplePositions(spline.getGridX2()); - std::vector dataPointGridU, dataPointGridV, dataPointF, dataPointWeight; + std::vector dataPointGridU; + std::vector dataPointGridV; + std::vector dataPointF; + std::vector dataPointWeight; dataPointGridU.reserve(gridU.size() * gridV.size()); dataPointGridV.reserve(gridU.size() * gridV.size()); dataPointF.reserve(3 * gridU.size() * gridV.size()); dataPointWeight.reserve(gridU.size() * gridV.size()); + std::vector converged; + converged.reserve(gridU.size() * gridV.size()); + // 2. one fit point per sample: position (u, v) of r, value d(m(r)) / s(r), as the inverse is evaluated as s(r) x spline (s(r) = 1 + // on the real grid, which ends where the spline scale starts) for (int iu = 0; iu < gridU.size(); iu++) { for (int iv = 0; iv < gridV.size(); iv++) { - float y, z; - correction.convGridToLocal(sector, row, gridU[iu], gridV[iv], y, z); - double dx = 0, dy = 0, dz = 0; - - // add corrections - for (int i = 0; i < corrections.size(); ++i) { - float dxTmp, dyTmp, dzTmp; - corrections[i]->getCorrectionLocal(sector, row, y, z, dxTmp, dyTmp, dzTmp); - dx += dxTmp * scaling[i]; - dy += dyTmp * scaling[i]; - dz += dzTmp * scaling[i]; + float yReal = 0.f; + float zReal = 0.f; + correction.convGridToRealLocal(sector, row, gridU[iu], gridV[iv], yReal, zReal); + float pointU = 0.f; + float pointV = 0.f; + float scale = 0.f; + correction.convRealLocalToGrid(sector, row, yReal, zReal, pointU, pointV, scale); + + double y = 0.; + double z = 0.; + double dx = 0.; + double dy = 0.; + double dz = 0.; + const bool ok = solveMeasured(yReal, zReal, y, z, dx, dy, dz); + if (!ok) { + nFailed[iThread]++; + directCorrection(yReal, zReal, dx, dy, dz); // placeholder (step 3), the direct correction at r } - float gridU, gridV, scale; - correction.convRealLocalToGrid(sector, row, y + dy, z + dz, gridU, gridV, scale); - dataPointGridU.push_back(gridU); - dataPointGridV.push_back(gridV); - dataPointF.push_back(scale * dx); - dataPointF.push_back(scale * dy); - dataPointF.push_back(scale * dz); - dataPointWeight.push_back(1.); + converged.push_back(ok); + dataPointGridU.push_back(pointU); + dataPointGridV.push_back(pointV); + const double invScale = scale > 1.e-6f ? 1. / scale : 0.; + dataPointF.push_back(dx * invScale); + dataPointF.push_back(dy * invScale); + dataPointF.push_back(dz * invScale); + + // weight: low beyond the drift-direction ends of the measured grid of any of the corrections (see kWeightBeyondDriftEnd) + bool beyondDriftEnd = false; + for (int i = 0; ok && i < corrections.size(); ++i) { + if (scaling[i] == 0.f) { + continue; + } + float measuredU = 0.f; + float measuredV = 0.f; + float measuredScale = 0.f; + corrections[i]->getRowInfo(row).gridMeasured.convLocalToGridUntruncated(sector, y, z, measuredU, measuredV, measuredScale); + const float vMax = corrections[i]->getSplineForRow(row).getGridX2().getUmax(); + // with a tolerance: a position at the grid end may come out beyond it by float rounding + beyondDriftEnd |= measuredV < -kDriftEndTolerance * vMax || measuredV > (1.f + kDriftEndTolerance) * vMax; + } + dataPointWeight.push_back(beyondDriftEnd ? kWeightBeyondDriftEnd : 1.); + } + } + + // 3. a point whose search failed borrows value and weight from the nearest point of the row whose search worked, so that its part + // of the map still has data. The sample points form a regular lattice (index iu along the row, iv along z). The neighbours are + // tried in square rings around the failed point: first its 8 direct neighbours, then the border of the 5 x 5 square around it, + // then of the 7 x 7 square, and so on. In the first ring that contains a successful point, the one closest to the failed point + // (in grid coordinates) is taken. If no point of the row succeeded at all, the points keep the first guess of the search, the + // direct correction at the corrected position r, and a warning is printed at the end. + const int nU = gridU.size(); + const int nV = gridV.size(); + const bool anyConverged = std::find(converged.begin(), converged.end(), 1) != converged.end(); + if (!anyConverged) { + nRowsFailed[iThread]++; + } + for (int i = 0; anyConverged && i < nU * nV; ++i) { + if (converged[i]) { + continue; + } + const int iu0 = i / nV; + const int iv0 = i % nV; + int nearest = -1; + double nearestDist2 = 1.e30; + for (int ring = 1; nearest < 0 && ring < std::max(nU, nV); ++ring) { + for (int iu = std::max(0, iu0 - ring); iu <= std::min(nU - 1, iu0 + ring); ++iu) { + // only the positions on the ring: all iv in its first and its last iu line, the two end points in the lines between + const int ivStep = (std::abs(iu - iu0) == ring) ? 1 : 2 * ring; + for (int iv = iv0 - ring; iv <= iv0 + ring; iv += ivStep) { + if (iv < 0 || iv >= nV || !converged[iu * nV + iv]) { + continue; + } + const int j = iu * nV + iv; + const double du = dataPointGridU[j] - dataPointGridU[i]; + const double dv = dataPointGridV[j] - dataPointGridV[i]; + if (du * du + dv * dv < nearestDist2) { + nearestDist2 = du * du + dv * dv; + nearest = j; + } + } + } + } + for (int k = 0; k < 3; ++k) { + dataPointF[3 * i + k] = dataPointF[3 * nearest + k]; } + dataPointWeight[i] = dataPointWeight[nearest]; } + // 4. fit the inverse splines (x, and y-z) to the points and store their parameters int nDataPoints = dataPointGridU.size(); splineParameters.resize(spline.getNumberOfParameters()); @@ -1182,7 +1386,18 @@ void TPCFastSpaceChargeCorrectionHelper::initInverse(std::vector 0) { + LOGP(warning, "Inverse: {} sector rows without any converged fit point, their inverse is the direct correction at the real position", nRowsFailedTotal); + } } void TPCFastSpaceChargeCorrectionHelper::addCorrections( @@ -1301,6 +1516,14 @@ void TPCFastSpaceChargeCorrectionHelper::addCorrections( } } + // TODO: the inverse corrections are added like the direct ones, i.e. the inverse of the sum is approximated by the scaled sum + // of the inverses, each one computed for its map alone. That holds only to lowest order: the added inverse is the added correction + // at the measured position of the added map alone instead of that of the sum (they differ by the main correction and by + // (1 - scale) x the added one), and the main inverse does not see the shift of the measured position by the added map. In a test + // with maps of PbPb run 568041 (a map with fine sector-edge knots plus its luminosity-derivative map scaled by 0.15) this roughly + // doubled the inverse error in the inner rows (99 % quantile ~80 -> ~150 um); each further added map contributes. Possible improvement: recompute the inverse of the summed map (initInverse with the list of + // corrections and scales) when the set of maps changes, and store for each added map its first-order term + // (1 + dC_main/dm)^-1 C_add(m) instead of its stand-alone inverse, so that the per-TF linear update stays as it is. float y, z; mainCorrection.convGridToRealLocal(sector, row, u, v, y, z); // return values: u, v, scaling factor