CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_6_1_2_SLHC4_patch1/src/RecoTracker/SpecialSeedGenerators/src/SimpleCosmicBONSeeder.cc

Go to the documentation of this file.
00001 //
00002 // Package:         RecoTracker/TkSeedGenerator
00003 // Class:           GlobalPixelLessSeedGenerator
00004 // 
00005 // From CosmicSeedGenerator+SimpleCosmicBONSeeder, with changes by Giovanni
00006 // to seed Cosmics with B != 0
00007 
00008 #include "RecoTracker/SpecialSeedGenerators/interface/SimpleCosmicBONSeeder.h"
00009 #include "DataFormats/TrackerRecHit2D/interface/SiStripMatchedRecHit2D.h"
00010 #include "DataFormats/TrackerRecHit2D/interface/SiStripRecHit2D.h"
00011 #include "FWCore/Utilities/interface/isFinite.h"
00012 typedef TransientTrackingRecHit::ConstRecHitPointer SeedingHit;
00013 
00014 #include <numeric>
00015 
00016 using namespace std;
00017 SimpleCosmicBONSeeder::SimpleCosmicBONSeeder(edm::ParameterSet const& conf) : 
00018   conf_(conf),
00019   theLsb(conf.getParameter<edm::ParameterSet>("TripletsPSet")),
00020   writeTriplets_(conf.getParameter<bool>("writeTriplets")),
00021   seedOnMiddle_(conf.existsAs<bool>("seedOnMiddle") ? conf.getParameter<bool>("seedOnMiddle") : false),
00022   rescaleError_(conf.existsAs<double>("rescaleError") ? conf.getParameter<double>("rescaleError") : 1.0),
00023   tripletsVerbosity_(conf.getParameter<edm::ParameterSet>("TripletsPSet").getUntrackedParameter<uint32_t>("debugLevel",0)),
00024   seedVerbosity_(conf.getUntrackedParameter<uint32_t>("seedDebugLevel",0)),
00025   helixVerbosity_(conf.getUntrackedParameter<uint32_t>("helixDebugLevel",0)),
00026   check_(conf.getParameter<edm::ParameterSet>("ClusterCheckPSet")),
00027   maxTriplets_(conf.getParameter<int32_t>("maxTriplets")),
00028   maxSeeds_(conf.getParameter<int32_t>("maxSeeds"))
00029 {
00030   edm::ParameterSet regionConf = conf_.getParameter<edm::ParameterSet>("RegionPSet");
00031   float ptmin        = regionConf.getParameter<double>("ptMin");
00032   float originradius = regionConf.getParameter<double>("originRadius");
00033   float halflength   = regionConf.getParameter<double>("originHalfLength");
00034   float originz      = regionConf.getParameter<double>("originZPosition");
00035   region_ = GlobalTrackingRegion(ptmin, originradius, halflength, originz);
00036   pMin_   = regionConf.getParameter<double>("pMin");
00037 
00038   builderName = conf_.getParameter<std::string>("TTRHBuilder");   
00039 
00040   //***top-bottom
00041   positiveYOnly=conf_.getParameter<bool>("PositiveYOnly");
00042   negativeYOnly=conf_.getParameter<bool>("NegativeYOnly");
00043   //***
00044 
00045   produces<TrajectorySeedCollection>();
00046   if (writeTriplets_) produces<edm::OwnVector<TrackingRecHit> >("cosmicTriplets");
00047 
00048   layerTripletNames_ = conf_.getParameter<edm::ParameterSet>("TripletsPSet").getParameter<std::vector<std::string> >("layerList");
00049 
00050   if (conf.existsAs<edm::ParameterSet>("ClusterChargeCheck")) {
00051       edm::ParameterSet cccc = conf.getParameter<edm::ParameterSet>("ClusterChargeCheck");
00052       checkCharge_          = cccc.getParameter<bool>("checkCharge");
00053       matchedRecHitUsesAnd_ = cccc.getParameter<bool>("matchedRecHitsUseAnd");
00054       chargeThresholds_.resize(7,0);
00055       edm::ParameterSet ccct = cccc.getParameter<edm::ParameterSet>("Thresholds");
00056       chargeThresholds_[StripSubdetector::TIB] = ccct.getParameter<int32_t>("TIB");
00057       chargeThresholds_[StripSubdetector::TID] = ccct.getParameter<int32_t>("TID");
00058       chargeThresholds_[StripSubdetector::TOB] = ccct.getParameter<int32_t>("TOB");
00059       chargeThresholds_[StripSubdetector::TEC] = ccct.getParameter<int32_t>("TEC");
00060   } else {
00061       checkCharge_ = false;
00062   }
00063   if (conf.existsAs<edm::ParameterSet>("HitsPerModuleCheck")) {
00064       edm::ParameterSet hpmcc = conf.getParameter<edm::ParameterSet>("HitsPerModuleCheck");
00065       checkMaxHitsPerModule_  = hpmcc.getParameter<bool>("checkHitsPerModule");
00066       maxHitsPerModule_.resize(7,std::numeric_limits<int32_t>::max());
00067       edm::ParameterSet hpmct = hpmcc.getParameter<edm::ParameterSet>("Thresholds");
00068       maxHitsPerModule_[StripSubdetector::TIB] = hpmct.getParameter<int32_t>("TIB");
00069       maxHitsPerModule_[StripSubdetector::TID] = hpmct.getParameter<int32_t>("TID");
00070       maxHitsPerModule_[StripSubdetector::TOB] = hpmct.getParameter<int32_t>("TOB");
00071       maxHitsPerModule_[StripSubdetector::TEC] = hpmct.getParameter<int32_t>("TEC");
00072   } else {
00073       checkMaxHitsPerModule_ = false;
00074   }
00075   if (checkCharge_ || checkMaxHitsPerModule_) {
00076       goodHitsPerSeed_ = conf.getParameter<int32_t>("minimumGoodHitsInSeed"); 
00077   } else {
00078       goodHitsPerSeed_ = 0;
00079   }
00080 
00081 }
00082 
00083 // Functions that gets called by framework every event
00084 void SimpleCosmicBONSeeder::produce(edm::Event& ev, const edm::EventSetup& es)
00085 {
00086   std::auto_ptr<TrajectorySeedCollection> output(new TrajectorySeedCollection());
00087   std::auto_ptr<edm::OwnVector<TrackingRecHit> > outtriplets(new edm::OwnVector<TrackingRecHit>());
00088 
00089   es.get<IdealMagneticFieldRecord>().get(magfield);
00090   if (magfield->inTesla(GlobalPoint(0,0,0)).mag() > 0.01) {
00091      size_t clustsOrZero = check_.tooManyClusters(ev);
00092      if (clustsOrZero) {
00093          edm::LogError("TooManyClusters") << "Found too many clusters (" << clustsOrZero << "), bailing out.\n";
00094      } else {
00095          init(es);
00096          bool tripletsOk = triplets(ev,es);
00097          if (tripletsOk) {
00098 
00099              bool seedsOk    = seeds(*output,es);
00100              if (!seedsOk) { }
00101 
00102              if (writeTriplets_) {
00103                  for (OrderedHitTriplets::const_iterator it = hitTriplets.begin(); it != hitTriplets.end(); ++it) {
00104                      const TrackingRecHit * hit1 = it->inner()->hit();    
00105                      const TrackingRecHit * hit2 = it->middle()->hit();
00106                      const TrackingRecHit * hit3 = it->outer()->hit();
00107                      outtriplets->push_back(hit1->clone());
00108                      outtriplets->push_back(hit2->clone());
00109                      outtriplets->push_back(hit3->clone());
00110                  }
00111              }
00112          }
00113          done();
00114      }
00115   }
00116 
00117   if (writeTriplets_) {
00118       ev.put(outtriplets, "cosmicTriplets");
00119   }
00120   ev.put(output);
00121 }
00122 
00123 void 
00124 SimpleCosmicBONSeeder::init(const edm::EventSetup& iSetup)
00125 {
00126     iSetup.get<TrackerDigiGeometryRecord>().get(tracker);
00127     iSetup.get<TransientRecHitRecord>().get(builderName,TTTRHBuilder);
00128 
00129     // FIXME: these should come from ES too!!
00130     thePropagatorAl = new PropagatorWithMaterial(alongMomentum,0.1057,&(*magfield) );
00131     thePropagatorOp = new PropagatorWithMaterial(oppositeToMomentum,0.1057,&(*magfield) );
00132     theUpdator      = new KFUpdator();
00133 
00134 }
00135 
00136 struct HigherInnerHit {
00137     bool operator()(const OrderedHitTriplet &trip1, const OrderedHitTriplet &trip2) const {
00138         //FIXME: inner gives a SEGV
00139 #if 0
00140         //const TransientTrackingRecHit::ConstRecHitPointer &ihit1 = trip1.inner();
00141         //const TransientTrackingRecHit::ConstRecHitPointer &ihit2 = trip2.inner();
00142         const TransientTrackingRecHit::ConstRecHitPointer &ihit1 = trip1.middle();
00143         const TransientTrackingRecHit::ConstRecHitPointer &ihit2 = trip2.middle();
00144         const TransientTrackingRecHit::ConstRecHitPointer &ohit1 = trip1.outer();
00145         const TransientTrackingRecHit::ConstRecHitPointer &ohit2 = trip2.outer();
00146 #endif
00147         TransientTrackingRecHit::ConstRecHitPointer ihit1 = trip1.inner();
00148         TransientTrackingRecHit::ConstRecHitPointer ihit2 = trip2.inner();
00149         TransientTrackingRecHit::ConstRecHitPointer ohit1 = trip1.outer();
00150         TransientTrackingRecHit::ConstRecHitPointer ohit2 = trip2.outer();
00151         float iy1 = ihit1->globalPosition().y();
00152         float oy1 = ohit1->globalPosition().y();
00153         float iy2 = ihit2->globalPosition().y();
00154         float oy2 = ohit2->globalPosition().y();
00155         if (oy1 - iy1 > 0) { // 1 Downgoing
00156             if (oy2 - iy2 > 0) { // 2 Downgoing
00157                 // sort by inner, or by outer if inners are the same
00158                 return (iy1 != iy2 ? (iy1 > iy2) : (oy1 > oy2));
00159             } else return true; // else prefer downgoing
00160         } else if (oy2 - iy2 > 0) {
00161             return false; // prefer downgoing
00162         } else { // both upgoing
00163             // sort by inner, or by outer
00164             return (iy1 != iy2 ? (iy1 < iy2) : (oy1 < oy2));
00165         }
00166     }
00167 };
00168 
00169 bool SimpleCosmicBONSeeder::triplets(const edm::Event& e, const edm::EventSetup& es) {
00170     using namespace ctfseeding;
00171 
00172     hitTriplets.clear();
00173     hitTriplets.reserve(0);
00174     SeedingLayerSets lss = theLsb.layers(es);
00175     SeedingLayerSets::const_iterator iLss;
00176 
00177     double minRho = region_.ptMin() / ( 0.003 * magfield->inTesla(GlobalPoint(0,0,0)).z() );
00178 
00179     for (iLss = lss.begin(); iLss != lss.end(); iLss++){
00180         SeedingLayers ls = *iLss;
00181         if (ls.size() != 3){
00182             throw cms::Exception("CtfSpecialSeedGenerator") << "You are using " << ls.size() <<" layers in set instead of 3 ";
00183         }
00184 
00186         std::vector<SeedingHit> innerHits  = region_.hits(e, es, &ls[0]);
00187         std::vector<SeedingHit> middleHits = region_.hits(e, es, &ls[1]);
00188         std::vector<SeedingHit> outerHits  = region_.hits(e, es, &ls[2]);
00189         std::vector<SeedingHit>::const_iterator iOuterHit,iMiddleHit,iInnerHit;
00190 
00191         if (tripletsVerbosity_ > 0) {
00192             std::cout << "GenericTripletGenerator iLss = " << layerTripletNames_[iLss - lss.begin()]
00193                     << " (" << (iLss - lss.begin()) << "): # = " 
00194                     << innerHits.size() << "/" << middleHits.size() << "/" << outerHits.size() << std::endl;
00195         }
00196 
00198         typedef TransientTrackingRecHit::RecHitPointer TTRH;
00199         std::vector<TTRH> innerTTRHs, middleTTRHs, outerTTRHs;
00200 
00202         std::vector<bool> innerOk( innerHits.size(),  true);
00203         std::vector<bool> middleOk(middleHits.size(), true);
00204         std::vector<bool> outerOk( outerHits.size(),  true);
00205 
00206         size_t sizBefore = hitTriplets.size();
00208         int idx = 0;
00209         for (iOuterHit = outerHits.begin(), idx = 0; iOuterHit != outerHits.end(); ++idx, ++iOuterHit){
00210             outerTTRHs.push_back(ls[2].hitBuilder()->build((**iOuterHit).hit()));
00211             if (checkCharge_ && !checkCharge(outerTTRHs.back()->hit())) outerOk[idx] = false;
00212         }
00213         for (iMiddleHit = middleHits.begin(), idx = 0; iMiddleHit != middleHits.end(); ++idx, ++iMiddleHit){
00214             middleTTRHs.push_back(ls[1].hitBuilder()->build((**iMiddleHit).hit()));
00215             if (checkCharge_ && !checkCharge(middleTTRHs.back()->hit())) middleOk[idx] = false;
00216         }
00217         for (iInnerHit = innerHits.begin(), idx = 0; iInnerHit != innerHits.end(); ++idx, ++iInnerHit){
00218             innerTTRHs.push_back(ls[0].hitBuilder()->build((**iInnerHit).hit()));
00219             if (checkCharge_ && !checkCharge(innerTTRHs.back()->hit())) innerOk[idx] = false;
00220         }
00221         if (checkMaxHitsPerModule_) {
00222             checkNoisyModules(innerTTRHs,  innerOk);
00223             checkNoisyModules(middleTTRHs, middleOk);
00224             checkNoisyModules(outerTTRHs,  outerOk);
00225         }
00226 
00227         for (iOuterHit = outerHits.begin(); iOuterHit != outerHits.end(); iOuterHit++){
00228             idx = iOuterHit - outerHits.begin();
00229             TTRH &       outerTTRH = outerTTRHs[idx];
00230             GlobalPoint  outerpos  = outerTTRH->globalPosition(); // this caches by itself
00231             bool         outerok   = outerOk[idx];
00232             if (outerok < goodHitsPerSeed_ - 2) {
00233                 if (tripletsVerbosity_ > 2) 
00234                     std::cout << "Skipping at first hit: " << (outerok) << " < " << (goodHitsPerSeed_ - 2) << std::endl;
00235                 continue; 
00236             }
00237 
00238             for (iMiddleHit = middleHits.begin(); iMiddleHit != middleHits.end(); iMiddleHit++){
00239                 idx = iMiddleHit - middleHits.begin();
00240                 TTRH &       middleTTRH = middleTTRHs[idx];
00241                 GlobalPoint  middlepos  = middleTTRH->globalPosition(); // this caches by itself
00242                 bool         middleok   = middleOk[idx];
00243                 if (outerok+middleok < goodHitsPerSeed_ - 1) {
00244                     if (tripletsVerbosity_ > 2) 
00245                         std::cout << "Skipping at second hit: " << (outerok+middleok) << " < " << (goodHitsPerSeed_ - 1) << std::endl;
00246                     continue; 
00247                 }
00248 
00249                 for (iInnerHit = innerHits.begin(); iInnerHit != innerHits.end(); iInnerHit++){
00250                     idx = iInnerHit - innerHits.begin();
00251                     TTRH &       innerTTRH = innerTTRHs[idx];
00252                     GlobalPoint  innerpos  = innerTTRH->globalPosition(); // this caches by itself
00253                     bool         innerok   = innerOk[idx];
00254                     if (outerok+middleok+innerok < goodHitsPerSeed_) {
00255                         if (tripletsVerbosity_ > 2) 
00256                             std::cout << "Skipping at third hit: " << (outerok+middleok+innerok) << " < " << (goodHitsPerSeed_) << std::endl;
00257                         continue;
00258                     } 
00259 
00260                     //***top-bottom
00261                     if (positiveYOnly && (innerpos.y()<0 || middlepos.y()<0 || outerpos.y()<0
00262                                           || outerpos.y() < innerpos.y()
00263                                           ) ) continue;
00264                     if (negativeYOnly && (innerpos.y()>0 || middlepos.y()>0 || outerpos.y()>0
00265                                           || outerpos.y() > innerpos.y()
00266                                           ) ) continue;
00267                     //***
00268                     
00269                     if (tripletsVerbosity_ > 2) std::cout << "Trying seed with: " << innerpos << " + " << middlepos << " + " << outerpos << std::endl;
00270                     if (goodTriplet(innerpos,middlepos,outerpos,minRho)) {
00271                         OrderedHitTriplet oht(*iInnerHit,*iMiddleHit,*iOuterHit);
00272                         hitTriplets.push_back(oht);
00273                         if ((maxTriplets_ > 0) && (hitTriplets.size() > size_t(maxTriplets_))) {
00274                             hitTriplets.clear();                      // clear
00275                             //OrderedHitTriplets().swap(hitTriplets); // really clear   
00276                             edm::LogError("TooManyTriplets") << "Found too many triplets, bailing out.\n";
00277                             return false;
00278                         }
00279                         if (tripletsVerbosity_ > 3) {
00280                             std::cout << " accepted seed #" << (hitTriplets.size()-1) << " w/: " 
00281                                 << innerpos << " + " << middlepos << " + " << outerpos << std::endl;
00282                         }
00283                         if (tripletsVerbosity_ == 2) {
00284                                 std::cout << " good seed #" << (hitTriplets.size()-1) << " w/: "     
00285                                     << innerpos << " + " << middlepos << " + " << outerpos << std::endl;
00286                         }
00287                         if (tripletsVerbosity_ > 3 && (helixVerbosity_ > 0)) { // debug the momentum here too
00288                             pqFromHelixFit(innerpos,middlepos,outerpos,es); 
00289                         }
00290                     }
00291                 }
00292             }
00293         }
00294         if ((tripletsVerbosity_ > 0) && (hitTriplets.size() > sizBefore)) {
00295             std::cout << "                        iLss = " << layerTripletNames_[iLss - lss.begin()]
00296                 << " (" << (iLss - lss.begin()) << "): # = " 
00297                 << innerHits.size() << "/" << middleHits.size() << "/" << outerHits.size() 
00298                 << ": Found " << (hitTriplets.size() - sizBefore) << " seeds [running total: " << hitTriplets.size() << "]"
00299                 << std::endl ;
00300         }
00301 
00302     }
00303     std::sort(hitTriplets.begin(),hitTriplets.end(),HigherInnerHit());
00304     return true;
00305 }
00306 bool SimpleCosmicBONSeeder::checkCharge(const TrackingRecHit *hit) const {
00307     DetId detid(hit->geographicalId());
00308     if (detid.det() != DetId::Tracker) return false; // should not happen
00309     int subdet = detid.subdetId(); 
00310     if (subdet < 3) { // pixel
00311         return true;
00312     } else {
00313         if (typeid(*hit) == typeid(SiStripMatchedRecHit2D)) {
00314             const SiStripMatchedRecHit2D *mhit = static_cast<const SiStripMatchedRecHit2D *>(hit);
00315             if (matchedRecHitUsesAnd_) {
00316                 return checkCharge(mhit->monoHit(), subdet) && checkCharge(mhit->stereoHit(), subdet);
00317             } else {
00318                 return checkCharge(mhit->monoHit(), subdet) || checkCharge(mhit->stereoHit(), subdet);
00319             }
00320         } else if (typeid(*hit) == typeid(SiStripRecHit2D)) {
00321             return checkCharge(static_cast<const SiStripRecHit2D &>(*hit), subdet);
00322         } else {
00323             return true;
00324         }
00325     }
00326 }
00327 
00328 // to be fixed to use OmniCluster
00329 bool SimpleCosmicBONSeeder::checkCharge(const SiStripRecHit2D &hit, int subdetid) const {
00330     const SiStripCluster *clust = (hit.cluster().isNonnull() ?  hit.cluster().get() : hit.cluster_regional().get());
00331     int charge = std::accumulate(clust->amplitudes().begin(), clust->amplitudes().end(), int(0));
00332     if (tripletsVerbosity_ > 1) {
00333         std::cerr << "Hit on " << subdetid << ", charge = " << charge << ", threshold = " << chargeThresholds_[subdetid] 
00334                   << ", detid = " <<  hit.geographicalId().rawId() << ", firstStrip = " << clust->firstStrip() << std::endl;
00335     } else if ((tripletsVerbosity_ == 1) && (charge < chargeThresholds_[subdetid])) {
00336         std::cerr << "Hit on " << subdetid << ", charge = " << charge << ", threshold = " << chargeThresholds_[subdetid] 
00337                   << ", detid = " <<  hit.geographicalId().rawId() << ", firstStrip = " << clust->firstStrip() << std::endl;
00338     }
00339     return charge > chargeThresholds_[subdetid];
00340 }
00341 
00342 void SimpleCosmicBONSeeder::checkNoisyModules(const std::vector<TransientTrackingRecHit::RecHitPointer> &hits, std::vector<bool> &oks) const {
00343     typedef TransientTrackingRecHit::RecHitPointer TTRH;
00344     std::vector<TTRH>::const_iterator it = hits.begin(),  start = it,   end = hits.end();
00345     std::vector<bool>::iterator       ok = oks.begin(), okStart = ok;
00346     while (start < end) {
00347         DetId lastid = (*start)->geographicalId();
00348         for (it = start + 1; (it < end) && ((*it)->geographicalId() == lastid); ++it) {
00349             ++ok;
00350         }
00351         if ( (it - start) > maxHitsPerModule_[lastid.subdetId()] ) { 
00352             if (tripletsVerbosity_ > 0) {
00353                 std::cerr << "SimpleCosmicBONSeeder: Marking noisy module " << lastid.rawId() << ", it has " << (it-start) << " rechits"
00354                           << " (threshold is " << maxHitsPerModule_[lastid.subdetId()] << ")" << std::endl;
00355             }
00356             std::fill(okStart,ok,false);
00357         } else if (tripletsVerbosity_ > 0) {
00358             if ( (it - start) > std::min(4,maxHitsPerModule_[lastid.subdetId()]/4) ) {
00359                 std::cerr << "SimpleCosmicBONSeeder: Not marking noisy module " << lastid.rawId() << ", it has " << (it-start) << " rechits"
00360                           << " (threshold is " << maxHitsPerModule_[lastid.subdetId()] << ")" << std::endl;
00361             }
00362         }
00363         start = it; okStart = ok;
00364     }
00365 }
00366 
00367 bool SimpleCosmicBONSeeder::goodTriplet(const GlobalPoint &inner, const GlobalPoint & middle, const GlobalPoint & outer, const double &minRho) const {
00368     float dyOM = outer.y() - middle.y(), dyIM = inner.y() - middle.y();
00369     if ((dyOM * dyIM > 0) && (fabs(dyOM)>10) && (fabs(dyIM)>10)) {
00370         if (tripletsVerbosity_ > 2) std::cout << "  fail for non coherent dy" << std::endl;
00371         return false;
00372     }
00373     float dzOM = outer.z() - middle.z(), dzIM = inner.z() - middle.z();
00374     if ((dzOM * dzIM > 0) && (fabs(dzOM)>50) && (fabs(dzIM)>50)) {
00375         if (tripletsVerbosity_ > 2) std::cout << "  fail for non coherent dz" << std::endl;
00376         return false;
00377     }
00378     if (minRho > 0) {
00379         FastCircle theCircle(inner,middle,outer);
00380         if (theCircle.rho() < minRho) {
00381             if (tripletsVerbosity_ > 2) std::cout << "  fail for pt cut" << std::endl;
00382             return false;
00383         }
00384     }
00385     return true;
00386 }
00387 
00388 std::pair<GlobalVector,int>
00389 SimpleCosmicBONSeeder::pqFromHelixFit(const GlobalPoint &inner, const GlobalPoint & middle, const GlobalPoint & outer, 
00390                                                          const edm::EventSetup& iSetup) const {
00391     if (helixVerbosity_ > 0) {
00392         std::cout << "DEBUG PZ =====" << std::endl;
00393         FastHelix helix(inner,middle,outer,iSetup);
00394         GlobalVector gv=helix.stateAtVertex().parameters().momentum(); // status on inner hit
00395         std::cout << "FastHelix P = " << gv   << "\n";
00396         std::cout << "FastHelix Q = " << helix.stateAtVertex().parameters().charge() << "\n";
00397     }
00398 
00399     // My attempt (with different approx from FastHelix)
00400     // 1) fit the circle
00401     FastCircle theCircle(inner,middle,outer);
00402     double rho = theCircle.rho();
00403 
00404     // 2) Get the PT
00405     GlobalVector tesla = magfield->inTesla(middle);
00406     double pt = 0.01 * rho * (0.3*tesla.z());
00407 
00408     // 3) Get the PX,PY at OUTER hit (VERTEX)
00409     double dx1 = outer.x()-theCircle.x0();
00410     double dy1 = outer.y()-theCircle.y0();
00411     double py = pt*dx1/rho, px = -pt*dy1/rho;
00412     if(px*(middle.x() - outer.x()) + py*(middle.y() - outer.y()) < 0.) {
00413         px *= -1.; py *= -1.;
00414     }
00415 
00416     // 4) Get the PZ through pz = pT*(dz/d(R*phi)))
00417     double dz = inner.z() - outer.z();
00418     double sinphi = ( dx1*(inner.y()-theCircle.y0()) - dy1*(inner.x()-theCircle.x0())) / (rho * rho);
00419     double dphi = std::abs(std::asin(sinphi));
00420     double pz = pt * dz / (dphi * rho); 
00421 
00422     int myq = ((theCircle.x0()*py - theCircle.y0()*px) / tesla.z()) > 0. ?  +1 : -1;
00423     
00424     std::pair<GlobalVector,int> mypq(GlobalVector(px,py,pz),myq);
00425 
00426     if (helixVerbosity_ > 1) {
00427         std::cout << "Gio: pt = " << pt << std::endl;
00428         std::cout << "Gio: dz = " << dz << ", sinphi = " << sinphi << ", dphi = " << dphi << ", dz/drphi = " << (dz/dphi/rho) << std::endl;
00429     }
00430     if (helixVerbosity_ > 0) {
00431         std::cout << "Gio's fit P = " << mypq.first << "\n";
00432         std::cout << "Gio's fit Q = " << myq  << "\n";
00433     }
00434 
00435     return mypq;
00436 }
00437 
00438 bool SimpleCosmicBONSeeder::seeds(TrajectorySeedCollection &output, const edm::EventSetup& iSetup)
00439 {
00440     typedef TrajectoryStateOnSurface TSOS;
00441     
00442     for (size_t it=0;it<hitTriplets.size();it++){
00443         const OrderedHitTriplet &trip = hitTriplets[it];
00444 
00445         GlobalPoint inner = tracker->idToDet((*(trip.inner())).geographicalId())->surface().
00446             toGlobal((*(trip.inner())).localPosition());
00447 
00448         GlobalPoint middle = tracker->idToDet((*(trip.middle())).geographicalId())->surface().
00449             toGlobal((*(trip.middle())).localPosition());
00450 
00451         GlobalPoint outer = tracker->idToDet((*(trip.outer())).geographicalId())->surface().
00452             toGlobal((*(trip.outer())).localPosition());   
00453 
00454         if (seedVerbosity_ > 1)
00455             std::cout << "Processing triplet " << it << ": " << inner << " + " << middle << " + " << outer << std::endl;
00456 
00457         if ( (outer.y()-inner.y())*outer.y() < 0 ) {
00458             std::swap(inner,outer);
00459             std::swap(const_cast<TransientTrackingRecHit::ConstRecHitPointer &>(trip.inner()),
00460                       const_cast<TransientTrackingRecHit::ConstRecHitPointer &>(trip.outer()) );
00461 
00462 //            std::swap(const_cast<ctfseeding::SeedingHit &>(trip.inner()), 
00463 //                      const_cast<ctfseeding::SeedingHit &>(trip.outer()) );
00464             if (seedVerbosity_ > 1) {
00465                 std::cout << "The seed was going away from CMS! swapped in <-> out" << std::endl;
00466                 std::cout << "Processing swapped triplet " << it << ": " << inner << " + " << middle << " + " << outer << std::endl;
00467             }
00468         }
00469 
00470         // First use FastHelix out of the box
00471         std::pair<GlobalVector,int> pq = pqFromHelixFit(inner,middle,outer,iSetup);
00472         GlobalVector gv = pq.first;
00473         float        ch = pq.second; 
00474         float Mom = sqrt( gv.x()*gv.x() + gv.y()*gv.y() + gv.z()*gv.z() ); 
00475 
00476         if(Mom > 10000 || edm::isNotFinite(Mom))  { 
00477             if (seedVerbosity_ > 1)
00478                 std::cout << "Processing triplet " << it << ": fail for momentum." << std::endl; 
00479             continue;
00480         }
00481 
00482         if (gv.perp() < region_.ptMin()) {
00483             if (seedVerbosity_ > 1)
00484                 std::cout << "Processing triplet " << it << ": fail for pt = " << gv.perp() << " < ptMin = " << region_.ptMin() << std::endl; 
00485             continue;
00486         }
00487 
00488         const Propagator * propagator = 0;  
00489         if((outer.y()-inner.y())>0){
00490             if (seedVerbosity_ > 1)
00491                 std::cout << "Processing triplet " << it << ":  downgoing." << std::endl; 
00492             propagator = thePropagatorAl;
00493         } else {
00494             gv = -1*gv; ch = -1.*ch;                        
00495             propagator = thePropagatorOp;
00496             if (seedVerbosity_ > 1)
00497                 std::cout << "Processing triplet " << it << ":  upgoing." << std::endl; 
00498         }
00499 
00500         if (seedVerbosity_ > 1) {
00501             if (( gv.z() * (outer.z()-inner.z()) > 0 ) && ( fabs(outer.z()-inner.z()) > 5) && (fabs(gv.z()) > .01))  {
00502                 std::cout << "ORRORE: outer.z()-inner.z() = " << (outer.z()-inner.z()) << ", gv.z() = " << gv.z() << std::endl;
00503             }
00504         }
00505 
00506         GlobalTrajectoryParameters Gtp(outer,
00507                 gv,int(ch), 
00508                 &(*magfield));
00509         FreeTrajectoryState CosmicSeed(Gtp,
00510                 CurvilinearTrajectoryError(AlgebraicSymMatrix55(AlgebraicMatrixID())));  
00511         CosmicSeed.rescaleError(100);
00512         if (seedVerbosity_ > 2) {
00513             std::cout << "Processing triplet " << it << ". start from " << std::endl;
00514             std::cout << "    X  = " << outer << ", P = " << gv << std::endl;
00515             std::cout << "    Cartesian error (X,P) = \n" << CosmicSeed.cartesianError().matrix() << std::endl;
00516         }
00517        
00518         edm::OwnVector<TrackingRecHit> hits;
00519         OrderedHitTriplet seedHits(trip.outer(),trip.middle(),trip.inner());
00520         TSOS propagated, updated;
00521         bool fail = false;
00522         for (size_t ih = 0; ih < 3; ++ih) {
00523             if ((ih == 2) && seedOnMiddle_) {
00524                 if (seedVerbosity_ > 2) 
00525                     std::cout << "Stopping at middle hit, as requested." << std::endl;
00526                 break;
00527             }
00528             if (seedVerbosity_ > 2)
00529                 std::cout << "Processing triplet " << it << ", hit " << ih << "." << std::endl;
00530             if (ih == 0) {
00531                 propagated = propagator->propagate(CosmicSeed, tracker->idToDet((*seedHits[ih]).geographicalId())->surface());
00532             } else {
00533                 propagated = propagator->propagate(updated, tracker->idToDet((*seedHits[ih]).geographicalId())->surface());
00534             }
00535             if (!propagated.isValid()) {
00536                 if (seedVerbosity_ > 1)
00537                     std::cout << "Processing triplet " << it << ", hit " << ih << ": failed propagation." << std::endl;
00538                 fail = true; break;
00539             } else {
00540                 if (seedVerbosity_ > 2)
00541                     std::cout << "Processing triplet " << it << ", hit " << ih << ": propagated state = " << propagated;
00542             }
00543             const TransientTrackingRecHit::ConstRecHitPointer & tthp   = seedHits[ih];
00544             TransientTrackingRecHit::RecHitPointer              newtth = tthp->clone(propagated);
00545             hits.push_back(newtth->hit()->clone());
00546             updated = theUpdator->update(propagated, *newtth);
00547             if (!updated.isValid()) {
00548                 if (seedVerbosity_ > 1)
00549                     std::cout << "Processing triplet " << it << ", hit " << ih << ": failed update." << std::endl;
00550                 fail = true; break;
00551             } else {
00552                 if (seedVerbosity_ > 2)
00553                     std::cout << "Processing triplet " << it << ", hit " << ih << ": updated state = " << updated;
00554             }
00555         }
00556         if (!fail && updated.isValid() && (updated.globalMomentum().perp() < region_.ptMin())) {
00557             if (seedVerbosity_ > 1)
00558                 std::cout << "Processing triplet " << it << 
00559                              ": failed for final pt " << updated.globalMomentum().perp() << " < " << region_.ptMin() << std::endl;
00560             fail = true;
00561         }
00562         if (!fail && updated.isValid() && (updated.globalMomentum().mag() < pMin_)) {
00563             if (seedVerbosity_ > 1)
00564                 std::cout << "Processing triplet " << it << 
00565                              ": failed for final p " << updated.globalMomentum().perp() << " < " << pMin_ << std::endl;
00566             fail = true;
00567         }
00568         if (!fail) {
00569             if (rescaleError_ != 1.0) {
00570                 if (seedVerbosity_ > 2) {
00571                     std::cout << "Processing triplet " << it << ", rescale error by " << rescaleError_ << ": state BEFORE rescaling " << updated;
00572                     std::cout << "    Cartesian error (X,P) before rescaling= \n" << updated.cartesianError().matrix() << std::endl;
00573                 }
00574                 updated.rescaleError(rescaleError_);
00575             }
00576             if (seedVerbosity_ > 0) {
00577                 std::cout << "Processed  triplet " << it << ": success (saved as #"<<output.size()<<") : " 
00578                         << inner << " + " << middle << " + " << outer << std::endl;
00579                 std::cout << "    pt = " << updated.globalMomentum().perp() <<
00580                              "    eta = " << updated.globalMomentum().eta() << 
00581                              "    phi = " << updated.globalMomentum().phi() <<
00582                              "    ch = " << updated.charge() << std::endl;
00583                 if (seedVerbosity_ > 1) {
00584                     std::cout << "    State:" << updated;
00585                 } else {
00586                     std::cout << "    X  = " << updated.globalPosition() << ", P = " << updated.globalMomentum() << std::endl;
00587                 }
00588                 std::cout << "    Cartesian error (X,P) = \n" << updated.cartesianError().matrix() << std::endl;
00589             }
00590             
00591             PTrajectoryStateOnDet const &  PTraj = trajectoryStateTransform::persistentState(updated, 
00592                                                             (*(seedOnMiddle_ ? trip.middle() : trip.inner())).geographicalId().rawId());
00593             output.push_back(TrajectorySeed(PTraj,hits,
00594                                                 ( (outer.y()-inner.y()>0) ? alongMomentum : oppositeToMomentum) ));
00595             if ((maxSeeds_ > 0) && (output.size() > size_t(maxSeeds_))) { 
00596                 output.clear(); 
00597                 edm::LogError("TooManySeeds") << "Found too many seeds, bailing out.\n";
00598                 return false;
00599             }
00600         }
00601     }
00602     return true;
00603 }
00604 
00605 void SimpleCosmicBONSeeder::done(){
00606   delete thePropagatorAl;
00607   delete thePropagatorOp;
00608   delete theUpdator;
00609 }
00610 
00611