Skip to content
Snippets Groups Projects
SiliconTracking.cpp~ 111 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
              }
            }
          }
        }
        if (minDist < _minDistCutAttach && trackToAttach != NULL) {
          int iopt = 2;
          AttachHitToTrack(trackToAttach,hit,iopt);
        }      
      }
    }
  }
}

void SiliconTracking::AttachRemainingVTXHitsSlow() {
  
  TrackerHitExtendedVec nonAttachedHits;
  nonAttachedHits.clear();
  
  for (int il=0;il<_nLayers;++il) {
    for (int ip=0;ip<_nDivisionsInPhi;++ip) {
      for (int it=0;it<_nDivisionsInTheta; ++it) {
        int iCode = il + _nLayers*ip + _nLayers*_nDivisionsInPhi*it;      
        TrackerHitExtendedVec& hitVec = _sectors[iCode];
        int nH = int(hitVec.size());
        for (int iH=0; iH<nH; ++iH) {
          TrackerHitExtended * hit = hitVec[iH];
          TrackExtendedVec& trackVec = hit->getTrackExtendedVec();
          // if (trackVec.size()==0)
          // nonAttachedHits.push_back( hit );
          //-- allow hits that are only used in triplets to be re-attached 
          unsigned int maxTrackSize = 0;
          for(unsigned int itrack = 0;itrack < trackVec.size();itrack++){
            TrackerHitExtendedVec hitVec_tmp= trackVec[itrack]->getTrackerHitExtendedVec();
            unsigned int isize = hitVec_tmp.size();
            if(isize>maxTrackSize)maxTrackSize = isize;
          }     
          if (maxTrackSize<=3) { 
            debug() << " Add non attached hit to list: id = " << hit->getTrackerHit()->id() << endmsg;
            nonAttachedHits.push_back( hit );
          } 
          
          
        }
      }
    }
  }
  
  int nNotAttached = int(nonAttachedHits.size());
  
  int nTrk = int(_trackImplVec.size()); 
  for (int iHit=0; iHit<nNotAttached; ++iHit) {
    TrackerHitExtended * hit = nonAttachedHits[iHit];
    debug() << " Try hit: id = " << hit->getTrackerHit()->id() << endmsg;
    int layer = getLayerID( hit->getTrackerHit() );
    if (layer > _minimalLayerToAttach) {
      float pos[3];
      for (int i=0; i<3; ++i) 
        pos[i] = hit->getTrackerHit()->getPosition()[i];      
      float minDist = 1e+10;
      TrackExtended * trackToAttach = NULL;
      for (int iTrk=0; iTrk<nTrk; ++iTrk) {
        TrackExtended * trackAR = _trackImplVec[iTrk];
        bool consider = true;
        if (_checkForDelta) {
          TrackerHitExtendedVec& hitVector = trackAR->getTrackerHitExtendedVec();
          int NHITS = int(hitVector.size());
          for (int IHIT=0;IHIT<NHITS;++IHIT) {
            
            // Here we are trying to find if a hits are too close i.e. closer than _minDistToDelta
	    edm4hep::TrackerHit* trkhit1 = hit->getTrackerHit();
	    edm4hep::TrackerHit* trkhit2 = hitVector[IHIT]->getTrackerHit();                  
            
            if ( trkhit1->getCellID() == trkhit2->getCellID() ){ // i.e. they are in the same sensor
              
              float distance = 0.;
              for (int iC=0;iC<3;++iC) {
                float posFirst = float(hit->getTrackerHit()->getPosition()[iC]);
                float posSecond = float(hitVector[IHIT]->getTrackerHit()->getPosition()[iC]);
                float deltaPos = posFirst - posSecond;
                distance += deltaPos*deltaPos;
              }
              distance = sqrt(distance);
              if (distance<_minDistToDelta) {
                consider = false;
                debug() << " hit: id = " << hit->getTrackerHit()->id() << " condsidered delta together with hit " << trkhit2->id() << endmsg;
                break;
              }
            }       
          }
        }
        if (consider) {
          HelixClass helix;
          float phi0 = trackAR->getPhi();
          float d0 = trackAR->getD0();
          float z0 = trackAR->getZ0();
          float omega = trackAR->getOmega();
          float tanlambda = trackAR->getTanLambda();
          helix.Initialize_Canonical(phi0,d0,z0,omega,tanlambda,_bField);
          float distance[3];
          float time = helix.getDistanceToPoint(pos,distance);
          if (time < 1.0e+10) {
            if (distance[2] < minDist) {
              minDist = distance[2];
              trackToAttach = trackAR;
            }
          }
        }
      }
      if (minDist < _minDistCutAttach && trackToAttach != NULL) {
        int iopt = 2;
        debug() << " Hit: id = " << hit->getTrackerHit()->id() << " : try attachement"<< endmsg;
        AttachHitToTrack(trackToAttach,hit,iopt);
      } else {
        debug() << " Hit: id = " << hit->getTrackerHit()->id() << " rejected due to distance cut of " <<_minDistCutAttach<< " min distance = "  << minDist << endmsg;
      }      
    }
  }  
}

void SiliconTracking::AttachRemainingFTDHitsSlow() {
  TrackerHitExtendedVec nonAttachedHits;
  nonAttachedHits.clear();
  
  for (int iS=0;iS<2;++iS) {
    for (unsigned int layer=0;layer<_nlayersFTD;++layer) {
      for (int ip=0;ip<_nPhiFTD;++ip) {
        int iCode = iS + 2*layer + 2*_nlayersFTD*ip;      
        TrackerHitExtendedVec& hitVec = _sectorsFTD[iCode];
        int nH = int(hitVec.size());
        for (int iH=0; iH<nH; ++iH) {
          TrackerHitExtended * hit = hitVec[iH];
          TrackExtendedVec& trackVec = hit->getTrackExtendedVec();
          if (trackVec.size()==0)
            nonAttachedHits.push_back( hit );
        }
      }
    }
  }
  
  int nNotAttached = int(nonAttachedHits.size());
  
  int nTrk = int(_trackImplVec.size()); 
  for (int iHit=0; iHit<nNotAttached; ++iHit) {
    TrackerHitExtended * hit = nonAttachedHits[iHit];
    float pos[3];
    for (int i=0; i<3; ++i) 
      pos[i] = hit->getTrackerHit()->getPosition()[i];      
    float minDist = 1e+10;
    TrackExtended * trackToAttach = NULL;
    for (int iTrk=0; iTrk<nTrk; ++iTrk) {
      TrackExtended * trackAR = _trackImplVec[iTrk];
      bool consider = true;
      TrackerHitExtendedVec& hitVector = trackAR->getTrackerHitExtendedVec();
      int NHITS = int(hitVector.size());
      
      for (int IHIT=0;IHIT<NHITS;++IHIT) {
        
        // SJA:FIXME: check to see if allowing no hits in the same sensor vs no hits in the same layer works 
        //        if (hit->getTrackerHit()->getType() == hitVector[IHIT]->getTrackerHit()->getType()) {
        if (hit->getTrackerHit()->getCellID() == hitVector[IHIT]->getTrackerHit()->getCellID()) {
          
          consider = false;
          break;
        }
      }
      
      
      if (consider) {
        HelixClass helix;
        float phi0 = trackAR->getPhi();
        float d0 = trackAR->getD0();
        float z0 = trackAR->getZ0();
        float omega = trackAR->getOmega();
        float tanlambda = trackAR->getTanLambda();
        if (tanlambda*float(getSideID(hit->getTrackerHit())) > 0) {
          helix.Initialize_Canonical(phi0,d0,z0,omega,tanlambda,_bField);
          float distance[3];
          float time = helix.getDistanceToPoint(pos,distance);
          if (time < 1.0e+10) {
            if (distance[2] < minDist) {
              minDist = distance[2];
              trackToAttach = trackAR;
            }
          }
        }
      }
    }
    if (minDist < _minDistCutAttach && trackToAttach != NULL) {
      int iopt = 2;
      AttachHitToTrack(trackToAttach,hit,iopt);
    }      
  }  
}


void SiliconTracking::AttachRemainingFTDHitsFast() {
  int nTrk = _trackImplVec.size();
  
  for (int iTrk=0; iTrk<nTrk; ++iTrk) {
    TrackExtended * trackAR = _trackImplVec[iTrk];
    HelixClass helix;
    float phi0 = trackAR->getPhi();
    float d0 = trackAR->getD0();
    float z0 = trackAR->getZ0();
    float omega = trackAR->getOmega();
    float tanlambda = trackAR->getTanLambda();
    helix.Initialize_Canonical(phi0,d0,z0,omega,tanlambda,_bField);
    int iSemiSphere = 0;
    if (tanlambda > 0) 
      iSemiSphere = 1;
    float ref[3];
    for (int i=0;i<3;++i) 
      ref[i] = helix.getReferencePoint()[i];
    // Start loop over FTD layers
    for (unsigned int layer=0;layer<_nlayersFTD;layer++) {
      float ZL = _zLayerFTD[layer];
      if (iSemiSphere == 0)
        ZL = - ZL;
      float point[3];
      helix.getPointInZ(ZL,ref,point);
      float Phi = atan2(point[1],point[0]);
      if (Phi < 0) 
        Phi = Phi + TWOPI;
      int iPhi = int(Phi/_dPhiFTD);
      float distMin = 1e+10;
      TrackerHitExtended * attachedHit = NULL;     
      for (int iP=iPhi-1;iP<=iPhi+1;++iP) {
        int iPP = iP;
        if (iP < 0) 
          iPP = iP + _nPhiFTD;
        if (iP >= _nPhiFTD)
          iPP = iP - _nPhiFTD;  
        int iCode = iSemiSphere + 2*layer + 2*_nlayersFTD*iPP;
        int nHits = int(_sectorsFTD[iCode].size());
        for (int iHit=0;iHit<nHits;++iHit) {
          TrackerHitExtended * hit = _sectorsFTD[iCode][iHit];
          bool consider = true;
          TrackerHitExtendedVec& hitVector = trackAR->getTrackerHitExtendedVec();
          int NHITS = int(hitVector.size());
          
          // SJA:FIXME: check to see if allowing no hits in the same sensor vs no hits in the same layer works 
          for (int IHIT=0;IHIT<NHITS;++IHIT) {
            //            if (hit->getTrackerHit()->getType() == hitVector[IHIT]->getTrackerHit()->getType()) {
            if (hit->getTrackerHit()->getCellID() == hitVector[IHIT]->getTrackerHit()->getCellID()) {
              consider = false;
              break;
            }
          }
          
          
          if (consider) {
            float pos[3];
            for (int i=0;i<3;++i) {
              pos[i] = hit->getTrackerHit()->getPosition()[i];
            }
            float distance[3];
            float time = helix.getDistanceToPoint(pos,distance);
            if (time < 1.0e+10) {
              if (distance[2] < distMin) {
                distMin = distance[2];
                attachedHit = hit;
              }
            }
          }
        }
      }
      if (distMin < _minDistCutAttach && attachedHit != NULL) {
        int iopt = 2;
        AttachHitToTrack(trackAR,attachedHit, iopt);
      }
    }
  }
}

void SiliconTracking::TrackingInFTD() {

  int nComb = int(_CombinationsFTD.size()) / 3;

  for (int iComb=0;iComb<nComb;++iComb) {

    int nLS[3];
    nLS[0] = _CombinationsFTD[3*iComb];
    nLS[1] = _CombinationsFTD[3*iComb+1];
    nLS[2] = _CombinationsFTD[3*iComb+2];

    for (int iS=0;iS<2;++iS) { // loop over +z and -z
      
      //      std::cout << "Combinations : " << iS << " " << nLS[0] << " " << nLS[1] << " " << nLS[2] << endmsg;
      //      int iC = iS + 2*nLS[0];
      //      TrackerHitExtendedVec& hitVec = _sectorsFTD[iC];
      //      int nO = int(hitVec.size());
      //      iC = iS + 2*nLS[1];
      //      hitVec = _sectorsFTD[iC];
      //      int nM = int(hitVec.size());
      //      iC = iS + 2*nLS[2];
      //      hitVec = _sectorsFTD[iC];
      //      int nI = int(hitVec.size());
      //      std::cout << nO << " " << nM << " " << nI << endmsg;

      for (int ipOuter=0;ipOuter<_nPhiFTD;++ipOuter) { 

        int ipMiddleLow = ipOuter - 1;
        int ipMiddleUp  = ipOuter + 1;
        
        unsigned int iCodeOuter = iS + 2*nLS[0] + 2*_nlayersFTD*ipOuter;
        
        if( iCodeOuter >= _sectorsFTD.size()){          
          error() << "iCodeOuter index out of range: iCodeOuter =   " << iCodeOuter << " _sectorsFTD.size() = " << _sectorsFTD.size() << " exit(1) called from file " << __FILE__ << " line " << __LINE__<< endmsg;
          exit(1);
        }
        
        TrackerHitExtendedVec& hitVecOuter = _sectorsFTD[iCodeOuter];
        
        int nOuter = int(hitVecOuter.size());

        for (int iOuter=0;iOuter<nOuter;++iOuter) {
          
          TrackerHitExtended * hitOuter = hitVecOuter[iOuter];
        
          for (int ipMiddle=ipMiddleLow;ipMiddle<=ipMiddleUp;++ipMiddle) {
            //for(int ipMiddle=0;ipMiddle<_nPhiFTD;++ipMiddle) {
            int ipM = ipMiddle;
            if (ipM < 0) 
              ipM = ipMiddle + _nPhiFTD;
            if (ipM >= _nPhiFTD)
              ipM = ipMiddle - _nPhiFTD;
            int iCodeMiddle = iS + 2*nLS[1] + 2*_nlayersFTD*ipM;
          
            TrackerHitExtendedVec& hitVecMiddle = _sectorsFTD[iCodeMiddle];
            int ipInnerLow,ipInnerUp;       
            ipInnerLow = ipMiddle - 1;
            ipInnerUp =  ipMiddle + 1;
            
            int nMiddle = int(hitVecMiddle.size());
            
            for (int iMiddle=0;iMiddle<nMiddle;++iMiddle) {
              TrackerHitExtended * hitMiddle = hitVecMiddle[iMiddle];
              for (int ipInner=ipInnerLow;ipInner<=ipInnerUp;++ipInner) {
                //for (int ipInner=0;ipInner<_nPhiFTD;++ipInner) {
                int ipI = ipInner;
                if (ipI < 0)
                  ipI = ipInner + _nPhiFTD;
                if (ipI >= _nPhiFTD) 
                  ipI = ipInner - _nPhiFTD;
                int iCodeInner = iS + 2*nLS[2] + 2*_nlayersFTD*ipI;
                TrackerHitExtendedVec& hitVecInner = _sectorsFTD[iCodeInner];
            
                int nInner = int(hitVecInner.size());
                
                for (int iInner=0;iInner<nInner;++iInner) {
                
                  TrackerHitExtended * hitInner = hitVecInner[iInner];
                  HelixClass helix;
                  //                  std::cout << endmsg;
                  //                  std::cout << "Outer Hit Type " << hitOuter->getTrackerHit()->getType() << " z = " << hitOuter->getTrackerHit()->getPosition()[2] 
                  //                  << "\nMiddle Hit Type "<< hitMiddle->getTrackerHit()->getType() << " z = " << hitMiddle->getTrackerHit()->getPosition()[2]  
                  //                  << "\nInner Hit Type "<< hitInner->getTrackerHit()->getType() << " z = " << hitInner->getTrackerHit()->getPosition()[2]  << endmsg;

                  debug() << " "
                  << std::setw(3) << ipOuter       << " "   << std::setw(3) << ipMiddle << " "      << std::setw(3) << ipInner << "       "
                  << std::setw(3) << iS << "     "
                  << std::setw(3) << nLS[0]     << " "   << std::setw(3) << nLS[1]   << " "      << std::setw(3) << nLS[2]  << "     "
                  << std::setw(3) << nOuter << " : " << std::setw(3) << nMiddle << " : " << std::setw(3) << nInner << "  :: "
                  << std::setw(3) << nOuter*nMiddle* nInner << endmsg;

                  
                  TrackExtended * trackAR = TestTriplet(hitOuter,hitMiddle,hitInner,helix);
                  if (trackAR != NULL) {
                    //                    std::cout << "FTD triplet found" << endmsg;
                    int nHits = BuildTrackFTD(trackAR,nLS,iS);
                    
                    _tracksWithNHitsContainer.getTracksWithNHitsVec( nHits ).push_back( trackAR );
                  }
                }
              }
            }
          }       
        }
      }
    }
  }
}


int SiliconTracking::BuildTrackFTD(TrackExtended * trackAR, int * nLR, int iS) {
  //  std::cout << "BuildTrackFTD: Layers = " << nLR[0] << " " << nLR[1] << " " << nLR[2] << endmsg;
  
  // initialise a helix from the track
  HelixClass helix;
  const float d0 = trackAR->getD0();
  const float z0 = trackAR->getZ0();
  const float phi0 = trackAR->getPhi();
  const float tanlambda = trackAR->getTanLambda();
  const float omega = trackAR->getOmega();
  helix.Initialize_Canonical(phi0,d0,z0,omega,tanlambda,_bField);
  float ref[3] = {helix.getReferencePoint()[0],
    helix.getReferencePoint()[1],
    helix.getReferencePoint()[2]};
  
  for (int iL=0; iL < static_cast<int>(_nlayersFTD); ++iL) {
    if (iL != nLR[0] && iL != nLR[1] && iL != nLR[2]) {
      float point[3];
      float ZL = _zLayerFTD[iL];
      if (iS == 0) 
        ZL = - ZL;
      helix.getPointInZ(ZL,ref,point);
      //      float Phi = atan2(point[1],point[0]);
      //      int iPhi = int(Phi/_dPhiFTD);
      float distMin = 1e+6;
      TrackerHitExtended * attachedHit = NULL;
      for (int ip=0;ip<=_nPhiFTD;++ip) {
        int iP = ip;
        if (iP < 0)
          iP = ip + _nPhiFTD;
        if (iP >= _nPhiFTD)
          iP = ip - _nPhiFTD;   
        int iCode = iS + 2*iL + 2*_nlayersFTD*iP;
        TrackerHitExtendedVec& hitVec = _sectorsFTD[iCode];
        int nH = int(hitVec.size());
        for (int iH=0; iH<nH; ++iH) {
          TrackerHitExtended * hit = hitVec[iH];
	  edm4hep::TrackerHit * trkHit = hit->getTrackerHit();
          float pos[3];
          for (int i=0;i<3;++i)
            pos[i] = float(trkHit->getPosition()[i]);
          float distance[3];
          float time = helix.getDistanceToPoint(pos,distance);
          if (time < 1.0e+10) {
            if (distance[2] < distMin) {
              distMin = distance[2];
              attachedHit = hit;
            }
          }
        }
      }
      //      std::cout << "Layer = " << iL << "  distMin = " << distMin << endmsg;
      if (distMin < _minDistCutAttach && attachedHit != NULL) {
        int iopt = 2;
        AttachHitToTrack( trackAR, attachedHit, iopt);
      }
    }
  }
  TrackerHitExtendedVec& hitVec = trackAR->getTrackerHitExtendedVec();
  int nH = int (hitVec.size());
  return nH;
}

int SiliconTracking::AttachHitToTrack(TrackExtended * trackAR, TrackerHitExtended * hit, int iopt) {
  
  int attached = 0;
  TrackerHitExtendedVec& hitVec = trackAR->getTrackerHitExtendedVec();
  int nHits = int(hitVec.size());
  
  double * xh = new double[nHits+1];
  double * yh = new double[nHits+1];
  float  * zh = new float[nHits+1];
  double * wrh = new double[nHits+1];
  float * wzh = new float[nHits+1];
  float * rh = new float[nHits+1];
  float * ph = new float[nHits+1];
  float par[5];
  float epar[15];
  
  for (int i=0; i<nHits; ++i) {
    edm4hep::TrackerHit * trkHit = hitVec[i]->getTrackerHit();
    xh[i] = double(trkHit->getPosition()[0]);
    yh[i] = double(trkHit->getPosition()[1]);
    zh[i] = float(trkHit->getPosition()[2]);
    ph[i] = float(atan2(yh[i],xh[i]));
    rh[i] = float(sqrt(xh[i]*xh[i]+yh[i]*yh[i]));
    float rR = hitVec[i]->getResolutionRPhi();
    float rZ = hitVec[i]->getResolutionZ();
    wrh[i] = double(1.0/(rR*rR));
    wzh[i] = 1.0/(rZ*rZ);
  }
  
  edm4hep::TrackerHit * trkHit = hit->getTrackerHit();
  xh[nHits] = double(trkHit->getPosition()[0]);
  yh[nHits] = double(trkHit->getPosition()[1]);
  zh[nHits] = float(trkHit->getPosition()[2]);
  ph[nHits] = float(atan2(yh[nHits],xh[nHits]));
  rh[nHits] = float(sqrt(xh[nHits]*xh[nHits]+yh[nHits]*yh[nHits]));
  
  float rR = hit->getResolutionRPhi();
  float rZ = hit->getResolutionZ();
  wrh[nHits] = double(1.0/(rR*rR));
  wzh[nHits] = 1.0/(rZ*rZ);
  
  
  int NPT = nHits + 1;
  
  // SJA:FIXME the newtonian part is giving crazy results for FTD so just use iopt 2 for simply attaching hits 
  // using SIT and VXD doesn't seem to give any problems, so make it a function parameter and let the caller decide
  //  int iopt = 3;
  
  float chi2RPhi = 0 ;
  float chi2Z = 0 ;
  
  
  int error = _fastfitter->fastHelixFit(NPT, xh, yh, rh, ph, wrh, zh, wzh,iopt, par, epar, chi2RPhi, chi2Z);
  par[3] = par[3]*par[0]/fabs(par[0]);
  
  
  float omega = par[0];
  float tanlambda = par[1];
  float phi0 = par[2];
  float d0 = par[3];
  float z0 = par[4];
  float chi2 = FLT_MAX;
  int ndf = INT_MAX;
  
  if (NPT == 3) {
    chi2 = chi2RPhi*_chi2WRPhiTriplet+chi2Z*_chi2WZTriplet;
  }
  if (NPT == 4) {
    chi2 = chi2RPhi*_chi2WRPhiQuartet+chi2Z*_chi2WZQuartet;
  }
  if (NPT > 4) {
    chi2 = chi2RPhi*_chi2WRPhiSeptet+chi2Z*_chi2WZSeptet;
  }
  ndf = 2*NPT-5;
  
  
  if ( error == 0 && chi2/float(ndf) < _chi2FitCut ) {
    trackAR->addTrackerHitExtended(hit);
    hit->addTrackExtended( trackAR );
    trackAR->setChi2( chi2 );
    trackAR->setOmega( omega );
    trackAR->setTanLambda( tanlambda );
    trackAR->setD0( d0 );
    trackAR->setZ0( z0 );
    trackAR->setPhi( phi0 );
    trackAR->setNDF( ndf );
    trackAR->setCovMatrix( epar );
    attached = 1;
    debug() << "Attachement succeeded chi2/float(ndf) = " << chi2/float(ndf) << "  cut = " <<  _chi2FitCut  << " chi2RPhi = " << chi2RPhi << " chi2Z = " << chi2Z << " error = " << error << endmsg;
  } else {
    debug() << "Attachement failed chi2/float(ndf) = " << chi2/float(ndf) << "  cut = " <<  _chi2FitCut  << " chi2RPhi = " << chi2RPhi << " chi2Z = " << chi2Z << " error = " << error << endmsg;
  }
  
  delete[] xh;
  delete[] yh;
  delete[] zh;
  delete[] wrh;
  delete[] wzh;
  delete[] rh;
  delete[] ph;
  
  return attached;
  
  
}

void SiliconTracking::FinalRefit(edm4hep::TrackCollection* trk_col) {
  
  int nTracks = int(_trackImplVec.size());
  
  int nSiSegments = 0;        
  float eTot = 0.;
  float pxTot = 0.;
  float pyTot = 0.;
  float pzTot = 0.;
  std::cout << "fucd============" << nTracks << std::endl;
  for (int iTrk=0;iTrk<nTracks;++iTrk) {
    
    TrackExtended * trackAR = _trackImplVec[iTrk];    
    TrackerHitExtendedVec& hitVec = trackAR->getTrackerHitExtendedVec();
    
    int nHits = int(hitVec.size());
    std::cout << "fucd-------------" << iTrk << ": " << nHits << std::endl;
    if( nHits >= _minimalHits) {
      //    int * lh = new int[nHits];
      std::vector<int> lh;
      lh.resize(nHits);
      
      for (int i=0; i<nHits; ++i) {
        lh[i]=0;
      }
      
      float d0 = trackAR->getD0();
      float z0 = trackAR->getZ0();
      float omega = trackAR->getOmega();
      float tanlambda = trackAR->getTanLambda();
      float phi0 = trackAR->getPhi();
      
      HelixClass * helix = new HelixClass();
      helix->Initialize_Canonical(phi0, d0, z0, omega, 
                                  tanlambda, _bField);
      
      
      // get the point of closest approach to the reference point
      // here it is implicitly assumed that the reference point is the origin 
      float Pos[3];
      Pos[0] = -d0*sin(phi0);
      Pos[1] = d0*cos(phi0);
      Pos[2] = z0;
      
      std::cout << "fucd------------------1" << std::endl; 
      // at this point is is possible to have hits from the same layer ...
      // so a check is made to ensure that the hit with the smallest distance to the 
      // current helix hypothosis is used, the other hit has lh set to 0 
      
      // start loop over the hits to
      for (int ihit=0;ihit<nHits;++ihit) {
        
        lh[ihit] = 1; // only hits which have lh=1 will be used for the fit
        
        // get the pointer to the lcio trackerhit for this hit
	edm4hep::TrackerHit * trkHit = hitVec[ihit]->getTrackerHit();
        
        int det = getDetectorID(trkHit);
        
        if (det == lcio::ILDDetID::VXD || det == lcio::ILDDetID::FTD || det == lcio::ILDDetID::SIT) { // only accept VXD, FTD or SIT
          
          
          //        int layer = getLayerID(trkHit);
          //        int moduleIndex = getModuleID(trkHit);
          
          // start a double loop over the hits which have already been checked 
          for (int lhit=0;lhit<ihit;++lhit) {
            
            // get the pointer to the lcio trackerhit for the previously checked hit
	    edm4hep::TrackerHit * trkHitS = hitVec[lhit]->getTrackerHit();
            
            
            //          int layerS = getLayerID(trkHitS);
            //          int moduleIndexS = getModuleID(trkHitS);
            
            // SJA:FIXME: check to see if allowing no hits in the same sensor vs no hits in the same layer works 
            // if they are on the same layer and the previously checked hits has been declared good for fitting
            //          if ((trkHitS->getType() == trkHit->getType()) && (lh[lhit] == 1)) {
            // check if the hits have the same layer and petal number
            //          hitVec[ihit]->
            //          if ((layer == layerS) && (moduleIndex==moduleIndexS) && (lh[lhit] == 1)) {
            if ( (trkHit->getCellID() == trkHitS->getCellID()) && (lh[lhit] == 1)) {
              
              // get the position of the hits 
              float xP[3];
              float xPS[3];
              for (int iC=0;iC<3;++iC) {
                xP[iC] = float(trkHit->getPosition()[iC]);
                xPS[iC] = float(trkHitS->getPosition()[iC]);
              }
              
              // get the intersection of the helix with the either the cylinder or plane containing the hit
              float Point[6];
              float PointS[6];
              
              if (det == lcio::ILDDetID::FTD) {

                float time = helix->getPointInZ(xP[2],Pos,Point);
                time = helix->getPointInZ(xPS[2],Pos,PointS);

              } else {

                float RAD = sqrt(xP[0]*xP[0]+xP[1]*xP[1]);
                float RADS = sqrt(xPS[0]*xPS[0]+xPS[1]*xPS[1]);
                float time = helix->getPointOnCircle(RAD,Pos,Point);
                time = helix->getPointOnCircle(RADS,Pos,PointS);

              }
              
              float DIST = 0;
              float DISTS = 0;
              
              // get the euclidean distance between the hit and the point of intersection
              for (int iC=0;iC<3;++iC) {
                DIST += (Point[iC]-xP[iC])*(Point[iC]-xP[iC]);
                DISTS += (PointS[iC]-xPS[iC])*(PointS[iC]-xPS[iC]);
              }
              if (DIST < DISTS) {
                lh[lhit] = 0;
              }
              else {
                lh[ihit] = 0;
              }
              break;
            }
          }
        }
      }
      
      delete helix;
      
      std::vector<TrackerHit*> trkHits;
      std::vector<TrackerHit*> trkHits_used_inFit;
      
      int nFit = 0;
      for (int i=0; i<nHits; ++i) {
        // check if the hit has been rejected as being on the same layer and further from the helix lh==0
        if (lh[i] == 1) {
	  edm4hep::TrackerHit * trkHit = hitVec[i]->getTrackerHit();
          nFit++;
          if(trkHit) { 
            trkHits.push_back(trkHit);   
          }
          else{
            throw EVENT::Exception( std::string("SiliconTracking::FinalRefit: TrackerHit pointer == NULL ")  ) ;
          }
        }
        else { // reject hit 
               // SJA:FIXME missuse of type find a better way to signal rejected hits
          hitVec[i]->setType(int(0));
        }
      }
      
      if( trkHits.size() < 3 ) {
        debug() << "SiliconTracking::FinalRefit: Cannot fit less than 3 hits. Number of hits =  " << trkHits.size() << endmsg;
        continue ; 
      }
      std::cout << "fucd------------------2" << std::endl;
      //TrackImpl* Track = new TrackImpl ;
      auto track = trk_col->create();
      //fucd
      //edm4hep::Track track;// = new edm4hep::Track;
      std::cout << "fucd------------------3" << std::endl;
      // setup initial dummy covariance matrix
      //std::vector<float> covMatrix;
      //covMatrix.resize(15);
      std::array<float,15> covMatrix;

      for (unsigned icov = 0; icov<covMatrix.size(); ++icov) {
        covMatrix[icov] = 0;
      }
      
      covMatrix[0]  = ( _initialTrackError_d0    ); //sigma_d0^2
      covMatrix[2]  = ( _initialTrackError_phi0  ); //sigma_phi0^2
      covMatrix[5]  = ( _initialTrackError_omega ); //sigma_omega^2
      covMatrix[9]  = ( _initialTrackError_z0    ); //sigma_z0^2
      covMatrix[14] = ( _initialTrackError_tanL  ); //sigma_tanl^2
      
      
      std::vector< std::pair<float, edm4hep::TrackerHit*> > r2_values;
      r2_values.reserve(trkHits.size());
      
      for (std::vector<edm4hep::TrackerHit*>::iterator it=trkHits.begin(); it!=trkHits.end(); ++it) {
        edm4hep::TrackerHit* h = *it;
        float r2 = h->getPosition()[0]*h->getPosition()[0]+h->getPosition()[1]*h->getPosition()[1];
        r2_values.push_back(std::make_pair(r2, *it));
      }
      
      sort(r2_values.begin(),r2_values.end());
      //std::cout << "fucd------------------3" << std::endl;
      trkHits.clear();
      trkHits.reserve(r2_values.size());

      for (std::vector< std::pair<float, edm4hep::TrackerHit*> >::iterator it=r2_values.begin(); it!=r2_values.end(); ++it) {
        trkHits.push_back(it->second);
      }
      //std::cout << "fucd------------------3 " << _trksystem << std::endl;
      //for (unsigned ihit_indx=0 ; ihit_indx < trkHits.size(); ++ihit_indx) {
      //  std::cout << "fucd trk hit " << *trkHits[ihit_indx] << " " << trkHits[ihit_indx]->getCovMatrix()[0]
      //		  << " " << BitSet32(trkHits[ihit_indx]->getType())[ ILDTrkHitTypeBit::COMPOSITE_SPACEPOINT ] << endmsg;
      //}
      /*
      auto _trackSystemSvc = service<ITrackSystemSvc>("TrackSystemSvc");
      if ( !_trackSystemSvc ) {
	error() << "Failed to find TrackSystemSvc ..." << endmsg;
	return;
      }
      _trksystem =  _trackSystemSvc->getTrackSystem();

      if( _trksystem == 0 ){
	error() << "Cannot initialize MarlinTrkSystem of Type: KalTest" <<endmsg;
	return;
      }
      debug() << "_trksystem pointer " << _trksystem << endmsg;
      
      _trksystem->setOption( IMarlinTrkSystem::CFG::useQMS,        _MSOn ) ;
      _trksystem->setOption( IMarlinTrkSystem::CFG::usedEdx,       _ElossOn) ;
      _trksystem->setOption( IMarlinTrkSystem::CFG::useSmoothing,  _SmoothOn) ;
      _trksystem->init() ;
      */
      bool fit_backwards = IMarlinTrack::backward;
      
      MarlinTrk::IMarlinTrack* marlinTrk = nullptr;
      try{
	marlinTrk = _trksystem->createTrack();
      }
      catch(...){
	error() << "Cannot create MarlinTrack ! " << endmsg;
	return;
      }
      
      int status = 0;
      std::cout << "fucd------------------3" << std::endl;
      try {
        status = MarlinTrk::createFinalisedLCIOTrack(marlinTrk, trkHits, &track, fit_backwards, covMatrix, _bField, _maxChi2PerHit);
      } catch (...) {
        
        //      delete Track;
        //      delete marlinTrk;
        error() << "MarlinTrk::createFinalisedLCIOTrack " << endmsg;
        throw ;
        
      }
      std::cout << "fucd------------------4" << std::endl;
      /*
#ifdef MARLINTRK_DIAGNOSTICS_ON
      if ( status != IMarlinTrack::success && _runMarlinTrkDiagnostics ) {        
        void * dcv = _trksystem->getDiagnositicsPointer();
        DiagnosticsController* dc = static_cast<DiagnosticsController*>(dcv);
        dc->skip_current_track();
      }        
#endif
      */
      
      std::vector<std::pair<edm4hep::TrackerHit* , double> > hits_in_fit ;  
      std::vector<std::pair<edm4hep::TrackerHit* , double> > outliers ;
      std::vector<edm4hep::TrackerHit*> all_hits;    
      all_hits.reserve(300);
      
      marlinTrk->getHitsInFit(hits_in_fit);
      
      for ( unsigned ihit = 0; ihit < hits_in_fit.size(); ++ihit) {
        all_hits.push_back(hits_in_fit[ihit].first);
      }
      
      UTIL::BitField64 cellID_encoder( lcio::ILDCellID0::encoder_string ) ; 
      
      MarlinTrk::addHitNumbersToTrack(&track, all_hits, true, cellID_encoder);
      
      marlinTrk->getOutliers(outliers);
      
      for ( unsigned ihit = 0; ihit < outliers.size(); ++ihit) {
        all_hits.push_back(outliers[ihit].first);
      }
      
      MarlinTrk::addHitNumbersToTrack(&track, all_hits, false, cellID_encoder);
      
      delete marlinTrk;

      int nhits_in_vxd = track.getSubDetectorHitNumbers(0);
      int nhits_in_ftd = track.getSubDetectorHitNumbers(1);
      int nhits_in_sit = track.getSubDetectorHitNumbers(2);
      
      //debug() << " Hit numbers for Track "<< track->id() << ": "
      debug() << " Hit numbers for Track "<< iTrk <<": "
	      << " vxd hits = " << nhits_in_vxd
	      << " ftd hits = " << nhits_in_ftd
	      << " sit hits = " << nhits_in_sit
	      << endmsg;
      
      //if (nhits_in_vxd > 0) Track->setTypeBit( lcio::ILDDetID::VXD ) ;
      //if (nhits_in_ftd > 0) Track->setTypeBit( lcio::ILDDetID::FTD ) ;
      //if (nhits_in_sit > 0) Track->setTypeBit( lcio::ILDDetID::SIT ) ;

      
      
      if( status != IMarlinTrack::success ) {       
        
        //delete track;
        debug() << "SiliconTracking::FinalRefit: Track fit failed with error code " << status << " track dropped. Number of hits = "<< trkHits.size() << endmsg;       
        continue ;
      }
      
      if( track.getNdf() < 0) {       
        //delete track;
        debug() << "SiliconTracking::FinalRefit: Track fit returns " << track.getNdf() << " degress of freedom track dropped. Number of hits = "<< trkHits.size() << endmsg;       
	//delete track;
        continue ;
      }
      
      //trk_col->addElement(Track);     
      //fucd
      //trk_col->push_back(track);
      for(int i=0;i<track.trackStates_size();i++){
	// 1 = lcio::EVENT::TrackState::AtIP
	edm4hep::TrackState trkStateIP = track.getTrackStates(i);
	if(trkStateIP.location !=1) continue;
      /*
      if (trkStateIP == 0) {
        debug() << "SiliconTracking::FinalRefit: Track fit returns " << track->getNdf() << " degress of freedom track dropped. Number of hits = "<< trkHits.size() << endmsg;       
        throw EVENT::Exception( std::string("SiliconTracking::FinalRefit: trkStateIP pointer == NULL ")  ) ;
      }
      */
      // note trackAR which is of type TrackExtended, only takes fits set for ref point = 0,0,0
	trackAR->setOmega(trkStateIP.omega);
	trackAR->setTanLambda(trkStateIP.tanLambda);
	trackAR->setPhi(trkStateIP.phi);
	trackAR->setD0(trkStateIP.D0);
	trackAR->setZ0(trkStateIP.Z0);
	
	float cov[15];
	
	for (int i = 0 ; i<15 ; ++i) {
	  cov[i] = trkStateIP.covMatrix.operator[](i);
	}
      
	trackAR->setCovMatrix(cov);
	trackAR->setChi2(track.getChi2());
	trackAR->setNDF(track.getNdf());
      
	nSiSegments++;
      
	HelixClass helix_final;
      
	helix_final.Initialize_Canonical(trkStateIP.phi,trkStateIP.D0,trkStateIP.Z0,trkStateIP.omega,trkStateIP.tanLambda,_bField);
      
	float trkPx = helix_final.getMomentum()[0];
	float trkPy = helix_final.getMomentum()[1];
	float trkPz = helix_final.getMomentum()[2];
	float trkP = sqrt(trkPx*trkPx+trkPy*trkPy+trkPz*trkPz);
	eTot += trkP;
	pxTot += trkPx;
	pyTot += trkPy;
	pzTot += trkPz;
      }
    }
  }
  
  debug() << "SiliconTracking -> run " << _nRun
	  << " event " << _nEvt << endmsg;
  debug() << "Number of Si tracks = " << nSiSegments << endmsg;
  debug() << "Total 4-momentum of Si Tracks : E = " << eTot
	  << " Px = " << pxTot
	  << " Py = " << pyTot
	  << " Pz = " << pzTot << endmsg;
  
  
}


StatusCode SiliconTracking::setupGearGeom(){
  auto _gear = service<IGearSvc>("GearSvc");
  if ( !_gear ) {
    error() << "Failed to find GearSvc ..." << endmsg;
    return StatusCode::FAILURE;
  }
  gear::GearMgr* gearMgr = _gear->getGearMgr();
  _bField = gearMgr->getBField().at( gear::Vector3D( 0.,0.,0.)  ).z() ;
  debug() << "Field " << _bField << endmsg;
  //-- VXD Parameters--
  _nLayersVTX = 0 ;
  const gear::VXDParameters* pVXDDetMain = 0;
  const gear::VXDLayerLayout* pVXDLayerLayout = 0;
  
  try{
    
    debug() << " filling VXD parameters from gear::SITParameters " << endmsg ;
    
    pVXDDetMain = &gearMgr->getVXDParameters();
    pVXDLayerLayout = &(pVXDDetMain->getVXDLayerLayout());
    _nLayersVTX = pVXDLayerLayout->getNLayers();
  }
  catch( gear::UnknownParameterException& e){
    
    debug() << " ### gear::VXDParameters Not Present in GEAR FILE" << endmsg ;
    
  }
  
  
  
  //-- SIT Parameters--
  _nLayersSIT = 0 ;
  const gear::ZPlanarParameters* pSITDetMain = 0;
  const gear::ZPlanarLayerLayout* pSITLayerLayout = 0;
  
  try{
    
    debug() << " filling SIT parameters from gear::SITParameters " << endmsg ;
    
    pSITDetMain = &gearMgr->getSITParameters();
    pSITLayerLayout = &(pSITDetMain->getZPlanarLayerLayout());
    _nLayersSIT = pSITLayerLayout->getNLayers();
    
  }
  catch( gear::UnknownParameterException& e){
    
    debug() << " ### gear::SITParameters Not Present in GEAR FILE" << endmsg ;
    
  }
  
  if( _nLayersSIT == 0 ){
    // try the old LOI style key value pairs as defined in the SSit03 Mokka drive
    try{
      
      info() << "  SiliconTracking - Simple Cylinder Based SIT using parameters defined by SSit03 Mokka driver " << endmsg ;
      
      // SIT
      
      const gear::GearParameters& pSIT = gearMgr->getGearParameters("SIT");
      
      const std::vector<double>& SIT_r   =  pSIT.getDoubleVals("SITLayerRadius" )  ;
      const std::vector<double>& SIT_hl  =  pSIT.getDoubleVals("SITSupportLayerHalfLength" )  ;
      
      _nLayersSIT = SIT_r.size() ; 
      
      if (_nLayersSIT != SIT_r.size() || _nLayersSIT != SIT_hl.size()) {
        
        error() << "ILDSITCylinderKalDetector miss-match between DoubleVec and nlayers exit(1) called from file " << __FILE__ << " line " << __LINE__  << endmsg ;
        exit(1);
        
      }
    }
    catch( gear::UnknownParameterException& e){
      
      debug() << " ### gear::SIT Parameters from as defined in SSit03 Not Present in GEAR FILE" << endmsg ;
      
    }