CMS 3D CMS Logo

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