CMS 3D CMS Logo

CMSSW_4_4_3_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 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 bool SimpleCosmicBONSeeder::checkCharge(const SiStripRecHit2D &hit, int subdetid) const {
00327     const SiStripCluster *clust = (hit.cluster().isNonnull() ?  hit.cluster().get() : hit.cluster_regional().get());
00328     int charge = std::accumulate(clust->amplitudes().begin(), clust->amplitudes().end(), int(0));
00329     if (tripletsVerbosity_ > 1) {
00330         std::cerr << "Hit on " << subdetid << ", charge = " << charge << ", threshold = " << chargeThresholds_[subdetid] 
00331                   << ", detid = " <<  hit.geographicalId().rawId() << ", firstStrip = " << clust->firstStrip() << std::endl;
00332     } else if ((tripletsVerbosity_ == 1) && (charge < chargeThresholds_[subdetid])) {
00333         std::cerr << "Hit on " << subdetid << ", charge = " << charge << ", threshold = " << chargeThresholds_[subdetid] 
00334                   << ", detid = " <<  hit.geographicalId().rawId() << ", firstStrip = " << clust->firstStrip() << std::endl;
00335     }
00336     return charge > chargeThresholds_[subdetid];
00337 }
00338 
00339 void SimpleCosmicBONSeeder::checkNoisyModules(const std::vector<TransientTrackingRecHit::RecHitPointer> &hits, std::vector<bool> &oks) const {
00340     typedef TransientTrackingRecHit::RecHitPointer TTRH;
00341     std::vector<TTRH>::const_iterator it = hits.begin(),  start = it,   end = hits.end();
00342     std::vector<bool>::iterator       ok = oks.begin(), okStart = ok, okEnd = oks.end();
00343     while (start < end) {
00344         DetId lastid = (*start)->geographicalId();
00345         for (it = start + 1; (it < end) && ((*it)->geographicalId() == lastid); ++it) {
00346             ++ok;
00347         }
00348         if ( (it - start) > maxHitsPerModule_[lastid.subdetId()] ) { 
00349             if (tripletsVerbosity_ > 0) {
00350                 std::cerr << "SimpleCosmicBONSeeder: Marking noisy module " << lastid.rawId() << ", it has " << (it-start) << " rechits"
00351                           << " (threshold is " << maxHitsPerModule_[lastid.subdetId()] << ")" << std::endl;
00352             }
00353             std::fill(okStart,ok,false);
00354         } else if (tripletsVerbosity_ > 0) {
00355             if ( (it - start) > std::min(4,maxHitsPerModule_[lastid.subdetId()]/4) ) {
00356                 std::cerr << "SimpleCosmicBONSeeder: Not marking noisy module " << lastid.rawId() << ", it has " << (it-start) << " rechits"
00357                           << " (threshold is " << maxHitsPerModule_[lastid.subdetId()] << ")" << std::endl;
00358             }
00359         }
00360         start = it; okStart = ok;
00361     }
00362 }
00363 
00364 bool SimpleCosmicBONSeeder::goodTriplet(const GlobalPoint &inner, const GlobalPoint & middle, const GlobalPoint & outer, const double &minRho) const {
00365     float dyOM = outer.y() - middle.y(), dyIM = inner.y() - middle.y();
00366     if ((dyOM * dyIM > 0) && (fabs(dyOM)>10) && (fabs(dyIM)>10)) {
00367         if (tripletsVerbosity_ > 2) std::cout << "  fail for non coherent dy" << std::endl;
00368         return false;
00369     }
00370     float dzOM = outer.z() - middle.z(), dzIM = inner.z() - middle.z();
00371     if ((dzOM * dzIM > 0) && (fabs(dzOM)>50) && (fabs(dzIM)>50)) {
00372         if (tripletsVerbosity_ > 2) std::cout << "  fail for non coherent dz" << std::endl;
00373         return false;
00374     }
00375     if (minRho > 0) {
00376         FastCircle theCircle(inner,middle,outer);
00377         if (theCircle.rho() < minRho) {
00378             if (tripletsVerbosity_ > 2) std::cout << "  fail for pt cut" << std::endl;
00379             return false;
00380         }
00381     }
00382     return true;
00383 }
00384 
00385 std::pair<GlobalVector,int>
00386 SimpleCosmicBONSeeder::pqFromHelixFit(const GlobalPoint &inner, const GlobalPoint & middle, const GlobalPoint & outer, 
00387                                                          const edm::EventSetup& iSetup) const {
00388     if (helixVerbosity_ > 0) {
00389         std::cout << "DEBUG PZ =====" << std::endl;
00390         FastHelix helix(inner,middle,outer,iSetup);
00391         GlobalVector gv=helix.stateAtVertex().parameters().momentum(); // status on inner hit
00392         std::cout << "FastHelix P = " << gv   << "\n";
00393         std::cout << "FastHelix Q = " << helix.stateAtVertex().parameters().charge() << "\n";
00394     }
00395 
00396     // My attempt (with different approx from FastHelix)
00397     // 1) fit the circle
00398     FastCircle theCircle(inner,middle,outer);
00399     double rho = theCircle.rho();
00400 
00401     // 2) Get the PT
00402     GlobalVector tesla = magfield->inTesla(middle);
00403     double pt = 0.01 * rho * (0.3*tesla.z());
00404 
00405     // 3) Get the PX,PY at OUTER hit (VERTEX)
00406     double dx1 = outer.x()-theCircle.x0();
00407     double dy1 = outer.y()-theCircle.y0();
00408     double py = pt*dx1/rho, px = -pt*dy1/rho;
00409     if(px*(middle.x() - outer.x()) + py*(middle.y() - outer.y()) < 0.) {
00410         px *= -1.; py *= -1.;
00411     }
00412 
00413     // 4) Get the PZ through pz = pT*(dz/d(R*phi)))
00414     double dz = inner.z() - outer.z();
00415     double sinphi = ( dx1*(inner.y()-theCircle.y0()) - dy1*(inner.x()-theCircle.x0())) / (rho * rho);
00416     double dphi = std::abs(std::asin(sinphi));
00417     double pz = pt * dz / (dphi * rho); 
00418 
00419     int myq = ((theCircle.x0()*py - theCircle.y0()*px) / tesla.z()) > 0. ?  +1 : -1;
00420     
00421     std::pair<GlobalVector,int> mypq(GlobalVector(px,py,pz),myq);
00422 
00423     if (helixVerbosity_ > 1) {
00424         std::cout << "Gio: pt = " << pt << std::endl;
00425         std::cout << "Gio: dz = " << dz << ", sinphi = " << sinphi << ", dphi = " << dphi << ", dz/drphi = " << (dz/dphi/rho) << std::endl;
00426     }
00427     if (helixVerbosity_ > 0) {
00428         std::cout << "Gio's fit P = " << mypq.first << "\n";
00429         std::cout << "Gio's fit Q = " << myq  << "\n";
00430     }
00431 
00432     return mypq;
00433 }
00434 
00435 bool SimpleCosmicBONSeeder::seeds(TrajectorySeedCollection &output, const edm::EventSetup& iSetup)
00436 {
00437     typedef TrajectoryStateOnSurface TSOS;
00438     
00439     for (size_t it=0;it<hitTriplets.size();it++){
00440         const OrderedHitTriplet &trip = hitTriplets[it];
00441 
00442         GlobalPoint inner = tracker->idToDet((*(trip.inner())).geographicalId())->surface().
00443             toGlobal((*(trip.inner())).localPosition());
00444 
00445         GlobalPoint middle = tracker->idToDet((*(trip.middle())).geographicalId())->surface().
00446             toGlobal((*(trip.middle())).localPosition());
00447 
00448         GlobalPoint outer = tracker->idToDet((*(trip.outer())).geographicalId())->surface().
00449             toGlobal((*(trip.outer())).localPosition());   
00450 
00451         if (seedVerbosity_ > 1)
00452             std::cout << "Processing triplet " << it << ": " << inner << " + " << middle << " + " << outer << std::endl;
00453 
00454         if ( (outer.y()-inner.y())*outer.y() < 0 ) {
00455             std::swap(inner,outer);
00456             std::swap(const_cast<TransientTrackingRecHit::ConstRecHitPointer &>(trip.inner()),
00457                       const_cast<TransientTrackingRecHit::ConstRecHitPointer &>(trip.outer()) );
00458 
00459 //            std::swap(const_cast<ctfseeding::SeedingHit &>(trip.inner()), 
00460 //                      const_cast<ctfseeding::SeedingHit &>(trip.outer()) );
00461             if (seedVerbosity_ > 1) {
00462                 std::cout << "The seed was going away from CMS! swapped in <-> out" << std::endl;
00463                 std::cout << "Processing swapped triplet " << it << ": " << inner << " + " << middle << " + " << outer << std::endl;
00464             }
00465         }
00466 
00467         // First use FastHelix out of the box
00468         std::pair<GlobalVector,int> pq = pqFromHelixFit(inner,middle,outer,iSetup);
00469         GlobalVector gv = pq.first;
00470         float        ch = pq.second; 
00471         float Mom = sqrt( gv.x()*gv.x() + gv.y()*gv.y() + gv.z()*gv.z() ); 
00472 
00473         if(Mom > 10000 || isnan(Mom))  { 
00474             if (seedVerbosity_ > 1)
00475                 std::cout << "Processing triplet " << it << ": fail for momentum." << std::endl; 
00476             continue;
00477         }
00478 
00479         if (gv.perp() < region_.ptMin()) {
00480             if (seedVerbosity_ > 1)
00481                 std::cout << "Processing triplet " << it << ": fail for pt = " << gv.perp() << " < ptMin = " << region_.ptMin() << std::endl; 
00482             continue;
00483         }
00484 
00485         const Propagator * propagator = 0;  
00486         if((outer.y()-inner.y())>0){
00487             if (seedVerbosity_ > 1)
00488                 std::cout << "Processing triplet " << it << ":  downgoing." << std::endl; 
00489             propagator = thePropagatorAl;
00490         } else {
00491             gv = -1*gv; ch = -1.*ch;                        
00492             propagator = thePropagatorOp;
00493             if (seedVerbosity_ > 1)
00494                 std::cout << "Processing triplet " << it << ":  upgoing." << std::endl; 
00495         }
00496 
00497         if (seedVerbosity_ > 1) {
00498             if (( gv.z() * (outer.z()-inner.z()) > 0 ) && ( fabs(outer.z()-inner.z()) > 5) && (fabs(gv.z()) > .01))  {
00499                 std::cout << "ORRORE: outer.z()-inner.z() = " << (outer.z()-inner.z()) << ", gv.z() = " << gv.z() << std::endl;
00500             }
00501         }
00502 
00503         GlobalTrajectoryParameters Gtp(outer,
00504                 gv,int(ch), 
00505                 &(*magfield));
00506         FreeTrajectoryState CosmicSeed(Gtp,
00507                 CurvilinearTrajectoryError(AlgebraicSymMatrix55(AlgebraicMatrixID())));  
00508         CosmicSeed.rescaleError(100);
00509         if (seedVerbosity_ > 2) {
00510             std::cout << "Processing triplet " << it << ". start from " << std::endl;
00511             std::cout << "    X  = " << outer << ", P = " << gv << std::endl;
00512             std::cout << "    Cartesian error (X,P) = \n" << CosmicSeed.cartesianError().matrix() << std::endl;
00513         }
00514        
00515         edm::OwnVector<TrackingRecHit> hits;
00516 //      OrderedHitTriplet::Hits seedHits;
00517         OrderedHitTriplet::RecHits seedHits;
00518         seedHits.push_back(trip.outer());
00519         seedHits.push_back(trip.middle());
00520         seedHits.push_back(trip.inner());
00521         TSOS propagated, updated;
00522         bool fail = false;
00523         for (size_t ih = 0; ih < 3; ++ih) {
00524             if ((ih == 2) && seedOnMiddle_) {
00525                 if (seedVerbosity_ > 2) 
00526                     std::cout << "Stopping at middle hit, as requested." << std::endl;
00527                 break;
00528             }
00529             if (seedVerbosity_ > 2)
00530                 std::cout << "Processing triplet " << it << ", hit " << ih << "." << std::endl;
00531             if (ih == 0) {
00532                 propagated = propagator->propagate(CosmicSeed, tracker->idToDet((*seedHits[ih]).geographicalId())->surface());
00533             } else {
00534                 propagated = propagator->propagate(updated, tracker->idToDet((*seedHits[ih]).geographicalId())->surface());
00535             }
00536             if (!propagated.isValid()) {
00537                 if (seedVerbosity_ > 1)
00538                     std::cout << "Processing triplet " << it << ", hit " << ih << ": failed propagation." << std::endl;
00539                 fail = true; break;
00540             } else {
00541                 if (seedVerbosity_ > 2)
00542                     std::cout << "Processing triplet " << it << ", hit " << ih << ": propagated state = " << propagated;
00543             }
00544             const TransientTrackingRecHit::ConstRecHitPointer & tthp   = seedHits[ih];
00545             TransientTrackingRecHit::RecHitPointer              newtth = tthp->clone(propagated);
00546             hits.push_back(newtth->hit()->clone());
00547             updated = theUpdator->update(propagated, *newtth);
00548             if (!updated.isValid()) {
00549                 if (seedVerbosity_ > 1)
00550                     std::cout << "Processing triplet " << it << ", hit " << ih << ": failed update." << std::endl;
00551                 fail = true; break;
00552             } else {
00553                 if (seedVerbosity_ > 2)
00554                     std::cout << "Processing triplet " << it << ", hit " << ih << ": updated state = " << updated;
00555             }
00556         }
00557         if (!fail && updated.isValid() && (updated.globalMomentum().perp() < region_.ptMin())) {
00558             if (seedVerbosity_ > 1)
00559                 std::cout << "Processing triplet " << it << 
00560                              ": failed for final pt " << updated.globalMomentum().perp() << " < " << region_.ptMin() << std::endl;
00561             fail = true;
00562         }
00563         if (!fail && updated.isValid() && (updated.globalMomentum().mag() < pMin_)) {
00564             if (seedVerbosity_ > 1)
00565                 std::cout << "Processing triplet " << it << 
00566                              ": failed for final p " << updated.globalMomentum().perp() << " < " << pMin_ << std::endl;
00567             fail = true;
00568         }
00569         if (!fail) {
00570             if (rescaleError_ != 1.0) {
00571                 if (seedVerbosity_ > 2) {
00572                     std::cout << "Processing triplet " << it << ", rescale error by " << rescaleError_ << ": state BEFORE rescaling " << updated;
00573                     std::cout << "    Cartesian error (X,P) before rescaling= \n" << updated.cartesianError().matrix() << std::endl;
00574                 }
00575                 updated.rescaleError(rescaleError_);
00576             }
00577             if (seedVerbosity_ > 0) {
00578                 std::cout << "Processed  triplet " << it << ": success (saved as #"<<output.size()<<") : " 
00579                         << inner << " + " << middle << " + " << outer << std::endl;
00580                 std::cout << "    pt = " << updated.globalMomentum().perp() <<
00581                              "    eta = " << updated.globalMomentum().eta() << 
00582                              "    phi = " << updated.globalMomentum().phi() <<
00583                              "    ch = " << updated.charge() << std::endl;
00584                 if (seedVerbosity_ > 1) {
00585                     std::cout << "    State:" << updated;
00586                 } else {
00587                     std::cout << "    X  = " << updated.globalPosition() << ", P = " << updated.globalMomentum() << std::endl;
00588                 }
00589                 std::cout << "    Cartesian error (X,P) = \n" << updated.cartesianError().matrix() << std::endl;
00590             }
00591             
00592             std::auto_ptr<PTrajectoryStateOnDet> PTraj(transformer.persistentState(updated, 
00593                                                             (*(seedOnMiddle_ ? trip.middle() : trip.inner())).geographicalId().rawId()));
00594             output.push_back(TrajectorySeed(*PTraj,hits,
00595                                                 ( (outer.y()-inner.y()>0) ? alongMomentum : oppositeToMomentum) ));
00596             if ((maxSeeds_ > 0) && (output.size() > size_t(maxSeeds_))) { 
00597                 output.clear(); 
00598                 edm::LogError("TooManySeeds") << "Found too many seeds, bailing out.\n";
00599                 return false;
00600             }
00601         }
00602     }
00603     return true;
00604 }
00605 
00606 void SimpleCosmicBONSeeder::done(){
00607   delete thePropagatorAl;
00608   delete thePropagatorOp;
00609   delete theUpdator;
00610 }
00611 
00612