Skip to content
Snippets Groups Projects
FullLDCTrackingAlg.cpp 175 KiB
Newer Older
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000
            covMatSi[iCov] = trkExtSi->getCovMatrix()[iCov];                
            covMat[iCov] = covMatSi[iCov];
          }

          float scaling = sqrt(covMatTPC[5]/covMatSi[5]);
          covMat[5]  = covMatTPC[5];
          covMat[3]  = scaling*covMatSi[3];
          covMat[4]  = scaling*covMatSi[4];
          covMat[8]  = scaling*covMatSi[8];
          covMat[12] = scaling*covMatSi[12];

          OutputTrack->setCovMatrix(covMat);
          TrackerHitExtendedVec tpcHitVec = trkExtTPC->getTrackerHitExtendedVec();
          TrackerHitExtendedVec siHitVec = trkExtSi->getTrackerHitExtendedVec();              

          int nTPCHits = int( tpcHitVec.size());
          int nSiHits = int( siHitVec.size());        

          float edges[2];
          edges[0] = 1.0e+20;
          edges[1] = -1.0e+20;

          // find the max and min z extents from hits
          for (int iH=0;iH<nSiHits;++iH) {
            TrackerHitExtended * hitExt = siHitVec[iH];
            OutputTrack->addTrackerHitExtended(hitExt);
            hitExt->setUsedInFit(true);
	    edm4hep::ConstTrackerHit hit = hitExt->getTrackerHit();
            float zpos = float(hit.getPosition()[2]);
            if (zpos<edges[0])
              edges[0] = zpos;
            if (zpos>edges[1])
              edges[1] = zpos;
          }       
          for (int iH=0;iH<nTPCHits;++iH) {
            TrackerHitExtended * hitExt = tpcHitVec[iH];
            OutputTrack->addTrackerHitExtended(hitExt);
            hitExt->setUsedInFit(true); 
	    edm4hep::ConstTrackerHit hit = hitExt->getTrackerHit();
            float zpos = float(hit.getPosition()[2]);
            if (zpos<edges[0])
              edges[0] = zpos;
            if (zpos>edges[1])
              edges[1] = zpos;
          }

          group->setEdges(edges);
          OutputTrack->setChi2(diffMin); // will be replaced if necessary
          OutputTrack->setNDF(int(1));   // will be replaced if necessary

          _allCombinedTracks.push_back( OutputTrack );
          allMergedTracks.push_back( OutputTrack );

        }
      }
    
    } // end of loop over TPC tracks
    
    
    // check that there are some merged tracks to process
    int nMerged = int(allMergedTracks.size());

    if (nMerged>0) {
    
      // sort all merged tracks by Chi2/NDF
      // although due to the fact that NDF for these tracks is set to the value 1 above,
      // it is really only a sort on Chi2 which was really the weighted difference in angle and omega

      Sorting(allMergedTracks);

      // loop over all merged tracks
      for (int iM=0;iM<nMerged;++iM) {

        
        TrackExtended * mergedTrack = allMergedTracks[iM];
        GroupTracks * grpTrk = mergedTrack->getGroupTracks();
        
        TrackExtendedVec trkVec = grpTrk->getTrackExtendedVec();
        TrackExtended * trkTPC = NULL;
        TrackExtended * trkSi = NULL;

        int nT = int(trkVec.size());

        // only consider tracks which have been composed of excactly 2 sub tracks
        if (nT==2) {

          trkTPC = trkVec[0];
          trkSi = trkVec[1];

          GroupTracks * groupTPC = trkTPC->getGroupTracks();
          GroupTracks * groupSi  = trkSi->getGroupTracks();

          // check that both the TPC and SI track have not already been combined with other tracks ...
          if (groupTPC == NULL && groupSi == NULL) {

            // set the grouping, meaning that these tracks will not be considered further
            trkTPC->setGroupTracks( grpTrk );
            trkSi->setGroupTracks( grpTrk );

            TrackerHitExtendedVec hitVec = mergedTrack->getTrackerHitExtendedVec();
            
            int nhits = int(hitVec.size());

            int totNdf = 2*nhits - 5;
            float totChi2 = trkTPC->getChi2() + trkSi->getChi2();

            mergedTrack->setNDF( totNdf );
            mergedTrack->setChi2( totChi2 );

            if (_debug >= 2) {
              int iopt = 2;
              // PrintOutMerging(trkTPC,trkSi,iopt);
            }
            _trkImplVec.push_back( mergedTrack );
          }
        }
      }
    }
  } // end of _forceMerging
  
  
  
  // clear buffer vector
  allMergedTracks.clear();
  
  // merging split up TPC segments
  if (_mergeTPCSegments) {

    std::vector<GroupTracks*> TPCSegments;
    TPCSegments.clear();

    int nNonAssignedTPCSeg = 0;

    // loop over all TPC Tracks
    for (int i=0;i<nTPCTrk;++i) {

      TrackExtended * trkExt = _allTPCTracks[i];
      GroupTracks * group = trkExt->getGroupTracks();

      debug() << " *****************  AddNotCombinedTracks: Check track " << trkExt << " id = " << trkExt->getTrack().id()  << endmsg;
      
      // only consider those tracks which have not yet been combined
      if (group == NULL) {

        // find the min and max z extents using the hits
        TrackerHitExtendedVec currentVec = trkExt->getTrackerHitExtendedVec();
        int nCur = int(currentVec.size());
        float zmin = 1e+20;
        float zmax = -1e+20;

        for (int iCur=0;iCur<nCur;++iCur) {
          TrackerHitExtended * curTrkHitExt = currentVec[iCur];
	  edm4hep::ConstTrackerHit curTrkHit = curTrkHitExt->getTrackerHit();
          float zpos = float(curTrkHit.getPosition()[2]);
          if (zpos < zmin)
            zmin = zpos;
          if (zpos > zmax)
            zmax = zpos;
        }

        
        nNonAssignedTPCSeg++;

        // current number of TPC segment groupings
        int nGroups = int(TPCSegments.size());

        float dPtMin = 1.0e+10;
        GroupTracks * groupToAttach = NULL;
        TrackExtended * trkToAttach = NULL;

        // loop over the current TPC segment groupings
        for (int iG=0;iG<nGroups;++iG) {

          GroupTracks * segments = TPCSegments[iG];
          TrackExtendedVec segVec = segments->getTrackExtendedVec();

          // number of segments with the candidate group
          int nTrk = int(segVec.size());
          bool consider = true;

          
          if (_forbidOverlapInZTPC==1) { // if overlap in Z of the two segments is forbidden

            // loop over all tracks in the current grouping
            for (int iTrk=0;iTrk<nTrk;++iTrk) {

              TrackExtended * trkInGroup = segVec[iTrk];

              // get the number of hits from the track
              TrackerHitExtendedVec hitInGroupVec = trkInGroup->getTrackerHitExtendedVec();
              int nHitsInGrp = int(hitInGroupVec.size());

              // loop over the hits and make sure that there is no overlap in z
              for (int iHitInGrp=0;iHitInGrp<nHitsInGrp;iHitInGrp++) {

                TrackerHitExtended * xTrkExt = hitInGroupVec[iHitInGrp];
		edm4hep::ConstTrackerHit xTrk = xTrkExt->getTrackerHit();

                float xZ = float(xTrk.getPosition()[2]);
                if (xZ>zmin&&xZ<zmax) {
                  consider = false;
                  break;
                }
              }
              if (!consider)
                break; // if the candiate track's min and max z are within that of the group
            }
          }

          if (consider) {

            // again loop over the tracks in the current group
            for (int iTrk=0;iTrk<nTrk;++iTrk) {

              TrackExtended * trkInGroup = segVec[iTrk];
              int iComp = 1;
              
              // compare the tracks ... 
              float dPt = CompareTrk(trkExt,trkInGroup,_d0CutToMergeTPC,_z0CutToMergeTPC,iComp);

              // check that this tracks has the lowest delta pt  and vetomerge (i.e. fullfill momentum cut and makes sure a large number of hits have not been lost in the merger)
              if (dPt < dPtMin && !VetoMerge(trkExt,trkInGroup)) {

                dPtMin = dPt;
                groupToAttach = segments;
                trkToAttach = trkInGroup;
                if (_debug>=3) {
                  int iopt = 5;
                  // PrintOutMerging(trkExt,trkInGroup,iopt);
                }
              }
              else {
                if (_debug>=3) {
                  int iopt = 9;
                  // PrintOutMerging(trkExt,trkInGroup,iopt);
                }
              }
            }
          }
          else {
            if (_debug >= 3) {
              int iopt = 9;
              for (int iTrk=0;iTrk<nTrk;++iTrk) {
                TrackExtended * trkInGroup = segVec[iTrk];
                int iComp = 1;
                float dPt = CompareTrk(trkExt,trkInGroup,_d0CutToMergeTPC,_z0CutToMergeTPC,iComp);              
                if (dPt >= dPtMin) {          
                  // PrintOutMerging(trkExt,trkInGroup,iopt);
                }
              }
            }
          }
        }

        // check the pt cut for merging and that a group has been found to match ..
        if (dPtMin < _dPCutToMergeTPC && groupToAttach != NULL) {
          
          // add the track to the group
          groupToAttach->addTrackExtended(trkExt);
          trkExt->setGroupTracks(groupToAttach);

          // set the min and max z extents
          float zminGroup = groupToAttach->getEdges()[0];
          float zmaxGroup = groupToAttach->getEdges()[1];

          float edges[2];
          edges[0] = zmin;
          if (zminGroup<zmin)
            edges[0] = zminGroup;
          edges[1] = zmax;
          if (zmaxGroup>zmax)
            edges[1] = zmaxGroup;
          groupToAttach->setEdges(edges);
          if (_debug>=3) {
            int iopt = 3;
            // PrintOutMerging(trkExt,trkToAttach,iopt);
          }
        } else {
          
          // create a new group of segments 
          GroupTracks * newSegment = new GroupTracks(trkExt);
          trkExt->setGroupTracks(newSegment);
          debug() << " *****************  AddNotCombinedTracks: Create new TPC Segment Group for track " << trkExt << " id = " << trkExt->getTrack().id()  << endmsg;
          
          TPCSegments.push_back(newSegment);
          float edges[2];
          edges[0] = zmin;
          edges[1] = zmax;
          newSegment->setEdges(edges);
        }
      }
    }

    // At this stage all tpc segements will have been grouped.
    
    // Now try to combine the groups of TPC segments with the
    // reconstructed tracks which have already been combined into full tracks
    // containing both Si and TPC segments
    
    int nCombTrk = int(_trkImplVec.size());
    int nSegments = int(TPCSegments.size());

    //    std::cout << "Combined tracks = " << nCombTrk << endmsg;
    //    std::cout << "nSegments = " << nSegments << endmsg;

    // loop over all the TPC segment collections
    for (int iS=0;iS<nSegments;++iS) {

      GroupTracks * segments = TPCSegments[iS];
      TrackExtendedVec segVec = segments->getTrackExtendedVec();

      float zminTPCSeg = segments->getEdges()[0];
      float zmaxTPCSeg = segments->getEdges()[1];

      int nTrk = int(segVec.size());
      TrackExtended * CombTrkToAttach = NULL;
      TrackExtended * keyTrack = NULL;

      float deltaPtMin = _dPCutToMergeTPC;

      // search over the combined (good) tracks
      for (int iCTrk=0;iCTrk<nCombTrk;++iCTrk) {

        TrackExtended * combTrk = _trkImplVec[iCTrk];
        GroupTracks * groupComb = combTrk->getGroupTracks();

        bool consider = true;

        if (_forbidOverlapInZComb==1) { // if overlap in Z of the two segments is forbidden
          float zminComb = groupComb->getEdges()[0];
          float zmaxComb = groupComb->getEdges()[1];
          consider = (zminTPCSeg>zmaxComb) || (zmaxTPCSeg<zminComb);
        }
        
        // if there are not overlaps in z, if _forbidOverlapInZComb is set above
        if (consider) {

          // loop over the TPC segments in the group
          for (int iTrk=0;iTrk<nTrk;++iTrk) {

            TrackExtended * trk = segVec[iTrk];
            int iopt = 0;

            // test for compatibility
            float dPt = CompareTrk(trk,combTrk,_d0CutToMergeTPC,_z0CutToMergeTPC,iopt);
            float angleSignificance(0.);
            float significance = CompareTrkIII(trk,combTrk,_d0CutToMergeTPC,_z0CutToMergeTPC,iopt,angleSignificance);
 
            // check if this is a better match than any before
            if ( (dPt<deltaPtMin || significance <5 ) ) {
              if(VetoMerge(trk,combTrk)==false){

                // asign the track to be attached
                CombTrkToAttach = combTrk;
                keyTrack = trk;
                deltaPtMin = dPt;
              }
            }
            else {
              if (_debug>=3) {
                GroupTracks * groupCur = combTrk->getGroupTracks();
                TrackExtended * dummySi = groupCur->getTrackExtendedVec()[0];
                int iopt_temp = 8;
                // PrintOutMerging(trk,dummySi,iopt_temp);
              }
            }
          }
        }
        else {
          if (_debug>=3) {
            for (int iTrk=0;iTrk<nTrk;++iTrk) {
              TrackExtended * trk = segVec[iTrk];
              int iopt = 0;
              float dPt = CompareTrk(trk,combTrk,_d0CutToMergeTPC,_z0CutToMergeTPC,iopt);
              if (dPt>deltaPtMin) {
                GroupTracks * groupCur = combTrk->getGroupTracks();
                TrackExtended * dummySi = groupCur->getTrackExtendedVec()[0];
                int iopt_temp = 8;
                // PrintOutMerging(trk,dummySi,iopt_temp);
              }
            }
          }
        }
      }
      
      if (CombTrkToAttach != NULL) { // attach TPC segment to existing Comb Track
        GroupTracks * groupToAttach = CombTrkToAttach->getGroupTracks();          
        TrackExtended * SiCombTrk = groupToAttach->getTrackExtendedVec()[0];
        TrackExtended * TpcCombTrk = groupToAttach->getTrackExtendedVec()[1];

        if (_debug>=3) {
          int iopt = 4;
          // PrintOutMerging(keyTrack,SiCombTrk,iopt);
          iopt = 5;
          // PrintOutMerging(keyTrack,TpcCombTrk,iopt);      
        }

        for (int iTrk=0;iTrk<nTrk;iTrk++) {

          TrackExtended * segmentTrack = segVec[iTrk];
          groupToAttach->addTrackExtended( segmentTrack );
          segmentTrack->setGroupTracks( groupToAttach );

          TrackerHitExtendedVec hitVec = segmentTrack->getTrackerHitExtendedVec();

          int nHitSeg = int(hitVec.size());

          for (int iHS=0;iHS<nHitSeg;++iHS) {

            // take the hit from the segment and attach it to CombTrkToAttach
            // flagging it as not to be used in the fit
            TrackerHitExtended * hitExt = hitVec[iHS];
            hitExt->setUsedInFit(false);
            CombTrkToAttach->addTrackerHitExtended( hitExt );

          }
        }
      }
      else {
        if (nTrk==1) { // create a new group 
          GroupTracks * newGrp = new GroupTracks();
          segVec[0]->setGroupTracks(newGrp);
          newGrp->addTrackExtended(segVec[0]);
          TrackerHitExtendedVec TpcHitVec = segVec[0]->getTrackerHitExtendedVec();
          int nTpcH = int(TpcHitVec.size());
          for (int iTpcH=0;iTpcH<nTpcH;++iTpcH) {
            TpcHitVec[iTpcH]->setUsedInFit( true );
          }
          _trkImplVec.push_back(segVec[0]);
          _allNonCombinedTPCTracks.push_back(segVec[0]);
        }
        else { // several segments
          
          float zMin = 1.0e+20;
          TrackExtended * chosenTrack = NULL;

          // loop over the segments
          for (int iTrk=0;iTrk<nTrk;++iTrk) {

            TrackExtended * segment = segVec[iTrk];

            // get the lcio track which is behind this segemnt
	    edm4hep::ConstTrack track = segment->getTrack();
            ConstTrackerHitVec hitVec(track.trackerHits_begin(), track.trackerHits_end());

            debug() << "Group of orphaned TPC tracks: trying track " << track.id() << endmsg;
            
            int nHits = int(hitVec.size());

            // loop over it's hits
            for (int iH=0;iH<nHits;++iH) {
              
              float zPosi = fabs(hitVec[iH].getPosition()[2]);

              // if this segment has the hit closest to the IP so far
              if (zPosi<zMin) {
                // take this as the chosen track and break
                chosenTrack = segment;
                zMin = zPosi;
                break;
              }
            }
          }
          
          if (chosenTrack!=NULL) { // can't really ever be null.
	    debug() << "Group of orphaned TPC tracks: chosen track taken as " << chosenTrack->getTrack().id() << endmsg;
            
            // create a new group of tracks
            GroupTracks * newGroup = new GroupTracks();

            // first add the chosen track
            chosenTrack->setGroupTracks( newGroup );
            newGroup->addTrackExtended( chosenTrack );
            
            // loop over the segments ...
            for (int iTrk=0;iTrk<nTrk;++iTrk) {

              TrackExtended * segment = segVec[iTrk];
              
              TrackerHitExtendedVec hitVecS = segment->getTrackerHitExtendedVec();
              int nHitS = int(hitVecS.size());                  

              // loop over the hits for the current segment
              for (int iH=0;iH<nHitS;++iH) {
                TrackerHitExtended * trkHitExt = hitVecS[iH];

                if (segment!=chosenTrack) { // ... then don't add the hits to the fit
                  // set the relation between group and track
                  segment->setGroupTracks( newGroup );
                  newGroup->addTrackExtended( segment );
                  trkHitExt->setUsedInFit( false );
                  chosenTrack->addTrackerHitExtended( trkHitExt );                              
                }
                else {
                  trkHitExt->setUsedInFit( true );
                }
              }
            }
            _allNonCombinedTPCTracks.push_back(chosenTrack);
            _trkImplVec.push_back(chosenTrack);
          }
        }
      }
    }
    for (int iS=0;iS<nSegments;++iS) {
      GroupTracks * segments = TPCSegments[iS];
      delete segments;
    }
    TPCSegments.clear();
  }
  else { // adding all TPC segments to the list of tracks (track splitting is allowed)
    for (int i=0;i<nTPCTrk;++i) {
      TrackExtended * trkExt = _allTPCTracks[i];
      edm4hep::ConstTrack track = trkExt->getTrack();
      GroupTracks * group = trkExt->getGroupTracks();

      if (group == NULL) {
        debug() << " *****************  AddNotCombinedTracks: _mergeTPCSegments = " << _mergeTPCSegments << " : Add non combined TPC track " << trkExt << " id = " << track.id()  << endmsg;

        TrackerHitExtendedVec hitVec = trkExt->getTrackerHitExtendedVec();
        int nHTPC = int(hitVec.size());

        for (int iHTPC=0;iHTPC<nHTPC;++iHTPC) {
          hitVec[iHTPC]->setUsedInFit(true);
        }
        _trkImplVec.push_back(trkExt);
        _allNonCombinedTPCTracks.push_back( trkExt );

        GroupTracks * newGrp = new GroupTracks();
        newGrp->addTrackExtended( trkExt );
        trkExt->setGroupTracks( newGrp );

      }
    }    
  }
  
  for (int i=0;i<nSiTrk;++i) { // adding left-over Si segments to the list of tracks
    TrackExtended * trkExt = _allSiTracks[i];
    edm4hep::ConstTrack track = trkExt->getTrack();
    GroupTracks * group = trkExt->getGroupTracks();

    if (group == NULL) {
      debug() << " *****************  AddNotCombinedTracks: Add non combined Silicon Track : " << trkExt << " id = " << track.id()  << endmsg;
      
      TrackerHitExtendedVec hitVec = trkExt->getTrackerHitExtendedVec();
      int nHSi = int(hitVec.size());

      for (int iHSi=0;iHSi<nHSi;++iHSi) {
        hitVec[iHSi]->setUsedInFit(true);
      }

      _trkImplVec.push_back(trkExt);
      _allNonCombinedSiTracks.push_back( trkExt );

      GroupTracks * newGrp = new GroupTracks();
      newGrp->addTrackExtended( trkExt );
      trkExt->setGroupTracks( newGrp );   

    }
  }
  
}

void FullLDCTrackingAlg::CheckTracks() {  
  
  for(unsigned int i = 0; i< _trkImplVec.size();i++){
    TrackExtended *first = _trkImplVec[i];
    if(first==NULL)continue;
    float d0First = first->getD0();
    float z0First = first->getZ0();
    float omegaFirst = first->getOmega();
    float tanLFirst = first->getTanLambda();
    float phiFirst = first->getPhi();
    HelixClass helixFirst;
    helixFirst.Initialize_Canonical(phiFirst,d0First,z0First,omegaFirst,tanLFirst,_bField);
    float momFirst[3];
    momFirst[0]= helixFirst.getMomentum()[0];
    momFirst[1]= helixFirst.getMomentum()[1];
    momFirst[2]= helixFirst.getMomentum()[2];
    float pFirst    = sqrt(momFirst[0]*momFirst[0]+momFirst[1]*momFirst[1]+momFirst[2]*momFirst[2]);
    if(std::isnan(pFirst))continue;
    TrackerHitExtendedVec firstHitVec  = first->getTrackerHitExtendedVec();
    if(firstHitVec.size()<1)continue;
    
    for(unsigned int j = i+1; j<_trkImplVec.size();j++){
      TrackExtended *second = _trkImplVec[j];
      if(second==NULL)continue;
      float d0Second = second->getD0();
      float z0Second = second->getZ0();
      float omegaSecond = second->getOmega();
      float tanLSecond = second->getTanLambda();
      float phiSecond = second->getPhi();
      HelixClass helixSecond;
      helixSecond.Initialize_Canonical(phiSecond,d0Second,z0Second,omegaSecond,tanLSecond,_bField);
      float momSecond[3];
      momSecond[0] = helixSecond.getMomentum()[0];
      momSecond[1] = helixSecond.getMomentum()[1];
      momSecond[2] = helixSecond.getMomentum()[2];
      float pSecond    = sqrt(momSecond[0]*momSecond[0]+momSecond[1]*momSecond[1]+momSecond[2]*momSecond[2]);
      if(std::isnan(pSecond))continue;
      TrackerHitExtendedVec secondHitVec  = second->getTrackerHitExtendedVec();
      if(secondHitVec.size()<1)continue;
      if(firstHitVec.size()+secondHitVec.size()<10)continue;
      
      
      float pdot = (momFirst[0]*momSecond[0]+momFirst[1]*momSecond[1]+momFirst[2]*momSecond[2])/pFirst/pSecond;
      if(pdot<0.999)continue;
      // const float sigmaPOverPFirst  = sqrt(first->getCovMatrix()[5])/fabs(omegaFirst);
      // const float sigmaPOverPSecond = sqrt(second->getCovMatrix()[5])/fabs(omegaSecond);
      // const float deltaP = fabs(pFirst-pSecond);
      // const float sigmaDeltaP = sqrt(pFirst*sigmaPOverPFirst*pFirst*sigmaPOverPFirst+pSecond*sigmaPOverPSecond*pSecond*sigmaPOverPSecond);
      //      const float significance = deltaP/sigmaDeltaP;
      
      TrackExtended * combinedTrack = CombineTracks(first,second, _maxAllowedPercentageOfOutliersForTrackCombination, true);
      if(combinedTrack != NULL){
        const int minHits = std::min(firstHitVec.size(),secondHitVec.size());
        const int maxHits = std::max(firstHitVec.size(),secondHitVec.size());
        
        if( combinedTrack->getNDF() <= 2*maxHits+minHits-5){
          delete combinedTrack->getGroupTracks();
          delete combinedTrack;
          continue;
        }
        
        float d0    = combinedTrack->getD0();
        float z0    = combinedTrack->getZ0();
        float omega = combinedTrack->getOmega();
        float tanL  = combinedTrack->getTanLambda();
        float phi   = combinedTrack->getPhi();
        
        HelixClass helix;
        helix.Initialize_Canonical(phi,d0,z0,omega,tanL,_bField);
        float mom[3];
        mom[0]  = helix.getMomentum()[0];
        mom[1]  = helix.getMomentum()[1];
        mom[2]  = helix.getMomentum()[2];
        // float p = sqrt(mom[0]*mom[0]+mom[1]*mom[1]+mom[2]*mom[2]);
        // float chi2Sig =  (combinedTrack->getChi2() - combinedTrack->getNDF());
        // chi2Sig = chi2Sig/sqrt(combinedTrack->getNDF()*2);
        
        
        
        int nTpcFirst(0);
        int nUsedFirst(0);
        for(unsigned int ihit = 0;ihit<firstHitVec.size();ihit++){
          
          if( getDetectorID(firstHitVec[ihit]->getTrackerHit()) == lcio::ILDDetID::TPC) nTpcFirst++;
          
          if( firstHitVec[ihit]->getUsedInFit()==true ) nUsedFirst++;
        }
        
        
        int nTpcSecond(0);
        int nUsedSecond(0);
        for(unsigned int ihit = 0;ihit<secondHitVec.size();ihit++){
          if( getDetectorID(secondHitVec[ihit]->getTrackerHit()) == lcio::ILDDetID::TPC) ++nTpcSecond;
          if( secondHitVec[ihit]->getUsedInFit()==true ) ++nUsedSecond;
        }
        delete combinedTrack->getGroupTracks();
        delete combinedTrack;
      }
    }
  }
  
  
}


/*
 
 compare the following:
 
 i)   delta omega < 2 * _dOmegaForMerging
 ii)  delta d0    < d0Cut
 iii) delta z0    < z0Cut

 if above three cuts are passed return:
 
 the angle between the two tracks (return by reference)
   and
 the difference in omega
 
 */


float FullLDCTrackingAlg::CompareTrkII(TrackExtended * first, TrackExtended * second, 
                                              float d0Cut, float z0Cut,int iopt,float & Angle) {
  
  
  float result = 1.0e+20;
  Angle  = 1.0e+20; 
  float omegaFirst = first->getOmega();
  float omegaSecond = second->getOmega();
  float deltaOmega = fabs((omegaFirst-omegaSecond)/omegaSecond);
  if(deltaOmega> 2*_dOmegaForMerging)return result;
  
  
  float d0First = first->getD0();
  float z0First = first->getZ0();
  float d0Second = second->getD0();
  float z0Second = second->getZ0();
  
  bool isCloseInIP = (fabs(d0First-d0Second)<d0Cut);
  isCloseInIP = isCloseInIP && (fabs(z0Second-z0First)<z0Cut);
  
  
  if(!isCloseInIP)return result;
  
  float tanLFirst = first->getTanLambda();
  float phiFirst = first->getPhi();
  float tanLSecond = second->getTanLambda();
  float phiSecond = second->getPhi();
  float qFirst = PIOVER2 - atan(tanLFirst);
  float qSecond = PIOVER2 - atan(tanLSecond);
  
  Angle = (cos(phiFirst)*cos(phiSecond)+sin(phiFirst)*sin(phiSecond))*
  sin(qFirst)*sin(qSecond)+cos(qFirst)*cos(qSecond);
  Angle = acos(Angle);
  
  result = deltaOmega;
  
  return result;
  
}


/*
 
 compare the following:

 i)   significance d0    < d0Cut
 ii)  significance z0    < z0Cut
 iii) pdot > 0.999

 if above three cuts are passed return:
 
 the significance dAngle (return by reference)
 and
 the significance dOmega
 
 */

float FullLDCTrackingAlg::CompareTrkIII(TrackExtended * first, TrackExtended * second, 
                                               float d0Cut, float z0Cut,int iopt, float & AngleSignificance) {
  
  
  float result = 1.0e+20;
  
  float d0First = first->getD0();
  float z0First = first->getZ0();
  float omegaFirst = first->getOmega();
  float tanLFirst = first->getTanLambda();
  float phiFirst = first->getPhi();
  float qFirst = PIOVER2 - atan(tanLFirst);
  
  
  float d0Second = second->getD0();
  float z0Second = second->getZ0();
  float omegaSecond = second->getOmega();
  float tanLSecond = second->getTanLambda();
  float phiSecond = second->getPhi();
  float qSecond = PIOVER2 - atan(tanLSecond);
  
  
  //MB 2010 03
  float d0ErrFirst = sqrt(first->getCovMatrix()[0]);
  float z0ErrFirst = sqrt(first->getCovMatrix()[9]);
  //  float omegaErrFirst = sqrt(first->getCovMatrix()[5]);
  float phiErrFirst = sqrt(first->getCovMatrix()[2]);
  float qErrFirst = sqrt(cos(qFirst)*cos(qFirst)*first->getCovMatrix()[14]);
  //MB END
  //MB 2010 03
  float d0ErrSecond = sqrt(second->getCovMatrix()[0]);
  float z0ErrSecond = sqrt(second->getCovMatrix()[9]);
  //  float omegaErrSecond = sqrt(second->getCovMatrix()[5]);
  float phiErrSecond = sqrt(second->getCovMatrix()[2]);
  float qErrSecond = sqrt(cos(qSecond)*cos(qSecond)*second->getCovMatrix()[14]);
  //MB END
  
  
  //  bool isCloseInIP = (fabs(d0First-d0Second)<d0Cut);
  //isCloseInIP = isCloseInIP && (fabs(z0Second-z0First)<z0Cut);
  
  //MB 2010 03
  bool isCloseInIP = (fabs(d0First-d0Second)/sqrt(d0ErrFirst*d0ErrFirst+d0ErrSecond*d0ErrSecond)<d0Cut);
  isCloseInIP = isCloseInIP && (fabs(z0Second-z0First)/sqrt(z0ErrFirst*z0ErrFirst+z0ErrSecond*z0ErrSecond)<z0Cut);
  
  if (!isCloseInIP)return result;
  
  float Angle = (cos(phiFirst)*cos(phiSecond)+sin(phiFirst)*sin(phiSecond))*
  sin(qFirst)*sin(qSecond)+cos(qFirst)*cos(qSecond);
  
  
  HelixClass helixFirst;
  helixFirst.Initialize_Canonical(phiFirst,d0First,z0First,omegaFirst,tanLFirst,_bField);
  HelixClass helixSecond;
  helixSecond.Initialize_Canonical(phiSecond,d0Second,z0Second,omegaSecond,tanLSecond,_bField);
  
  float pFirst[3];
  float pSecond[3];
  float momFirst = 0;
  float momSecond = 0;
  
  for (int iC=0;iC<3;++iC) {
    pFirst[iC] = helixFirst.getMomentum()[iC];
    pSecond[iC] = helixSecond.getMomentum()[iC];
    momFirst += pFirst[iC]* pFirst[iC];
    momSecond += pSecond[iC]*pSecond[iC];
  }
  momFirst = sqrt(momFirst);
  momSecond = sqrt(momSecond);
  
  
  float pdot = (pFirst[0]*pSecond[0]+pFirst[1]*pSecond[1]+pFirst[2]*pSecond[2])/momFirst/momSecond;
  if(pdot<0.999)return result;
  
  const float sigmaPOverPFirst  = sqrt(first->getCovMatrix()[5])/fabs(omegaFirst);
  const float sigmaPOverPSecond = sqrt(second->getCovMatrix()[5])/fabs(omegaSecond);
  const float deltaP = fabs(momFirst-momSecond);
  const float sigmaPFirst = momFirst*sigmaPOverPFirst;
  const float sigmaPSecond = momSecond*sigmaPOverPSecond;
  const float sigmaDeltaP = sqrt(sigmaPFirst*sigmaPFirst+sigmaPSecond*sigmaPSecond);
  const float significance = deltaP/sigmaDeltaP;
  
  //MB 2010 03
  float errorAngle =sin(phiFirst)*sin(phiFirst)*phiErrFirst*phiErrFirst*cos(phiSecond)*cos(phiSecond)+
  sin(phiSecond)*sin(phiSecond)*phiErrSecond*phiErrSecond*cos(phiFirst)*cos(phiFirst)+
  sin(qFirst)*sin(qFirst)*qErrFirst*qErrFirst*cos(qSecond)*cos(qSecond)+
  sin(qSecond)*sin(qSecond)*qErrSecond*qErrSecond*cos(qFirst)*cos(qFirst)+
  cos(phiFirst)*cos(phiFirst)*phiErrFirst*phiErrFirst*(sin(phiSecond)*sin(qFirst)*sin(qSecond))*(sin(phiSecond)*sin(qFirst)*sin(qSecond))+
  cos(phiSecond)*cos(phiSecond)*phiErrSecond*phiErrSecond*(sin(phiFirst)*sin(qFirst)*sin(qSecond))*(sin(phiFirst)*sin(qFirst)*sin(qSecond))+
  cos(qFirst)*cos(qFirst)*qErrFirst*qErrFirst*(sin(phiFirst)*sin(phiSecond)*sin(qSecond))*(sin(phiFirst)*sin(phiSecond)*sin(qSecond))+
  cos(qSecond)*cos(qSecond)*qErrSecond*qErrSecond*(sin(phiFirst)*sin(phiSecond)*sin(qFirst))*(sin(phiFirst)*sin(phiSecond)*sin(qFirst));
  
  if(Angle<1.){
    errorAngle = sqrt(1./(1.-Angle*Angle)*errorAngle);
  }else{
    errorAngle = sqrt(errorAngle);
  }
  
  if(errorAngle<1.e-6)errorAngle=1.e-6;
  
  AngleSignificance = fabs(acos(Angle)/errorAngle);
    
  return significance;
  
}

/*
 
 compare the following:
 
 i)   delta d0    < d0Cut  and optionally (d0_1 + d0_2) < d0cut
 ii)  delta z0    < z0Cut
 
 if above two cuts are passed then:
 
 if ( (ptFirst<_PtCutToMergeTPC) && (ptSecond<_PtCutToMergeTPC) ) {
 
     then check the difference in momentum 
 
 else 
 
     check for cases where PatRec splits non-looping TPC tracks
     look for two tracks where total tpc hits are not more than total number
     of pad rows and that the hits on one track are close to the helix of the
     other track.
 
     Check that the angular and momentum difference meets the cuts for either hight or low  pt
     also check if the angle is very small between the tracks and that the significance of the difference in pt is less than 10
 
 
 .... 
 
 note currently this is only used in AddNotCombinedTracks
 
 */


float FullLDCTrackingAlg::CompareTrk(TrackExtended * first, TrackExtended * second, float d0Cut, float z0Cut,int iopt) {
  
  float result = 1.0e+20;
  
  float d0First = first->getD0();
  float z0First = first->getZ0();
  float omegaFirst = first->getOmega();
  float tanLFirst = first->getTanLambda();
  float phiFirst = first->getPhi();
  
  float d0Second = second->getD0();
  float z0Second = second->getZ0();
  float omegaSecond = second->getOmega();
  float tanLSecond = second->getTanLambda();
  float phiSecond = second->getPhi();
  
  bool isCloseInIP = (fabs(d0First-d0Second)<d0Cut);
  
  if (iopt>0) isCloseInIP = isCloseInIP || (fabs(d0First+d0Second)<d0Cut);
  
  isCloseInIP = isCloseInIP && (fabs(z0Second-z0First)<z0Cut);
  
  
  HelixClass helixFirst;
  helixFirst.Initialize_Canonical(phiFirst,d0First,z0First,omegaFirst,tanLFirst,_bField);
  HelixClass helixSecond;
  helixSecond.Initialize_Canonical(phiSecond,d0Second,z0Second,omegaSecond,tanLSecond,_bField);
  
  float pFirst[3];
  float pSecond[3];
  float dPminus[3];
  float dPplus[3];
  float momFirst = 0;
  float momSecond = 0;
  float momMinus = 0;
  float momPlus = 0;
  
  if ( isCloseInIP ) {
    
    for (int iC=0;iC<3;++iC) {

      pFirst[iC] = helixFirst.getMomentum()[iC];
      pSecond[iC] = helixSecond.getMomentum()[iC];

      momFirst += pFirst[iC]* pFirst[iC];
      momSecond += pSecond[iC]*pSecond[iC];

      dPminus[iC] = pFirst[iC] - pSecond[iC];
      dPplus[iC] = pFirst[iC] + pSecond[iC];

      momMinus += dPminus[iC]*dPminus[iC];
      momPlus += dPplus[iC]*dPplus[iC];
    }

    momFirst = sqrt(momFirst);
    momSecond = sqrt(momSecond);
    
    float ptFirst = sqrt(pFirst[0]*pFirst[0]+pFirst[1]*pFirst[1]);
    float ptSecond = sqrt(pSecond[0]*pSecond[0]+pSecond[1]*pSecond[1]);
    
    // if both track's pt are lower than _PtCutToMergeTPC
    if ( (ptFirst<_PtCutToMergeTPC) && (ptSecond<_PtCutToMergeTPC) ) {
      
      momMinus = sqrt(momMinus);
      momPlus = sqrt(momPlus);

      float nom = momMinus;

      // get the smaller difference for the nominator
      if (momPlus<nom && iopt>0)
        nom = momPlus;

      float den = momFirst;

      // get the smallest momentum for the denominator
      if (momSecond<momFirst)
        den = momSecond;
      
      result = nom/den;     
      
    }
    else {
      
      
      // check for cases where PatRec splits non-looping TPC tracks 
      // look for two tracks where total tpc hits are not more than total number
      // of pad rows and that the hits on one track are close to the helix of the
      // other track
      
      float dpOverP = 2.0*fabs(momFirst-momSecond)/(momFirst+momSecond);
      const float pdot = (pFirst[0]*pSecond[0]+pFirst[1]*pSecond[1]+pFirst[2]*pSecond[2])/momFirst/momSecond;
      const float sigmaPOverPFirst  = sqrt(first->getCovMatrix()[5])/fabs(omegaFirst);
      const float sigmaPOverPSecond = sqrt(second->getCovMatrix()[5])/fabs(omegaSecond);
      const float deltaP = fabs(momFirst-momSecond);
      const float sigmaPFirst = momFirst*sigmaPOverPFirst;
      const float sigmaPSecond = momSecond*sigmaPOverPSecond;
      const float sigmaDeltaP = sqrt(sigmaPFirst*sigmaPFirst+sigmaPSecond*sigmaPSecond);
      const float significance = deltaP/sigmaDeltaP;
      
      
      //compare angle between the two vectors (cos theta) and their momentum
      if( (pdot>_cosThetaCutHighPtMerge && dpOverP<_momDiffCutHighPtMerge) 
         || 
         (pdot>_cosThetaCutSoftHighPtMerge && dpOverP<_momDiffCutSoftHighPtMerge) 
         || (pdot > 0.9999 && significance <10) 
         ){
        
        
        int nTrkGrpFirst = 0;
        int nTrkGrpSecond = 0;
        ConstTrackerHitVec hitvecFirst;
        ConstTrackerHitVec hitvecSecond;
        GroupTracks * groupFirst = first->getGroupTracks();
        GroupTracks * groupSecond = second->getGroupTracks();

        // does the first track belong to a group ...
        // if it does then get all the hits from the group
        if(groupFirst!=NULL){
          
          TrackExtendedVec tracksInGroupFirst = groupFirst->getTrackExtendedVec();
          nTrkGrpFirst = int(tracksInGroupFirst.size());