Skip to content
Snippets Groups Projects
RecActsTracking.cpp 41.8 KiB
Newer Older
Yizhou Zhang's avatar
Yizhou Zhang committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <sstream>

// dependence
#include "RecActsTracking.h"

#include "GearSvc/IGearSvc.h"

// csv parser
// #include "csv2/writer.hpp"

// MC
#include "CLHEP/Units/SystemOfUnits.h"


using namespace Acts::UnitLiterals;

DECLARE_COMPONENT(RecActsTracking)

RecActsTracking::RecActsTracking(const std::string& name, ISvcLocator* svcLoc)
    : GaudiAlgorithm(name, svcLoc)
{
    // input collections
    // declareProperty("VXDTrackerHits", _inVTXTrackHdl, "Handle of the Input VTX TrackerHits collection");
    // declareProperty("SITTrackerHits", _inSITTrackHdl, "Handle of the Input SIT TrackerHits collection");

    // declareProperty("VXDCollection", _inVTXColHdl, "Handle of the Input VTX Sim Hit collection");
    // declareProperty("SITCollection", _inSITColHdl, "Handle of the Input SIT Sim Hit collection");

    // declareProperty("MCParticleCollection", _inMCColHdl, "Handle of the Input MCParticle collection");

    // Output Collections
    // declareProperty("OutputTracks", _outColHdl, "Handle of the ACTS SiTrack output collection");
}

StatusCode RecActsTracking::initialize()
{
    chronoStatSvc = service<IChronoStatSvc>("ChronoStatSvc");
    _nEvt = 0;

    if (!std::filesystem::exists(TGeo_path.value())) {
        error() << "CEPC TGeo file: " << TGeo_path.value() << " does not exist!" << endmsg;
        return StatusCode::FAILURE;
    }

    if (!std::filesystem::exists(TGeo_config_path.value())) {
        error() << "CEPC TGeo config file: " << TGeo_config_path.value() << " does not exist!" << endmsg;
        return StatusCode::FAILURE;
    }

    if (!std::filesystem::exists(MaterialMap_path.value())) {
        error() << "CEPC Material map file: " << MaterialMap_path.value() << " does not exist!" << endmsg;
        return StatusCode::FAILURE;
    }

    TGeo_ROOTFilePath = TGeo_path.value();
    TGeoConfig_jFilePath = TGeo_config_path.value();
    MaterialMap_jFilePath = MaterialMap_path.value();

    chronoStatSvc->chronoStart("read geometry");
    m_geosvc = service<IGeomSvc>("GeomSvc");
    if (!m_geosvc) {
        error() << "Failed to find GeomSvc." << endmsg;
        return StatusCode::FAILURE;
    }

    if(m_geosvc){
        const dd4hep::Direction& field = m_geosvc->lcdd()->field().magneticField(dd4hep::Position(0,0,0));
        m_field = field.z()/dd4hep::tesla;
    }

    m_vtx_surfaces = m_geosvc->getSurfaceMap("VXD");
    debug() << "Surface map size: " << m_vtx_surfaces->size() << endmsg;

    m_sit_surfaces = m_geosvc->getSurfaceMap("SIT");
    debug() << "Surface map size: " << m_sit_surfaces->size() << endmsg;

    vxd_decoder = m_geosvc->getDecoder("VXDCollection");
    if(!vxd_decoder){
        return StatusCode::FAILURE;
    }

    sit_decoder = m_geosvc->getDecoder("SITCollection");
    if(!sit_decoder){
        return StatusCode::FAILURE;
    }

    info() << "ACTS Tracking Geometry initialized successfully!" << endmsg;
    // initialize tgeo detector
    auto logger = Acts::getDefaultLogger("TGeoDetector", Acts::Logging::INFO);
    trackingGeometry = buildTGeoDetector(geoContext, detElementStore, TGeo_ROOTFilePath, TGeoConfig_jFilePath, MaterialMap_jFilePath, *logger);

    info() << "Seeding tools initialized successfully!" << endmsg;

    // configure the acts tools
    seed_cfg.seedFinderOptions.bFieldInZ = 3_T;
    seed_cfg.seedFinderConfig.deltaRMin = 4_mm;
    seed_cfg.seedFinderConfig.deltaRMax = 25_mm;
    seed_cfg.seedFinderConfig.rMax = 40_mm;
    seed_cfg.seedFinderConfig.rMin = 8_mm;
    seed_cfg.seedFinderConfig.impactMax = 4_mm;
    seed_cfg.seedFinderConfig.useVariableMiddleSPRange = false;
    seed_cfg.seedFinderConfig.rMinMiddle = 15_mm; // range for middle spacepoint (TDR)
    seed_cfg.seedFinderConfig.rMaxMiddle = 30_mm; // range for middle spacepoint (TDR)

    // initialize the acts tools
    seed_cfg.seedFilterConfig = seed_cfg.seedFilterConfig.toInternalUnits();
    seed_cfg.seedFinderConfig.seedFilter =
        std::make_unique<Acts::SeedFilter<SimSpacePoint>>(seed_cfg.seedFilterConfig);
    seed_cfg.seedFinderConfig =
        seed_cfg.seedFinderConfig.toInternalUnits().calculateDerivedQuantities();
    seed_cfg.seedFinderOptions =
        seed_cfg.seedFinderOptions.toInternalUnits().calculateDerivedQuantities(seed_cfg.seedFinderConfig);
    seed_cfg.gridConfig = seed_cfg.gridConfig.toInternalUnits();
    seed_cfg.gridOptions = seed_cfg.gridOptions.toInternalUnits();

    if (std::isnan(seed_cfg.seedFinderConfig.deltaRMaxTopSP)) {
        seed_cfg.seedFinderConfig.deltaRMaxTopSP = seed_cfg.seedFinderConfig.deltaRMax;}
    if (std::isnan(seed_cfg.seedFinderConfig.deltaRMinTopSP)) {
        seed_cfg.seedFinderConfig.deltaRMinTopSP = seed_cfg.seedFinderConfig.deltaRMin;}
    if (std::isnan(seed_cfg.seedFinderConfig.deltaRMaxBottomSP)) {
        seed_cfg.seedFinderConfig.deltaRMaxBottomSP = seed_cfg.seedFinderConfig.deltaRMax;}
    if (std::isnan(seed_cfg.seedFinderConfig.deltaRMinBottomSP)) {
        seed_cfg.seedFinderConfig.deltaRMinBottomSP = seed_cfg.seedFinderConfig.deltaRMin;}
        
    m_bottomBinFinder = std::make_unique<const Acts::GridBinFinder<2ul>>(
        seed_cfg.numPhiNeighbors, seed_cfg.zBinNeighborsBottom);
    m_topBinFinder = std::make_unique<const Acts::GridBinFinder<2ul>>(
        seed_cfg.numPhiNeighbors, seed_cfg.zBinNeighborsTop);

    seed_cfg.seedFinderConfig.seedFilter =
        std::make_unique<Acts::SeedFilter<SimSpacePoint>>(seed_cfg.seedFilterConfig);
    m_seedFinder =
        Acts::SeedFinder<SimSpacePoint, Acts::CylindricalSpacePointGrid<SimSpacePoint>>(seed_cfg.seedFinderConfig);

    // initialize the ckf
    findTracks = makeTrackFinderFunction(trackingGeometry, magneticField);

    info() << "CKF Track Finder initialized successfully!" << endmsg;
    chronoStatSvc->chronoStop("read geometry");

    return GaudiAlgorithm::initialize();
}

StatusCode RecActsTracking::execute()
{
    auto trkCol = _outColHdl.createAndPut();

    bool MCsuccess = true;
    const edm4hep::MCParticleCollection* mcCols = nullptr;
    mcCols = _inMCColHdl.get();
    if(mcCols)
    {
        for(auto particle : *mcCols)
        {
            if (particle.getPDG() != 13)
            {
                MCsuccess = false;
                continue;
            }
            break;
        }
    }

    if (!MCsuccess)
    {
        _nEvt++;
        return StatusCode::SUCCESS;
    }

    SpacePointPtrs.clear();
    sourceLinks.clear();
    measurements.clear();
    initialParameters.clear();
    Selected_Seeds.clear();

    chronoStatSvc->chronoStart("read input hits");
    int successVTX = InitialiseVTX();

    if (successVTX == 0)
    {
        _nEvt++;
        return StatusCode::SUCCESS;
    }

    int successSIT = InitialiseSIT();
    if (successSIT == 0)
    {
        _nEvt++;
        return StatusCode::SUCCESS;
    }

    chronoStatSvc->chronoStop("read input hits");
    // info() << "Generated " << SpacePointPtrs.size() << " spacepoints for event " << _nEvt << "!" << endmsg;
    // info() << "Generated " << measurements.size() << " measurements for event " << _nEvt << "!" << endmsg;

    // --------------------------------------------
    //                 Seeding
    // --------------------------------------------
    chronoStatSvc->chronoStart("seeding");

    // construct the seeding tools
    // covariance tool, extracts covariances per spacepoint as required
    auto extractGlobalQuantities = [=](const SimSpacePoint& sp, float, float, float)
    {
        Acts::Vector3 position{sp.x(), sp.y(), sp.z()};
        Acts::Vector2 covariance{sp.varianceR(), sp.varianceZ()};
        return std::make_tuple(position, covariance, sp.t());
    };

    // extent used to store r range for middle spacepoint
    Acts::Extent rRangeSPExtent;

    // construct the seeding tool
    Acts::CylindricalSpacePointGrid<SimSpacePoint> grid =
        Acts::CylindricalSpacePointGridCreator::createGrid<SimSpacePoint>(seed_cfg.gridConfig, seed_cfg.gridOptions);
    Acts::CylindricalSpacePointGridCreator::fillGrid(
        seed_cfg.seedFinderConfig, seed_cfg.seedFinderOptions, grid,
        SpacePointPtrs.begin(), SpacePointPtrs.end(), extractGlobalQuantities, rRangeSPExtent);

    std::array<std::vector<std::size_t>, 2ul> navigation;
    navigation[1ul] = seed_cfg.seedFinderConfig.zBinsCustomLooping;

    auto spacePointsGrouping = Acts::CylindricalBinnedGroup<SimSpacePoint>(
        std::move(grid), *m_bottomBinFinder, *m_topBinFinder, std::move(navigation));

    // safely clamp double to float
    float up = Acts::clampValue<float>(
        std::floor(rRangeSPExtent.max(Acts::binR) / 2) * 2);

    /// variable middle SP radial region of interest
    const Acts::Range1D<float> rMiddleSPRange(
        std::floor(rRangeSPExtent.min(Acts::binR) / 2) * 2 +
        seed_cfg.seedFinderConfig.deltaRMiddleMinSPRange,
        up - seed_cfg.seedFinderConfig.deltaRMiddleMaxSPRange);

    // run the seeding
    static thread_local SimSeedContainer seeds;
    seeds.clear();
    static thread_local decltype(m_seedFinder)::SeedingState state;
    state.spacePointData.resize(
        SpacePointPtrs.size(),
        seed_cfg.seedFinderConfig.useDetailedDoubleMeasurementInfo);

    // use double stripe measurement
    if (seed_cfg.seedFinderConfig.useDetailedDoubleMeasurementInfo)
    {
        for (std::size_t grid_glob_bin(0); grid_glob_bin < spacePointsGrouping.grid().size(); ++grid_glob_bin)
        {
            const auto& collection = spacePointsGrouping.grid().at(grid_glob_bin);
            for (const auto& sp : collection)
            {
                std::size_t index = sp->index();
                const float topHalfStripLength =
                    seed_cfg.seedFinderConfig.getTopHalfStripLength(sp->sp());
                const float bottomHalfStripLength =
                    seed_cfg.seedFinderConfig.getBottomHalfStripLength(sp->sp());
                const Acts::Vector3 topStripDirection =
                    seed_cfg.seedFinderConfig.getTopStripDirection(sp->sp());
                const Acts::Vector3 bottomStripDirection =
                    seed_cfg.seedFinderConfig.getBottomStripDirection(sp->sp());

                state.spacePointData.setTopStripVector(
                    index, topHalfStripLength * topStripDirection);
                state.spacePointData.setBottomStripVector(
                    index, bottomHalfStripLength * bottomStripDirection);
                state.spacePointData.setStripCenterDistance(
                    index, seed_cfg.seedFinderConfig.getStripCenterDistance(sp->sp()));
                state.spacePointData.setTopStripCenterPosition(
                    index, seed_cfg.seedFinderConfig.getTopStripCenterPosition(sp->sp()));
            }
        }
    }

    for (const auto [bottom, middle, top] : spacePointsGrouping)
    {
        m_seedFinder.createSeedsForGroup(
            seed_cfg.seedFinderOptions, state, spacePointsGrouping.grid(),
            std::back_inserter(seeds), bottom, middle, top, rMiddleSPRange);
    }

    // int seed_counter = 0;
    // for (const auto& seed : seeds)
    // {
    //     for (const auto& sp : seed.sp())
    //     {
    //         info() << "found seed #" << seed_counter << ": x:" << sp->x() << " y: " << sp->y() << " z: " << sp->z() << endmsg;
    //     }
    //     seed_counter++;
    // }

    chronoStatSvc->chronoStop("seeding");
    debug() << "Found " << seeds.size() << " seeds for event " << _nEvt << "!" << endmsg;

    // --------------------------------------------
    //            track estimation
    // --------------------------------------------
    chronoStatSvc->chronoStart("track_param");

    IndexSourceLink::SurfaceAccessor surfaceAccessor{*trackingGeometry};

    for (std::size_t iseed = 0; iseed < seeds.size(); ++iseed)
    {
        const auto& seed = seeds[iseed];
        // Get the bottom space point and its reference surface
        const auto bottomSP = seed.sp().front();
        const auto& sourceLink = bottomSP->sourceLinks()[0];
        const Acts::Surface* surface = surfaceAccessor(sourceLink);
        if (surface == nullptr) {
            debug() << "Surface from source link is not found in the tracking geometry: iseed " << iseed << endmsg;
            continue;
        }

        auto optParams = Acts::estimateTrackParamsFromSeed(
            geoContext, seed.sp().begin(), seed.sp().end(), *surface, acts_field_value, bFieldMin);
        
        if (!optParams.has_value()) {
            debug() << "Estimation of track parameters for seed " << iseed << " failed." << endmsg;
            continue;
        }

        const auto& params = optParams.value();
        Acts::BoundSquareMatrix cov = Acts::BoundSquareMatrix::Zero();
        for (std::size_t i = Acts::eBoundLoc0; i < Acts::eBoundSize; ++i) {
            double sigma = initialSigmas[i];
            sigma += initialSimgaQoverPCoefficients[i] * params[Acts::eBoundQOverP];
            double var = sigma * sigma;
            if (i == Acts::eBoundTime && !bottomSP->t().has_value()) { var *= noTimeVarInflation; }
            var *= initialVarInflation[i];
            
            cov(i, i) = var;
        }
        initialParameters.emplace_back(surface->getSharedPtr(), params, cov, particleHypothesis);
        Selected_Seeds.push_back(seed);
    }

    chronoStatSvc->chronoStop("track_param");
    debug() << "Found " << initialParameters.size() << " tracks for event " << _nEvt << "!" << endmsg;

    // --------------------------------------------
    //            CKF track finding
    // --------------------------------------------
    chronoStatSvc->chronoStart("ckf_findTracks");

    // Construct a perigee surface as the target surface
    auto pSurface = Acts::Surface::makeShared<Acts::PerigeeSurface>(Acts::Vector3{0., 0., 0.});
    PassThroughCalibrator pcalibrator;
    MeasurementCalibratorAdapter calibrator(pcalibrator, measurements);
    Acts::GainMatrixUpdater kfUpdater;
    Acts::MeasurementSelector::Config measurementSelectorCfg =
    {
        {Acts::GeometryIdentifier(), {{}, {30}, {1u}}},
    };

    MeasurementSelector measSel{ Acts::MeasurementSelector(measurementSelectorCfg) };
    using Extensions = Acts::CombinatorialKalmanFilterExtensions<Acts::VectorMultiTrajectory>;
    BranchStopper branchStopper(trackSelectorCfg);

    // Construct the CKF
    Extensions extensions;
    extensions.calibrator.connect<&MeasurementCalibratorAdapter::calibrate>(&calibrator);
    extensions.updater.connect<&Acts::GainMatrixUpdater::operator()<Acts::VectorMultiTrajectory>>(&kfUpdater);
    extensions.measurementSelector.connect<&MeasurementSelector::select>(&measSel);
    extensions.branchStopper.connect<&BranchStopper::operator()>(&branchStopper);

    IndexSourceLinkAccessor slAccessor;
    slAccessor.container = &sourceLinks;
    Acts::SourceLinkAccessorDelegate<IndexSourceLinkAccessor::Iterator> slAccessorDelegate;
    slAccessorDelegate.connect<&IndexSourceLinkAccessor::range>(&slAccessor);

    Acts::PropagatorPlainOptions firstPropOptions;
    firstPropOptions.maxSteps = maxSteps;
    firstPropOptions.direction = Acts::Direction::Forward;

    Acts::PropagatorPlainOptions secondPropOptions;
    secondPropOptions.maxSteps = maxSteps;
    secondPropOptions.direction = firstPropOptions.direction.invert();

    // Set the CombinatorialKalmanFilter options
    TrackFinderOptions firstOptions(
        geoContext, magFieldContext, calibContext,
        slAccessorDelegate, extensions, firstPropOptions);
    
    TrackFinderOptions secondOptions(
        geoContext, magFieldContext, calibContext,
        slAccessorDelegate, extensions, secondPropOptions);
    secondOptions.targetSurface = pSurface.get();

    Acts::Propagator<Acts::EigenStepper<>, Acts::Navigator> extrapolator(
        Acts::EigenStepper<>(magneticField), Acts::Navigator({trackingGeometry}));

    Acts::PropagatorOptions<Acts::ActionList<Acts::MaterialInteractor>, Acts::AbortList<Acts::EndOfWorldReached>>
        extrapolationOptions(geoContext, magFieldContext);

    auto trackContainer = std::make_shared<Acts::VectorTrackContainer>();
    auto trackStateContainer = std::make_shared<Acts::VectorMultiTrajectory>();
    auto trackContainerTemp = std::make_shared<Acts::VectorTrackContainer>();
    auto trackStateContainerTemp = std::make_shared<Acts::VectorMultiTrajectory>();
    TrackContainer tracks(trackContainer, trackStateContainer);
    TrackContainer tracksTemp(trackContainerTemp, trackStateContainerTemp);

    tracks.addColumn<unsigned int>("trackGroup");
    tracksTemp.addColumn<unsigned int>("trackGroup");
    Acts::ProxyAccessor<unsigned int> seedNumber("trackGroup");

    unsigned int nSeed = 0;
    // A map indicating whether a seed has been discovered already
    std::unordered_map<SeedIdentifier, bool> discoveredSeeds;
    auto addTrack = [&](const TrackProxy& track)
    {
        ++m_nFoundTracks;
        // flag seeds which are covered by the track
        visitSeedIdentifiers(track, [&](const SeedIdentifier& seedIdentifier)
        {
            if (auto it = discoveredSeeds.find(seedIdentifier); it != discoveredSeeds.end())
            {
                it->second = true;
            }
        });

        if (m_trackSelector.has_value() && !m_trackSelector->isValidTrack(track)) { return; }

        ++m_nSelectedTracks;
        auto destProxy = tracks.makeTrack();
        // make sure we copy track states!
        destProxy.copyFrom(track, true);
    };

    for (const auto& seed : Selected_Seeds) {
        SeedIdentifier seedIdentifier = makeSeedIdentifier(seed);
        discoveredSeeds.emplace(seedIdentifier, false);
    }

    for (std::size_t iSeed = 0; iSeed < initialParameters.size(); ++iSeed)
    {           
        m_nTotalSeeds++;
        const auto& seed = Selected_Seeds[iSeed];

        SeedIdentifier seedIdentifier = makeSeedIdentifier(seed);
        // check if the seed has been discovered already
        if (auto it = discoveredSeeds.find(seedIdentifier); it != discoveredSeeds.end() && it->second)
        {
            m_nDeduplicatedSeeds++;
            continue;
        }

        /// Whether to stick on the seed measurements during track finding.
        // measSel.setSeed(seed);

        // Clear trackContainerTemp and trackStateContainerTemp
        tracksTemp.clear();

        const Acts::BoundTrackParameters& firstInitialParameters = initialParameters.at(iSeed);
        auto firstResult = (*findTracks)(firstInitialParameters, firstOptions, tracksTemp);

        nSeed++;
        if (!firstResult.ok())
        {
            m_nFailedSeeds++;
            continue;
        }

        auto& firstTracksForSeed = firstResult.value();
        for (auto& firstTrack : firstTracksForSeed)
        {
            auto trackCandidate = tracksTemp.makeTrack();
            trackCandidate.copyFrom(firstTrack, true);

            auto firstSmoothingResult = Acts::smoothTrack(geoContext, trackCandidate);

            if (!firstSmoothingResult.ok())
            {
                m_nFailedSmoothing++;
                continue;
            }

            seedNumber(trackCandidate) = nSeed - 1;

            auto firstExtrapolationResult = Acts::extrapolateTrackToReferenceSurface(
                trackCandidate, *pSurface, extrapolator, extrapolationOptions, extrapolationStrategy);

            if (!firstExtrapolationResult.ok())
            {
                m_nFailedExtrapolation++;
                continue;
            }

            addTrack(trackCandidate);
        }
    }

    chronoStatSvc->chronoStop("ckf_findTracks");
    debug() << "CKF found " << tracks.size() << " tracks for event " << _nEvt << "!" << endmsg;

    m_memoryStatistics.local().hist += tracks.trackStateContainer().statistics().hist;
    auto constTrackStateContainer = std::make_shared<Acts::ConstVectorMultiTrajectory>(std::move(*trackStateContainer));
    auto constTrackContainer = std::make_shared<Acts::ConstVectorTrackContainer>(std::move(*trackContainer));
    ConstTrackContainer constTracks{constTrackContainer, constTrackStateContainer};

    chronoStatSvc->chronoStart("writeout tracks");

    if (constTracks.size() == 0) {
        chronoStatSvc->chronoStop("writeout tracks");
        _nEvt++;
        return StatusCode::SUCCESS;
    }

    for (const auto& cur_track : constTracks)
    {
        auto writeout_track = trkCol->create();
        int nVTXHit = 0, nFTDHit = 0, nSITHit = 0;
        int getFirstHit = 0;
        
        writeout_track.setChi2(cur_track.chi2());
        writeout_track.setNdf(cur_track.nDoF());
        writeout_track.setDEdx(cur_track.absoluteMomentum() / Acts::UnitConstants::GeV);
        writeout_track.setDEdxError(cur_track.qOverP());
        for (auto trackState : cur_track.trackStates()){
            if (trackState.hasUncalibratedSourceLink()){
                auto cur_measurement_sl = trackState.getUncalibratedSourceLink();
                const auto& MeasSourceLink = cur_measurement_sl.get<IndexSourceLink>();
                auto cur_measurement = measurements[MeasSourceLink.index()];
                auto cur_measurement_gid = MeasSourceLink.geometryId();
                if (std::find(VXD_inner_volume_ids.begin(), VXD_inner_volume_ids.end(), cur_measurement_gid.volume()) != VXD_inner_volume_ids.end()){
                    nVTXHit++;
                } else if (std::find(SIT_acts_volume_ids.begin(), SIT_acts_volume_ids.end(), cur_measurement_gid.volume()) != SIT_acts_volume_ids.end()){
                    nSITHit++;
                }

                writeout_track.addToTrackerHits(MeasSourceLink.getTrackerHit());

                if (!getFirstHit){
                    const auto& par = std::get<1>(cur_measurement).parameters();
                    const Acts::Surface* surface = surfaceAccessor(cur_measurement_sl);
                    auto acts_global_postion = surface->localToGlobal(geoContext, par, globalFakeMom);
                    writeout_track.setRadiusOfInnermostHit(
                    std::sqrt(acts_global_postion[0] * acts_global_postion[0] + 
                              acts_global_postion[1] * acts_global_postion[1] + 
                              acts_global_postion[2] * acts_global_postion[2])
                    );
                    getFirstHit = 1;
                }
            }
        }

        // SubdetectorHitNumbers: VXD = 0, FTD = 1, SIT = 2
        writeout_track.addToSubdetectorHitNumbers(nVTXHit);
        writeout_track.addToSubdetectorHitNumbers(nFTDHit);
        writeout_track.addToSubdetectorHitNumbers(nSITHit);
        
        std::array<float, 21> writeout_covMatrix;
        auto cur_track_covariance = cur_track.covariance();
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 6-i; j++) {
                writeout_covMatrix[i * 6 + j] = cur_track_covariance(writeout_indices[i], writeout_indices[j]);
            }
        }
        // location: At{Other|IP|FirstHit|LastHit|Calorimeter|Vertex}|LastLocation
        // TrackState: location, d0, phi, omega, z0, tanLambda, time, referencePoint, covMatrix
        edm4hep::TrackState writeout_trackState{
            0, // location: AtOther
            cur_track.loc0() / Acts::UnitConstants::mm, // d0
            cur_track.phi(), // phi
            cur_track.qOverP() * sin(cur_track.theta()) * _FCT * m_field, // omega = qop * sin(theta) * _FCT * bf
            cur_track.loc1() / Acts::UnitConstants::mm, // z0
            1 / tan(cur_track.theta()), // tanLambda = 1 / tan(theta)
            cur_track.time(), // time
            ::edm4hep::Vector3f(0, 0, 0), // referencePoint
            writeout_covMatrix
        };

        debug() << "Found track with momentum " << cur_track.absoluteMomentum() / Acts::UnitConstants::GeV << " !" << endmsg;
        writeout_track.addToTrackStates(writeout_trackState);
    }

    chronoStatSvc->chronoStop("writeout tracks");

    _nEvt++;
    return StatusCode::SUCCESS;
}

StatusCode RecActsTracking::finalize()
{
    debug() << "finalize RecActsTracking" << endmsg;
    info() << "Total number of events processed: " << _nEvt << endmsg;
    info() << "Total number of **TotalSeeds** processed: " << m_nTotalSeeds << endmsg;
    info() << "Total number of **FoundTracks** processed: " << m_nFoundTracks << endmsg;
    info() << "Total number of **SelectedTracks** processed: " << m_nSelectedTracks << endmsg;
    
    return GaudiAlgorithm::finalize();
}

int RecActsTracking::InitialiseVTX()
{   
    int success = 1;

    const edm4hep::TrackerHitCollection* hitVTXCol = nullptr;
    const edm4hep::SimTrackerHitCollection* SimhitVTXCol = nullptr;

    try {
        hitVTXCol = _inVTXTrackHdl.get();
    } catch (GaudiException& e) {
        debug() << "Collection " << _inVTXTrackHdl.fullKey() << " is unavailable in event " << _nEvt << endmsg;
        success = 0;
    }

    try {
        SimhitVTXCol = _inVTXColHdl.get();
    } catch (GaudiException& e) {
        debug() << "Sim Collection " << _inVTXColHdl.fullKey() << " is unavailable in event " << _nEvt << endmsg;
        success = 0;
    }

    if(hitVTXCol && SimhitVTXCol)
    {
        int nelem = hitVTXCol->size();
        debug() << "Number of VTX hits = " << nelem << endmsg;
        if ((nelem < 3) or (nelem > 10)) { success = 0; }

        // std::string truth_file = "obj/vtx/truth/event" + std::to_string(_nEvt) + ".csv";
        // std::ofstream truth_stream(truth_file);
        // csv2::Writer<csv2::delimiter<','>> truth_writer(truth_stream);
        // std::vector<std::string> truth_header = {"layer", "x", "y", "z"};
        // truth_writer.write_row(truth_header);

        // std::string converted_file = "obj/vtx/converted/event" + std::to_string(_nEvt) + ".csv";
        // std::ofstream converted_stream(converted_file);
        // csv2::Writer<csv2::delimiter<','>> converted_writer(converted_stream);
        // std::vector<std::string> converted_header = {"layer", "x", "y", "z"};
        // converted_writer.write_row(converted_header);

        for (int ielem = 0; ielem < nelem; ++ielem)
        {
            auto hit = hitVTXCol->at(ielem);
            auto simhit = SimhitVTXCol->at(ielem);

            auto simcellid = simhit.getCellID();
            // system:5,side:-2,layer:9,module:8,sensor:32:8
            uint64_t m_layer   = vxd_decoder->get(simcellid, "layer");
            uint64_t m_module  = vxd_decoder->get(simcellid, "module");
            uint64_t m_sensor  = vxd_decoder->get(simcellid, "sensor");
            double acts_x = simhit.getPosition()[0];
            double acts_y = simhit.getPosition()[1];
            double acts_z = simhit.getPosition()[2];

            double momentum_x = simhit.getMomentum()[0];
            double momentum_y = simhit.getMomentum()[1];
            double momentum_z = simhit.getMomentum()[2];

            dd4hep::rec::ISurface* surface = nullptr;
            auto it = m_vtx_surfaces->find(simcellid);
            if (it != m_vtx_surfaces->end()) {
                surface = it->second;
                if (!surface) {
                    fatal() << "found surface for VTX cell id " << simcellid << ", but NULL" << endmsg;
                    return 0;
                }
            }
            else {
                fatal() << "not found surface for VTX cell id " << simcellid << endmsg;
                return 0;
            }

            // dd4hep::rec::Vector3D oldPos(simhit.getPosition()[0]*dd4hep::mm/CLHEP::mm, simhit.getPosition()[1]*dd4hep::mm/CLHEP::mm, simhit.getPosition()[2]*dd4hep::mm/CLHEP::mm);
            // dd4hep::rec::Vector2D localPoint = surface->globalToLocal(oldPos);

            // if (m_layer < current_layer){
            //     info() << "ring hits happend in layer " << m_layer << " before layer " << current_layer << ", at event " << _nEvt << endmsg;
            //     success = 0;
            //     break;
            // }
            // current_layer = m_layer;

            if (m_layer <= 3){
                // set acts geometry identifier
                // VXD_inner_volume_ids{16, 17, 18, 19};
                uint64_t acts_volume = VXD_inner_volume_ids[m_layer];
                uint64_t acts_boundary = 0;
                uint64_t acts_layer = 2;
                uint64_t acts_approach = 0;
                uint64_t acts_sensitive = m_module + 1;

                Acts::GeometryIdentifier moduleGeoId;
                moduleGeoId.setVolume(acts_volume);
                moduleGeoId.setBoundary(acts_boundary);
                moduleGeoId.setLayer(acts_layer);
                moduleGeoId.setApproach(acts_approach);
                moduleGeoId.setSensitive(acts_sensitive);
        
                // create and store the source link
                uint32_t measurementIdx = measurements.size();
                IndexSourceLink sourceLink{moduleGeoId, measurementIdx, hit};
                sourceLinks.insert(sourceLinks.end(), sourceLink);
                Acts::SourceLink sl{sourceLink};
                boost::container::static_vector<Acts::SourceLink, 2> slinks;
                slinks.emplace_back(sl);

                // get the surface of the hit
                IndexSourceLink::SurfaceAccessor surfaceAccessor{*trackingGeometry};
                const Acts::Surface* acts_surface = surfaceAccessor(sl);

                // get the local position of the hit
                const Acts::Vector3 globalPos{acts_x, acts_y, acts_z};
                const Acts::Vector3 globalmom{momentum_x, momentum_y, momentum_z};
                auto acts_local_postion = acts_surface->globalToLocal(geoContext, globalPos, globalmom, onSurfaceTolerance);
                if (!acts_local_postion.ok()){
                    info() << "Error: failed to get local position for VTX hit " << simcellid << endmsg;
                    acts_local_postion = acts_surface->globalToLocal(geoContext, globalPos, globalmom, 100*onSurfaceTolerance);
                }
                const std::array<Acts::BoundIndices, 2> indices{Acts::BoundIndices::eBoundLoc0, Acts::BoundIndices::eBoundLoc1};
                const Acts::Vector2 par{acts_local_postion.value()[0], acts_local_postion.value()[1]};

                // *** debug ***
                debug() << "VXD measurements global position(x,y,z): " << simhit.getPosition()[0] << ", " << simhit.getPosition()[1] << ", " << simhit.getPosition()[2]
                       << "; local position(loc0, loc1): "<< acts_local_postion.value()[0] << ", " << acts_local_postion.value()[1] << endmsg;
                auto acts_global_postion = acts_surface->localToGlobal(geoContext, par, globalFakeMom);
                debug() << "debug surface at: x:" << acts_global_postion[0] << ", y:" << acts_global_postion[1] << ", z:" << acts_global_postion[2] << endmsg;

                // SimSpacePoint *hitExt = new SimSpacePoint(hit, simhit, slinks);
                SimSpacePoint *hitExt = new SimSpacePoint(hit, acts_global_postion[0], acts_global_postion[1], acts_global_postion[2], 0.002, slinks);
                // debug() << "debug hitExt at: x:" << hitExt->x() << ", y:" << hitExt->y() << ", z:" << hitExt->z() << endmsg;
                SpacePointPtrs.push_back(hitExt);

                // create and store the measurement
                Acts::ActsSquareMatrix<2> cov = Acts::ActsSquareMatrix<2>::Identity();
                cov(0, 0) = std::max<double>(std::abs(acts_global_postion[0] - simhit.getPosition()[0]), eps);
                cov(1, 1) = std::max<double>(std::abs(acts_global_postion[1] - simhit.getPosition()[1]), eps);
                measurements.emplace_back(Acts::Measurement<Acts::BoundIndices, 2>(sl, indices, par, cov));

                // std::vector<std::string> truth_col = {std::to_string(m_layer*2 + m_module), std::to_string(simhit.getPosition()[0]), std::to_string(simhit.getPosition()[1]), std::to_string(simhit.getPosition()[2])};
                // truth_writer.write_row(truth_col);
                // std::vector<std::string> converted_col = {std::to_string(m_layer*2 + m_module), std::to_string(acts_global_postion[0]), std::to_string(acts_global_postion[1]), std::to_string(acts_global_postion[2])};
                // converted_writer.write_row(converted_col);

            } else {
                // set acts geometry identifier
                // VXD_outer_volume_id = 20;
                uint64_t acts_volume = VXD_outer_volume_id;
                uint64_t acts_boundary = 0;
                uint64_t acts_layer = 2;
                uint64_t acts_approach = 0;
                uint64_t acts_sensitive = (m_layer == 5) ? m_module*2 + 1 : m_module*2 + 2;

                Acts::GeometryIdentifier moduleGeoId;
                moduleGeoId.setVolume(acts_volume);
                moduleGeoId.setBoundary(acts_boundary);
                moduleGeoId.setLayer(acts_layer);
                moduleGeoId.setApproach(acts_approach);
                moduleGeoId.setSensitive(acts_sensitive);
        
                // create and store the source link
                uint32_t measurementIdx = measurements.size();
                IndexSourceLink sourceLink{moduleGeoId, measurementIdx, hit};
                sourceLinks.insert(sourceLinks.end(), sourceLink);
                Acts::SourceLink sl{sourceLink};

                // get the local position of the hit
                IndexSourceLink::SurfaceAccessor surfaceAccessor{*trackingGeometry};
                const Acts::Surface* acts_surface = surfaceAccessor(sl);
                const Acts::Vector3 globalPos{acts_x, acts_y, acts_z};
                const Acts::Vector3 globalmom{momentum_x, momentum_y, momentum_z};
                auto acts_local_postion = acts_surface->globalToLocal(geoContext, globalPos, globalmom, onSurfaceTolerance);
                if (!acts_local_postion.ok()){
                    info() << "Error: failed to get local position for VTX hit " << simcellid << endmsg;
                    acts_local_postion = acts_surface->globalToLocal(geoContext, globalPos, globalmom, 100*onSurfaceTolerance);
                }
                const std::array<Acts::BoundIndices, 2> indices{Acts::BoundIndices::eBoundLoc0, Acts::BoundIndices::eBoundLoc1};
                const Acts::Vector2 par{acts_local_postion.value()[0], acts_local_postion.value()[1]};

                // *** debug ***
                debug() << "VXD measurements global position(x,y,z): " << simhit.getPosition()[0] << ", " << simhit.getPosition()[1] << ", " << simhit.getPosition()[2]
                       << "; local position(loc0, loc1): "<< acts_local_postion.value()[0] << ", " << acts_local_postion.value()[1] << endmsg;
                auto acts_global_postion = acts_surface->localToGlobal(geoContext, par, globalFakeMom);
                debug() << "debug surface at: x:" << acts_global_postion[0] << ", y:" << acts_global_postion[1] << ", z:" << acts_global_postion[2] << endmsg;

                // create and store the measurement
                Acts::ActsSquareMatrix<2> cov = Acts::ActsSquareMatrix<2>::Identity();
                cov(0, 0) = std::max<double>(std::abs(acts_global_postion[0] - simhit.getPosition()[0]), eps);
                cov(1, 1) = std::max<double>(std::abs(acts_global_postion[1] - simhit.getPosition()[1]), eps);
                measurements.emplace_back(Acts::Measurement<Acts::BoundIndices, 2>(sl, indices, par, cov));

                // std::vector<std::string> truth_col = {std::to_string(m_layer+4), std::to_string(simhit.getPosition()[0]), std::to_string(simhit.getPosition()[1]), std::to_string(simhit.getPosition()[2])};
                // truth_writer.write_row(truth_col);
                // std::vector<std::string> converted_col = {std::to_string(m_layer+4), std::to_string(acts_global_postion[0]), std::to_string(acts_global_postion[1]), std::to_string(acts_global_postion[2])};
                // converted_writer.write_row(converted_col);
            }
        }
    } else { success = 0; }

    return success;
}

int RecActsTracking::InitialiseSIT()
{    
    int success = 1;

    const edm4hep::TrackerHitCollection* hitSITCol = nullptr;
    const edm4hep::SimTrackerHitCollection* SimhitSITCol = nullptr;

    double min_z = 0;
    try {
        hitSITCol = _inSITTrackHdl.get();
    } catch (GaudiException& e) {
        debug() << "Collection " << _inSITTrackHdl.fullKey() << " is unavailable in event " << _nEvt << endmsg;
        success = 0;
    }

    try {
        SimhitSITCol = _inSITColHdl.get();
    } catch (GaudiException& e) {
        debug() << "Sim Collection " << _inSITColHdl.fullKey() << " is unavailable in event " << _nEvt << endmsg;
        success = 0;
    }

    if(hitSITCol && SimhitSITCol)
    {
        int nelem = hitSITCol->size();
        debug() << "Number of SIT hits = " << nelem << endmsg;
        // SpacePointPtrs.resize(nelem);

        // std::string truth_file = "obj/sit/truth/event" + std::to_string(_nEvt) + ".csv";
        // std::ofstream truth_stream(truth_file);
        // csv2::Writer<csv2::delimiter<','>> truth_writer(truth_stream);
        // std::vector<std::string> truth_header = {"layer", "x", "y", "z"};
        // truth_writer.write_row(truth_header);

        // std::string converted_file = "obj/sit/converted/event" + std::to_string(_nEvt) + ".csv";
        // std::ofstream converted_stream(converted_file);
        // csv2::Writer<csv2::delimiter<','>> converted_writer(converted_stream);
        // std::vector<std::string> converted_header = {"layer", "x", "y", "z"};
        // converted_writer.write_row(converted_header);

        for (int ielem = 0; ielem < nelem; ++ielem)
        {
            auto hit = hitSITCol->at(ielem);
            auto simhit = SimhitSITCol->at(ielem);

            auto simcellid = simhit.getCellID();
            // <id>system:5,side:-2,layer:9,stave:8,module:8,sensor:5,y:-11,z:-11</id>
            uint64_t m_layer   = sit_decoder->get(simcellid, "layer");
            uint64_t m_stave   = sit_decoder->get(simcellid, "stave");
            uint64_t m_module  = sit_decoder->get(simcellid, "module");
            uint64_t m_sensor  = sit_decoder->get(simcellid, "sensor");
            double acts_x = simhit.getPosition()[0];
            double acts_y = simhit.getPosition()[1];
            double acts_z = simhit.getPosition()[2];
            double momentum_x = simhit.getMomentum()[0];
            double momentum_y = simhit.getMomentum()[1];
            double momentum_z = simhit.getMomentum()[2];

            dd4hep::rec::ISurface* surface = nullptr;
            auto it = m_sit_surfaces->find(simcellid);
            if (it != m_sit_surfaces->end()) {
                surface = it->second;
                if (!surface) {
                    fatal() << "found surface for SIT cell id " << simcellid << ", but NULL" << endmsg;
                    return 0;
                }
            }
            else {
                fatal() << "not found surface for SIT cell id " << simcellid << endmsg;
                return 0;
            }

            if (ielem == 0) {
                min_z = hitSITCol->at(ielem).getPosition()[2];
            } else {
                if (std::abs(acts_z - min_z) > 100) {
                    continue;
                }
            }

            // set acts geometry identifier
            uint64_t acts_volume = SIT_acts_volume_ids[m_layer];
            uint64_t acts_boundary = 0;
            uint64_t acts_layer = 2;
            uint64_t acts_approach = 0;
            uint64_t acts_sensitive = m_stave*SIT_module_nums[m_layer]*SIT_sensor_nums + m_module*SIT_sensor_nums + m_sensor + 1;

            Acts::GeometryIdentifier moduleGeoId;
            moduleGeoId.setVolume(acts_volume);
            moduleGeoId.setBoundary(acts_boundary);
            moduleGeoId.setLayer(acts_layer);
            moduleGeoId.setApproach(acts_approach);
            moduleGeoId.setSensitive(acts_sensitive);
    
            // create and store the source link
            uint32_t measurementIdx = measurements.size();
            IndexSourceLink sourceLink{moduleGeoId, measurementIdx, hit};
            sourceLinks.insert(sourceLinks.end(), sourceLink);
            Acts::SourceLink sl{sourceLink};

            // get the local position of the hit
            IndexSourceLink::SurfaceAccessor surfaceAccessor{*trackingGeometry};
            const Acts::Surface* acts_surface = surfaceAccessor(sl);
            const Acts::Vector3 globalPos{acts_x, acts_y, acts_z};
            const Acts::Vector3 globalmom{momentum_x, momentum_y, momentum_z};
            auto acts_local_postion = acts_surface->globalToLocal(geoContext, globalPos, globalmom, onSurfaceTolerance);
            if (!acts_local_postion.ok()){
                info() << "Error: failed to get local position for SIT hit " << simcellid << endmsg;
                acts_local_postion = acts_surface->globalToLocal(geoContext, globalPos, globalmom, 100*onSurfaceTolerance);
            }
            const std::array<Acts::BoundIndices, 2> indices{Acts::BoundIndices::eBoundLoc0, Acts::BoundIndices::eBoundLoc1};
            const Acts::Vector2 par{acts_local_postion.value()[0], acts_local_postion.value()[1]};

            // *** debug ***
            debug() << "SIT measurements global position(x,y,z): " << simhit.getPosition()[0] << ", " << simhit.getPosition()[1] << ", " << simhit.getPosition()[2]
                << "; local position(loc0, loc1): "<< acts_local_postion.value()[0] << ", " << acts_local_postion.value()[1] << endmsg;
            auto acts_global_postion = acts_surface->localToGlobal(geoContext, par, globalFakeMom);
            debug() << "debug surface at: x:" << acts_global_postion[0] << ", y:" << acts_global_postion[1] << ", z:" << acts_global_postion[2] << endmsg;

            // create and store the measurement
            Acts::ActsSquareMatrix<2> cov = Acts::ActsSquareMatrix<2>::Identity();
            cov(0, 0) = std::max<double>(std::abs(acts_global_postion[0] - simhit.getPosition()[0]), eps);
            cov(1, 1) = std::max<double>(std::abs(acts_global_postion[1] - simhit.getPosition()[1]), eps);
            measurements.emplace_back(Acts::Measurement<Acts::BoundIndices, 2>(sl, indices, par, cov));

            // std::vector<std::string> truth_col = {std::to_string(m_layer), std::to_string(simhit.getPosition()[0]), std::to_string(simhit.getPosition()[1]), std::to_string(simhit.getPosition()[2])};
            // truth_writer.write_row(truth_col);
            // std::vector<std::string> converted_col = {std::to_string(m_layer), std::to_string(acts_global_postion[0]), std::to_string(acts_global_postion[1]), std::to_string(acts_global_postion[2])};
            // converted_writer.write_row(converted_col);
        }
    } else { success = 0; }

    return success;
}