diff --git a/MagneticField/GeomBuilder/plugins/AutoMagneticFieldESProducer.cc b/MagneticField/GeomBuilder/plugins/AutoMagneticFieldESProducer.cc index ce3f54d368ddb..bcf11e3a7da23 100644 --- a/MagneticField/GeomBuilder/plugins/AutoMagneticFieldESProducer.cc +++ b/MagneticField/GeomBuilder/plugins/AutoMagneticFieldESProducer.cc @@ -26,10 +26,9 @@ using namespace std; using namespace edm; using namespace magneticfield; - AutoMagneticFieldESProducer::AutoMagneticFieldESProducer(const edm::ParameterSet& iConfig) : pset(iConfig) { - setWhatProduced(this, pset.getUntrackedParameter("label","")); - nominalCurrents = pset.getUntrackedParameter >("nominalCurrents"); + setWhatProduced(this, pset.getUntrackedParameter("label", "")); + nominalCurrents = pset.getUntrackedParameter >("nominalCurrents"); maps = pset.getUntrackedParameter >("mapLabels"); if (maps.empty() || (maps.size() != nominalCurrents.size())) { @@ -37,15 +36,9 @@ AutoMagneticFieldESProducer::AutoMagneticFieldESProducer(const edm::ParameterSet } } +AutoMagneticFieldESProducer::~AutoMagneticFieldESProducer() {} -AutoMagneticFieldESProducer::~AutoMagneticFieldESProducer() -{ -} - - -std::unique_ptr -AutoMagneticFieldESProducer::produce(const IdealMagneticFieldRecord& iRecord) -{ +std::unique_ptr AutoMagneticFieldESProducer::produce(const IdealMagneticFieldRecord& iRecord) { float current = pset.getParameter("valueOverride"); string message; @@ -59,33 +52,28 @@ AutoMagneticFieldESProducer::produce(const IdealMagneticFieldRecord& iRecord) message = " (from valueOverride card)"; } - string model = closerModel(current); - - edm::LogInfo("MagneticField|AutoMagneticField") << "Current: " << current << message << "; using map with label: " << model; + string model = closerModel(current); + edm::LogInfo("MagneticField|AutoMagneticField") + << "Current: " << current << message << "; using map with label: " << model; edm::ESHandle map; - - iRecord.get(model,map); + + iRecord.get(model, map); MagneticField* result = map.product()->clone(); return std::unique_ptr(result); } - std::string AutoMagneticFieldESProducer::closerModel(float current) { - int i=0; - for(;i<(int)maps.size()-1;i++) { - if(2*current < nominalCurrents[i]+nominalCurrents[i+1] ) + int i = 0; + for (; i < (int)maps.size() - 1; i++) { + if (2 * current < nominalCurrents[i] + nominalCurrents[i + 1]) return maps[i]; } - return maps[i]; + return maps[i]; } - - #include "FWCore/Framework/interface/ModuleFactory.h" DEFINE_FWK_EVENTSETUP_MODULE(AutoMagneticFieldESProducer); - - diff --git a/MagneticField/GeomBuilder/plugins/AutoMagneticFieldESProducer.h b/MagneticField/GeomBuilder/plugins/AutoMagneticFieldESProducer.h index cd452802d13cc..d889cd412aa33 100644 --- a/MagneticField/GeomBuilder/plugins/AutoMagneticFieldESProducer.h +++ b/MagneticField/GeomBuilder/plugins/AutoMagneticFieldESProducer.h @@ -19,19 +19,19 @@ class IdealMagneticFieldRecord; namespace magneticfield { - class AutoMagneticFieldESProducer : public edm::ESProducer - { + class AutoMagneticFieldESProducer : public edm::ESProducer { public: AutoMagneticFieldESProducer(const edm::ParameterSet&); ~AutoMagneticFieldESProducer() override; - + std::unique_ptr produce(const IdealMagneticFieldRecord&); edm::ParameterSet pset; + private: std::string closerModel(float current); std::vector nominalCurrents; std::vector maps; }; -} +} // namespace magneticfield #endif diff --git a/MagneticField/GeomBuilder/plugins/VolumeBasedMagneticFieldESProducer.cc b/MagneticField/GeomBuilder/plugins/VolumeBasedMagneticFieldESProducer.cc index 42a46266a8530..007d108af120b 100644 --- a/MagneticField/GeomBuilder/plugins/VolumeBasedMagneticFieldESProducer.cc +++ b/MagneticField/GeomBuilder/plugins/VolumeBasedMagneticFieldESProducer.cc @@ -27,14 +27,13 @@ using namespace std; using namespace magneticfield; -VolumeBasedMagneticFieldESProducer::VolumeBasedMagneticFieldESProducer(const edm::ParameterSet& iConfig) : pset(iConfig) -{ - setWhatProduced(this, pset.getUntrackedParameter("label","")); +VolumeBasedMagneticFieldESProducer::VolumeBasedMagneticFieldESProducer(const edm::ParameterSet& iConfig) + : pset(iConfig) { + setWhatProduced(this, pset.getUntrackedParameter("label", "")); } // ------------ method called to produce the data ------------ -std::unique_ptr VolumeBasedMagneticFieldESProducer::produce(const IdealMagneticFieldRecord & iRecord) -{ +std::unique_ptr VolumeBasedMagneticFieldESProducer::produce(const IdealMagneticFieldRecord& iRecord) { bool debug = pset.getUntrackedParameter("debugBuilder", false); if (debug) { cout << "VolumeBasedMagneticFieldESProducer::produce() " << pset.getParameter("version") << endl; @@ -43,33 +42,36 @@ std::unique_ptr VolumeBasedMagneticFieldESProducer::produce(const MagFieldConfig conf(pset, debug); edm::ESTransientHandle cpv; - iRecord.get("magfield",cpv ); - MagGeoBuilderFromDDD builder(conf.version, - conf.geometryVersion, - debug); + iRecord.get("magfield", cpv); + MagGeoBuilderFromDDD builder(conf.version, conf.geometryVersion, debug); // Set scaling factors if (!conf.keys.empty()) { builder.setScaling(conf.keys, conf.values); } - + // Set specification for the grid tables to be used. if (!conf.gridFiles.empty()) { builder.setGridFiles(conf.gridFiles); } - + builder.build(*cpv); // Get slave field (from ES) edm::ESHandle paramField; - if (pset.getParameter("useParametrizedTrackerField")) {; - iRecord.get(pset.getParameter("paramLabel"),paramField); + if (pset.getParameter("useParametrizedTrackerField")) { + ; + iRecord.get(pset.getParameter("paramLabel"), paramField); } - return std::make_unique(conf.geometryVersion,builder.barrelLayers(), builder.endcapSectors(), builder.barrelVolumes(), builder.endcapVolumes(), builder.maxR(), builder.maxZ(), paramField.product(), false); + return std::make_unique(conf.geometryVersion, + builder.barrelLayers(), + builder.endcapSectors(), + builder.barrelVolumes(), + builder.endcapVolumes(), + builder.maxR(), + builder.maxZ(), + paramField.product(), + false); } - - - - DEFINE_FWK_EVENTSETUP_MODULE(VolumeBasedMagneticFieldESProducer); diff --git a/MagneticField/GeomBuilder/plugins/VolumeBasedMagneticFieldESProducer.h b/MagneticField/GeomBuilder/plugins/VolumeBasedMagneticFieldESProducer.h index 37c3b0f2d95a6..e263501349a81 100644 --- a/MagneticField/GeomBuilder/plugins/VolumeBasedMagneticFieldESProducer.h +++ b/MagneticField/GeomBuilder/plugins/VolumeBasedMagneticFieldESProducer.h @@ -21,8 +21,8 @@ namespace magneticfield { class VolumeBasedMagneticFieldESProducer : public edm::ESProducer { public: VolumeBasedMagneticFieldESProducer(const edm::ParameterSet& iConfig); - - std::unique_ptr produce(const IdealMagneticFieldRecord & iRecord); + + std::unique_ptr produce(const IdealMagneticFieldRecord& iRecord); private: // forbid copy ctor and assignment op. @@ -31,7 +31,6 @@ namespace magneticfield { edm::ParameterSet pset; }; -} - +} // namespace magneticfield #endif diff --git a/MagneticField/GeomBuilder/plugins/VolumeBasedMagneticFieldESProducerFromDB.cc b/MagneticField/GeomBuilder/plugins/VolumeBasedMagneticFieldESProducerFromDB.cc index 77ef777193542..5f1dea19118d8 100644 --- a/MagneticField/GeomBuilder/plugins/VolumeBasedMagneticFieldESProducerFromDB.cc +++ b/MagneticField/GeomBuilder/plugins/VolumeBasedMagneticFieldESProducerFromDB.cc @@ -51,8 +51,8 @@ namespace magneticfield { class VolumeBasedMagneticFieldESProducerFromDB : public edm::ESProducer { public: VolumeBasedMagneticFieldESProducerFromDB(const edm::ParameterSet& iConfig); - - std::unique_ptr produce(const IdealMagneticFieldRecord & iRecord); + + std::unique_ptr produce(const IdealMagneticFieldRecord& iRecord); private: // forbid copy ctor and assignment op. @@ -63,24 +63,19 @@ namespace magneticfield { edm::ParameterSet pset; std::vector nominalCurrents; std::vector nominalLabels; - }; -} +} // namespace magneticfield - -VolumeBasedMagneticFieldESProducerFromDB::VolumeBasedMagneticFieldESProducerFromDB(const edm::ParameterSet& iConfig) : pset(iConfig) -{ - setWhatProduced(this, pset.getUntrackedParameter("label","")); - nominalCurrents={-1, 0,9558,14416,16819,18268,19262}; - nominalLabels ={"3.8T","0T","2T", "3T", "3.5T", "3.8T", "4T"}; +VolumeBasedMagneticFieldESProducerFromDB::VolumeBasedMagneticFieldESProducerFromDB(const edm::ParameterSet& iConfig) + : pset(iConfig) { + setWhatProduced(this, pset.getUntrackedParameter("label", "")); + nominalCurrents = {-1, 0, 9558, 14416, 16819, 18268, 19262}; + nominalLabels = {"3.8T", "0T", "2T", "3T", "3.5T", "3.8T", "4T"}; } - - // ------------ method called to produce the data ------------ -std::unique_ptr VolumeBasedMagneticFieldESProducerFromDB::produce(const IdealMagneticFieldRecord & iRecord) -{ - +std::unique_ptr VolumeBasedMagneticFieldESProducerFromDB::produce( + const IdealMagneticFieldRecord& iRecord) { bool debug = pset.getUntrackedParameter("debugBuilder", false); // Get value of the current from condition DB @@ -94,45 +89,43 @@ std::unique_ptr VolumeBasedMagneticFieldESProducerFromDB::produce } else { message = " (from valueOverride card)"; } - string configLabel = closerNominalLabel(current); + string configLabel = closerNominalLabel(current); // Get configuration ESHandle confESH; iRecord.getRecord().get(configLabel, confESH); const MagFieldConfig* conf = &*confESH; - edm::LogInfo("MagneticField|AutoMagneticField") << "Current: " << current << message << "; using map configuration with label: " << configLabel << endl - << "Version: " << conf->version - << " geometryVersion: " << conf->geometryVersion - << " slaveFieldVersion: " << conf->slaveFieldVersion; + edm::LogInfo("MagneticField|AutoMagneticField") + << "Current: " << current << message << "; using map configuration with label: " << configLabel << endl + << "Version: " << conf->version << " geometryVersion: " << conf->geometryVersion + << " slaveFieldVersion: " << conf->slaveFieldVersion; // Get the parametrized field - std::unique_ptr paramField = ParametrizedMagneticFieldFactory::get(conf->slaveFieldVersion, conf->slaveFieldParameters); - + std::unique_ptr paramField = + ParametrizedMagneticFieldFactory::get(conf->slaveFieldVersion, conf->slaveFieldParameters); if (conf->version == "parametrizedMagneticField") { // The map consist of only the parametrization in this case return paramField; } else { // Full VolumeBased map + parametrization - MagGeoBuilderFromDDD builder(conf->version, - conf->geometryVersion, - debug); + MagGeoBuilderFromDDD builder(conf->version, conf->geometryVersion, debug); // Set scaling factors if (!conf->keys.empty()) { builder.setScaling(conf->keys, conf->values); } - + // Set specification for the grid tables to be used. if (!conf->gridFiles.empty()) { builder.setGridFiles(conf->gridFiles); } // Build the geomeytry (DDDCompactView) from the DB blob - // (code taken from GeometryReaders/XMLIdealGeometryESSource/src/XMLIdealMagneticFieldGeometryESProducer.cc) + // (code taken from GeometryReaders/XMLIdealGeometryESSource/src/XMLIdealMagneticFieldGeometryESProducer.cc) edm::ESTransientHandle gdd; - iRecord.getRecord().get( std::to_string(conf->geometryVersion), gdd ); + iRecord.getRecord().get(std::to_string(conf->geometryVersion), gdd); auto cpv = std::make_unique(DDName("cmsMagneticField:MAGF")); DDLParser parser(*cpv); @@ -141,24 +134,29 @@ std::unique_ptr VolumeBasedMagneticFieldESProducerFromDB::produce std::unique_ptr > tb = (*gdd).getUncompressedBlob(); parser.parse(*tb, tb->size()); cpv->lockdown(); - + builder.build(*cpv); // Build the VB map. Ownership of the parametrization is transferred to it - return std::make_unique(conf->geometryVersion,builder.barrelLayers(), builder.endcapSectors(), builder.barrelVolumes(), builder.endcapVolumes(), builder.maxR(), builder.maxZ(), paramField.release(), true); + return std::make_unique(conf->geometryVersion, + builder.barrelLayers(), + builder.endcapSectors(), + builder.barrelVolumes(), + builder.endcapVolumes(), + builder.maxR(), + builder.maxZ(), + paramField.release(), + true); } } - std::string VolumeBasedMagneticFieldESProducerFromDB::closerNominalLabel(float current) { - - int i=0; - for(;i<(int)nominalLabels.size()-1;i++) { - if(2*current < nominalCurrents[i]+nominalCurrents[i+1] ) + int i = 0; + for (; i < (int)nominalLabels.size() - 1; i++) { + if (2 * current < nominalCurrents[i] + nominalCurrents[i + 1]) return nominalLabels[i]; } return nominalLabels[i]; } - DEFINE_FWK_EVENTSETUP_MODULE(VolumeBasedMagneticFieldESProducerFromDB); diff --git a/MagneticField/GeomBuilder/src/FakeInterpolator.h b/MagneticField/GeomBuilder/src/FakeInterpolator.h index 3c2800f00d7c4..5f078b5ff5827 100644 --- a/MagneticField/GeomBuilder/src/FakeInterpolator.h +++ b/MagneticField/GeomBuilder/src/FakeInterpolator.h @@ -8,18 +8,16 @@ * \author N. Amapane - CERN */ - #include "MagneticField/Interpolation/interface/MagProviderInterpol.h" +#include "MagneticField/Interpolation/interface/MagProviderInterpol.h" namespace magneticfield { -class FakeInterpolator : public MagProviderInterpol { - public: - /// Constructor - FakeInterpolator() {}; - - // Operations - LocalVectorType valueInTesla( const LocalPointType& p) const override { - return LocalVectorType(0.,0.,0.); - } -}; -} + class FakeInterpolator : public MagProviderInterpol { + public: + /// Constructor + FakeInterpolator(){}; + + // Operations + LocalVectorType valueInTesla(const LocalPointType& p) const override { return LocalVectorType(0., 0., 0.); } + }; +} // namespace magneticfield #endif diff --git a/MagneticField/GeomBuilder/src/MagGeoBuilderFromDDD.cc b/MagneticField/GeomBuilder/src/MagGeoBuilderFromDDD.cc index 9b0a7d2858f7e..fd80822e0e104 100644 --- a/MagneticField/GeomBuilder/src/MagGeoBuilderFromDDD.cc +++ b/MagneticField/GeomBuilder/src/MagGeoBuilderFromDDD.cc @@ -51,72 +51,66 @@ #include #include "Utilities/General/interface/precomputed_value_sort.h" - bool MagGeoBuilderFromDDD::debug; using namespace std; using namespace magneticfield; - -MagGeoBuilderFromDDD::MagGeoBuilderFromDDD(string tableSet_,int geometryVersion_, bool debug_) : - tableSet (tableSet_), - geometryVersion(geometryVersion_), - theGridFiles(nullptr) -{ +MagGeoBuilderFromDDD::MagGeoBuilderFromDDD(string tableSet_, int geometryVersion_, bool debug_) + : tableSet(tableSet_), geometryVersion(geometryVersion_), theGridFiles(nullptr) { debug = debug_; - if (debug) cout << "Constructing a MagGeoBuilderFromDDD" < ptrs; + set ptrs; handles::const_iterator first = volumes.begin(); handles::const_iterator last = volumes.end(); - for (handles::const_iterator i=first; i!=last; ++i){ - if (int((*i)->shape())>4) continue; // FIXME: implement test for missing shapes... + for (handles::const_iterator i = first; i != last; ++i) { + if (int((*i)->shape()) > 4) + continue; // FIXME: implement test for missing shapes... for (int side = 0; side < 6; ++side) { - int references = (*i)->references(side); + int references = (*i)->references(side); if ((*i)->isPlaneMatched(side)) { - ++iassigned; - bool firstOcc = (ptrs.insert(&((*i)->surface(side)))).second; - if (firstOcc) iref_ass+=references; - if (references<2){ - cout << "*** Only 1 ref, vol: " << (*i)->volumeno << " # " - << (*i)->copyno << " side: " << side << endl; - } + ++iassigned; + bool firstOcc = (ptrs.insert(&((*i)->surface(side)))).second; + if (firstOcc) + iref_ass += references; + if (references < 2) { + cout << "*** Only 1 ref, vol: " << (*i)->volumeno << " # " << (*i)->copyno << " side: " << side << endl; + } } else { - iref_nass+=references; - if (references>1){ - cout << "*** Ref_nass >1 " < 1) { + cout << "*** Ref_nass >1 " << endl; + } } } } iunique = ptrs.size(); - cout << " volumes " << ivolumes << endl + cout << " volumes " << ivolumes << endl << " surfaces " << isurfaces << endl << " assigned " << iassigned << endl << " unique " << iunique << endl @@ -124,147 +118,152 @@ void MagGeoBuilderFromDDD::summary(handles & volumes){ << " iref_nass " << iref_nass << endl; } - -void MagGeoBuilderFromDDD::build(const DDCompactView & cpva) -{ -// DDCompactView cpv; +void MagGeoBuilderFromDDD::build(const DDCompactView& cpva) { + // DDCompactView cpv; DDExpandedView fv(cpva); - if (debug) cout << "**********************************************************" < bInterpolators; map eInterpolators; - + // Counter of different volumes int bVolCount = 0; int eVolCount = 0; - if (fv.logicalPart().name().name()!="MAGF") { - std::string topNodeName(fv.logicalPart().name().name()); - - //see if one of the children is MAGF - bool doSubDets = fv.firstChild(); - - bool go=true; - while(go&& doSubDets) { - if (fv.logicalPart().name().name()=="MAGF") - break; - else - go = fv.nextSibling(); - } - if (!go) { - throw cms::Exception("NoMAGFinDDD")<<" Neither the top node, nor any child node of the DDCompactView is \"MAGF\" but the top node is instead \""<volumeno)*100+v->copyno; + if (theGridFiles != nullptr) { + int key = (v->volumeno) * 100 + v->copyno; TableFileMap::const_iterator itable = theGridFiles->find(key); if (itable == theGridFiles->end()) { - key = (v->volumeno)*100; - itable = theGridFiles->find(key); + key = (v->volumeno) * 100; + itable = theGridFiles->find(key); } if (itable != theGridFiles->end()) { - string magFile = (*itable).second.first; - stringstream conv; - string svol, ssec; - conv << setfill('0') << setw(3) << v->volumeno << " " << setw(2) << v->copyno; // volume assumed to have 0s padding to 3 digits; sector assumed to have 0s padding to 2 digits - conv >> svol >> ssec; - boost::replace_all(magFile, "[v]",svol); - boost::replace_all(magFile, "[s]",ssec); - int masterSector = (*itable).second.second; - if (masterSector==0) masterSector=v->copyno; - v->magFile = magFile; - v->masterSector = masterSector; + string magFile = (*itable).second.first; + stringstream conv; + string svol, ssec; + conv << setfill('0') << setw(3) << v->volumeno << " " << setw(2) + << v->copyno; // volume assumed to have 0s padding to 3 digits; sector assumed to have 0s padding to 2 digits + conv >> svol >> ssec; + boost::replace_all(magFile, "[v]", svol); + boost::replace_all(magFile, "[s]", ssec); + int masterSector = (*itable).second.second; + if (masterSector == 0) + masterSector = v->copyno; + v->magFile = magFile; + v->masterSector = masterSector; } else { - edm::LogError("MagGeoBuilderFromDDDbuild") << "ERROR: no table spec found for V " << v->volumeno << ":" << v->copyno; + edm::LogError("MagGeoBuilderFromDDDbuild") + << "ERROR: no table spec found for V " << v->volumeno << ":" << v->copyno; } } - // Select volumes, build volume handles. float Z = v->center().z(); float R = v->center().perp(); - // v 85l: Barrel is everything up to |Z| = 661.0, excluding + // v 85l: Barrel is everything up to |Z| = 661.0, excluding // volume #7, centered at 6477.5 // v 1103l: same numbers work fine. #16 instead of #7, same coords; // see comment below for V6,7 //ASSUMPTION: no misalignment is applied to mag volumes. //FIXME: implement barrel/endcap flags as DDD SpecPars. - if ((fabs(Z)<647. || (R>350. && fabs(Z)<662.)) && - !(fabs(Z)>480 && R<172) // in 1103l we place V_6 and V_7 in the - // endcaps to preserve nice layer structure - // in the barrel. This does not hurt in v85l - // where there is a single V1 - ) { // Barrel - if (debug) cout << " (Barrel)" < 350. && fabs(Z) < 662.)) && + !(fabs(Z) > 480 && R < 172) // in 1103l we place V_6 and V_7 in the + // endcaps to preserve nice layer structure + // in the barrel. This does not hurt in v85l + // where there is a single V1 + ) { // Barrel + if (debug) + cout << " (Barrel)" << endl; bVolumes.push_back(v); - // Build the interpolator of the "master" volume (the one which is // not replicated in phi) // ASSUMPTION: copyno == sector. - if (v->copyno==v->masterSector) { - buildInterpolator(v, bInterpolators); - ++bVolCount; + if (v->copyno == v->masterSector) { + buildInterpolator(v, bInterpolators); + ++bVolCount; } - } else { // Endcaps - if (debug) cout << " (Endcaps)" <copyno==v->masterSector) { - buildInterpolator(v, eInterpolators); - ++eVolCount; + if (v->copyno == v->masterSector) { + buildInterpolator(v, eInterpolators); + ++eVolCount; } } - doSubDets = fv.nextSibling(); // end of loop over MAGF + doSubDets = fv.nextSibling(); // end of loop over MAGF } - + if (debug) { - cout << "Number of volumes (barrel): " << bVolumes.size() < layers; // the barrel layers + vector layers; // the barrel layers precomputed_value_sort(bVolumes.begin(), bVolumes.end(), ExtractRN()); // Find the layers (in R) - const float resolution = 1.; // cm - float rmin = bVolumes.front()->RN()-resolution; - float rmax = bVolumes.back()->RN()+resolution; - ClusterizingHistogram hisR( int((rmax-rmin)/resolution) + 1, rmin, rmax); + const float resolution = 1.; // cm + float rmin = bVolumes.front()->RN() - resolution; + float rmax = bVolumes.back()->RN() + resolution; + ClusterizingHistogram hisR(int((rmax - rmin) / resolution) + 1, rmin, rmax); - if (debug) cout << " R layers: " << rmin << " " << rmax << endl; + if (debug) + cout << " R layers: " << rmin << " " << rmax << endl; handles::const_iterator first = bVolumes.begin(); - handles::const_iterator last = bVolumes.end(); + handles::const_iterator last = bVolumes.end(); - for (handles::const_iterator i=first; i!=last; ++i){ + for (handles::const_iterator i = first; i != last; ++i) { hisR.fill((*i)->RN()); } vector rClust = hisR.clusterize(resolution); @@ -309,111 +308,113 @@ void MagGeoBuilderFromDDD::build(const DDCompactView & cpva) handles::const_iterator ringStart = first; handles::const_iterator separ = first; - for (unsigned int i=0; i sectors; // the endcap sectors + vector sectors; // the endcap sectors // Find the number of sectors (should be 12 or 24 depending on the geometry model) - float phireso = 0.05; // rad - ClusterizingHistogram hisPhi( int((Geom::ftwoPi())/phireso) + 1, - -Geom::fpi(), Geom::fpi()); - - for (handles::const_iterator i=eVolumes.begin(); i!=eVolumes.end(); ++i){ + float phireso = 0.05; // rad + ClusterizingHistogram hisPhi(int((Geom::ftwoPi()) / phireso) + 1, -Geom::fpi(), Geom::fpi()); + + for (handles::const_iterator i = eVolumes.begin(); i != eVolumes.end(); ++i) { hisPhi.fill((*i)->minPhi()); } vector phiClust = hisPhi.clusterize(phireso); int nESectors = phiClust.size(); - if (debug && (nESectors%12)!=0) cout << "ERROR: unexpected # of sectors: " << nESectors << endl; + if (debug && (nESectors % 12) != 0) + cout << "ERROR: unexpected # of sectors: " << nESectors << endl; //Sort in phi precomputed_value_sort(eVolumes.begin(), eVolumes.end(), ExtractPhi()); - - // Handle the -pi/pi boundary: volumes crossing it could be half at the begin and half at end of the sorted list. + + // Handle the -pi/pi boundary: volumes crossing it could be half at the begin and half at end of the sorted list. // So, check if any of the volumes that should belong to the first bin (at -phi) are at the end of the list: float lastBinPhi = phiClust.back(); handles::reverse_iterator ri = eVolumes.rbegin(); - while ((*ri)->center().phi()>lastBinPhi) {++ri;} - if (ri!=eVolumes.rbegin()) { + while ((*ri)->center().phi() > lastBinPhi) { + ++ri; + } + if (ri != eVolumes.rbegin()) { // ri points to the first element that is within the last bin. // We need to move the following element (ie ri.base()) to the beginning of the list, handles::iterator newbeg = ri.base(); - rotate(eVolumes.begin(),newbeg, eVolumes.end()); - } + rotate(eVolumes.begin(), newbeg, eVolumes.end()); + } //Group volumes in sectors - int offset = eVolumes.size()/nESectors; - for (int i = 0; iname << ":" << (*iv)->copyno << " differs from others in same sectors " << secCopyNo << endl; - secCopyNo = (*iv)->copyno; + for (handles::const_iterator iv = eVolumes.begin() + ((i)*offset); iv != eVolumes.begin() + ((i + 1) * offset); + ++iv) { + if (secCopyNo >= 0 && (*iv)->copyno != secCopyNo) + cout << "ERROR: volume copyno" << (*iv)->name << ":" << (*iv)->copyno + << " differs from others in same sectors " << secCopyNo << endl; + secCopyNo = (*iv)->copyno; } } - sectors.push_back(eSector(eVolumes.begin()+((i)*offset), - eVolumes.begin()+((i+1)*offset))); + sectors.push_back(eSector(eVolumes.begin() + ((i)*offset), eVolumes.begin() + ((i + 1) * offset))); } - - if (debug) cout << "Endcap: Found " - << sectors.size() << " sectors " << endl; + if (debug) + cout << "Endcap: Found " << sectors.size() << " sectors " << endl; - //---------------------------------------------------------------------- + //---------------------------------------------------------------------- // Match surfaces. -// cout << "------------------" << endl << "Now associating planes..." << endl; - -// // Loop on layers -// for (vector::const_iterator ilay = layers.begin(); -// ilay!= layers.end(); ++ilay) { -// cout << "On Layer: " << ilay-layers.begin() << " RN: " << (*ilay).RN() -// <::const_iterator iwheel = (*ilay).wheels.begin(); -// iwheel != (*ilay).wheels.end(); ++iwheel) { -// cout << " On Wheel: " << iwheel- (*ilay).wheels.begin()<< " Z: " -// << (*iwheel).minZ() << " " << (*iwheel).maxZ() << " " -// << ((*iwheel).minZ()+(*iwheel).maxZ())/2. <::const_iterator ilay = layers.begin(); + // ilay!= layers.end(); ++ilay) { + // cout << "On Layer: " << ilay-layers.begin() << " RN: " << (*ilay).RN() + // <::const_iterator iwheel = (*ilay).wheels.begin(); + // iwheel != (*ilay).wheels.end(); ++iwheel) { + // cout << " On Wheel: " << iwheel- (*ilay).wheels.begin()<< " Z: " + // << (*iwheel).minZ() << " " << (*iwheel).maxZ() << " " + // << ((*iwheel).minZ()+(*iwheel).maxZ())/2. <::const_iterator ilay = layers.begin(); - ilay!= layers.end(); ++ilay) { + for (vector::const_iterator ilay = layers.begin(); ilay != layers.end(); ++ilay) { mBLayers.push_back((*ilay).buildMagBLayer()); } - if (debug) { + if (debug) { cout << "*** BARREL ********************************************" << endl - << "Number of different volumes = " << bVolCount << endl - << "Number of interpolators built = " << bInterpolators.size() << endl - << "Number of MagBLayers built = " << mBLayers.size() << endl; + << "Number of different volumes = " << bVolCount << endl + << "Number of interpolators built = " << bInterpolators.size() << endl + << "Number of MagBLayers built = " << mBLayers.size() << endl; - testInside(bVolumes); // FIXME: all volumes should be checked in one go. + testInside(bVolumes); // FIXME: all volumes should be checked in one go. } - + //--- Endcap // Build MagVolumes and associate interpolators to them buildMagVolumes(eVolumes, eInterpolators); // Build the MagESectors - for (vector::const_iterator isec = sectors.begin(); - isec!= sectors.end(); ++isec) { + for (vector::const_iterator isec = sectors.begin(); isec != sectors.end(); ++isec) { mESectors.push_back((*isec).buildMagESector()); } if (debug) { cout << "*** ENDCAP ********************************************" << endl - << "Number of different volumes = " << eVolCount << endl - << "Number of interpolators built = " << eInterpolators.size() << endl - << "Number of MagESector built = " << mESectors.size() << endl; + << "Number of different volumes = " << eVolCount << endl + << "Number of interpolators built = " << eInterpolators.size() << endl + << "Number of MagESector built = " << mESectors.size() << endl; - testInside(eVolumes); // FIXME: all volumes should be checked in one go. + testInside(eVolumes); // FIXME: all volumes should be checked in one go. } } - -void MagGeoBuilderFromDDD::buildMagVolumes(const handles & volumes, map & interpolators) { +void MagGeoBuilderFromDDD::buildMagVolumes(const handles& volumes, map& interpolators) { // Build all MagVolumes setting the MagProviderInterpol - for (handles::const_iterator vol=volumes.begin(); vol!=volumes.end(); - ++vol){ + for (handles::const_iterator vol = volumes.begin(); vol != volumes.end(); ++vol) { const MagProviderInterpol* mp = nullptr; - if (interpolators.find((*vol)->magFile)!=interpolators.end()) { + if (interpolators.find((*vol)->magFile) != interpolators.end()) { mp = interpolators[(*vol)->magFile]; } else { - edm::LogError("MagGeoBuilderFromDDDbuildMagVolumes") << "No interpolator found for file " << (*vol)->magFile - << " vol: " << (*vol)->volumeno << "\n" << interpolators.size() <magFile << " vol: " << (*vol)->volumeno << "\n" + << interpolators.size() << endl; + } // Search for [volume,sector] in the list of scaling factors; sector = 0 handled as wildcard // ASSUMPTION: copyno == sector. - int key = ((*vol)->volumeno)*100+(*vol)->copyno; + int key = ((*vol)->volumeno) * 100 + (*vol)->copyno; map::const_iterator isf = theScalingFactors.find(key); if (isf == theScalingFactors.end()) { - key = ((*vol)->volumeno)*100; + key = ((*vol)->volumeno) * 100; isf = theScalingFactors.find(key); } - + double sf = 1.; if (isf != theScalingFactors.end()) { sf = (*isf).second; - edm::LogInfo("MagneticField|VolumeBasedMagneticFieldESProducer") << "Applying scaling factor " << sf << " to "<< (*vol)->volumeno << "["<< (*vol)->copyno << "] (key:" << key << ")" << endl; + edm::LogInfo("MagneticField|VolumeBasedMagneticFieldESProducer") + << "Applying scaling factor " << sf << " to " << (*vol)->volumeno << "[" << (*vol)->copyno << "] (key:" << key + << ")" << endl; } - const GloballyPositioned * gpos = (*vol)->placement(); - (*vol)->magVolume = new MagVolume6Faces(gpos->position(), - gpos->rotation(), - (*vol)->sides(), - mp, sf); + const GloballyPositioned* gpos = (*vol)->placement(); + (*vol)->magVolume = new MagVolume6Faces(gpos->position(), gpos->rotation(), (*vol)->sides(), mp, sf); - if ((*vol)->copyno==(*vol)->masterSector) { + if ((*vol)->copyno == (*vol)->masterSector) { (*vol)->magVolume->ownsFieldProvider(true); } @@ -505,27 +502,21 @@ void MagGeoBuilderFromDDD::buildMagVolumes(const handles & volumes, map & interpolators){ - +void MagGeoBuilderFromDDD::buildInterpolator(const volumeHandle* vol, + map& interpolators) { // Phi of the master sector - double masterSectorPhi = (vol->masterSector-1)*Geom::pi()/6.; + double masterSectorPhi = (vol->masterSector - 1) * Geom::pi() / 6.; if (debug) { - cout << "Building interpolator from " - << vol->volumeno << " copyno " << vol->copyno - << " at " << vol->center() - << " phi: " << vol->center().phi() - << " file: " << vol->magFile - << " master : " << vol->masterSector - << endl; - - if ( fabs(vol->center().phi() - masterSectorPhi) > Geom::pi()/9.) { + cout << "Building interpolator from " << vol->volumeno << " copyno " << vol->copyno << " at " << vol->center() + << " phi: " << vol->center().phi() << " file: " << vol->magFile << " master : " << vol->masterSector << endl; + + if (fabs(vol->center().phi() - masterSectorPhi) > Geom::pi() / 9.) { cout << "***WARNING wrong sector? " << endl; } } - if (tableSet == "fake" || vol->magFile== "fake") { + if (tableSet == "fake" || vol->magFile == "fake") { interpolators[vol->magFile] = new magneticfield::FakeInterpolator(); return; } @@ -533,173 +524,150 @@ void MagGeoBuilderFromDDD::buildInterpolator(const volumeHandle * vol, mapmagFile); + edm::FileInPath mydata("MagneticField/Interpolation/data/" + tableSet + "/" + vol->magFile); fullPath = mydata.fullPath(); } catch (edm::Exception& exc) { cerr << "MagGeoBuilderFromDDD: exception in reading table; " << exc.what() << endl; - if (!debug) throw; + if (!debug) + throw; return; } - - - try{ - if (vol->toExpand()){ + + try { + if (vol->toExpand()) { //FIXME: see discussion on mergeCylinders above. -// interpolators[vol->magFile] = -// MFGridFactory::build( fullPath, *(vol->placement()), vol->minPhi(), vol->maxPhi()); + // interpolators[vol->magFile] = + // MFGridFactory::build( fullPath, *(vol->placement()), vol->minPhi(), vol->maxPhi()); } else { - // If the table is in "local" coordinates, must create a reference + // If the table is in "local" coordinates, must create a reference // frame that is appropriately rotated along the CMS Z axis. GloballyPositioned rf = *(vol->placement()); if (vol->masterSector != 1) { - typedef Basic3DVector Vector; + typedef Basic3DVector Vector; - GloballyPositioned::RotationType rot(Vector(0,0,1), -masterSectorPhi); - Vector vpos(vol->placement()->position()); - + GloballyPositioned::RotationType rot(Vector(0, 0, 1), -masterSectorPhi); + Vector vpos(vol->placement()->position()); - rf = GloballyPositioned(GloballyPositioned::PositionType(rot.multiplyInverse(vpos)), vol->placement()->rotation()*rot); + rf = GloballyPositioned(GloballyPositioned::PositionType(rot.multiplyInverse(vpos)), + vol->placement()->rotation() * rot); } - interpolators[vol->magFile] = - MFGridFactory::build( fullPath, rf); + interpolators[vol->magFile] = MFGridFactory::build(fullPath, rf); } } catch (MagException& exc) { cout << exc.what() << endl; interpolators.erase(vol->magFile); - if (!debug) throw; + if (!debug) + throw; return; } - - if (debug) { + if (debug) { // Check that all grid points of the interpolator are inside the volume. - const MagVolume6Faces tempVolume(vol->placement()->position(), - vol->placement()->rotation(), - vol->sides(), - interpolators[vol->magFile]); - - const MFGrid* grid = dynamic_cast(interpolators[vol->magFile]); - if (grid!=nullptr) { - - Dimensions sizes = grid->dimensions(); - cout << "Grid has 3 dimensions " - << " number of nodes is " << sizes.w << " " << sizes.h - << " " << sizes.d << endl; - - const double tolerance = 0.03; - - - size_t dumpCount = 0; - for (int j=0; j < sizes.h; j++) { - for (int k=0; k < sizes.d; k++) { - for (int i=0; i < sizes.w; i++) { - MFGrid::LocalPoint lp = grid->nodePosition( i, j, k); - if (! tempVolume.inside(lp, tolerance)) { - if (++dumpCount < 2) { - MFGrid::GlobalPoint gp = tempVolume.toGlobal(lp); - cout << "GRID ERROR: " << i << " " << j << " " << k - << " local: " << lp - << " global: " << gp - << " R= " << gp.perp() << " phi=" << gp.phi() << endl; - } - } - } - } - } - - cout << "Volume:" << vol->volumeno << " : Number of grid points outside the MagVolume: " << dumpCount << "/" << sizes.w*sizes.h*sizes.d << endl; + const MagVolume6Faces tempVolume( + vol->placement()->position(), vol->placement()->rotation(), vol->sides(), interpolators[vol->magFile]); + + const MFGrid* grid = dynamic_cast(interpolators[vol->magFile]); + if (grid != nullptr) { + Dimensions sizes = grid->dimensions(); + cout << "Grid has 3 dimensions " + << " number of nodes is " << sizes.w << " " << sizes.h << " " << sizes.d << endl; + + const double tolerance = 0.03; + + size_t dumpCount = 0; + for (int j = 0; j < sizes.h; j++) { + for (int k = 0; k < sizes.d; k++) { + for (int i = 0; i < sizes.w; i++) { + MFGrid::LocalPoint lp = grid->nodePosition(i, j, k); + if (!tempVolume.inside(lp, tolerance)) { + if (++dumpCount < 2) { + MFGrid::GlobalPoint gp = tempVolume.toGlobal(lp); + cout << "GRID ERROR: " << i << " " << j << " " << k << " local: " << lp << " global: " << gp + << " R= " << gp.perp() << " phi=" << gp.phi() << endl; + } + } + } + } } + + cout << "Volume:" << vol->volumeno << " : Number of grid points outside the MagVolume: " << dumpCount << "/" + << sizes.w * sizes.h * sizes.d << endl; } + } } - - -void MagGeoBuilderFromDDD::testInside(handles & volumes) { +void MagGeoBuilderFromDDD::testInside(handles& volumes) { // test inside() for all volumes. cout << "--------------------------------------------------" << endl; cout << " inside(center) test" << endl; - for (handles::const_iterator vol=volumes.begin(); vol!=volumes.end(); - ++vol){ - for (handles::const_iterator i=volumes.begin(); i!=volumes.end(); - ++i){ - if ((*i)==(*vol)) continue; + for (handles::const_iterator vol = volumes.begin(); vol != volumes.end(); ++vol) { + for (handles::const_iterator i = volumes.begin(); i != volumes.end(); ++i) { + if ((*i) == (*vol)) + continue; //if ((*i)->magVolume == 0) continue; if ((*i)->magVolume->inside((*vol)->center())) { - cout << "*** ERROR: center of V " << (*vol)->volumeno << ":" << (*vol)->copyno << " is inside V " - << (*i)->volumeno << ":" << (*i)->copyno << endl; + cout << "*** ERROR: center of V " << (*vol)->volumeno << ":" << (*vol)->copyno << " is inside V " + << (*i)->volumeno << ":" << (*i)->copyno << endl; } } - + if ((*vol)->magVolume->inside((*vol)->center())) { cout << "V " << (*vol)->volumeno << " OK " << endl; } else { - cout << "*** ERROR: center of volume is not inside it, " - << (*vol)->volumeno << endl; + cout << "*** ERROR: center of volume is not inside it, " << (*vol)->volumeno << endl; } } cout << "--------------------------------------------------" << endl; } +vector MagGeoBuilderFromDDD::barrelLayers() const { return mBLayers; } -vector MagGeoBuilderFromDDD::barrelLayers() const{ - return mBLayers; -} - -vector MagGeoBuilderFromDDD::endcapSectors() const{ - return mESectors; -} +vector MagGeoBuilderFromDDD::endcapSectors() const { return mESectors; } -vector MagGeoBuilderFromDDD::barrelVolumes() const{ +vector MagGeoBuilderFromDDD::barrelVolumes() const { vector v; v.reserve(bVolumes.size()); - for (handles::const_iterator i=bVolumes.begin(); - i!=bVolumes.end(); ++i){ + for (handles::const_iterator i = bVolumes.begin(); i != bVolumes.end(); ++i) { v.push_back((*i)->magVolume); } return v; } -vector MagGeoBuilderFromDDD::endcapVolumes() const{ +vector MagGeoBuilderFromDDD::endcapVolumes() const { vector v; v.reserve(eVolumes.size()); - for (handles::const_iterator i=eVolumes.begin(); - i!=eVolumes.end(); ++i){ + for (handles::const_iterator i = eVolumes.begin(); i != eVolumes.end(); ++i) { v.push_back((*i)->magVolume); } return v; } - -float MagGeoBuilderFromDDD::maxR() const{ +float MagGeoBuilderFromDDD::maxR() const { //FIXME: should get it from the actual geometry return 900.; } -float MagGeoBuilderFromDDD::maxZ() const{ +float MagGeoBuilderFromDDD::maxZ() const { //FIXME: should get it from the actual geometry - if (geometryVersion>=160812) return 2400.; - else if (geometryVersion>=120812) return 2000.; - else return 1600.; + if (geometryVersion >= 160812) + return 2400.; + else if (geometryVersion >= 120812) + return 2000.; + else + return 1600.; } - -void MagGeoBuilderFromDDD::setScaling(const std::vector& keys, - const std::vector& values) -{ +void MagGeoBuilderFromDDD::setScaling(const std::vector& keys, const std::vector& values) { if (keys.size() != values.size()) { - throw cms::Exception("InvalidParameter") << "Invalid field scaling parameters 'scalingVolumes' and 'scalingFactors' "; + throw cms::Exception("InvalidParameter") + << "Invalid field scaling parameters 'scalingVolumes' and 'scalingFactors' "; } - for (unsigned int i=0; i& keys, const std::vector& values); void setGridFiles(const magneticfield::TableFileMap& gridFiles); @@ -53,15 +52,14 @@ class MagGeoBuilderFromDDD { float maxR() const; - float maxZ() const; + float maxZ() const; private: typedef ConstReferenceCountingPointer RCPS; - // Build the geometry. + // Build the geometry. //virtual void build(); - virtual void build(const DDCompactView & cpv); - + virtual void build(const DDCompactView& cpv); // FIXME: only for temporary tests and debug, to be removed friend class TestMagVolume; @@ -70,8 +68,7 @@ class MagGeoBuilderFromDDD { friend class magneticfield::VolumeBasedMagneticFieldESProducerFromDB; friend class magneticfield::AutoMagneticFieldESProducer; - - std::vector barrelVolumes() const; + std::vector barrelVolumes() const; std::vector endcapVolumes() const; // Temporary container to manipulate volumes and their surfaces. @@ -79,18 +76,16 @@ class MagGeoBuilderFromDDD { typedef std::vector handles; // Build interpolator for the volume with "correct" rotation - void buildInterpolator(const volumeHandle * vol, - std::map& interpolators); + void buildInterpolator(const volumeHandle* vol, std::map& interpolators); // Build all MagVolumes setting the MagProviderInterpol - void buildMagVolumes(const handles & volumes, - std::map & interpolators); + void buildMagVolumes(const handles& volumes, std::map& interpolators); // Print checksums for surfaces. - void summary(handles & volumes); + void summary(handles& volumes); // Perform simple sanity checks - void testInside(handles & volumes); + void testInside(handles& volumes); // A layer of barrel volumes. class bLayer; @@ -101,12 +96,11 @@ class MagGeoBuilderFromDDD { // A slab of volumes in a rod. class bSlab; // A sector of endcap volumes. - class eSector; + class eSector; // A layer of volumes in an endcap sector. class eLayer; - - - // Extractors for precomputed_value_sort (to sort containers of volumeHandles). + + // Extractors for precomputed_value_sort (to sort containers of volumeHandles). struct ExtractZ; struct ExtractAbsZ; struct ExtractPhi; @@ -120,16 +114,15 @@ class MagGeoBuilderFromDDD { handles bVolumes; // the barrel volumes. handles eVolumes; // the endcap volumes. - std::vector mBLayers; // Finally built barrel geometry - std::vector mESectors; // Finally built barrel geometry + std::vector mBLayers; // Finally built barrel geometry + std::vector mESectors; // Finally built barrel geometry - std::string tableSet; // Version of the data files to be used - int geometryVersion; // Version of MF geometry + std::string tableSet; // Version of the data files to be used + int geometryVersion; // Version of MF geometry std::map theScalingFactors; - const magneticfield::TableFileMap* theGridFiles; // Non-owned pointer assumed to be valid until build() is called + const magneticfield::TableFileMap* theGridFiles; // Non-owned pointer assumed to be valid until build() is called static bool debug; - }; #endif diff --git a/MagneticField/GeomBuilder/src/bLayer.cc b/MagneticField/GeomBuilder/src/bLayer.cc index cd03e61298399..23ea5b95e9fb9 100644 --- a/MagneticField/GeomBuilder/src/bLayer.cc +++ b/MagneticField/GeomBuilder/src/bLayer.cc @@ -16,106 +16,100 @@ using namespace SurfaceOrientation; //The ctor is in charge of finding sectors inside the layer. -MagGeoBuilderFromDDD::bLayer::bLayer(handles::const_iterator begin, - handles::const_iterator end) : - size(end-begin), - theVolumes(begin,end), - mlayer(nullptr) -{ +MagGeoBuilderFromDDD::bLayer::bLayer(handles::const_iterator begin, handles::const_iterator end) + : size(end - begin), theVolumes(begin, end), mlayer(nullptr) { // Sort in phi precomputed_value_sort(theVolumes.begin(), theVolumes.end(), ExtractPhi()); - + if (MagGeoBuilderFromDDD::debug) { std::cout << " elements: " << theVolumes.size() << " unique volumes: "; volumeHandle::printUniqueNames(theVolumes.begin(), theVolumes.end()); } - // Find sectors in phi handles::iterator secBegin = theVolumes.begin(); handles::iterator secEnd; int binOffset = 0; - const Surface & refSurf = (*secBegin)->surface(outer); + const Surface& refSurf = (*secBegin)->surface(outer); - int newbegin=0; - int newend=0; + int newbegin = 0; + int newend = 0; // A sector is made of several volumes in R, and, for planar layers - // (box and traps) also in phi, so it might cross the -phi boundary. - // For those, we have to look for the end of first sector and rotate the + // (box and traps) also in phi, so it might cross the -phi boundary. + // For those, we have to look for the end of first sector and rotate the // vector of volumes. // ASSUMPTION: all volumes in a layer must be of compatible type. - - if (size==1) { // Only one volume; this is the case for barrel + if (size == 1) { // Only one volume; this is the case for barrel // cylinders. // FIXME sectors.push_back(bSector(theVolumes.begin(),theVolumes.end()); - if (MagGeoBuilderFromDDD::debug) std::cout <<" Sector is just one volume." << std::endl; + if (MagGeoBuilderFromDDD::debug) + std::cout << " Sector is just one volume." << std::endl; - } else if (size==12 || // In this case, each volume is a sector. - (((*secBegin)->shape()!=DDSolidShape::ddtrap) && (*secBegin)->shape()!=DDSolidShape::ddbox)) { - secEnd = secBegin+size/12; + } else if (size == 12 || // In this case, each volume is a sector. + (((*secBegin)->shape() != DDSolidShape::ddtrap) && (*secBegin)->shape() != DDSolidShape::ddbox)) { + secEnd = secBegin + size / 12; - } else { // there are more than one volume per sector. - float tolerance = 0.025; // 250 micron + } else { // there are more than one volume per sector. + float tolerance = 0.025; // 250 micron do { - if (MagGeoBuilderFromDDD::debug) std::cout << (*secBegin)->name - << " " << (*secBegin)->copyno << std::endl; + if (MagGeoBuilderFromDDD::debug) + std::cout << (*secBegin)->name << " " << (*secBegin)->copyno << std::endl; ++secBegin; - } while ((secBegin != theVolumes.end()) && - (*secBegin)->sameSurface(refSurf,outer, tolerance)); // This works only if outer surface is a plane, otherwise sameSurface returns always true! - + } while ( + (secBegin != theVolumes.end()) && + (*secBegin)->sameSurface( + refSurf, + outer, + tolerance)); // This works only if outer surface is a plane, otherwise sameSurface returns always true! + secEnd = secBegin; - secBegin = theVolumes.begin()+bin((secEnd-theVolumes.begin())-size/12);; - newend = secEnd-theVolumes.begin(); - newbegin = secBegin-theVolumes.begin(); - + secBegin = theVolumes.begin() + bin((secEnd - theVolumes.begin()) - size / 12); + ; + newend = secEnd - theVolumes.begin(); + newbegin = secBegin - theVolumes.begin(); + // Rotate the begin of the first sector to the vector beginning. - rotate(theVolumes.begin(),secBegin,theVolumes.end()); + rotate(theVolumes.begin(), secBegin, theVolumes.end()); secBegin = theVolumes.begin(); - secEnd = secBegin+size/12; + secEnd = secBegin + size / 12; // Test it is correct... - if (!((*secBegin)->sameSurface((*(secEnd-1))->surface(outer), - outer, tolerance))) { - std::cout << "*** ERROR: Big mess while looking for sectors " - << (*secBegin)->name << " " << (*secBegin)->copyno << " " - << (*(secEnd-1))->name << " " << (*(secEnd-1))->copyno - << std::endl; + if (!((*secBegin)->sameSurface((*(secEnd - 1))->surface(outer), outer, tolerance))) { + std::cout << "*** ERROR: Big mess while looking for sectors " << (*secBegin)->name << " " << (*secBegin)->copyno + << " " << (*(secEnd - 1))->name << " " << (*(secEnd - 1))->copyno << std::endl; } } if (MagGeoBuilderFromDDD::debug) { - std::cout << " First sector: volumes " << secEnd-theVolumes.begin() - << " from " << newbegin - << " (phi = " << (*secBegin)->center().phi() << ") " - << " to " << newend - << " (phi = " << (*secEnd)->center().phi() << ") " - << " # " << (*secBegin)->copyno << " "; - std::cout << GlobalVector( refSurf.rotation().zx(), refSurf.rotation().zy(), - refSurf.rotation().zz()) << std::endl; + std::cout << " First sector: volumes " << secEnd - theVolumes.begin() << " from " << newbegin + << " (phi = " << (*secBegin)->center().phi() << ") " + << " to " << newend << " (phi = " << (*secEnd)->center().phi() << ") " + << " # " << (*secBegin)->copyno << " "; + std::cout << GlobalVector(refSurf.rotation().zx(), refSurf.rotation().zy(), refSurf.rotation().zz()) << std::endl; } - if (size!=1) { // Build the 12 sectors - int offset = size/12; + if (size != 1) { // Build the 12 sectors + int offset = size / 12; sectors.resize(12); - for (int i = 0; i<12; ++i) { - int isec = (i+binOffset)%12; - sectors[isec>=0?isec:isec+12] = bSector(theVolumes.begin()+((i)*offset), - theVolumes.begin()+((i+1)*offset)); + for (int i = 0; i < 12; ++i) { + int isec = (i + binOffset) % 12; + sectors[isec >= 0 ? isec : isec + 12] = + bSector(theVolumes.begin() + ((i)*offset), theVolumes.begin() + ((i + 1) * offset)); } } - if (MagGeoBuilderFromDDD::debug) std::cout << "-----------------------" << std::endl; - + if (MagGeoBuilderFromDDD::debug) + std::cout << "-----------------------" << std::endl; } -MagGeoBuilderFromDDD::bLayer::~bLayer(){} +MagGeoBuilderFromDDD::bLayer::~bLayer() {} int MagGeoBuilderFromDDD::bLayer::bin(int i) const { - i = i%size; - return (i>=0?i:i+size); + i = i % size; + return (i >= 0 ? i : i + size); } // const MagGeoBuilderFromDDD::bSector & @@ -124,25 +118,22 @@ int MagGeoBuilderFromDDD::bLayer::bin(int i) const { // return sectors[i>=0?i:i+12]; // } - double MagGeoBuilderFromDDD::bLayer::minR() const { - // ASSUMPTION: a layer is only 1 volume thick (by construction). + // ASSUMPTION: a layer is only 1 volume thick (by construction). return theVolumes.front()->minR(); } // double MagGeoBuilderFromDDD::bLayer::maxR() const { -// // ASSUMPTION: a layer is only 1 volume thick (by construction). +// // ASSUMPTION: a layer is only 1 volume thick (by construction). // return theVolumes.front()->maxR(); // } -MagBLayer * MagGeoBuilderFromDDD::bLayer::buildMagBLayer() const { - if (mlayer==nullptr) { - +MagBLayer* MagGeoBuilderFromDDD::bLayer::buildMagBLayer() const { + if (mlayer == nullptr) { // If we have only one volume, do not build any MagBSector. if (sectors.empty()) { - if (MagGeoBuilderFromDDD::debug && size!=0) { - std::cout << "ERROR: bLayer::buildMagBLayer, 0 sectors but " - << size << " volumes" << std::endl; + if (MagGeoBuilderFromDDD::debug && size != 0) { + std::cout << "ERROR: bLayer::buildMagBLayer, 0 sectors but " << size << " volumes" << std::endl; } // Technically we might have only one bSector built and we would // not need a separate MagBLayer constructor... @@ -151,11 +142,10 @@ MagBLayer * MagGeoBuilderFromDDD::bLayer::buildMagBLayer() const { // If we have several sectors, create the MagBSector std::vector mSectors; - for (unsigned int i=0; iRN(); - } + const float RN() const { return theVolumes.front()->RN(); } /// Return the list of all volumes. - const handles & volumes() const {return theVolumes;} + const handles& volumes() const { return theVolumes; } /// Return sector at i (handling periodicity) // const bSector & sector(int i) const; @@ -41,18 +39,17 @@ class MagGeoBuilderFromDDD::bLayer { // double maxR() const; /// Construct the MagBLayer upon request. - MagBLayer * buildMagBLayer() const; + MagBLayer* buildMagBLayer() const; private: - int size; //< the number of volumes + int size; //< the number of volumes // Check periodicity; int bin(int i) const; - std::vector sectors; // the sectors in this layer - handles theVolumes; // pointer to all volumes in this layer + std::vector sectors; // the sectors in this layer + handles theVolumes; // pointer to all volumes in this layer - mutable MagBLayer * mlayer; + mutable MagBLayer* mlayer; }; #endif - diff --git a/MagneticField/GeomBuilder/src/bRod.cc b/MagneticField/GeomBuilder/src/bRod.cc index 5b2eb3ba97434..eb3d2431652bb 100644 --- a/MagneticField/GeomBuilder/src/bRod.cc +++ b/MagneticField/GeomBuilder/src/bRod.cc @@ -14,55 +14,53 @@ using namespace SurfaceOrientation; -MagGeoBuilderFromDDD::bRod::~bRod(){} +MagGeoBuilderFromDDD::bRod::~bRod() {} //The ctor is in charge of finding slabs inside the rod. -MagGeoBuilderFromDDD::bRod::bRod(handles::const_iterator begin, - handles::const_iterator end) : - volumes(begin,end), - mrod(nullptr) -{ +MagGeoBuilderFromDDD::bRod::bRod(handles::const_iterator begin, handles::const_iterator end) + : volumes(begin, end), mrod(nullptr) { precomputed_value_sort(volumes.begin(), volumes.end(), ExtractZ()); // Clusterize in Z - const float resolution = 5.; // cm - float zmin = volumes.front()->center().z()-resolution; - float zmax = volumes.back()->center().z()+resolution; - ClusterizingHistogram hisZ( int((zmax-zmin)/resolution) + 1, zmin, zmax); + const float resolution = 5.; // cm + float zmin = volumes.front()->center().z() - resolution; + float zmax = volumes.back()->center().z() + resolution; + ClusterizingHistogram hisZ(int((zmax - zmin) / resolution) + 1, zmin, zmax); - if (MagGeoBuilderFromDDD::debug) std::cout << " Z slabs: " << zmin << " " << zmax << std::endl; + if (MagGeoBuilderFromDDD::debug) + std::cout << " Z slabs: " << zmin << " " << zmax << std::endl; handles::const_iterator first = volumes.begin(); - handles::const_iterator last = volumes.end(); + handles::const_iterator last = volumes.end(); - for (handles::const_iterator i=first; i!=last; ++i){ + for (handles::const_iterator i = first; i != last; ++i) { hisZ.fill((*i)->center().z()); } std::vector zClust = hisZ.clusterize(resolution); - if (MagGeoBuilderFromDDD::debug) std::cout << " Found " << zClust.size() << " clusters in Z, " - << " slabs: " << std::endl; + if (MagGeoBuilderFromDDD::debug) + std::cout << " Found " << zClust.size() << " clusters in Z, " + << " slabs: " << std::endl; handles::const_iterator slabStart = first; handles::const_iterator separ = first; - for (unsigned int i=0; icenter().z() < zSepar) ++separ; + for (unsigned int i = 0; i < zClust.size() - 1; ++i) { + float zSepar = (zClust[i] + zClust[i + 1]) / 2.f; + while ((*separ)->center().z() < zSepar) + ++separ; if (MagGeoBuilderFromDDD::debug) { - std::cout << " Slab at: " << zClust[i] - << " elements: " << separ-slabStart << " unique volumes: "; + std::cout << " Slab at: " << zClust[i] << " elements: " << separ - slabStart << " unique volumes: "; volumeHandle::printUniqueNames(slabStart, separ); } - + slabs.push_back(bSlab(slabStart, separ)); slabStart = separ; } { if (MagGeoBuilderFromDDD::debug) { - std::cout << " Slab at: " << zClust.back() <<" elements: " << last-separ - << " unique volumes: "; - volumeHandle::printUniqueNames(separ,last); + std::cout << " Slab at: " << zClust.back() << " elements: " << last - separ << " unique volumes: "; + volumeHandle::printUniqueNames(separ, last); } slabs.push_back(bSlab(separ, last)); } @@ -71,24 +69,21 @@ MagGeoBuilderFromDDD::bRod::bRod(handles::const_iterator begin, std::vector::const_iterator i = slabs.begin(); Geom::Phi phimax = (*i).maxPhi(); Geom::Phi phimin = (*i).minPhi(); - for (++i; i!= slabs.end(); ++i) { - if(fabs(phimax - (*i).maxPhi()) > 0.001 || - fabs(phimin - (*i).minPhi()) > 0.001){ - if (MagGeoBuilderFromDDD::debug) std::cout << "*** WARNING: slabs in this rod have different dphi!" < 0.001 || fabs(phimin - (*i).minPhi()) > 0.001) { + if (MagGeoBuilderFromDDD::debug) + std::cout << "*** WARNING: slabs in this rod have different dphi!" << std::endl; } } } - - -MagBRod* MagGeoBuilderFromDDD::bRod::buildMagBRod() const{ - if (mrod==nullptr) { +MagBRod* MagGeoBuilderFromDDD::bRod::buildMagBRod() const { + if (mrod == nullptr) { std::vector mSlabs; - for (std::vector::const_iterator slab = slabs.begin(); - slab!=slabs.end(); ++slab) { + for (std::vector::const_iterator slab = slabs.begin(); slab != slabs.end(); ++slab) { mSlabs.push_back((*slab).buildMagBSlab()); } - mrod = new MagBRod(mSlabs,slabs.front().minPhi()); //FIXME + mrod = new MagBRod(mSlabs, slabs.front().minPhi()); //FIXME } return mrod; } diff --git a/MagneticField/GeomBuilder/src/bRod.h b/MagneticField/GeomBuilder/src/bRod.h index 80b44ee5f0b91..93a1db362d42e 100644 --- a/MagneticField/GeomBuilder/src/bRod.h +++ b/MagneticField/GeomBuilder/src/bRod.h @@ -21,18 +21,16 @@ class MagGeoBuilderFromDDD::bRod { /// Destructor ~bRod(); - + /// Distance from center along sector normal. - const float RN() const { - return volumes.front()->RN(); - } + const float RN() const { return volumes.front()->RN(); } /// Construct the MagBRod upon request. MagBRod* buildMagBRod() const; private: std::vector slabs; - handles volumes; // pointers to all volumes in the rod + handles volumes; // pointers to all volumes in the rod mutable MagBRod* mrod; }; diff --git a/MagneticField/GeomBuilder/src/bSector.cc b/MagneticField/GeomBuilder/src/bSector.cc index e75459586d8f2..eaece6b43594d 100644 --- a/MagneticField/GeomBuilder/src/bSector.cc +++ b/MagneticField/GeomBuilder/src/bSector.cc @@ -18,128 +18,117 @@ using namespace SurfaceOrientation; using namespace std; - // Default ctor needed to have arrays. -MagGeoBuilderFromDDD::bSector::bSector(){} +MagGeoBuilderFromDDD::bSector::bSector() {} -MagGeoBuilderFromDDD::bSector::~bSector(){} +MagGeoBuilderFromDDD::bSector::~bSector() {} // The ctor is in charge of finding rods inside the sector. -MagGeoBuilderFromDDD::bSector::bSector(handles::const_iterator begin, - handles::const_iterator end) : - volumes(begin,end), - msector(nullptr) -{ - if (MagGeoBuilderFromDDD::debug) cout << " Sector at Phi " << volumes.front()->center().phi() << " " - << volumes.back()->center().phi() << endl; +MagGeoBuilderFromDDD::bSector::bSector(handles::const_iterator begin, handles::const_iterator end) + : volumes(begin, end), msector(nullptr) { + if (MagGeoBuilderFromDDD::debug) + cout << " Sector at Phi " << volumes.front()->center().phi() << " " << volumes.back()->center().phi() << endl; if (volumes.size() == 1) { - if (MagGeoBuilderFromDDD::debug) { - cout << " Rod at: 0 elements: " << end-begin - << " unique volumes: "; - volumeHandle::printUniqueNames(begin,end); + if (MagGeoBuilderFromDDD::debug) { + cout << " Rod at: 0 elements: " << end - begin << " unique volumes: "; + volumeHandle::printUniqueNames(begin, end); } - rods.push_back(bRod(begin,end)); + rods.push_back(bRod(begin, end)); } else { - // Clusterize in phi. Use bin edge so that complete clusters can be + // Clusterize in phi. Use bin edge so that complete clusters can be // easily found (not trivial using bin centers!) - // Unfortunately this makes the result more sensitive to the + // Unfortunately this makes the result more sensitive to the // "resolution" parameter... // To avoid +-pi boundary problems, take phi distance from min phi. // Caveat of implicit conversions of Geom::Phi!!! // Sort volumes in DELTA phi - i.e. phi(j)-phi(i) > 0 if j>1. - precomputed_value_sort(volumes.begin(), volumes.end(), - ExtractPhiMax(), LessDPhi()); + precomputed_value_sort(volumes.begin(), volumes.end(), ExtractPhiMax(), LessDPhi()); - const Geom::Phi resolution(0.01); // rad + const Geom::Phi resolution(0.01); // rad Geom::Phi phi0 = volumes.front()->maxPhi(); - float phiMin = -(float) resolution; - float phiMax = volumes.back()->maxPhi() - phi0 + resolution; ///FIXME: (float) resolution; ?? + float phiMin = -(float)resolution; + float phiMax = volumes.back()->maxPhi() - phi0 + resolution; ///FIXME: (float) resolution; ?? + + ClusterizingHistogram hisPhi(int((phiMax - phiMin) / resolution) + 1, phiMin, phiMax); - ClusterizingHistogram hisPhi( int((phiMax-phiMin)/resolution) + 1, - phiMin, phiMax); - handles::const_iterator first = volumes.begin(); - handles::const_iterator last = volumes.end(); + handles::const_iterator last = volumes.end(); - for (handles::const_iterator i=first; i!=last; ++i){ - hisPhi.fill((*i)->maxPhi()-phi0); + for (handles::const_iterator i = first; i != last; ++i) { + hisPhi.fill((*i)->maxPhi() - phi0); } vector phiClust = hisPhi.clusterize(resolution); - if (MagGeoBuilderFromDDD::debug) cout << " Found " << phiClust.size() << " clusters in Phi, " - << " rods: " << endl; + if (MagGeoBuilderFromDDD::debug) + cout << " Found " << phiClust.size() << " clusters in Phi, " + << " rods: " << endl; handles::const_iterator rodStart = first; handles::const_iterator separ = first; - - float DZ = (*max_element(first,last,LessZ()))->maxZ() - - (*min_element(first,last,LessZ()))->minZ(); + + float DZ = (*max_element(first, last, LessZ()))->maxZ() - (*min_element(first, last, LessZ()))->minZ(); float DZ1 = 0.; - for (unsigned int i=0; imaxPhi()-phi0 < phiSepar ) { - DZ1 += ((*separ)->maxZ() - (*separ)->minZ()); - if (MagGeoBuilderFromDDD::debug) cout << " " << (*separ)->name << " " - << (*separ)->maxPhi()-phi0 << " " - << (*separ)->maxZ() << " " << (*separ)->minZ() << " " - << DZ1 << endl; - ++separ; + if (MagGeoBuilderFromDDD::debug) + cout << " cluster " << i << " phisepar " << phiSepar << endl; + while (separ < last && (*separ)->maxPhi() - phi0 < phiSepar) { + DZ1 += ((*separ)->maxZ() - (*separ)->minZ()); + if (MagGeoBuilderFromDDD::debug) + cout << " " << (*separ)->name << " " << (*separ)->maxPhi() - phi0 << " " << (*separ)->maxZ() << " " + << (*separ)->minZ() << " " << DZ1 << endl; + ++separ; } // FIXME: print warning for small discrepancies. Tolerance (below) // had to be increased since discrepancies sum to up to ~ 2 mm. - if (fabs(DZ-DZ1) > 0.001 && fabs(DZ-DZ1) < 0.5) { - if (MagGeoBuilderFromDDD::debug) cout << "*** WARNING: Z lenght mismatch by " << DZ-DZ1 - << " " << DZ << " " << DZ1 << endl; - + if (fabs(DZ - DZ1) > 0.001 && fabs(DZ - DZ1) < 0.5) { + if (MagGeoBuilderFromDDD::debug) + cout << "*** WARNING: Z lenght mismatch by " << DZ - DZ1 << " " << DZ << " " << DZ1 << endl; } - if (fabs(DZ-DZ1) > 0.25 ) { // FIXME hardcoded tolerance - if (MagGeoBuilderFromDDD::debug) cout << " Incomplete, use also next cluster: " - << DZ << " " << DZ1 << " " << DZ-DZ1 << endl; - DZ1 = 0.; - continue; - } else if (DZ1>DZ+0.05) { // Wrong: went past max lenght // FIXME hardcoded tolerance - cout << " *** ERROR: bSector finding messed up." << endl; - volumeHandle::printUniqueNames(rodStart, separ); - DZ1 = 0.; + if (fabs(DZ - DZ1) > 0.25) { // FIXME hardcoded tolerance + if (MagGeoBuilderFromDDD::debug) + cout << " Incomplete, use also next cluster: " << DZ << " " << DZ1 << " " << DZ - DZ1 << endl; + DZ1 = 0.; + continue; + } else if (DZ1 > DZ + 0.05) { // Wrong: went past max lenght // FIXME hardcoded tolerance + cout << " *** ERROR: bSector finding messed up." << endl; + volumeHandle::printUniqueNames(rodStart, separ); + DZ1 = 0.; } else { - if (MagGeoBuilderFromDDD::debug) { - cout << " Rod at: " << phiClust[i] <<" elements: " - << separ-rodStart << " unique volumes: "; - volumeHandle::printUniqueNames(rodStart, separ); - } - - rods.push_back(bRod(rodStart, separ)); - rodStart = separ; - DZ1 = 0.; + if (MagGeoBuilderFromDDD::debug) { + cout << " Rod at: " << phiClust[i] << " elements: " << separ - rodStart << " unique volumes: "; + volumeHandle::printUniqueNames(rodStart, separ); + } + + rods.push_back(bRod(rodStart, separ)); + rodStart = separ; + DZ1 = 0.; } } - - if (rods.empty()) cout << " *** ERROR: bSector has no rods " << DZ << " " << DZ1 << endl; - if (MagGeoBuilderFromDDD::debug) cout << "-----------------------" << endl; + if (rods.empty()) + cout << " *** ERROR: bSector has no rods " << DZ << " " << DZ1 << endl; + if (MagGeoBuilderFromDDD::debug) + cout << "-----------------------" << endl; } } - -MagBSector* MagGeoBuilderFromDDD::bSector::buildMagBSector() const{ - if (msector==nullptr) { +MagBSector* MagGeoBuilderFromDDD::bSector::buildMagBSector() const { + if (msector == nullptr) { vector mRods; - for (vector::const_iterator rod = rods.begin(); - rod!=rods.end(); ++rod) { + for (vector::const_iterator rod = rods.begin(); rod != rods.end(); ++rod) { mRods.push_back((*rod).buildMagBRod()); } - msector = new MagBSector(mRods, volumes.front()->minPhi()); //FIXME + msector = new MagBSector(mRods, volumes.front()->minPhi()); //FIXME } return msector; } diff --git a/MagneticField/GeomBuilder/src/bSector.h b/MagneticField/GeomBuilder/src/bSector.h index 7a5de97632917..1724bc1d96941 100644 --- a/MagneticField/GeomBuilder/src/bSector.h +++ b/MagneticField/GeomBuilder/src/bSector.h @@ -26,19 +26,17 @@ class MagGeoBuilderFromDDD::bSector { ~bSector(); /// Distance from center along normal of sectors. - const float RN() const { - return volumes.front()->RN(); - } + const float RN() const { return volumes.front()->RN(); } /// Return all volumes in this sector - const handles & getVolumes() const {return volumes;} + const handles& getVolumes() const { return volumes; } /// Construct the MagBSector upon request. MagBSector* buildMagBSector() const; private: - std::vector rods; // the rods in this layer - handles volumes; // pointers to all volumes in the sector + std::vector rods; // the rods in this layer + handles volumes; // pointers to all volumes in the sector mutable MagBSector* msector; }; #endif diff --git a/MagneticField/GeomBuilder/src/bSlab.cc b/MagneticField/GeomBuilder/src/bSlab.cc index 616bbaaea7a3f..fd8b9b109a8be 100644 --- a/MagneticField/GeomBuilder/src/bSlab.cc +++ b/MagneticField/GeomBuilder/src/bSlab.cc @@ -14,55 +14,45 @@ using namespace SurfaceOrientation; using namespace std; -MagGeoBuilderFromDDD::bSlab::~bSlab(){} +MagGeoBuilderFromDDD::bSlab::~bSlab() {} -MagGeoBuilderFromDDD::bSlab::bSlab(handles::const_iterator begin, handles::const_iterator end) : - volumes(begin, end), - mslab(nullptr) -{ +MagGeoBuilderFromDDD::bSlab::bSlab(handles::const_iterator begin, handles::const_iterator end) + : volumes(begin, end), mslab(nullptr) { if (volumes.size() > 1) { // Sort volumes by dphi i.e. phi(j)-phi(i) > 0 if j>1. - precomputed_value_sort(volumes.begin(), volumes.end(), - ExtractPhiMax(), LessDPhi()); + precomputed_value_sort(volumes.begin(), volumes.end(), ExtractPhiMax(), LessDPhi()); - if (MagGeoBuilderFromDDD::debug) cout << " Slab has " << volumes.size() - << " volumes" << endl; + if (MagGeoBuilderFromDDD::debug) + cout << " Slab has " << volumes.size() << " volumes" << endl; // Check that all volumes have the same dZ handles::const_iterator i = volumes.begin(); float Zmax = (*i)->surface(zplus).position().z(); - float Zmin= (*i)->surface(zminus).position().z(); - for (++i; i != volumes.end(); ++i){ - const float epsilon = 0.001; + float Zmin = (*i)->surface(zminus).position().z(); + for (++i; i != volumes.end(); ++i) { + const float epsilon = 0.001; if (fabs(Zmax - (*i)->surface(zplus).position().z()) > epsilon || - fabs(Zmin - (*i)->surface(zminus).position().z()) > epsilon) { - if (MagGeoBuilderFromDDD::debug) cout << "*** WARNING: slabs Z coords not matching: D_Zmax = " - << fabs(Zmax - (*i)->surface(zplus).position().z()) - << " D_Zmin = " - << fabs(Zmin - (*i)->surface(zminus).position().z()) - << endl; + fabs(Zmin - (*i)->surface(zminus).position().z()) > epsilon) { + if (MagGeoBuilderFromDDD::debug) + cout << "*** WARNING: slabs Z coords not matching: D_Zmax = " + << fabs(Zmax - (*i)->surface(zplus).position().z()) + << " D_Zmin = " << fabs(Zmin - (*i)->surface(zminus).position().z()) << endl; } } } } -Geom::Phi MagGeoBuilderFromDDD::bSlab::minPhi() const { - return volumes.front()->minPhi(); -} - -Geom::Phi MagGeoBuilderFromDDD::bSlab::maxPhi() const { - return volumes.back()->maxPhi(); -} +Geom::Phi MagGeoBuilderFromDDD::bSlab::minPhi() const { return volumes.front()->minPhi(); } +Geom::Phi MagGeoBuilderFromDDD::bSlab::maxPhi() const { return volumes.back()->maxPhi(); } -MagBSlab * MagGeoBuilderFromDDD::bSlab::buildMagBSlab() const { - if (mslab==nullptr) { +MagBSlab* MagGeoBuilderFromDDD::bSlab::buildMagBSlab() const { + if (mslab == nullptr) { vector mVols; - for (handles::const_iterator vol = volumes.begin(); - vol!=volumes.end(); ++vol) { + for (handles::const_iterator vol = volumes.begin(); vol != volumes.end(); ++vol) { mVols.push_back((*vol)->magVolume); } - mslab = new MagBSlab(mVols, volumes.front()->surface(zminus).position().z()); //FIXME + mslab = new MagBSlab(mVols, volumes.front()->surface(zminus).position().z()); //FIXME } return mslab; } diff --git a/MagneticField/GeomBuilder/src/bSlab.h b/MagneticField/GeomBuilder/src/bSlab.h index 3208e4e2f482a..73f539b4d2625 100644 --- a/MagneticField/GeomBuilder/src/bSlab.h +++ b/MagneticField/GeomBuilder/src/bSlab.h @@ -22,11 +22,9 @@ class MagGeoBuilderFromDDD::bSlab { /// Destructor ~bSlab(); - + /// Distance from center along sector normal. - const float RN() const { - return volumes.front()->RN(); - } + const float RN() const { return volumes.front()->RN(); } /// Boundary in phi. // FIXME: use volumeHandle [max|min]Phi, which returns phi at median of @@ -34,13 +32,13 @@ class MagGeoBuilderFromDDD::bSlab { Geom::Phi minPhi() const; /// Boundary in phi. - Geom::Phi maxPhi() const; + Geom::Phi maxPhi() const; /// Construct the MagBSlab upon request. MagBSlab* buildMagBSlab() const; private: - handles volumes; // pointers to all volumes in the slab + handles volumes; // pointers to all volumes in the slab mutable MagBSlab* mslab; }; diff --git a/MagneticField/GeomBuilder/src/buildBox.icc b/MagneticField/GeomBuilder/src/buildBox.icc index 4623f34ad4c44..9b7a0ea768c95 100644 --- a/MagneticField/GeomBuilder/src/buildBox.icc +++ b/MagneticField/GeomBuilder/src/buildBox.icc @@ -5,25 +5,25 @@ */ void MagGeoBuilderFromDDD::volumeHandle::buildBox(const DDExpandedView &fv) { - if (MagGeoBuilderFromDDD::debug) cout << "Building box surfaces...: " <toGlobal(LocalVector( 1, 0, 0)); - GlobalVector planeYAxis = refPlane->toGlobal(LocalVector( 0, 1, 0)); - GlobalVector planeZAxis = refPlane->toGlobal(LocalVector( 0, 0, 1)); + GlobalVector planeXAxis = refPlane->toGlobal(LocalVector(1, 0, 0)); + GlobalVector planeYAxis = refPlane->toGlobal(LocalVector(0, 1, 0)); + GlobalVector planeZAxis = refPlane->toGlobal(LocalVector(0, 0, 1)); - - // FIXME Assumption: it is assumed that in the following that + // FIXME Assumption: it is assumed that in the following that // local Z is always along global Z // (true for version 1103l, not necessarily in the future) - + // To determine the orientation of other local axes, - // find local axis closest to global R + // find local axis closest to global R GlobalVector Rvol(refPlane->position().x(), refPlane->position().y(), refPlane->position().z()); double rnX = planeXAxis.dot(Rvol); double rnY = planeYAxis.dot(Rvol); @@ -32,8 +32,8 @@ void MagGeoBuilderFromDDD::volumeHandle::buildBox(const DDExpandedView &fv) { GlobalPoint pos_inner; GlobalPoint pos_phiplus; GlobalPoint pos_phiminus; - GlobalPoint pos_zplus(refPlane->toGlobal(LocalPoint(0.,0.,halfZ))); - GlobalPoint pos_zminus(refPlane->toGlobal(LocalPoint(0.,0.,-halfZ))); + GlobalPoint pos_zplus(refPlane->toGlobal(LocalPoint(0., 0., halfZ))); + GlobalPoint pos_zminus(refPlane->toGlobal(LocalPoint(0., 0., -halfZ))); Surface::RotationType rot_R; Surface::RotationType rot_phi; @@ -42,51 +42,44 @@ void MagGeoBuilderFromDDD::volumeHandle::buildBox(const DDExpandedView &fv) { if (fabs(rnX) > fabs(rnY)) { // X is ~parallel to global R dir, Y is along +/- phi theRN = fabs(rnX); - if (rnX<0) { + if (rnX < 0) { halfX = -halfX; halfY = -halfY; } - pos_outer = GlobalPoint(refPlane->toGlobal(LocalPoint(halfX,0.,0.))); - pos_inner = GlobalPoint(refPlane->toGlobal(LocalPoint(-halfX,0.,0.))); - pos_phiplus = GlobalPoint(refPlane->toGlobal(LocalPoint(0.,halfY,0.))); - pos_phiminus = GlobalPoint(refPlane->toGlobal(LocalPoint(0.,-halfY,0.))); + pos_outer = GlobalPoint(refPlane->toGlobal(LocalPoint(halfX, 0., 0.))); + pos_inner = GlobalPoint(refPlane->toGlobal(LocalPoint(-halfX, 0., 0.))); + pos_phiplus = GlobalPoint(refPlane->toGlobal(LocalPoint(0., halfY, 0.))); + pos_phiminus = GlobalPoint(refPlane->toGlobal(LocalPoint(0., -halfY, 0.))); rot_R = Surface::RotationType(planeZAxis, planeYAxis); - rot_phi = Surface::RotationType(planeZAxis, planeXAxis); // opposite to y axis + rot_phi = Surface::RotationType(planeZAxis, planeXAxis); // opposite to y axis } else { // Y is ~parallel to global R dir, X is along +/- phi theRN = fabs(rnY); - if (rnY<0) { + if (rnY < 0) { halfX = -halfX; halfY = -halfY; } - pos_outer = GlobalPoint(refPlane->toGlobal(LocalPoint(0.,halfY,0.))); - pos_inner = GlobalPoint(refPlane->toGlobal(LocalPoint(0.,-halfY,0.))); - pos_phiplus = GlobalPoint(refPlane->toGlobal(LocalPoint(-halfX,0.,0.))); - pos_phiminus = GlobalPoint(refPlane->toGlobal(LocalPoint(halfX,0.,0.))); + pos_outer = GlobalPoint(refPlane->toGlobal(LocalPoint(0., halfY, 0.))); + pos_inner = GlobalPoint(refPlane->toGlobal(LocalPoint(0., -halfY, 0.))); + pos_phiplus = GlobalPoint(refPlane->toGlobal(LocalPoint(-halfX, 0., 0.))); + pos_phiminus = GlobalPoint(refPlane->toGlobal(LocalPoint(halfX, 0., 0.))); rot_R = Surface::RotationType(planeZAxis, planeXAxis); - rot_phi = Surface::RotationType(planeZAxis, planeYAxis); // opposite to x axis + rot_phi = Surface::RotationType(planeZAxis, planeYAxis); // opposite to x axis } + if (MagGeoBuilderFromDDD::debug) + cout << " halfX: " << halfX << " halfY: " << halfY << " halfZ: " << halfZ << endl + << "RN " << theRN << endl; - if (MagGeoBuilderFromDDD::debug) cout << " halfX: " << halfX - << " halfY: " << halfY - << " halfZ: " << halfZ << endl - << "RN " << theRN << endl; - - if (MagGeoBuilderFromDDD::debug) cout << "pos_outer " << pos_outer << " " - << pos_outer.perp() << " " << pos_outer.phi() << endl - << "pos_inner " << pos_inner << " " - << pos_inner.perp() << " " << pos_inner.phi() << endl - << "pos_zplus " << pos_zplus << " " - << pos_zplus.perp() << " " << pos_zplus.phi() << endl - << "pos_zminus " << pos_zminus << " " - << pos_zminus.perp() << " " << pos_zminus.phi() << endl - << "pos_phiplus " << pos_phiplus << " " - << pos_phiplus.perp() << " " << pos_phiplus.phi() <(pos_phiplus.phi()-pos_phiminus.phi()) < 0. ) { + if (Geom::Phi(pos_phiplus.phi() - pos_phiminus.phi()) < 0.) { cout << "*** WARNING: pos_phiplus < pos_phiminus for box" << endl; } - } + } // FIXME: use builder - surfaces[outer] = new Plane(pos_outer, rot_R); - surfaces[inner] = new Plane(pos_inner, rot_R); - surfaces[zplus] = new Plane(pos_zplus, rot_Z); - surfaces[zminus] = new Plane(pos_zminus, rot_Z); - surfaces[phiplus] = new Plane(pos_phiplus, rot_phi); + surfaces[outer] = new Plane(pos_outer, rot_R); + surfaces[inner] = new Plane(pos_inner, rot_R); + surfaces[zplus] = new Plane(pos_zplus, rot_Z); + surfaces[zminus] = new Plane(pos_zminus, rot_Z); + surfaces[phiplus] = new Plane(pos_phiplus, rot_phi); surfaces[phiminus] = new Plane(pos_phiminus, rot_phi); if (MagGeoBuilderFromDDD::debug) { - cout << "rot_R " << surfaces[outer]->toGlobal(LocalVector(0.,0.,1.)) <toGlobal(LocalVector(0.,0.,1.)) <toGlobal(LocalVector(0.,0.,1.)) - << endl; + cout << "rot_R " << surfaces[outer]->toGlobal(LocalVector(0., 0., 1.)) << endl + << "rot_Z " << surfaces[zplus]->toGlobal(LocalVector(0., 0., 1.)) << endl + << "rot_phi " << surfaces[phiplus]->toGlobal(LocalVector(0., 0., 1.)) << endl; } - + // Save volume boundaries - theRMin = fabs(surfaces[inner]->toLocal(GlobalPoint(0,0,0)).z()); - theRMax = fabs(surfaces[outer]->toLocal(GlobalPoint(0,0,0)).z()); + theRMin = fabs(surfaces[inner]->toLocal(GlobalPoint(0, 0, 0)).z()); + theRMax = fabs(surfaces[outer]->toLocal(GlobalPoint(0, 0, 0)).z()); // FIXME: use phi of middle plane of phiminus surface. Is not the absolute phimin! thePhiMin = surfaces[phiminus]->position().phi(); } diff --git a/MagneticField/GeomBuilder/src/buildCons.icc b/MagneticField/GeomBuilder/src/buildCons.icc index 5b4771bce2d95..23f70af2286cd 100644 --- a/MagneticField/GeomBuilder/src/buildCons.icc +++ b/MagneticField/GeomBuilder/src/buildCons.icc @@ -7,87 +7,76 @@ #include "DataFormats/GeometrySurface/interface/SimpleConeBounds.h" void MagGeoBuilderFromDDD::volumeHandle::buildCons(const DDExpandedView &fv) { - if (MagGeoBuilderFromDDD::debug) cout << "Building cons surfaces...: " < phiCenter(startPhi + deltaPhi/2.); - center_ = refPlane->toGlobal(LocalPoint(rCentr*cos(phiCenter), - rCentr*sin(phiCenter), 0.)); + double rZmin = (rInMinusZ + rOutMinusZ) / 2.; + double rZmax = (rInPlusZ + rOutPlusZ) / 2.; + double rCentr = (rZmin + rZmax) / 2.; + Geom::Phi phiCenter(startPhi + deltaPhi / 2.); + center_ = refPlane->toGlobal(LocalPoint(rCentr * cos(phiCenter), rCentr * sin(phiCenter), 0.)); // For cons and tubs RN = R. theRN = rCentr; - + const double epsilon = 1e-5; - if (abs(rInPlusZ-rInMinusZ)(&(*surfaces[outer]))->bounds().width() < -// dynamic_cast(&(*surfaces[inner]))->bounds().width()){ -// cout << "*** WARNING: pos_outer < pos_inner " << endl; -// } + // if (dynamic_cast(&(*surfaces[outer]))->bounds().width() < + // dynamic_cast(&(*surfaces[inner]))->bounds().width()){ + // cout << "*** WARNING: pos_outer < pos_inner " << endl; + // } // Save volume boundaries theRMin = min(rInMinusZ, rInPlusZ); diff --git a/MagneticField/GeomBuilder/src/buildPseudoTrap.icc b/MagneticField/GeomBuilder/src/buildPseudoTrap.icc index 40dde9ab2cfcc..3f3ff10376290 100644 --- a/MagneticField/GeomBuilder/src/buildPseudoTrap.icc +++ b/MagneticField/GeomBuilder/src/buildPseudoTrap.icc @@ -11,52 +11,52 @@ */ void MagGeoBuilderFromDDD::volumeHandle::buildPseudoTrap(const DDExpandedView &fv) { - if (MagGeoBuilderFromDDD::debug) cout << "Building PseudoTrap surfaces...: " < epsilon ) { + if (MagGeoBuilderFromDDD::debug) { + if (y1 - y2 > epsilon) { cout << "*** WARNING: unexpected pseudotrapezoid parameters." << endl; } // Check that volume is convex (no concave volume in current geometry...) - if (radius*(atMinusZ?-1.:+1)<0.) { + if (radius * (atMinusZ ? -1. : +1) < 0.) { cout << "*** WARNING: pseudotrapezoid is concave" << endl; } } - + // CAVEAT: pseudotraps are rotated in a different way as traps, // since they have local Z along global R... - GlobalVector planeXAxis = refPlane->toGlobal(LocalVector( 1, 0, 0)); - GlobalVector planeYAxis = refPlane->toGlobal(LocalVector( 0, 1, 0)); - GlobalVector planeZAxis = refPlane->toGlobal(LocalVector( 0, 0, 1)); + GlobalVector planeXAxis = refPlane->toGlobal(LocalVector(1, 0, 0)); + GlobalVector planeYAxis = refPlane->toGlobal(LocalVector(0, 1, 0)); + GlobalVector planeZAxis = refPlane->toGlobal(LocalVector(0, 0, 1)); //FIXME assumption: here we do use the assumption on the orientation / //of local Z (see above) - GlobalVector Rvol(refPlane->position().x(), refPlane->position().y(), refPlane->position().z()); + GlobalVector Rvol(refPlane->position().x(), refPlane->position().y(), refPlane->position().z()); theRN = fabs(planeZAxis.dot(Rvol)); - double fR = fabs(radius); Sides cyl_side; Sides plane_side; @@ -67,41 +67,38 @@ void MagGeoBuilderFromDDD::volumeHandle::buildPseudoTrap(const DDExpandedView &f cyl_side = outer; plane_side = inner; } - GlobalPoint pos_Rplane(refPlane->toGlobal(LocalPoint(0.,0.,(atMinusZ ? +halfZ : -halfZ)))); - GlobalPoint pos_zplus(refPlane->toGlobal(LocalPoint(0.,y1,0.))); - GlobalPoint pos_zminus(refPlane->toGlobal(LocalPoint(0.,-y1,0.))); - double halfX((x1+x2)/2.); - GlobalPoint pos_phiplus(refPlane->toGlobal(LocalPoint(+halfX,0.,0.))); - GlobalPoint pos_phiminus(refPlane->toGlobal(LocalPoint(-halfX,0.,0.))); + GlobalPoint pos_Rplane(refPlane->toGlobal(LocalPoint(0., 0., (atMinusZ ? +halfZ : -halfZ)))); + GlobalPoint pos_zplus(refPlane->toGlobal(LocalPoint(0., y1, 0.))); + GlobalPoint pos_zminus(refPlane->toGlobal(LocalPoint(0., -y1, 0.))); + double halfX((x1 + x2) / 2.); + GlobalPoint pos_phiplus(refPlane->toGlobal(LocalPoint(+halfX, 0., 0.))); + GlobalPoint pos_phiminus(refPlane->toGlobal(LocalPoint(-halfX, 0., 0.))); //Check that cylinder is centered on beam axis... float rcheck; - if(atMinusZ) rcheck = refPlane->toGlobal(LocalPoint(x1,0.,-halfZ)).perp(); - else rcheck = refPlane->toGlobal(LocalPoint(x2,0.,+halfZ)).perp(); + if (atMinusZ) + rcheck = refPlane->toGlobal(LocalPoint(x1, 0., -halfZ)).perp(); + else + rcheck = refPlane->toGlobal(LocalPoint(x2, 0., +halfZ)).perp(); if (MagGeoBuilderFromDDD::debug) { - if ( fabs(rcheck - fR) > 100.*epsilon){ //FIXME! + if (fabs(rcheck - fR) > 100. * epsilon) { //FIXME! cout << setprecision(10); - cout << "*** WARNING: Cylinder surface not centered on beam axis " - << rcheck << " " << fR << " " << fabs(rcheck - fR) << endl; + cout << "*** WARNING: Cylinder surface not centered on beam axis " << rcheck << " " << fR << " " + << fabs(rcheck - fR) << endl; cout << setprecision(6); } } if (MagGeoBuilderFromDDD::debug) { - cout << "RN " << theRN << endl - << "pos_Rplane " << pos_Rplane << " " - << pos_Rplane.perp() << " " << pos_Rplane.phi() << endl - << "pos_zplus " << pos_zplus << " " - << pos_zplus.perp() << " " << pos_zplus.phi() << endl - << "pos_zminus " << pos_zminus << " " - << pos_zminus.perp() << " " << pos_zminus.phi() << endl - << "pos_phiplus " << pos_phiplus << " " - << pos_phiplus.perp() << " " << pos_phiplus.phi() <(pos_phiplus.phi()-pos_phiminus.phi()) < 0. ) { + if (Geom::Phi(pos_phiplus.phi() - pos_phiminus.phi()) < 0.) { cout << "*** WARNING: pos_phiplus < pos_phiminus for pseudotrapezoid" << endl; } - - GlobalVector z_phiplus = - (refPlane->toGlobal(LocalVector((x2-x1)/2.,0.,halfZ))).unit(); - GlobalVector z_phiminus = - (refPlane->toGlobal(LocalVector(-(x2-x1)/2.,0.,halfZ))).unit(); + GlobalVector z_phiplus = (refPlane->toGlobal(LocalVector((x2 - x1) / 2., 0., halfZ))).unit(); + GlobalVector z_phiminus = (refPlane->toGlobal(LocalVector(-(x2 - x1) / 2., 0., halfZ))).unit(); if (MagGeoBuilderFromDDD::debug) { cout << "z_phiplus " << z_phiplus << " " << z_phiplus.phi() << endl; @@ -126,34 +120,29 @@ void MagGeoBuilderFromDDD::volumeHandle::buildPseudoTrap(const DDExpandedView &f Surface::RotationType rot_R(planeYAxis, planeXAxis); Surface::RotationType rot_Z(planeXAxis, planeZAxis); - Surface::RotationType rot_phiplus(planeYAxis, z_phiplus); + Surface::RotationType rot_phiplus(planeYAxis, z_phiplus); Surface::RotationType rot_phiminus(planeYAxis, z_phiminus); - + // FIXME: use builder surfaces[plane_side] = new Plane(pos_Rplane, rot_R); - surfaces[cyl_side] = new Cylinder(fR,Surface::PositionType(0,0,center_.z()), - Surface::RotationType()); - + surfaces[cyl_side] = new Cylinder(fR, Surface::PositionType(0, 0, center_.z()), Surface::RotationType()); - surfaces[zplus] = new Plane(pos_zplus, rot_Z); - surfaces[zminus] = new Plane(pos_zminus, rot_Z); - surfaces[phiplus] = new Plane(pos_phiplus, rot_phiplus); + surfaces[zplus] = new Plane(pos_zplus, rot_Z); + surfaces[zminus] = new Plane(pos_zminus, rot_Z); + surfaces[phiplus] = new Plane(pos_phiplus, rot_phiplus); surfaces[phiminus] = new Plane(pos_phiminus, rot_phiminus); if (MagGeoBuilderFromDDD::debug) { - cout << "rot_R " << surfaces[plane_side]->toGlobal(LocalVector(0.,0.,1.)) << endl - << "rot_Z " << surfaces[zplus]->toGlobal(LocalVector(0.,0.,1.)) << endl - << "rot_phi+ " << surfaces[phiplus]->toGlobal(LocalVector(0.,0.,1.)) - << " phi " << surfaces[phiplus]->toGlobal(LocalVector(0.,0.,1.)).phi() - << endl - << "rot_phi- " << surfaces[phiminus]->toGlobal(LocalVector(0.,0.,1.)) - << " phi " << surfaces[phiminus]->toGlobal(LocalVector(0.,0.,1.)).phi() - << endl; + cout << "rot_R " << surfaces[plane_side]->toGlobal(LocalVector(0., 0., 1.)) << endl + << "rot_Z " << surfaces[zplus]->toGlobal(LocalVector(0., 0., 1.)) << endl + << "rot_phi+ " << surfaces[phiplus]->toGlobal(LocalVector(0., 0., 1.)) << " phi " + << surfaces[phiplus]->toGlobal(LocalVector(0., 0., 1.)).phi() << endl + << "rot_phi- " << surfaces[phiminus]->toGlobal(LocalVector(0., 0., 1.)) << " phi " + << surfaces[phiminus]->toGlobal(LocalVector(0., 0., 1.)).phi() << endl; } - // Save volume boundaries - double R1 = fabs(surfaces[plane_side]->toLocal(GlobalPoint(0,0,0)).z()); + double R1 = fabs(surfaces[plane_side]->toLocal(GlobalPoint(0, 0, 0)).z()); theRMin = min(fR, R1); theRMax = max(fR, R1); // FIXME: use phi of middle plane of phiminus surface. Is not the absolute phimin! diff --git a/MagneticField/GeomBuilder/src/buildTrap.icc b/MagneticField/GeomBuilder/src/buildTrap.icc index dbf57753009e8..8f2e728676cfe 100644 --- a/MagneticField/GeomBuilder/src/buildTrap.icc +++ b/MagneticField/GeomBuilder/src/buildTrap.icc @@ -4,59 +4,56 @@ * \author N. Amapane - INFN Torino */ - void MagGeoBuilderFromDDD::volumeHandle::buildTrap(const DDExpandedView &fv) { - if (MagGeoBuilderFromDDD::debug) cout << "Building trapezoid surfaces...: " < epsilon || - phi > epsilon || - y1-y2 > epsilon || - x1-x3 > epsilon || - x2-x4 > epsilon || - alpha1-alpha2>epsilon) { + if (theta > epsilon || phi > epsilon || y1 - y2 > epsilon || x1 - x3 > epsilon || x2 - x4 > epsilon || + alpha1 - alpha2 > epsilon) { cout << "*** WARNING: unexpected trapezoid parameters." << endl; } } - + // Used parameters halfZ, x1, x2, y1, alpha1 - GlobalVector planeXAxis = refPlane->toGlobal(LocalVector( 1, 0, 0)); - GlobalVector planeYAxis = refPlane->toGlobal(LocalVector( 0, 1, 0)); - GlobalVector planeZAxis = refPlane->toGlobal(LocalVector( 0, 0, 1)); + GlobalVector planeXAxis = refPlane->toGlobal(LocalVector(1, 0, 0)); + GlobalVector planeYAxis = refPlane->toGlobal(LocalVector(0, 1, 0)); + GlobalVector planeZAxis = refPlane->toGlobal(LocalVector(0, 0, 1)); // For the correct definition of inner, outer, phiplus, phiminus, - // Zplus, zminus the orientation of axes must be checked. - // Normal (convention in version 85l_030919): - // planeXAxis in the direction of decreasing global phi; - // planeZAxis in the direction of global Z; + // Zplus, zminus the orientation of axes must be checked. + // Normal (convention in version 85l_030919): + // planeXAxis in the direction of decreasing global phi; + // planeZAxis in the direction of global Z; // => Invert the sign of local X and Z if planeZAxis points to - global Z // FIXME Assumption: it is assumed that local Y is always along global R @@ -64,34 +61,29 @@ void MagGeoBuilderFromDDD::volumeHandle::buildTrap(const DDExpandedView &fv) { GlobalVector Rvol(refPlane->position().x(), refPlane->position().y(), refPlane->position().z()); theRN = fabs(planeYAxis.dot(Rvol)); - if (planeZAxis.z()<0.) { + if (planeZAxis.z() < 0.) { x1 = -x1; x2 = -x2; halfZ = -halfZ; } - double halfX((x1+x2)/2.); - - GlobalPoint pos_outer(refPlane->toGlobal(LocalPoint(0.,y1,0.))); - GlobalPoint pos_inner(refPlane->toGlobal(LocalPoint(0.,-y1,0.))); - GlobalPoint pos_zplus(refPlane->toGlobal(LocalPoint(0.,0.,halfZ))); - GlobalPoint pos_zminus(refPlane->toGlobal(LocalPoint(0.,0.,-halfZ))); - GlobalPoint pos_phiplus(refPlane->toGlobal(LocalPoint(-halfX,0.,0.))); - GlobalPoint pos_phiminus(refPlane->toGlobal(LocalPoint(halfX,0.,0.))); - - if (MagGeoBuilderFromDDD::debug) cout << "RN " << theRN << endl - << "pos_outer " << pos_outer << " " - << pos_outer.perp() << " " << pos_outer.phi() << endl - << "pos_inner " << pos_inner << " " - << pos_inner.perp() << " " << pos_inner.phi() << endl - << "pos_zplus " << pos_zplus << " " - << pos_zplus.perp() << " " << pos_zplus.phi() << endl - << "pos_zminus " << pos_zminus << " " - << pos_zminus.perp() << " " << pos_zminus.phi() << endl - << "pos_phiplus " << pos_phiplus << " " - << pos_phiplus.perp() << " " << pos_phiplus.phi() <toGlobal(LocalPoint(0., y1, 0.))); + GlobalPoint pos_inner(refPlane->toGlobal(LocalPoint(0., -y1, 0.))); + GlobalPoint pos_zplus(refPlane->toGlobal(LocalPoint(0., 0., halfZ))); + GlobalPoint pos_zminus(refPlane->toGlobal(LocalPoint(0., 0., -halfZ))); + GlobalPoint pos_phiplus(refPlane->toGlobal(LocalPoint(-halfX, 0., 0.))); + GlobalPoint pos_phiminus(refPlane->toGlobal(LocalPoint(halfX, 0., 0.))); + + if (MagGeoBuilderFromDDD::debug) + cout << "RN " << theRN << endl + << "pos_outer " << pos_outer << " " << pos_outer.perp() << " " << pos_outer.phi() << endl + << "pos_inner " << pos_inner << " " << pos_inner.perp() << " " << pos_inner.phi() << endl + << "pos_zplus " << pos_zplus << " " << pos_zplus.perp() << " " << pos_zplus.phi() << endl + << "pos_zminus " << pos_zminus << " " << pos_zminus.perp() << " " << pos_zminus.phi() << endl + << "pos_phiplus " << pos_phiplus << " " << pos_phiplus.perp() << " " << pos_phiplus.phi() << endl + << "pos_phiminus " << pos_phiminus << " " << pos_phiminus.perp() << " " << pos_phiminus.phi() << endl; // Check ordering. if (MagGeoBuilderFromDDD::debug) { @@ -101,61 +93,57 @@ void MagGeoBuilderFromDDD::volumeHandle::buildTrap(const DDExpandedView &fv) { if (pos_zplus.z() < pos_zminus.z()) { cout << "*** WARNING: pos_zplus < pos_zminus for trapezoid" << endl; } - if (Geom::Phi(pos_phiplus.phi()-pos_phiminus.phi()) < 0. ) { + if (Geom::Phi(pos_phiplus.phi() - pos_phiminus.phi()) < 0.) { cout << "*** WARNING: pos_phiplus < pos_phiminus for trapezoid" << endl; - } + } } - + // Local Y axis of the faces at +-phi. The local X is = global Z. - GlobalVector y_phiplus = - (refPlane->toGlobal(LocalVector((tan(alpha1)*y1-(x2-x1)/2.),y1,0.))).unit(); - GlobalVector y_phiminusV = (refPlane->toGlobal(LocalVector((tan(alpha1)*y1+(x2-x1)/2.),y1,0.))); + GlobalVector y_phiplus = (refPlane->toGlobal(LocalVector((tan(alpha1) * y1 - (x2 - x1) / 2.), y1, 0.))).unit(); + GlobalVector y_phiminusV = (refPlane->toGlobal(LocalVector((tan(alpha1) * y1 + (x2 - x1) / 2.), y1, 0.))); GlobalVector y_phiminus = y_phiminusV.unit(); - - if (MagGeoBuilderFromDDD::debug) { + if (MagGeoBuilderFromDDD::debug) { cout << "y_phiplus " << y_phiplus << endl; cout << "y_phiminus " << y_phiminus << endl; } - + Surface::RotationType rot_R(planeZAxis, planeXAxis); Surface::RotationType rot_Z(planeXAxis, planeYAxis); - Surface::RotationType rot_phiplus(planeZAxis, y_phiplus); + Surface::RotationType rot_phiplus(planeZAxis, y_phiplus); Surface::RotationType rot_phiminus(planeZAxis, y_phiminus); // FIXME: use builder - surfaces[outer] = new Plane(pos_outer, rot_R); - surfaces[inner] = new Plane(pos_inner, rot_R); - surfaces[zplus] = new Plane(pos_zplus, rot_Z); - surfaces[zminus] = new Plane(pos_zminus, rot_Z); - surfaces[phiplus] = new Plane(pos_phiplus, rot_phiplus); + surfaces[outer] = new Plane(pos_outer, rot_R); + surfaces[inner] = new Plane(pos_inner, rot_R); + surfaces[zplus] = new Plane(pos_zplus, rot_Z); + surfaces[zminus] = new Plane(pos_zminus, rot_Z); + surfaces[phiplus] = new Plane(pos_phiplus, rot_phiplus); surfaces[phiminus] = new Plane(pos_phiminus, rot_phiminus); // Save volume boundaries - theRMin = fabs(surfaces[inner]->toLocal(GlobalPoint(0,0,0)).z()); - theRMax = fabs(surfaces[outer]->toLocal(GlobalPoint(0,0,0)).z()); + theRMin = fabs(surfaces[inner]->toLocal(GlobalPoint(0, 0, 0)).z()); + theRMax = fabs(surfaces[outer]->toLocal(GlobalPoint(0, 0, 0)).z()); // Setting "absolute" phi boundary spots a problem in V85l // e.g. vol 139 (origin: small inconsistency in volumes.txt) // So let's keep phi at middle phi- plane... - // FIXME: Remove this workaround once support for v85l is dropped. - if (name.substr(0,3)=="V_Z") { + // FIXME: Remove this workaround once support for v85l is dropped. + if (name.substr(0, 3) == "V_Z") { thePhiMin = surfaces[phiminus]->position().phi(); } else { - thePhiMin = min((pos_phiminus+y_phiminusV).phi(), (pos_phiminus-y_phiminusV).phi()); + thePhiMin = min((pos_phiminus + y_phiminusV).phi(), (pos_phiminus - y_phiminusV).phi()); } - + if (MagGeoBuilderFromDDD::debug) { - cout << "rot_R " << surfaces[outer]->toGlobal(LocalVector(0.,0.,1.)) << endl - << "rot_Z " << surfaces[zplus]->toGlobal(LocalVector(0.,0.,1.)) << endl - << "rot_phi+ " << surfaces[phiplus]->toGlobal(LocalVector(0.,0.,1.)) - << " phi " << surfaces[phiplus]->toGlobal(LocalVector(0.,0.,1.)).phi() - << endl - << "rot_phi- " << surfaces[phiminus]->toGlobal(LocalVector(0.,0.,1.)) - << " phi " << surfaces[phiminus]->toGlobal(LocalVector(0.,0.,1.)).phi() - << endl; - - if (fabs(surfaces[phiminus]->position().phi() - thePhiMin)>1e-5) { + cout << "rot_R " << surfaces[outer]->toGlobal(LocalVector(0., 0., 1.)) << endl + << "rot_Z " << surfaces[zplus]->toGlobal(LocalVector(0., 0., 1.)) << endl + << "rot_phi+ " << surfaces[phiplus]->toGlobal(LocalVector(0., 0., 1.)) << " phi " + << surfaces[phiplus]->toGlobal(LocalVector(0., 0., 1.)).phi() << endl + << "rot_phi- " << surfaces[phiminus]->toGlobal(LocalVector(0., 0., 1.)) << " phi " + << surfaces[phiminus]->toGlobal(LocalVector(0., 0., 1.)).phi() << endl; + + if (fabs(surfaces[phiminus]->position().phi() - thePhiMin) > 1e-5) { cout << " Trapez. phiMin = " << thePhiMin << endl; } } diff --git a/MagneticField/GeomBuilder/src/buildTruncTubs.icc b/MagneticField/GeomBuilder/src/buildTruncTubs.icc index b604a7e92f489..61603cc305fe9 100644 --- a/MagneticField/GeomBuilder/src/buildTruncTubs.icc +++ b/MagneticField/GeomBuilder/src/buildTruncTubs.icc @@ -10,101 +10,97 @@ */ void MagGeoBuilderFromDDD::volumeHandle::buildTruncTubs(const DDExpandedView &fv) { - if (MagGeoBuilderFromDDD::debug) cout << "Building TruncTubs surfaces...: " <toGlobal(LocalVector( 1, 0, 0)); // GlobalVector planeYAxis = refPlane->toGlobal(LocalVector( 0, 1, 0)); - GlobalVector planeZAxis = refPlane->toGlobal(LocalVector( 0, 0, 1)); - + GlobalVector planeZAxis = refPlane->toGlobal(LocalVector(0, 0, 1)); Sides cyl_side; Sides plane_side; - double rCyl=0; - double rCentr=0; + double rCyl = 0; + double rCentr = 0; if (cutInside) { cyl_side = outer; rCyl = rOut; plane_side = inner; - rCentr = (max(max(rIn,cutAtStart),cutAtDelta)+rOut)/2.; + rCentr = (max(max(rIn, cutAtStart), cutAtDelta) + rOut) / 2.; } else { cyl_side = inner; rCyl = rIn; plane_side = outer; - rCentr = (rIn+min(min(rOut,cutAtStart),cutAtDelta))/2.; + rCentr = (rIn + min(min(rOut, cutAtStart), cutAtDelta)) / 2.; } // Recalculate center: (for a DDTruncTubs, DDD gives 0,0,Z) - // The R of center is in the middle of the arc of cylinder fully contained + // The R of center is in the middle of the arc of cylinder fully contained // in the trunctubs. - Geom::Phi phiCenter(startPhi + deltaPhi/2.); - center_ = refPlane->toGlobal(LocalPoint(rCentr*cos(phiCenter), - rCentr*sin(phiCenter), 0.)); - - // FIXME!! Actually should recompute RN from pos_Rplane; should not + Geom::Phi phiCenter(startPhi + deltaPhi / 2.); + center_ = refPlane->toGlobal(LocalPoint(rCentr * cos(phiCenter), rCentr * sin(phiCenter), 0.)); + + // FIXME!! Actually should recompute RN from pos_Rplane; should not // matter anyhow - theRN = rCentr; - + theRN = rCentr; + // For simplicity, the position of the cut plane is taken at one of the - // phi edges, where R is known - // FIXME! move to center of plane + // phi edges, where R is known + // FIXME! move to center of plane // FIXME: compute. in double prec (not float) GlobalPoint pos_Rplane(refPlane->toGlobal(LocalPoint(LocalPoint::Cylindrical(cutAtStart, startPhi, 0.)))); // Compute angle of the cut plane // Got any easier formula? // FIXME: check that it still holds for cutAtStart > cutAtDelta - double c = sqrt(cutAtDelta*cutAtDelta + - cutAtStart*cutAtStart - - 2*cutAtDelta*cutAtStart*cos(deltaPhi)); - double alpha = startPhi - asin(sin(deltaPhi)*cutAtDelta/c); - GlobalVector x_Rplane = refPlane->toGlobal(LocalVector(cos(alpha),sin(alpha),0)); + double c = sqrt(cutAtDelta * cutAtDelta + cutAtStart * cutAtStart - 2 * cutAtDelta * cutAtStart * cos(deltaPhi)); + double alpha = startPhi - asin(sin(deltaPhi) * cutAtDelta / c); + GlobalVector x_Rplane = refPlane->toGlobal(LocalVector(cos(alpha), sin(alpha), 0)); Surface::RotationType rot_R(planeZAxis, x_Rplane); // FIXME: use builder surfaces[plane_side] = new Plane(pos_Rplane, rot_R); - surfaces[cyl_side] = new Cylinder(rCyl, Surface::PositionType(0,0,center_.z()), - Surface::RotationType()); - + surfaces[cyl_side] = new Cylinder(rCyl, Surface::PositionType(0, 0, center_.z()), Surface::RotationType()); // Build lateral surfaces. - // Note that with the choice of center descrived above, the + // Note that with the choice of center descrived above, the // plane position (origin of r.f.) of the smallest phi face // will be its center, while this is not true for the largest phi face. - buildPhiZSurf(startPhi, deltaPhi, zhalf, rCentr); + buildPhiZSurf(startPhi, deltaPhi, zhalf, rCentr); if (MagGeoBuilderFromDDD::debug) { - cout << "pos_Rplane " << pos_Rplane << " " - << pos_Rplane.perp() << " " << pos_Rplane.phi() << endl - << "rot_R " << surfaces[plane_side]->toGlobal(LocalVector(0.,0.,1.)) << " phi " << surfaces[plane_side]->toGlobal(LocalVector(0.,0.,1.)).phi() << endl - << "cyl radius " << rCyl << endl; + cout << "pos_Rplane " << pos_Rplane << " " << pos_Rplane.perp() << " " << pos_Rplane.phi() << endl + << "rot_R " << surfaces[plane_side]->toGlobal(LocalVector(0., 0., 1.)) << " phi " + << surfaces[plane_side]->toGlobal(LocalVector(0., 0., 1.)).phi() << endl + << "cyl radius " << rCyl << endl; -// // Check ordering. - if ((pos_Rplane.perp() < rCyl) != cutInside) { + // // Check ordering. + if ((pos_Rplane.perp() < rCyl) != cutInside) { cout << "*** WARNING: pos_outer < pos_inner " << endl; } } - + // Save volume boundaries theRMin = rIn; theRMax = rOut; diff --git a/MagneticField/GeomBuilder/src/buildTubs.icc b/MagneticField/GeomBuilder/src/buildTubs.icc index d4faa21ddacca..b376d1baf3cd9 100644 --- a/MagneticField/GeomBuilder/src/buildTubs.icc +++ b/MagneticField/GeomBuilder/src/buildTubs.icc @@ -1,52 +1,48 @@ void MagGeoBuilderFromDDD::volumeHandle::buildTubs(const DDExpandedView &fv) { - if (MagGeoBuilderFromDDD::debug) cout << "Building tubs surfaces...: " < phiCenter(startPhi + deltaPhi/2.); - center_ = refPlane->toGlobal(LocalPoint(rCentr*cos(phiCenter), - rCentr*sin(phiCenter), 0.)); + double rCentr = (rIn + rOut) / 2.; + Geom::Phi phiCenter(startPhi + deltaPhi / 2.); + center_ = refPlane->toGlobal(LocalPoint(rCentr * cos(phiCenter), rCentr * sin(phiCenter), 0.)); // For cons and tubs RN = R. theRN = rCentr; // FIXME: use builder - surfaces[outer] = new Cylinder(rOut,Surface::PositionType(0,0,center_.z()), - Surface::RotationType()); - - + surfaces[outer] = new Cylinder(rOut, Surface::PositionType(0, 0, center_.z()), Surface::RotationType()); // The inner cylider may be degenreate. Not easy to have a null surface // in the current implementation (surfaces[inner] is a RCP!) - surfaces[inner] = new Cylinder(rIn, Surface::PositionType(0,0,center_.z()), - Surface::RotationType()); - - + surfaces[inner] = new Cylinder(rIn, Surface::PositionType(0, 0, center_.z()), Surface::RotationType()); + // All other surfaces buildPhiZSurf(startPhi, deltaPhi, zhalf, rCentr); // Check ordering. - if (MagGeoBuilderFromDDD::debug) { - if (dynamic_cast(&(*surfaces[outer]))->radius() < - dynamic_cast(&(*surfaces[inner]))->radius()){ + if (MagGeoBuilderFromDDD::debug) { + if (dynamic_cast(&(*surfaces[outer]))->radius() < + dynamic_cast(&(*surfaces[inner]))->radius()) { cout << "*** WARNING: pos_outer < pos_inner " << endl; } } - + // Save volume boundaries theRMin = rIn; theRMax = rOut; diff --git a/MagneticField/GeomBuilder/src/eLayer.cc b/MagneticField/GeomBuilder/src/eLayer.cc index 7d48ed067141f..e0e5e8d767180 100644 --- a/MagneticField/GeomBuilder/src/eLayer.cc +++ b/MagneticField/GeomBuilder/src/eLayer.cc @@ -16,43 +16,39 @@ using namespace SurfaceOrientation; using namespace std; //The ctor is in charge of finding sectors inside the layer. -MagGeoBuilderFromDDD::eLayer::eLayer(handles::const_iterator begin, - handles::const_iterator end) : - theVolumes(begin,end), - mlayer(nullptr) -{ +MagGeoBuilderFromDDD::eLayer::eLayer(handles::const_iterator begin, handles::const_iterator end) + : theVolumes(begin, end), mlayer(nullptr) { // bool debug=MagGeoBuilderFromDDD::debug; - // Sort in R + // Sort in R precomputed_value_sort(theVolumes.begin(), theVolumes.end(), ExtractR()); -// if (debug) { -// cout << " elements: " << theVolumes.size() << " unique volumes: "; -// volumeHandle::printUniqueNames(theVolumes.begin(), theVolumes.end()); -// } + // if (debug) { + // cout << " elements: " << theVolumes.size() << " unique volumes: "; + // volumeHandle::printUniqueNames(theVolumes.begin(), theVolumes.end()); + // } } -MagGeoBuilderFromDDD::eLayer::~eLayer(){} +MagGeoBuilderFromDDD::eLayer::~eLayer() {} // double MagGeoBuilderFromDDD::eLayer::minR() const { -// // ASSUMPTION: a layer is only 1 volume thick (by construction). +// // ASSUMPTION: a layer is only 1 volume thick (by construction). // return theVolumes.front()->minR(); // } // double MagGeoBuilderFromDDD::eLayer::maxR() const { -// // ASSUMPTION: a layer is only 1 volume thick (by construction). +// // ASSUMPTION: a layer is only 1 volume thick (by construction). // return theVolumes.front()->maxR(); // } -MagELayer * MagGeoBuilderFromDDD::eLayer::buildMagELayer() const { - if (mlayer==nullptr) { +MagELayer* MagGeoBuilderFromDDD::eLayer::buildMagELayer() const { + if (mlayer == nullptr) { //FIXME not guaranteed that all volumes in layer have the same zmin // and zmax! double zmin = 1e19; double zmax = -1e19; vector mVols; - for (handles::const_iterator vol = theVolumes.begin(); - vol!=theVolumes.end(); ++vol) { + for (handles::const_iterator vol = theVolumes.begin(); vol != theVolumes.end(); ++vol) { mVols.push_back((*vol)->magVolume); zmin = min(zmin, (*vol)->minZ()); zmax = max(zmax, (*vol)->maxZ()); @@ -61,4 +57,3 @@ MagELayer * MagGeoBuilderFromDDD::eLayer::buildMagELayer() const { } return mlayer; } - diff --git a/MagneticField/GeomBuilder/src/eLayer.h b/MagneticField/GeomBuilder/src/eLayer.h index 4d1d2aab111f5..726a7ad2cd2d9 100644 --- a/MagneticField/GeomBuilder/src/eLayer.h +++ b/MagneticField/GeomBuilder/src/eLayer.h @@ -21,15 +21,14 @@ class MagGeoBuilderFromDDD::eLayer { /// Destructor ~eLayer(); -// /// Return the list of all volumes. -// const handles & volumes() const {return theVolumes;} + // /// Return the list of all volumes. + // const handles & volumes() const {return theVolumes;} /// Construct the MagELayer upon request. - MagELayer * buildMagELayer() const; + MagELayer* buildMagELayer() const; private: handles theVolumes; // pointer to all volumes in this layer - mutable MagELayer * mlayer; + mutable MagELayer* mlayer; }; #endif - diff --git a/MagneticField/GeomBuilder/src/eSector.cc b/MagneticField/GeomBuilder/src/eSector.cc index c9b2667eace79..1572d27f3851f 100644 --- a/MagneticField/GeomBuilder/src/eSector.cc +++ b/MagneticField/GeomBuilder/src/eSector.cc @@ -18,75 +18,68 @@ using namespace SurfaceOrientation; using namespace std; // The ctor is in charge of finding layers inside the sector. -MagGeoBuilderFromDDD::eSector::eSector(handles::const_iterator begin, - handles::const_iterator end) : - theVolumes(begin,end), - msector(nullptr) -{ +MagGeoBuilderFromDDD::eSector::eSector(handles::const_iterator begin, handles::const_iterator end) + : theVolumes(begin, end), msector(nullptr) { //FIXME!!! //precomputed_value_sort(theVolumes.begin(), theVolumes.end(), ExtractAbsZ()); precomputed_value_sort(theVolumes.begin(), theVolumes.end(), ExtractZ()); - // Clusterize in Z - const float resolution = 1.; // cm //FIXME ?? - float zmin = theVolumes.front()->center().z()-resolution; - float zmax = theVolumes.back()->center().z()+resolution; - ClusterizingHistogram hisZ( int((zmax-zmin)/resolution) + 1, zmin, zmax); + const float resolution = 1.; // cm //FIXME ?? + float zmin = theVolumes.front()->center().z() - resolution; + float zmax = theVolumes.back()->center().z() + resolution; + ClusterizingHistogram hisZ(int((zmax - zmin) / resolution) + 1, zmin, zmax); - if (MagGeoBuilderFromDDD::debug) cout << " Z layers: " << zmin << " " << zmax << endl; + if (MagGeoBuilderFromDDD::debug) + cout << " Z layers: " << zmin << " " << zmax << endl; handles::const_iterator first = theVolumes.begin(); - handles::const_iterator last = theVolumes.end(); + handles::const_iterator last = theVolumes.end(); - for (handles::const_iterator i=first; i!=last; ++i){ + for (handles::const_iterator i = first; i != last; ++i) { hisZ.fill((*i)->center().z()); } vector zClust = hisZ.clusterize(resolution); - if (MagGeoBuilderFromDDD::debug) cout << " Found " << zClust.size() << " clusters in Z, " - << " layers: " << endl; + if (MagGeoBuilderFromDDD::debug) + cout << " Found " << zClust.size() << " clusters in Z, " + << " layers: " << endl; handles::const_iterator layStart = first; handles::const_iterator separ = first; - for (unsigned int i=0; icenter().z() < zSepar) ++separ; + for (unsigned int i = 0; i < zClust.size() - 1; ++i) { + float zSepar = (zClust[i] + zClust[i + 1]) / 2.f; + while ((*separ)->center().z() < zSepar) + ++separ; if (MagGeoBuilderFromDDD::debug) { - cout << " Layer at: " << zClust[i] - << " elements: " << separ-layStart << " unique volumes: "; + cout << " Layer at: " << zClust[i] << " elements: " << separ - layStart << " unique volumes: "; volumeHandle::printUniqueNames(layStart, separ); } - + layers.push_back(eLayer(layStart, separ)); layStart = separ; } { if (MagGeoBuilderFromDDD::debug) { - cout << " Layer at: " << zClust.back() <<" elements: " << last-separ - << " unique volumes: "; - volumeHandle::printUniqueNames(separ,last); + cout << " Layer at: " << zClust.back() << " elements: " << last - separ << " unique volumes: "; + volumeHandle::printUniqueNames(separ, last); } layers.push_back(eLayer(separ, last)); } - // FIXME: Check that all layers have the same dz?. - + // FIXME: Check that all layers have the same dz?. } +MagGeoBuilderFromDDD::eSector::~eSector() {} -MagGeoBuilderFromDDD::eSector::~eSector(){} - - -MagESector* MagGeoBuilderFromDDD::eSector::buildMagESector() const{ - if (msector==nullptr) { +MagESector* MagGeoBuilderFromDDD::eSector::buildMagESector() const { + if (msector == nullptr) { vector mLayers; - for (vector::const_iterator lay = layers.begin(); - lay!=layers.end(); ++lay) { + for (vector::const_iterator lay = layers.begin(); lay != layers.end(); ++lay) { mLayers.push_back((*lay).buildMagELayer()); } - msector = new MagESector(mLayers, theVolumes.front()->minPhi()); //FIXME + msector = new MagESector(mLayers, theVolumes.front()->minPhi()); //FIXME } return msector; } diff --git a/MagneticField/GeomBuilder/src/eSector.h b/MagneticField/GeomBuilder/src/eSector.h index ba05fc0ce3ac6..d99fe59388ae2 100644 --- a/MagneticField/GeomBuilder/src/eSector.h +++ b/MagneticField/GeomBuilder/src/eSector.h @@ -22,15 +22,15 @@ class MagGeoBuilderFromDDD::eSector { /// Destructor ~eSector(); -// /// Return all volumes in this sector -// const handles & getVolumes() const {return volumes;} + // /// Return all volumes in this sector + // const handles & getVolumes() const {return volumes;} /// Construct the MagESector upon request. MagESector* buildMagESector() const; private: - std::vector layers; // the layers in this sectors - handles theVolumes; // pointers to all volumes in the sector + std::vector layers; // the layers in this sectors + handles theVolumes; // pointers to all volumes in the sector mutable MagESector* msector; }; #endif diff --git a/MagneticField/GeomBuilder/src/volumeHandle.cc b/MagneticField/GeomBuilder/src/volumeHandle.cc index 832d47dd74306..e1f0ad33e7ed0 100644 --- a/MagneticField/GeomBuilder/src/volumeHandle.cc +++ b/MagneticField/GeomBuilder/src/volumeHandle.cc @@ -31,41 +31,33 @@ using namespace SurfaceOrientation; using namespace std; - -MagGeoBuilderFromDDD::volumeHandle::~volumeHandle(){ - delete refPlane; -} +MagGeoBuilderFromDDD::volumeHandle::~volumeHandle() { delete refPlane; } MagGeoBuilderFromDDD::volumeHandle::volumeHandle(const DDExpandedView &fv, bool expand2Pi) - : name(fv.logicalPart().name().name()), - copyno(fv.copyno()), - magVolume(nullptr), - masterSector(1), - theRN(0.), - theRMin(0.), - theRMax(0.), - refPlane(nullptr), - solid(fv.logicalPart().solid()), - center_(GlobalPoint(fv.translation().x()/cm, - fv.translation().y()/cm, - fv.translation().z()/cm)), - expand(expand2Pi), - isIronFlag(false) -{ + : name(fv.logicalPart().name().name()), + copyno(fv.copyno()), + magVolume(nullptr), + masterSector(1), + theRN(0.), + theRMin(0.), + theRMax(0.), + refPlane(nullptr), + solid(fv.logicalPart().solid()), + center_(GlobalPoint(fv.translation().x() / cm, fv.translation().y() / cm, fv.translation().z() / cm)), + expand(expand2Pi), + isIronFlag(false) { // ASSUMPTION: volume names ends with "_NUM" where NUM is the volume number string volName = name; - volName.erase(0,volName.rfind('_')+1); - volumeno =boost::lexical_cast(volName); + volName.erase(0, volName.rfind('_') + 1); + volumeno = boost::lexical_cast(volName); - for (int i=0; i<6; ++i) { + for (int i = 0; i < 6; ++i) { isAssigned[i] = false; } - - if (MagGeoBuilderFromDDD::debug) { + if (MagGeoBuilderFromDDD::debug) { cout.precision(7); } - referencePlane(fv); @@ -75,289 +67,267 @@ MagGeoBuilderFromDDD::volumeHandle::volumeHandle(const DDExpandedView &fv, bool buildTrap(fv); } else if (solid.shape() == DDSolidShape::ddcons) { buildCons(fv); - } else if (solid.shape() == DDSolidShape::ddtubs) { + } else if (solid.shape() == DDSolidShape::ddtubs) { buildTubs(fv); - } else if (solid.shape() == DDSolidShape::ddpseudotrap) { + } else if (solid.shape() == DDSolidShape::ddpseudotrap) { buildPseudoTrap(fv); - } else if (solid.shape() == DDSolidShape::ddtrunctubs) { + } else if (solid.shape() == DDSolidShape::ddtrunctubs) { buildTruncTubs(fv); } else { cout << "volumeHandle ctor: Unexpected solid: " << DDSolidShapesName::name(solid.shape()) << endl; } - // NOTE: Table name and master sector are no longer taken from xml! -// DDsvalues_type sv(fv.mergedSpecifics()); - -// { // Extract the name of associated field file. -// std::vector temp; -// std::string pname = "table"; -// DDValue val(pname); -// DDsvalues_type sv(fv.mergedSpecifics()); -// if (DDfetch(&sv,val)) { -// temp = val.strings(); -// if (temp.size() != 1) { -// cout << "*** WARNING: volume has > 1 SpecPar " << pname << endl; -// } -// magFile = temp[0]; - -// string find="[copyNo]"; -// std::size_t j; -// for ( ; (j = magFile.find(find)) != string::npos ; ) { -// stringstream conv; -// conv << setfill('0') << setw(2) << copyno; -// string repl; -// conv >> repl; -// magFile.replace(j, find.length(), repl); -// } - -// } else { -// cout << "*** WARNING: volume does not have a SpecPar " << pname << endl; -// cout << " DDsvalues_type: " << fv.mergedSpecifics() << endl; -// } -// } - -// { // Extract the number of the master sector. -// std::vector temp; -// const std::string pname = "masterSector"; -// DDValue val(pname); -// if (DDfetch(&sv,val)) { -// temp = val.doubles(); -// if (temp.size() != 1) { -// cout << "*** WARNING: volume has > 1 SpecPar " << pname << endl; -// } -// masterSector = int(temp[0]+.5); -// } else { -// if (MagGeoBuilderFromDDD::debug) { -// cout << "Volume does not have a SpecPar " << pname -// << " using: " << copyno << endl; -// cout << " DDsvalues_type: " << fv.mergedSpecifics() << endl; -// } -// masterSector = copyno; -// } -// } - + // DDsvalues_type sv(fv.mergedSpecifics()); + + // { // Extract the name of associated field file. + // std::vector temp; + // std::string pname = "table"; + // DDValue val(pname); + // DDsvalues_type sv(fv.mergedSpecifics()); + // if (DDfetch(&sv,val)) { + // temp = val.strings(); + // if (temp.size() != 1) { + // cout << "*** WARNING: volume has > 1 SpecPar " << pname << endl; + // } + // magFile = temp[0]; + + // string find="[copyNo]"; + // std::size_t j; + // for ( ; (j = magFile.find(find)) != string::npos ; ) { + // stringstream conv; + // conv << setfill('0') << setw(2) << copyno; + // string repl; + // conv >> repl; + // magFile.replace(j, find.length(), repl); + // } + + // } else { + // cout << "*** WARNING: volume does not have a SpecPar " << pname << endl; + // cout << " DDsvalues_type: " << fv.mergedSpecifics() << endl; + // } + // } + + // { // Extract the number of the master sector. + // std::vector temp; + // const std::string pname = "masterSector"; + // DDValue val(pname); + // if (DDfetch(&sv,val)) { + // temp = val.doubles(); + // if (temp.size() != 1) { + // cout << "*** WARNING: volume has > 1 SpecPar " << pname << endl; + // } + // masterSector = int(temp[0]+.5); + // } else { + // if (MagGeoBuilderFromDDD::debug) { + // cout << "Volume does not have a SpecPar " << pname + // << " using: " << copyno << endl; + // cout << " DDsvalues_type: " << fv.mergedSpecifics() << endl; + // } + // masterSector = copyno; + // } + // } + // Get material for this volume - if (fv.logicalPart().material().name().name() == "Iron") isIronFlag=true; + if (fv.logicalPart().material().name().name() == "Iron") + isIronFlag = true; + if (MagGeoBuilderFromDDD::debug) { + cout << " RMin = " << theRMin << endl; + cout << " RMax = " << theRMax << endl; - if (MagGeoBuilderFromDDD::debug) { - cout << " RMin = " << theRMin <side(center_,0.3)]; + std::string sideName[3] = {"positiveSide", "negativeSide", "onSurface"}; + for (int i = 0; i < 6; ++i) { + cout << " " << i << ":" << sideName[surfaces[i]->side(center_, 0.3)]; } cout << endl; } } +const Surface::GlobalPoint &MagGeoBuilderFromDDD::volumeHandle::center() const { return center_; } -const Surface::GlobalPoint & MagGeoBuilderFromDDD::volumeHandle::center() const { - return center_; -} - -void MagGeoBuilderFromDDD::volumeHandle::referencePlane(const DDExpandedView &fv){ - // The refPlane is the "main plane" for the solid. It corresponds to the +void MagGeoBuilderFromDDD::volumeHandle::referencePlane(const DDExpandedView &fv) { + // The refPlane is the "main plane" for the solid. It corresponds to the // x,y plane in the DDD local frame, and defines a frame where the local - // coordinates are the same as in DDD. - // In the geometry version 85l_030919, this plane is normal to the + // coordinates are the same as in DDD. + // In the geometry version 85l_030919, this plane is normal to the // beam line for all volumes but pseudotraps, so that global R is along Y, // global phi is along -X and global Z along Z: // - // Global(for vol at pi/2) Local + // Global(for vol at pi/2) Local // +R (+Y) +Y // +phi(-X) -X // +Z +Z // // For pseudotraps the refPlane is parallel to beam line and global R is // along Z, global phi is along +-X and and global Z along Y: - // - // Global(for vol at pi/2) Local + // + // Global(for vol at pi/2) Local // +R (+Y) +Z // +phi(-X) +X // +Z +Y // // Note that the frame is centered in the DDD volume center, which is // inside the volume for DDD boxes and (pesudo)trapezoids, on the beam line - // for tubs, cons and trunctubs. + // for tubs, cons and trunctubs. // In geometry version 1103l, trapezoids have X and Z in the opposite direction - // than the above. Boxes are either oriented as described above or in some case + // than the above. Boxes are either oriented as described above or in some case // have opposite direction for Y and X. // The global position - Surface::PositionType & posResult = center_; + Surface::PositionType &posResult = center_; // The reference plane rotation DD3Vector x, y, z; - fv.rotation().GetComponents(x,y,z); + fv.rotation().GetComponents(x, y, z); if (MagGeoBuilderFromDDD::debug) { if (x.Cross(y).Dot(z) < 0.5) { - cout << "*** WARNING: Rotation is not RH "<< endl; + cout << "*** WARNING: Rotation is not RH " << endl; } } - + // The global rotation - Surface::RotationType - rotResult(float(x.X()),float(x.Y()),float(x.Z()), - float(y.X()),float(y.Y()),float(y.Z()), - float(z.X()),float(z.Y()),float(z.Z())); + Surface::RotationType rotResult(float(x.X()), + float(x.Y()), + float(x.Z()), + float(y.X()), + float(y.Y()), + float(y.Z()), + float(z.X()), + float(z.Y()), + float(z.Z())); refPlane = new GloballyPositioned(posResult, rotResult); // Check correct orientation if (MagGeoBuilderFromDDD::debug) { - cout << "Refplane pos " << refPlane->position() << endl; // See comments above for the conventions for orientation. - LocalVector globalZdir(0.,0.,1.); // Local direction of the axis along global Z + LocalVector globalZdir(0., 0., 1.); // Local direction of the axis along global Z if (solid.shape() == DDSolidShape::ddpseudotrap) { - globalZdir = LocalVector(0.,1.,0.); + globalZdir = LocalVector(0., 1., 0.); } - if (refPlane->toGlobal(globalZdir).z()<0.) { - globalZdir=-globalZdir; + if (refPlane->toGlobal(globalZdir).z() < 0.) { + globalZdir = -globalZdir; } - float chk = refPlane->toGlobal(globalZdir).dot(GlobalVector(0,0,1)); - if (chk < .999) cout << "*** WARNING RefPlane check failed!***" - << chk << endl; + float chk = refPlane->toGlobal(globalZdir).dot(GlobalVector(0, 0, 1)); + if (chk < .999) + cout << "*** WARNING RefPlane check failed!***" << chk << endl; } } - - -void MagGeoBuilderFromDDD::volumeHandle::buildPhiZSurf(double startPhi, - double deltaPhi, - double zhalf, - double rCentr) { +void MagGeoBuilderFromDDD::volumeHandle::buildPhiZSurf(double startPhi, double deltaPhi, double zhalf, double rCentr) { // This is 100% equal for cons and tubs!!! - GlobalVector planeXAxis = refPlane->toGlobal(LocalVector( 1, 0, 0)); - GlobalVector planeYAxis = refPlane->toGlobal(LocalVector( 0, 1, 0)); - GlobalVector planeZAxis = refPlane->toGlobal(LocalVector( 0, 0, 1)); + GlobalVector planeXAxis = refPlane->toGlobal(LocalVector(1, 0, 0)); + GlobalVector planeYAxis = refPlane->toGlobal(LocalVector(0, 1, 0)); + GlobalVector planeZAxis = refPlane->toGlobal(LocalVector(0, 0, 1)); // Local Y axis of the faces at +-phi. - GlobalVector y_phiplus = refPlane->toGlobal(LocalVector(cos(startPhi+deltaPhi), - sin(startPhi+deltaPhi),0.)); - GlobalVector y_phiminus = refPlane->toGlobal(LocalVector(cos(startPhi), - sin(startPhi),0.)); + GlobalVector y_phiplus = refPlane->toGlobal(LocalVector(cos(startPhi + deltaPhi), sin(startPhi + deltaPhi), 0.)); + GlobalVector y_phiminus = refPlane->toGlobal(LocalVector(cos(startPhi), sin(startPhi), 0.)); - Surface::RotationType rot_Z(planeXAxis,planeYAxis); - Surface::RotationType rot_phiplus(planeZAxis, y_phiplus); + Surface::RotationType rot_Z(planeXAxis, planeYAxis); + Surface::RotationType rot_phiplus(planeZAxis, y_phiplus); Surface::RotationType rot_phiminus(planeZAxis, y_phiminus); - GlobalPoint pos_zplus(center_.x(),center_.y(),center_.z()+zhalf); - GlobalPoint pos_zminus(center_.x(),center_.y(),center_.z()-zhalf); - // BEWARE: in this case, the origin for phiplus,phiminus surfaces is + GlobalPoint pos_zplus(center_.x(), center_.y(), center_.z() + zhalf); + GlobalPoint pos_zminus(center_.x(), center_.y(), center_.z() - zhalf); + // BEWARE: in this case, the origin for phiplus,phiminus surfaces is // at radius R and not on a plane passing by center_ orthogonal to the radius. - GlobalPoint pos_phiplus(refPlane->toGlobal(LocalPoint(rCentr*cos(startPhi+deltaPhi),rCentr*sin(startPhi+deltaPhi),0.))); - GlobalPoint pos_phiminus(refPlane->toGlobal(LocalPoint(rCentr*cos(startPhi), - rCentr*sin(startPhi), - 0.))); - surfaces[zplus] = new Plane(pos_zplus, rot_Z); - surfaces[zminus] = new Plane(pos_zminus, rot_Z); - surfaces[phiplus] = new Plane(pos_phiplus, rot_phiplus); - surfaces[phiminus] = new Plane(pos_phiminus, rot_phiminus); - + GlobalPoint pos_phiplus( + refPlane->toGlobal(LocalPoint(rCentr * cos(startPhi + deltaPhi), rCentr * sin(startPhi + deltaPhi), 0.))); + GlobalPoint pos_phiminus(refPlane->toGlobal(LocalPoint(rCentr * cos(startPhi), rCentr * sin(startPhi), 0.))); + surfaces[zplus] = new Plane(pos_zplus, rot_Z); + surfaces[zminus] = new Plane(pos_zminus, rot_Z); + surfaces[phiplus] = new Plane(pos_phiplus, rot_phiplus); + surfaces[phiminus] = new Plane(pos_phiminus, rot_phiminus); + if (MagGeoBuilderFromDDD::debug) { - cout << "Actual Center at: " << center_ << " R " << center_.perp() - << " phi " << center_.phi() << endl; + cout << "Actual Center at: " << center_ << " R " << center_.perp() << " phi " << center_.phi() << endl; cout << "RN " << theRN << endl; - cout << "pos_zplus " << pos_zplus << " " - << pos_zplus.perp() << " " << pos_zplus.phi() << endl - << "pos_zminus " << pos_zminus << " " - << pos_zminus.perp() << " " << pos_zminus.phi() << endl - << "pos_phiplus " << pos_phiplus << " " - << pos_phiplus.perp() << " " << pos_phiplus.phi() <toGlobal(LocalVector(0.,0.,1.)) << endl - << "rot_phi+ " << surfaces[phiplus]->toGlobal(LocalVector(0.,0.,1.)) - << " phi " << surfaces[phiplus]->toGlobal(LocalVector(0.,0.,1.)).phi() - << endl - << "rot_phi- " << surfaces[phiminus]->toGlobal(LocalVector(0.,0.,1.)) - << " phi " << surfaces[phiminus]->toGlobal(LocalVector(0.,0.,1.)).phi() - << endl; + cout << "rot_Z " << surfaces[zplus]->toGlobal(LocalVector(0., 0., 1.)) << endl + << "rot_phi+ " << surfaces[phiplus]->toGlobal(LocalVector(0., 0., 1.)) << " phi " + << surfaces[phiplus]->toGlobal(LocalVector(0., 0., 1.)).phi() << endl + << "rot_phi- " << surfaces[phiminus]->toGlobal(LocalVector(0., 0., 1.)) << " phi " + << surfaces[phiminus]->toGlobal(LocalVector(0., 0., 1.)).phi() << endl; } - -// // Check ordering. + + // // Check ordering. if (MagGeoBuilderFromDDD::debug) { if (pos_zplus.z() < pos_zminus.z()) { cout << "*** WARNING: pos_zplus < pos_zminus " << endl; } - if (Geom::Phi(pos_phiplus.phi()-pos_phiminus.phi()) < 0. ) { + if (Geom::Phi(pos_phiplus.phi() - pos_phiminus.phi()) < 0.) { cout << "*** WARNING: pos_phiplus < pos_phiminus " << endl; } } } - - -bool MagGeoBuilderFromDDD::volumeHandle::sameSurface(const Surface & s1, Sides which_side, float tolerance) -{ +bool MagGeoBuilderFromDDD::volumeHandle::sameSurface(const Surface &s1, Sides which_side, float tolerance) { //Check for null comparison - if (&s1==(surfaces[which_side]).get()){ - if (MagGeoBuilderFromDDD::debug) cout << " sameSurface: OK (same ptr)" << endl; + if (&s1 == (surfaces[which_side]).get()) { + if (MagGeoBuilderFromDDD::debug) + cout << " sameSurface: OK (same ptr)" << endl; return true; } - const float maxtilt = 0.999; + const float maxtilt = 0.999; - const Surface & s2 = *(surfaces[which_side]); + const Surface &s2 = *(surfaces[which_side]); // Try with a plane. - const Plane * p1 = dynamic_cast(&s1); - if (p1!=nullptr) { - const Plane * p2 = dynamic_cast(&s2); - if (p2==nullptr) { - if (MagGeoBuilderFromDDD::debug) cout << " sameSurface: different types" << endl; + const Plane *p1 = dynamic_cast(&s1); + if (p1 != nullptr) { + const Plane *p2 = dynamic_cast(&s2); + if (p2 == nullptr) { + if (MagGeoBuilderFromDDD::debug) + cout << " sameSurface: different types" << endl; return false; } - - if ( (fabs(p1->normalVector().dot(p2->normalVector())) > maxtilt) - && (fabs((p1->toLocal(p2->position())).z()) < tolerance) ) { - if (MagGeoBuilderFromDDD::debug) cout << " sameSurface: OK " - << fabs(p1->normalVector().dot(p2->normalVector())) - << " " << fabs((p1->toLocal(p2->position())).z()) << endl; + + if ((fabs(p1->normalVector().dot(p2->normalVector())) > maxtilt) && + (fabs((p1->toLocal(p2->position())).z()) < tolerance)) { + if (MagGeoBuilderFromDDD::debug) + cout << " sameSurface: OK " << fabs(p1->normalVector().dot(p2->normalVector())) << " " + << fabs((p1->toLocal(p2->position())).z()) << endl; return true; - } else{ - if (MagGeoBuilderFromDDD::debug) cout << " sameSurface: not the same: " - << p1->normalVector() << p1->position() << endl - << " " - << p2->normalVector() << p2->position() << endl - << fabs(p1->normalVector().dot(p2->normalVector())) - << " " << (p1->toLocal(p2->position())).z()<< endl; + } else { + if (MagGeoBuilderFromDDD::debug) + cout << " sameSurface: not the same: " << p1->normalVector() << p1->position() << endl + << " " << p2->normalVector() << p2->position() << endl + << fabs(p1->normalVector().dot(p2->normalVector())) << " " << (p1->toLocal(p2->position())).z() << endl; return false; } } - // Try with a cylinder. - const Cylinder * cy1 = dynamic_cast(&s1); - if (cy1!=nullptr) { - const Cylinder * cy2 = dynamic_cast(&s2); - if (cy2==nullptr) { - if (MagGeoBuilderFromDDD::debug) cout << " sameSurface: different types" << endl; + // Try with a cylinder. + const Cylinder *cy1 = dynamic_cast(&s1); + if (cy1 != nullptr) { + const Cylinder *cy2 = dynamic_cast(&s2); + if (cy2 == nullptr) { + if (MagGeoBuilderFromDDD::debug) + cout << " sameSurface: different types" << endl; return false; } // Assume axis is the same! @@ -368,120 +338,113 @@ bool MagGeoBuilderFromDDD::volumeHandle::sameSurface(const Surface & s1, Sides w } } - // Try with a cone. - const Cone * co1 = dynamic_cast(&s1); - if (co1!=nullptr) { - const Cone * co2 = dynamic_cast(&s2); - if (co2==nullptr) { - if (MagGeoBuilderFromDDD::debug) cout << " sameSurface: different types" << endl; + // Try with a cone. + const Cone *co1 = dynamic_cast(&s1); + if (co1 != nullptr) { + const Cone *co2 = dynamic_cast(&s2); + if (co2 == nullptr) { + if (MagGeoBuilderFromDDD::debug) + cout << " sameSurface: different types" << endl; return false; } // FIXME - if (fabs(co1->openingAngle()-co2->openingAngle()) < maxtilt - && (co1->vertex()-co2->vertex()).mag() < tolerance) { + if (fabs(co1->openingAngle() - co2->openingAngle()) < maxtilt && + (co1->vertex() - co2->vertex()).mag() < tolerance) { return true; } else { return false; } } - if (MagGeoBuilderFromDDD::debug) cout << " sameSurface: unknown surfaces..." << endl; + if (MagGeoBuilderFromDDD::debug) + cout << " sameSurface: unknown surfaces..." << endl; return false; } - - -bool MagGeoBuilderFromDDD::volumeHandle::setSurface(const Surface & s1, Sides which_side) -{ - //Check for null assignment - if (&s1==(surfaces[which_side]).get()){ +bool MagGeoBuilderFromDDD::volumeHandle::setSurface(const Surface &s1, Sides which_side) { + //Check for null assignment + if (&s1 == (surfaces[which_side]).get()) { isAssigned[which_side] = true; return true; } - if (!sameSurface(s1,which_side)){ - cout << "***ERROR: setSurface: trying to assign a surface that does not match destination surface. Skipping." << endl; - const Surface & s2 = *(surfaces[which_side]); + if (!sameSurface(s1, which_side)) { + cout << "***ERROR: setSurface: trying to assign a surface that does not match destination surface. Skipping." + << endl; + const Surface &s2 = *(surfaces[which_side]); //FIXME: Just planes for the time being!!! - const Plane * p1 = dynamic_cast(&s1); - const Plane * p2 = dynamic_cast(&s2); - if (p1!=nullptr && p2 !=nullptr) - cout << p1->normalVector() << p1->position() << endl - << p2->normalVector() << p2->position() << endl; + const Plane *p1 = dynamic_cast(&s1); + const Plane *p2 = dynamic_cast(&s2); + if (p1 != nullptr && p2 != nullptr) + cout << p1->normalVector() << p1->position() << endl << p2->normalVector() << p2->position() << endl; return false; } - if (isAssigned[which_side]) { - if (&s1!=(surfaces[which_side]).get()){ - cout << "*** WARNING volumeHandle::setSurface: trying to reassign a surface to a different surface instance" << endl; + if (&s1 != (surfaces[which_side]).get()) { + cout << "*** WARNING volumeHandle::setSurface: trying to reassign a surface to a different surface instance" + << endl; return false; } } else { surfaces[which_side] = &s1; isAssigned[which_side] = true; - if (MagGeoBuilderFromDDD::debug) cout << " Volume " << name << " # " << copyno << " Assigned: " << (int) which_side << endl; + if (MagGeoBuilderFromDDD::debug) + cout << " Volume " << name << " # " << copyno << " Assigned: " << (int)which_side << endl; return true; } - return false; // let the compiler be happy + return false; // let the compiler be happy } +const Surface &MagGeoBuilderFromDDD::volumeHandle::surface(Sides which_side) const { return *(surfaces[which_side]); } - -const Surface & -MagGeoBuilderFromDDD::volumeHandle::surface(Sides which_side) const { +const Surface &MagGeoBuilderFromDDD::volumeHandle::surface(int which_side) const { + assert(which_side >= 0 && which_side < 6); return *(surfaces[which_side]); } - - -const Surface & -MagGeoBuilderFromDDD::volumeHandle::surface(int which_side) const { - assert(which_side >=0 && which_side <6); - return *(surfaces[which_side]); -} - - -std::vector -MagGeoBuilderFromDDD::volumeHandle::sides() const{ +std::vector MagGeoBuilderFromDDD::volumeHandle::sides() const { std::vector result; - for (int i=0; i<6; ++i){ + for (int i = 0; i < 6; ++i) { // If this is just a master volume out of wich a 2pi volume // should be built (e.g. central cylinder), skip the phi boundaries. - if (expand && (i==phiplus || i==phiminus)) continue; + if (expand && (i == phiplus || i == phiminus)) + continue; // FIXME: Skip null inner degenerate cylindrical surface - if (solid.shape() == DDSolidShape::ddtubs && i == SurfaceOrientation::inner && theRMin < 0.001) continue; + if (solid.shape() == DDSolidShape::ddtubs && i == SurfaceOrientation::inner && theRMin < 0.001) + continue; - ReferenceCountingPointer s = const_cast (surfaces[i].get()); - result.push_back(VolumeSide(s, GlobalFace(i), - surfaces[i]->side(center_,0.3))); + ReferenceCountingPointer s = const_cast(surfaces[i].get()); + result.push_back(VolumeSide(s, GlobalFace(i), surfaces[i]->side(center_, 0.3))); } return result; } -void MagGeoBuilderFromDDD::volumeHandle::printUniqueNames(handles::const_iterator begin, handles::const_iterator end, bool uniq) { - std::vector names; - for (handles::const_iterator i = begin; - i != end; ++i){ - if (uniq) names.push_back((*i)->name); - else names.push_back((*i)->name+":"+std::to_string((*i)->copyno)); - } - - sort(names.begin(),names.end()); - if (uniq) { - std::vector::iterator i = unique(names.begin(),names.end()); - int nvols = int(i - names.begin()); - cout << nvols << " "; - copy(names.begin(), i, ostream_iterator(cout, " ")); - } else { - cout << names.size() << " "; - copy(names.begin(), names.end(), ostream_iterator(cout, " ")); - } - cout << endl; -} +void MagGeoBuilderFromDDD::volumeHandle::printUniqueNames(handles::const_iterator begin, + handles::const_iterator end, + bool uniq) { + std::vector names; + for (handles::const_iterator i = begin; i != end; ++i) { + if (uniq) + names.push_back((*i)->name); + else + names.push_back((*i)->name + ":" + std::to_string((*i)->copyno)); + } + sort(names.begin(), names.end()); + if (uniq) { + std::vector::iterator i = unique(names.begin(), names.end()); + int nvols = int(i - names.begin()); + cout << nvols << " "; + copy(names.begin(), i, ostream_iterator(cout, " ")); + } else { + cout << names.size() << " "; + copy(names.begin(), names.end(), ostream_iterator(cout, " ")); + } + cout << endl; +} #include "MagneticField/GeomBuilder/src/buildBox.icc" #include "MagneticField/GeomBuilder/src/buildTrap.icc" diff --git a/MagneticField/GeomBuilder/src/volumeHandle.h b/MagneticField/GeomBuilder/src/volumeHandle.h index bab907a324272..440d84c81b156 100644 --- a/MagneticField/GeomBuilder/src/volumeHandle.h +++ b/MagneticField/GeomBuilder/src/volumeHandle.h @@ -21,38 +21,35 @@ class DDExpandedView; class MagVolume6Faces; - class MagGeoBuilderFromDDD::volumeHandle { public: - typedef Surface::GlobalPoint GlobalPoint; - typedef Surface::LocalPoint LocalPoint; - typedef Surface::LocalVector LocalVector; + typedef Surface::GlobalPoint GlobalPoint; + typedef Surface::LocalPoint LocalPoint; + typedef Surface::LocalVector LocalVector; typedef SurfaceOrientation::GlobalFace Sides; - volumeHandle(const DDExpandedView & fv, bool expand2Pi=false); + volumeHandle(const DDExpandedView& fv, bool expand2Pi = false); ~volumeHandle(); /// Return the center of the volume - const GlobalPoint & center() const; - /// Distance of (x,y) plane from origin - const double RN() const {return theRN;} + const GlobalPoint& center() const; + /// Distance of (x,y) plane from origin + const double RN() const { return theRN; } /// Get the current surface on specified side. - const Surface & surface(int which_side) const; - const Surface & surface(Sides which_side) const; + const Surface& surface(int which_side) const; + const Surface& surface(Sides which_side) const; /// Find out if two surfaces are the same physical surface - bool sameSurface(const Surface & s1, Sides which_side, float tolerance = 0.01); + bool sameSurface(const Surface& s1, Sides which_side, float tolerance = 0.01); /// Assign a shared surface perorming sanity checks. - bool setSurface(const Surface & s1, Sides which_side); + bool setSurface(const Surface& s1, Sides which_side); /// if the specified surface has been matched. - bool isPlaneMatched(int which_side) const { - return isAssigned[which_side]; - } + bool isPlaneMatched(int which_side) const { return isAssigned[which_side]; } - int references(int which_side) const { // FIXME! -/* return surfaces[which_side]->references(); */ + int references(int which_side) const { // FIXME! + /* return surfaces[which_side]->references(); */ return 0; } - /// Name of the volume + /// Name of the volume std::string name; /// Name of magnetic field table file std::string magFile; @@ -62,39 +59,37 @@ class MagGeoBuilderFromDDD::volumeHandle { unsigned short copyno; /// Just for debugging... - static void printUniqueNames(handles::const_iterator begin, - handles::const_iterator end, bool uniq=true); - + static void printUniqueNames(handles::const_iterator begin, handles::const_iterator end, bool uniq = true); // Phi ranges: Used by: LessDPhiMax; bSector; bSlab::[min|max]Phi(); // MagBSector, MagBRod /// Minimum value of phi covered by the volume - // FIXME: actually returns phi of the point on median plane of the -phi + // FIXME: actually returns phi of the point on median plane of the -phi // surface, except for trapezoids where the absoulte min has been implemented - Geom::Phi minPhi() const {return thePhiMin;} + Geom::Phi minPhi() const { return thePhiMin; } /// Maximum value of phi covered by the volume - // FIXME: actually returns phi of the point on median plane of the +phi + // FIXME: actually returns phi of the point on median plane of the +phi // surface - Geom::Phi maxPhi() const {return surface(SurfaceOrientation::phiplus).position().phi();} + Geom::Phi maxPhi() const { return surface(SurfaceOrientation::phiplus).position().phi(); } - /// Z limits. + /// Z limits. // ASSUMPTION: Computed on median Z plane, but this is not a problem since // all Z planes are orthogonal to the beam line in the current geometry. - double minZ() const {return surface(SurfaceOrientation::zminus).position().z();} - double maxZ() const {return surface(SurfaceOrientation::zplus).position().z();} + double minZ() const { return surface(SurfaceOrientation::zminus).position().z(); } + double maxZ() const { return surface(SurfaceOrientation::zplus).position().z(); } /// Minimum R for any point within the volume - double minR() const {return theRMin;} + double minR() const { return theRMin; } /// FIXME: currently returns max RN (to be fixed?). Used by: bLayer::maxR() - // double maxR() const {return theRMax;} + // double maxR() const {return theRMax;} /// Position and rotation - const GloballyPositioned * placement() const {return refPlane;} + const GloballyPositioned* placement() const { return refPlane; } /// Shape of the solid - DDSolidShape shape() const {return solid.shape();} + DDSolidShape shape() const { return solid.shape(); } /// The surfaces and they orientation, as required to build a MagVolume. std::vector sides() const; @@ -102,10 +97,10 @@ class MagGeoBuilderFromDDD::volumeHandle { /// Pointer to the final MagVolume (must be set from outside) MagVolume6Faces* magVolume; - bool toExpand() const {return expand;} + bool toExpand() const { return expand; } /// Temporary hack to pass information on material. Will eventually be replaced! - bool isIron() const{return isIronFlag;} + bool isIron() const { return isIronFlag; } /// The sector for which an interpolator for this class of volumes should be built int masterSector; @@ -114,7 +109,7 @@ class MagGeoBuilderFromDDD::volumeHandle { // Disallow Default/copy ctor & assignment op. // (we want to handle only pointers!!!) volumeHandle(const volumeHandle& v) = delete; - volumeHandle operator=(const volumeHandle &v) = delete; + volumeHandle operator=(const volumeHandle& v) = delete; // The volume's six surfaces. RCPS surfaces[6]; @@ -122,71 +117,63 @@ class MagGeoBuilderFromDDD::volumeHandle { bool isAssigned[6]; // initialise the refPlane - void referencePlane(const DDExpandedView &fv); + void referencePlane(const DDExpandedView& fv); // Build the surfaces for a box - void buildBox(const DDExpandedView & fv); + void buildBox(const DDExpandedView& fv); // Build the surfaces for a trapezoid - void buildTrap(const DDExpandedView & fv); + void buildTrap(const DDExpandedView& fv); // Build the surfaces for a ddtubs shape - void buildTubs(const DDExpandedView & fv); + void buildTubs(const DDExpandedView& fv); // Build the surfaces for a ddcons shape - void buildCons(const DDExpandedView & fv); + void buildCons(const DDExpandedView& fv); // Build the surfaces for a ddpseudotrap shape - void buildPseudoTrap(const DDExpandedView & fv); + void buildPseudoTrap(const DDExpandedView& fv); // Build the surfaces for a ddtrunctubs shape - void buildTruncTubs(const DDExpandedView & fv); + void buildTruncTubs(const DDExpandedView& fv); // Build phi, z surfaces (common for ddtubs and ddcons) - void buildPhiZSurf(double startPhi, double deltaPhi, double zhalf, - double rCentr); + void buildPhiZSurf(double startPhi, double deltaPhi, double zhalf, double rCentr); // Distance from the origin along the normal to the volume's zphi plane. double theRN; - + // Max and min radius for _any_ point within the volume // FIXME! double theRMin; double theRMax; Geom::Phi thePhiMin; - // The refPlane is the "main plane" for the solid. It corresponds to the + // The refPlane is the "main plane" for the solid. It corresponds to the // x,y plane in the DDD local frame, and defines a frame where the local // coordinates are the same as in DDD. - GloballyPositioned * refPlane; + GloballyPositioned* refPlane; // the DDSolid. - DDSolid solid; + DDSolid solid; // the center of the volume GlobalPoint center_; - // Flag this as a master volume out of wich a 2pi volume should be built + // Flag this as a master volume out of wich a 2pi volume should be built // (e.g. central cylinder); this is taken into account by sides(). bool expand; - // Temporary hack to keep information on material. Will eventually be replaced! + // Temporary hack to keep information on material. Will eventually be replaced! bool isIronFlag; - }; - // Extractors for precomputed_value_sort() (safe sorting) // To sort volumes in Z struct MagGeoBuilderFromDDD::ExtractZ { - double operator()(const volumeHandle* v) const { - return v->center().z(); - } + double operator()(const volumeHandle* v) const { return v->center().z(); } }; // To sort volumes in abs(Z) struct MagGeoBuilderFromDDD::ExtractAbsZ { - double operator()(const volumeHandle* v) const { - return fabs(v->center().z()); - } + double operator()(const volumeHandle* v) const { return fabs(v->center().z()); } }; - // To sort volumes in phi (from -pi to pi). struct MagGeoBuilderFromDDD::ExtractPhi { double operator()(const volumeHandle* v) const { @@ -202,45 +189,39 @@ struct MagGeoBuilderFromDDD::ExtractPhiMax { // note that Geom::Phi is implicitly converted to double. // Periodicity is guaranteed. return v->maxPhi(); - } + } }; // To sort volumes in R struct MagGeoBuilderFromDDD::ExtractR { - double operator()(const volumeHandle* v) const { - return v->center().perp(); - } + double operator()(const volumeHandle* v) const { return v->center().perp(); } }; // To sort volumes in RN (distance of (x,y) plane from origin) struct MagGeoBuilderFromDDD::ExtractRN { - double operator()(const volumeHandle* v) const { - return v->RN(); - } + double operator()(const volumeHandle* v) const { return v->RN(); } }; - // To sort angles within any range SMALLER THAN PI "counter-clockwise", // even if the angles cross the pi boundary. -// CAVEAT: // The result is undefined if the input values cover a +// CAVEAT: // The result is undefined if the input values cover a // range larger than pi!!! struct MagGeoBuilderFromDDD::LessDPhi { bool operator()(double phi1, double phi2) const { // handle periodicity - return ((Geom::Phi(phi2)-Geom::Phi(phi1))>0.); - } + return ((Geom::Phi(phi2) - Geom::Phi(phi1)) > 0.); + } }; // Compare the Z of volumes. -// Should be used ONLY for std::max_element and std::min_element +// Should be used ONLY for std::max_element and std::min_element // and NEVER for sorting (use precomputed_value_sort with ExtractZ instead) struct MagGeoBuilderFromDDD::LessZ { - bool operator()(const volumeHandle * v1, const volumeHandle * v2) const - { - if (v1->center().z() < v2->center().z()) return true; + bool operator()(const volumeHandle* v1, const volumeHandle* v2) const { + if (v1->center().z() < v2->center().z()) + return true; return false; } }; #endif - diff --git a/MagneticField/GeomBuilder/test/stubs/GlobalPointProvider.h b/MagneticField/GeomBuilder/test/stubs/GlobalPointProvider.h index 40f740a4d8046..5b7b431b8203f 100644 --- a/MagneticField/GeomBuilder/test/stubs/GlobalPointProvider.h +++ b/MagneticField/GeomBuilder/test/stubs/GlobalPointProvider.h @@ -13,24 +13,11 @@ #include - - class GlobalPointProvider { - public: - GlobalPointProvider(double minR, - double maxR, - double minPhi, - double maxPhi, - double minZ, - double maxZ) : - theMinR(minR), - theMaxR(maxR), - theMinPhi(minPhi), - theMaxPhi(maxPhi), - theMinZ(minZ), - theMaxZ(maxZ) - {} - +public: + GlobalPointProvider(double minR, double maxR, double minPhi, double maxPhi, double minZ, double maxZ) + : theMinR(minR), theMaxR(maxR), theMinPhi(minPhi), theMaxPhi(maxPhi), theMinZ(minZ), theMaxZ(maxZ) {} + GlobalPointProvider(bool zSymmetric = true, bool barrelOnly = false) { theMinR = 0.; theMaxR = 1000.; @@ -41,19 +28,19 @@ class GlobalPointProvider { if (barrelOnly) { theMinZ = -662.; - theMaxZ = 662.; + theMaxZ = 662.; } - if (zSymmetric) theMaxZ=0.; + if (zSymmetric) + theMaxZ = 0.; } - - GlobalPoint getPoint() { - //Turn - double R = CLHEP::RandFlat::shoot(theMinR,theMaxR); - double Z = CLHEP::RandFlat::shoot(theMinZ,theMaxZ); - double phi = CLHEP::RandFlat::shoot(theMinPhi,theMaxPhi); + GlobalPoint getPoint() { + //Turn + double R = CLHEP::RandFlat::shoot(theMinR, theMaxR); + double Z = CLHEP::RandFlat::shoot(theMinZ, theMaxZ); + double phi = CLHEP::RandFlat::shoot(theMinPhi, theMaxPhi); - GlobalPoint gp(GlobalPoint::Cylindrical(R,phi,Z)); + GlobalPoint gp(GlobalPoint::Cylindrical(R, phi, Z)); // if not in barrel, retry // if (barrelOnly && !(theGeometry->inBarrel(gp))) gp=getPoint(); @@ -61,10 +48,9 @@ class GlobalPointProvider { return gp; } - - private: +private: double theMinR; - double theMaxR; + double theMaxR; double theMinPhi; double theMaxPhi; double theMinZ; @@ -72,4 +58,3 @@ class GlobalPointProvider { }; #endif - diff --git a/MagneticField/GeomBuilder/test/stubs/MagGeometryAnalyzer.cc b/MagneticField/GeomBuilder/test/stubs/MagGeometryAnalyzer.cc index 30118ed1f8c54..81a94876a1fd6 100644 --- a/MagneticField/GeomBuilder/test/stubs/MagGeometryAnalyzer.cc +++ b/MagneticField/GeomBuilder/test/stubs/MagGeometryAnalyzer.cc @@ -22,33 +22,30 @@ using namespace std; class testMagGeometryAnalyzer : public edm::EDAnalyzer { - public: +public: /// Constructor - testMagGeometryAnalyzer(const edm::ParameterSet& pset) {}; + testMagGeometryAnalyzer(const edm::ParameterSet& pset){}; /// Destructor - virtual ~testMagGeometryAnalyzer() {}; + virtual ~testMagGeometryAnalyzer(){}; /// Perform the real analysis - void analyze(const edm::Event & event, const edm::EventSetup& eventSetup); + void analyze(const edm::Event& event, const edm::EventSetup& eventSetup); - virtual void endJob() { - } - - private: - void testGrids( const vector& bvol); + virtual void endJob() {} + +private: + void testGrids(const vector& bvol); }; using namespace edm; -void testMagGeometryAnalyzer::analyze(const edm::Event & event, const edm::EventSetup& eventSetup) { - +void testMagGeometryAnalyzer::analyze(const edm::Event& event, const edm::EventSetup& eventSetup) { ESHandle magfield; eventSetup.get().get(magfield); const MagGeometry* field = (dynamic_cast(magfield.product()))->field; - - + // Test that findVolume succeeds for random points MagGeometryExerciser exe(field); @@ -56,41 +53,39 @@ void testMagGeometryAnalyzer::analyze(const edm::Event & event, const edm::Event exe.testFindVolume(10000000); // Test that random points are inside one and only one volume - // exe.testInside(100000,0.03); + // exe.testInside(100000,0.03); - // Test that each grid point is inside its own volume if (false) { cout << "***TEST GRIDS: barrel volumes: " << field->barrelVolumes().size() << endl; - testGrids( field->barrelVolumes()); - + testGrids(field->barrelVolumes()); + cout << "***TEST GRIDS: endcap volumes: " << field->endcapVolumes().size() << endl; - testGrids( field->endcapVolumes()); + testGrids(field->endcapVolumes()); } } - #include "MagneticField/VolumeGeometry/interface/MagVolume6Faces.h" #include "VolumeGridTester.h" - void testMagGeometryAnalyzer::testGrids(const vector& bvol) { - static map nameCalls; + static map nameCalls; - for (vector::const_iterator i=bvol.begin(); - i!=bvol.end(); i++) { + for (vector::const_iterator i = bvol.begin(); i != bvol.end(); i++) { if ((*i)->copyno != 1) { continue; } const MagProviderInterpol* prov = (**i).provider(); if (prov == 0) { - cout << (*i)->volumeNo << " No interpolator; skipping " << endl; + cout << (*i)->volumeNo << " No interpolator; skipping " << endl; continue; } VolumeGridTester tester(*i, prov); - if (tester.testInside()) cout << "testGrids: success: " << (**i).volumeNo << endl; - else cout << "testGrids: ERROR: " << (**i).volumeNo << endl; + if (tester.testInside()) + cout << "testGrids: success: " << (**i).volumeNo << endl; + else + cout << "testGrids: ERROR: " << (**i).volumeNo << endl; } } diff --git a/MagneticField/GeomBuilder/test/stubs/MagGeometryExerciser.cc b/MagneticField/GeomBuilder/test/stubs/MagGeometryExerciser.cc index 6110fcc45876b..73023a32bc934 100644 --- a/MagneticField/GeomBuilder/test/stubs/MagGeometryExerciser.cc +++ b/MagneticField/GeomBuilder/test/stubs/MagGeometryExerciser.cc @@ -15,7 +15,7 @@ using namespace std; -MagGeometryExerciser::MagGeometryExerciser(const MagGeometry * g) : theGeometry(g) { +MagGeometryExerciser::MagGeometryExerciser(const MagGeometry* g) : theGeometry(g) { const vector& theBVolumes = theGeometry->barrelVolumes(); const vector& theEVolumes = theGeometry->endcapVolumes(); @@ -23,64 +23,56 @@ MagGeometryExerciser::MagGeometryExerciser(const MagGeometry * g) : theGeometry( volumes.insert(volumes.end(), theEVolumes.begin(), theEVolumes.end()); } - -MagGeometryExerciser::~MagGeometryExerciser(){} - +MagGeometryExerciser::~MagGeometryExerciser() {} //---------------------------------------------------------------------- // Check if findVolume succeeds for random points. // Note: findVolumeTolerance in pset to change the tolerance. -void MagGeometryExerciser::testFindVolume(int ntry){ - - cout <geometryVersion>=160812) maxZ=2400.; + if (theGeometry->geometryVersion >= 160812) + maxZ = 2400.; - GlobalPointProvider p(0.,900., -Geom::pi(), Geom::pi(), -maxZ, maxZ); + GlobalPointProvider p(0., 900., -Geom::pi(), Geom::pi(), -maxZ, maxZ); cout << "Random points: (|Z| < " << maxZ << ")" << endl; int success = 0; - for (int i = 0; ifindVolume(gp, tolerance); - bool ok = (vol!=0); + MagVolume6Faces const* vol = (MagVolume6Faces const*)theGeometry->findVolume(gp, tolerance); + bool ok = (vol != 0); - if (vol==0) { - cout << "ERROR no volume found! " - << gp << " " << gp.z() << " " << gp.perp() - << " isBarrel: " << theGeometry->inBarrel(gp) - << endl; - + if (vol == 0) { + cout << "ERROR no volume found! " << gp << " " << gp.z() << " " << gp.perp() + << " isBarrel: " << theGeometry->inBarrel(gp) << endl; // Try with a linear search - vol = (MagVolume6Faces const*) theGeometry->findVolume1(gp,tolerance); + vol = (MagVolume6Faces const*)theGeometry->findVolume1(gp, tolerance); cout << "Was in volume: "; - if (vol !=0) + if (vol != 0) cout << vol->volumeNo << ":" << int(vol->copyno); - else + else cout << "-1"; cout << endl; } @@ -88,70 +80,64 @@ bool MagGeometryExerciser::testFindVolume(const GlobalPoint & gp){ return ok; } - - //---------------------------------------------------------------------- // Check that a set of points is inside() one and only one volume. void MagGeometryExerciser::testInside(int ntry, float tolerance) { - - cout << "-----------------------------------------------------" << endl - << " inside(random) test" << endl; - + cout << "-----------------------------------------------------" << endl << " inside(random) test" << endl; // Test random points: they should be found inside() one and only one volume // Test some known overlaps/gaps - if (false) { //FIXME + if (false) { //FIXME cout << "Known points:" << endl; - testInside(GlobalPoint(0.,0.,0.)); - testInside(GlobalPoint(331.358,-278.042,-648.788));//V_ZN_81 V_ZN_82 - testInside(GlobalPoint(-426.188,75.1483,-533.075));//V_ZN_81 V_ZN_82 - testInside(GlobalPoint(-586.27,157.094,150.702)); //V_ZN_170 V_ZN_174 - testInside(GlobalPoint(-465.562,-465.616,-222.224));//203 205 - testInside(GlobalPoint(637.078,170.737,-222.632)); //203 205 - testInside(GlobalPoint(162.971,-608.294,-306.791)); //203 205 - testInside(GlobalPoint(-633.925,-169.839,-390.589)); //203 205 - testInside(GlobalPoint(170.358,635.857,-535.735)); //207 209 - testInside(GlobalPoint(166.836,622.58,-513.872)); //207 209 - testInside(GlobalPoint(-12.7086,-3.99366,-1313.01)); //53 56 - testInside(GlobalPoint(106.178,-538.867,-69.2348)); //147 148 - testInside(GlobalPoint(19.1496,522.831,-1333)); //50 64 - testInside(GlobalPoint(355.516,-479.729,-1333.01)); //50 64 - testInside(GlobalPoint(157.96,-389.223,-1333.01)); //50 64 - testInside(GlobalPoint(-464.338,464.234,-473.616)); // 207 209 - testInside(GlobalPoint(17.474,-669.279,-1333.01)); // 50 64 - testInside(GlobalPoint(-453.683,-453.601,-204.895)); // 203 205 - testInside(GlobalPoint(165.092,-615.998,-494.625)); // 207 209 - testInside(GlobalPoint(-586.27,157.094,-617.882)); // 177 177 - testInside(GlobalPoint(-142.226,390.763,-553.809)); //81 79 - testInside(GlobalPoint(-141.701,389.32,-142.088)); //81 79 + testInside(GlobalPoint(0., 0., 0.)); + testInside(GlobalPoint(331.358, -278.042, -648.788)); //V_ZN_81 V_ZN_82 + testInside(GlobalPoint(-426.188, 75.1483, -533.075)); //V_ZN_81 V_ZN_82 + testInside(GlobalPoint(-586.27, 157.094, 150.702)); //V_ZN_170 V_ZN_174 + testInside(GlobalPoint(-465.562, -465.616, -222.224)); //203 205 + testInside(GlobalPoint(637.078, 170.737, -222.632)); //203 205 + testInside(GlobalPoint(162.971, -608.294, -306.791)); //203 205 + testInside(GlobalPoint(-633.925, -169.839, -390.589)); //203 205 + testInside(GlobalPoint(170.358, 635.857, -535.735)); //207 209 + testInside(GlobalPoint(166.836, 622.58, -513.872)); //207 209 + testInside(GlobalPoint(-12.7086, -3.99366, -1313.01)); //53 56 + testInside(GlobalPoint(106.178, -538.867, -69.2348)); //147 148 + testInside(GlobalPoint(19.1496, 522.831, -1333)); //50 64 + testInside(GlobalPoint(355.516, -479.729, -1333.01)); //50 64 + testInside(GlobalPoint(157.96, -389.223, -1333.01)); //50 64 + testInside(GlobalPoint(-464.338, 464.234, -473.616)); // 207 209 + testInside(GlobalPoint(17.474, -669.279, -1333.01)); // 50 64 + testInside(GlobalPoint(-453.683, -453.601, -204.895)); // 203 205 + testInside(GlobalPoint(165.092, -615.998, -494.625)); // 207 209 + testInside(GlobalPoint(-586.27, 157.094, -617.882)); // 177 177 + testInside(GlobalPoint(-142.226, 390.763, -553.809)); //81 79 + testInside(GlobalPoint(-141.701, 389.32, -142.088)); //81 79 } - // Full CMS float maxZ = 1999.9; - if (theGeometry->geometryVersion>=160812) maxZ=2399.9; + if (theGeometry->geometryVersion >= 160812) + maxZ = 2399.9; - GlobalPointProvider p(0,900,-Geom::pi(),Geom::pi(),-maxZ,maxZ); + GlobalPointProvider p(0, 900, -Geom::pi(), Geom::pi(), -maxZ, maxZ); // Zoom of one sector // GlobalPointProvider p(350.,900.,-0.27,0.27,-1999.9,1999.9); // GlobalPointProvider p(0.,900.,-0.27,0.27,-1999.9,1999.9); cout << "Random points:" << volumes.size() << " volumes" << endl; - for (int i = 0; i& vols = volumes; @@ -159,68 +145,62 @@ bool MagGeometryExerciser::testInside(const GlobalPoint & gp, float tolerance){ // const vector& vols = theGeometry->barrelVolumes(); MagVolume6Faces const* found = 0; - for (vector::const_iterator v = vols.begin(); - v!=vols.end(); ++v){ - if ((*v)==0) { + for (vector::const_iterator v = vols.begin(); v != vols.end(); ++v) { + if ((*v) == 0) { cout << endl << "ERROR: no magvlolume" << endl; continue; } if ((*v)->inside(gp, tolerance)) { - if (reportSuccess) cout << gp << " is inside vol: " << (*v)->volumeNo; - if (found!=0) { - cout << " ***ERROR: for " << gp << " found " << (*v)->volumeNo - << " volume already found: " << found->volumeNo << endl; + if (reportSuccess) + cout << gp << " is inside vol: " << (*v)->volumeNo; + if (found != 0) { + cout << " ***ERROR: for " << gp << " found " << (*v)->volumeNo << " volume already found: " << found->volumeNo + << endl; } found = (*v); } } - - - if (found==0) { - MagVolume6Faces const * foundP = 0; - MagVolume6Faces const * foundN = 0; + if (found == 0) { + MagVolume6Faces const* foundP = 0; + MagVolume6Faces const* foundN = 0; // Look for the closest neighbouring volumes - const float phi=gp.phi(); + const float phi = gp.phi(); GlobalPoint gpP, gpN; - int ntry=0; - while ((foundP==0 || foundP==0) && ntry < 60) { + int ntry = 0; + while ((foundP == 0 || foundP == 0) && ntry < 60) { ++ntry; - for (vector::const_iterator v = vols.begin(); - v!=vols.end(); ++v){ - if (foundP==0) { - float phiP=phi+ntry*0.008727; - GlobalPoint gpP(GlobalPoint::Cylindrical(gp.perp(),phiP,gp.z())); - if ((*v)->inside(gpP)) { - foundP=(*v); - } - } - if (foundN==0) { - float phiN=phi-ntry*0.008727; - GlobalPoint gpN(GlobalPoint::Cylindrical(gp.perp(),phiN,gp.z())); - if ((*v)->inside(gpN)) { - foundN=(*v); - } - } + for (vector::const_iterator v = vols.begin(); v != vols.end(); ++v) { + if (foundP == 0) { + float phiP = phi + ntry * 0.008727; + GlobalPoint gpP(GlobalPoint::Cylindrical(gp.perp(), phiP, gp.z())); + if ((*v)->inside(gpP)) { + foundP = (*v); + } + } + if (foundN == 0) { + float phiN = phi - ntry * 0.008727; + GlobalPoint gpN(GlobalPoint::Cylindrical(gp.perp(), phiN, gp.z())); + if ((*v)->inside(gpN)) { + foundN = (*v); + } + } } } - - cout << gp << " ***ERROR no volume found! : closests: " - << ((foundP==0) ? -1 : foundP->volumeNo) - << " at dphi: " << gpP.phi()-phi << " " - << ((foundN==0) ? -1 :foundN->volumeNo) - << " at dphi: " << gpN.phi()-phi - << endl; + + cout << gp << " ***ERROR no volume found! : closests: " << ((foundP == 0) ? -1 : foundP->volumeNo) + << " at dphi: " << gpP.phi() - phi << " " << ((foundN == 0) ? -1 : foundN->volumeNo) + << " at dphi: " << gpN.phi() - phi << endl; } - - return true; //FIXME + + return true; //FIXME } //---------------------------------------------------------------------- // if (test82) { // minZ = -660; -// maxZ = 660.; +// maxZ = 660.; // minR = 411.5; //V81 // maxR = 447.; //V83 // minPhi= 104./180.*Geom::pi(); diff --git a/MagneticField/GeomBuilder/test/stubs/MagGeometryExerciser.h b/MagneticField/GeomBuilder/test/stubs/MagGeometryExerciser.h index 546cd50230df5..6711896f0140e 100644 --- a/MagneticField/GeomBuilder/test/stubs/MagGeometryExerciser.h +++ b/MagneticField/GeomBuilder/test/stubs/MagGeometryExerciser.h @@ -13,32 +13,28 @@ class MagGeometry; class MagVolume6Faces; - class MagGeometryExerciser { public: /// Constructor - MagGeometryExerciser(const MagGeometry * g); + MagGeometryExerciser(const MagGeometry* g); /// Destructor ~MagGeometryExerciser(); - - void testFindVolume(int ntry = 100000); // findVolume(random) test - void testInside(int ntry = 100000, float tolerance=0.); // inside(random) test + void testFindVolume(int ntry = 100000); // findVolume(random) test + void testInside(int ntry = 100000, float tolerance = 0.); // inside(random) test // void testFieldRandom(int ntry = 1000);// fieldInTesla vs MagneticField::inTesla (random) // void testFieldVol1(); // fieldInTesla within vol 1 (tiny region) // void testFieldLinear(int ntry = 1000);// fieldInTesla vs MagneticField::inTesla (track-like pattern) - private: // Check if inside succeeds for the given point. - bool testInside(const GlobalPoint & gp, float tolerance=0.); + bool testInside(const GlobalPoint& gp, float tolerance = 0.); // Check if findVolume succeeds for the given point. - bool testFindVolume(const GlobalPoint & gp); + bool testFindVolume(const GlobalPoint& gp); - const MagGeometry * theGeometry; + const MagGeometry* theGeometry; std::vector volumes; }; #endif - diff --git a/MagneticField/GeomBuilder/test/stubs/VolumeGridTester.cc b/MagneticField/GeomBuilder/test/stubs/VolumeGridTester.cc index 405903b933bff..c138c9ed66bc3 100644 --- a/MagneticField/GeomBuilder/test/stubs/VolumeGridTester.cc +++ b/MagneticField/GeomBuilder/test/stubs/VolumeGridTester.cc @@ -5,70 +5,62 @@ #include #include - using namespace std; +bool VolumeGridTester::testInside() const { + // static string lastName("firstcall"); + // if (lastName == volume_->name) return true; // skip multiple calls + // else lastName = volume_->name; -bool VolumeGridTester::testInside() const -{ - -// static string lastName("firstcall"); -// if (lastName == volume_->name) return true; // skip multiple calls -// else lastName = volume_->name; - - - const MFGrid * grid = dynamic_cast(magProvider_); + const MFGrid* grid = dynamic_cast(magProvider_); if (grid == 0) { - cout << "VolumeGridTester: magProvider is not a MFGrid3D, cannot test it..." << endl - << "expected "; + cout << "VolumeGridTester: magProvider is not a MFGrid3D, cannot test it..." << endl << "expected "; return false; } bool result = true; const double tolerance = 0.03; - + cout << "The volume position is " << volume_->position() << endl; - cout << "Is the volume position inside the volume? " - << volume_->inside( volume_->position(), tolerance) <inside(volume_->position(), tolerance) << endl; Dimensions sizes = grid->dimensions(); - cout << "Grid has " << 3 << " dimensions " + cout << "Grid has " << 3 << " dimensions " << " number of nodes is " << sizes.w << " " << sizes.h << " " << sizes.d << endl; size_t dumpCount = 0; - for (int j=0; j < sizes.h; j++) { - for (int k=0; k < sizes.d; k++) { - for (int i=0; i < sizes.w; i++) { - MFGrid::LocalPoint lp = grid->nodePosition( i, j, k); - if (! volume_->inside(lp, tolerance)) { - result = false; - if (++dumpCount < 2) dumpProblem( lp, tolerance); - else return result; - } + for (int j = 0; j < sizes.h; j++) { + for (int k = 0; k < sizes.d; k++) { + for (int i = 0; i < sizes.w; i++) { + MFGrid::LocalPoint lp = grid->nodePosition(i, j, k); + if (!volume_->inside(lp, tolerance)) { + result = false; + if (++dumpCount < 2) + dumpProblem(lp, tolerance); + else + return result; + } } } } return result; } -void VolumeGridTester::dumpProblem( const MFGrid::LocalPoint& lp, double tolerance) const -{ - MFGrid::GlobalPoint gp( volume_->toGlobal(lp)); - cout << "Point " << lp << " (local) " - << gp << " (global) " << gp.perp() << " " << gp.phi() +void VolumeGridTester::dumpProblem(const MFGrid::LocalPoint& lp, double tolerance) const { + MFGrid::GlobalPoint gp(volume_->toGlobal(lp)); + cout << "Point " << lp << " (local) " << gp << " (global) " << gp.perp() << " " << gp.phi() << " (R,phi global) not in volume!" << endl; const vector& faces = volume_->faces(); - for (vector::const_iterator v=faces.begin(); v!=faces.end(); v++) { - cout << "Volume face has position " << v->surface().position() - << " side " << (int) v->surfaceSide() << " rotation " << endl - << v->surface().rotation() << endl; + for (vector::const_iterator v = faces.begin(); v != faces.end(); v++) { + cout << "Volume face has position " << v->surface().position() << " side " << (int)v->surfaceSide() << " rotation " + << endl + << v->surface().rotation() << endl; - Surface::Side side = v->surface().side( gp, tolerance); - if ( side != v->surfaceSide() && side != SurfaceOrientation::onSurface) { - cout << "Wrong side: " << (int) side - << " local position in surface frame " << v->surface().toLocal(gp) << endl; - } - else cout << "Correct side: " << (int) side << endl; + Surface::Side side = v->surface().side(gp, tolerance); + if (side != v->surfaceSide() && side != SurfaceOrientation::onSurface) { + cout << "Wrong side: " << (int)side << " local position in surface frame " << v->surface().toLocal(gp) << endl; + } else + cout << "Correct side: " << (int)side << endl; } } diff --git a/MagneticField/GeomBuilder/test/stubs/VolumeGridTester.h b/MagneticField/GeomBuilder/test/stubs/VolumeGridTester.h index 58cd17b43365d..9eeb35b95d6d8 100644 --- a/MagneticField/GeomBuilder/test/stubs/VolumeGridTester.h +++ b/MagneticField/GeomBuilder/test/stubs/VolumeGridTester.h @@ -16,19 +16,15 @@ class MagVolume6Faces; class VolumeGridTester { public: - - VolumeGridTester( const MagVolume6Faces* vol, const MagProviderInterpol* mp) : - volume_(vol), magProvider_(mp) {} + VolumeGridTester(const MagVolume6Faces* vol, const MagProviderInterpol* mp) : volume_(vol), magProvider_(mp) {} bool testInside() const; private: - const MagVolume6Faces* volume_; const MagProviderInterpol* magProvider_; - void dumpProblem( const MFGrid::LocalPoint& lp, double tolerance) const; - + void dumpProblem(const MFGrid::LocalPoint& lp, double tolerance) const; }; #endif diff --git a/RecoBTau/JetTagComputer/interface/GenericMVAComputer.h b/RecoBTau/JetTagComputer/interface/GenericMVAComputer.h index 047672ad958b4..63fe06baa4b4b 100644 --- a/RecoBTau/JetTagComputer/interface/GenericMVAComputer.h +++ b/RecoBTau/JetTagComputer/interface/GenericMVAComputer.h @@ -11,139 +11,128 @@ // overload MVAComputer and replace eval() methods to work on TaggingVariable class GenericMVAComputer : public PhysicsTools::MVAComputer { +public: + // forward declarations; + template + class TaggingVariableIterator; + class TaggingVariableMapping; + + GenericMVAComputer(const PhysicsTools::Calibration::MVAComputer *calib) : PhysicsTools::MVAComputer(calib) {} + + // create wrapping iterator + template + inline TaggingVariableIterator iterator(Iter_t iter) const { + return TaggingVariableIterator(&mapping, iter); + } + + // overload eval method to work on containers of TaggingVariable + template + inline double eval(Iter_t first, Iter_t last) const { + typedef TaggingVariableIterator Wrapped_t; + return PhysicsTools::MVAComputer::template eval(iterator(first), iterator(last)); + } + + template + inline double eval(const Container_t &values) const { + typedef typename Container_t::const_iterator Iter_t; + return this->template eval(values.begin(), values.end()); + } + + // iterator wrapper with on-the-fly TaggingVariableName -> AtomicId mapping + // + // Notice that this tells the computer to completely inline it + // this is reasonable since inlining it means that the optimizer + // will not produce any additional code for the wrapper + // (it is entirely optimized away), except for the actual mapping + // which is no more than a simple array lookup. + // + // The result will be inlined into the eval() template of MVAComputer + // which will be instantiated as one single tightly-integrated + // function. + template + class TaggingVariableIterator { + public: + // class implementing MVAComputer::Variable::Value interface + struct Value { public: - // forward declarations; - template class TaggingVariableIterator; - class TaggingVariableMapping; - - GenericMVAComputer(const PhysicsTools::Calibration::MVAComputer *calib) : - PhysicsTools::MVAComputer(calib) {} - - // create wrapping iterator - template - inline TaggingVariableIterator iterator(Iter_t iter) const - { return TaggingVariableIterator(&mapping, iter); } - - // overload eval method to work on containers of TaggingVariable - template - inline double eval(Iter_t first, Iter_t last) const - { - typedef TaggingVariableIterator Wrapped_t; - return PhysicsTools::MVAComputer::template eval( - iterator(first), iterator(last)); - } - - template - inline double eval(const Container_t &values) const - { - typedef typename Container_t::const_iterator Iter_t; - return this->template eval(values.begin(), values.end()); - } - - // iterator wrapper with on-the-fly TaggingVariableName -> AtomicId mapping - // - // Notice that this tells the computer to completely inline it - // this is reasonable since inlining it means that the optimizer - // will not produce any additional code for the wrapper - // (it is entirely optimized away), except for the actual mapping - // which is no more than a simple array lookup. - // - // The result will be inlined into the eval() template of MVAComputer - // which will be instantiated as one single tightly-integrated - // function. - template - class TaggingVariableIterator { - public: - // class implementing MVAComputer::Variable::Value interface - struct Value { - public: - // the actual operator doing the mapping - inline PhysicsTools::AtomicId getName() const - { return mapping->getAtomicId(iter->first); } - - inline double getValue() const - { return iter->second; } - - operator PhysicsTools::Variable::Value() const - { - return PhysicsTools::Variable::Value( - getName(), getValue()); - } - - protected: - friend class TaggingVariableIterator; - - inline Value(TaggingVariableMapping const* mapping, - const Iter_t &iter) : - mapping(mapping), iter(iter) {} - - private: - // pointer to the current mapping - TaggingVariableMapping const* mapping; - // iterator to reco::TaggingVariable in orig. container - Iter_t iter; - }; - - typedef std::forward_iterator_tag iterator_category; - typedef Value value_type; - typedef typename std::iterator_traits::difference_type difference_type; - typedef const Value *pointer; - typedef const Value &reference; - - inline ~TaggingVariableIterator() {} - - // methods to make class a standard forward iterator - - inline const Value &operator * () const { return value; } - inline Value &operator * () { return value; } - - inline const Value *operator -> () const { return &value; } - inline Value *operator -> () { return &value; } - - inline bool operator == (const TaggingVariableIterator &other) const - { return value.iter == other.value.iter; } - inline bool operator != (const TaggingVariableIterator &other) const - { return value.iter != other.value.iter; } - inline bool operator < (const TaggingVariableIterator &other) const - { return value.iter < other.value.iter; } - - inline TaggingVariableIterator &operator ++ () - { ++value.iter; return *this; } - - inline TaggingVariableIterator operator ++ (int dummy) - { TaggingVariableIterator orig = *this; ++value.iter; return orig; } - - protected: - friend class GenericMVAComputer; - inline TaggingVariableIterator(TaggingVariableMapping const* mapping, - const Iter_t &iter) : - value(mapping, iter) {} - - private: - // holds the current "value" - // it's really only an iterator that points the original - // current TaggingVariable plus required methods - Value value; - }; - - // TaggingVariableName -> PhysicsTools::AtomicId mapping - class TaggingVariableMapping { - public: - typedef PhysicsTools::AtomicId AtomicId; - typedef reco::TaggingVariableName TaggingName; - - TaggingVariableMapping(); - ~TaggingVariableMapping() {} - - inline AtomicId getAtomicId(TaggingName taggingName) const - { return taggingVarToAtomicId[taggingName]; } - - private: - std::vector taggingVarToAtomicId; - }; + // the actual operator doing the mapping + inline PhysicsTools::AtomicId getName() const { return mapping->getAtomicId(iter->first); } + + inline double getValue() const { return iter->second; } + + operator PhysicsTools::Variable::Value() const { return PhysicsTools::Variable::Value(getName(), getValue()); } + + protected: + friend class TaggingVariableIterator; + + inline Value(TaggingVariableMapping const *mapping, const Iter_t &iter) : mapping(mapping), iter(iter) {} private: - static const TaggingVariableMapping mapping; + // pointer to the current mapping + TaggingVariableMapping const *mapping; + // iterator to reco::TaggingVariable in orig. container + Iter_t iter; + }; + + typedef std::forward_iterator_tag iterator_category; + typedef Value value_type; + typedef typename std::iterator_traits::difference_type difference_type; + typedef const Value *pointer; + typedef const Value &reference; + + inline ~TaggingVariableIterator() {} + + // methods to make class a standard forward iterator + + inline const Value &operator*() const { return value; } + inline Value &operator*() { return value; } + + inline const Value *operator->() const { return &value; } + inline Value *operator->() { return &value; } + + inline bool operator==(const TaggingVariableIterator &other) const { return value.iter == other.value.iter; } + inline bool operator!=(const TaggingVariableIterator &other) const { return value.iter != other.value.iter; } + inline bool operator<(const TaggingVariableIterator &other) const { return value.iter < other.value.iter; } + + inline TaggingVariableIterator &operator++() { + ++value.iter; + return *this; + } + + inline TaggingVariableIterator operator++(int dummy) { + TaggingVariableIterator orig = *this; + ++value.iter; + return orig; + } + + protected: + friend class GenericMVAComputer; + inline TaggingVariableIterator(TaggingVariableMapping const *mapping, const Iter_t &iter) : value(mapping, iter) {} + + private: + // holds the current "value" + // it's really only an iterator that points the original + // current TaggingVariable plus required methods + Value value; + }; + + // TaggingVariableName -> PhysicsTools::AtomicId mapping + class TaggingVariableMapping { + public: + typedef PhysicsTools::AtomicId AtomicId; + typedef reco::TaggingVariableName TaggingName; + + TaggingVariableMapping(); + ~TaggingVariableMapping() {} + + inline AtomicId getAtomicId(TaggingName taggingName) const { return taggingVarToAtomicId[taggingName]; } + + private: + std::vector taggingVarToAtomicId; + }; + +private: + static const TaggingVariableMapping mapping; }; -#endif // RecoBTau_BTauComputer_GenericMVAComputer_h +#endif // RecoBTau_BTauComputer_GenericMVAComputer_h diff --git a/RecoBTau/JetTagComputer/interface/GenericMVAComputerCache.h b/RecoBTau/JetTagComputer/interface/GenericMVAComputerCache.h index afe8203a6d625..338ea5d722876 100644 --- a/RecoBTau/JetTagComputer/interface/GenericMVAComputerCache.h +++ b/RecoBTau/JetTagComputer/interface/GenericMVAComputerCache.h @@ -10,33 +10,32 @@ #include "RecoBTau/JetTagComputer/interface/GenericMVAComputer.h" class GenericMVAComputerCache { - public: - GenericMVAComputerCache(const std::vector &labels); - ~GenericMVAComputerCache(); +public: + GenericMVAComputerCache(const std::vector &labels); + ~GenericMVAComputerCache(); - bool - update(const PhysicsTools::Calibration::MVAComputerContainer *calib); + bool update(const PhysicsTools::Calibration::MVAComputerContainer *calib); - GenericMVAComputer const* getComputer(int index) const; + GenericMVAComputer const *getComputer(int index) const; - bool isEmpty() const; + bool isEmpty() const; - private: - struct IndividualComputer { - IndividualComputer(); - IndividualComputer(const IndividualComputer &orig); - ~IndividualComputer(); +private: + struct IndividualComputer { + IndividualComputer(); + IndividualComputer(const IndividualComputer &orig); + ~IndividualComputer(); - std::string label; - std::unique_ptr computer; - PhysicsTools::Calibration::MVAComputer::CacheId cacheId; - }; + std::string label; + std::unique_ptr computer; + PhysicsTools::Calibration::MVAComputer::CacheId cacheId; + }; - std::vector computers; - PhysicsTools::Calibration::MVAComputerContainer::CacheId cacheId; - bool initialized; - bool empty; - std::string errorUpdatingLabel; + std::vector computers; + PhysicsTools::Calibration::MVAComputerContainer::CacheId cacheId; + bool initialized; + bool empty; + std::string errorUpdatingLabel; }; -#endif // RecoBTau_JetTagComputer_GenericMVAComputerCache_h +#endif // RecoBTau_JetTagComputer_GenericMVAComputerCache_h diff --git a/RecoBTau/JetTagComputer/interface/GenericMVAJetTagComputer.h b/RecoBTau/JetTagComputer/interface/GenericMVAJetTagComputer.h index fc9e466903bed..6224380e66e0d 100644 --- a/RecoBTau/JetTagComputer/interface/GenericMVAJetTagComputer.h +++ b/RecoBTau/JetTagComputer/interface/GenericMVAJetTagComputer.h @@ -14,23 +14,21 @@ class JetTagComputerRecord; class GenericMVAJetTagComputer : public JetTagComputer { - public: - GenericMVAJetTagComputer(const edm::ParameterSet ¶meters); - ~GenericMVAJetTagComputer() override; +public: + GenericMVAJetTagComputer(const edm::ParameterSet ¶meters); + ~GenericMVAJetTagComputer() override; - void initialize(const JetTagComputerRecord &) override; + void initialize(const JetTagComputerRecord &) override; - float discriminator(const TagInfoHelper &info) const override; + float discriminator(const TagInfoHelper &info) const override; - virtual reco::TaggingVariableList - taggingVariables(const reco::BaseTagInfo &tagInfo) const; - virtual reco::TaggingVariableList - taggingVariables(const TagInfoHelper &info) const; + virtual reco::TaggingVariableList taggingVariables(const reco::BaseTagInfo &tagInfo) const; + virtual reco::TaggingVariableList taggingVariables(const TagInfoHelper &info) const; - private: - std::unique_ptr categorySelector_; - GenericMVAComputerCache computerCache_; - std::string recordLabel_; +private: + std::unique_ptr categorySelector_; + GenericMVAComputerCache computerCache_; + std::string recordLabel_; }; -#endif // RecoBTau_JetTagComputer_GenericMVAJetTagComputer_h +#endif // RecoBTau_JetTagComputer_GenericMVAJetTagComputer_h diff --git a/RecoBTau/JetTagComputer/interface/GenericMVAJetTagComputerWrapper.h b/RecoBTau/JetTagComputer/interface/GenericMVAJetTagComputerWrapper.h index 359c355eec7cc..bd378376280ec 100644 --- a/RecoBTau/JetTagComputer/interface/GenericMVAJetTagComputerWrapper.h +++ b/RecoBTau/JetTagComputer/interface/GenericMVAJetTagComputerWrapper.h @@ -31,117 +31,129 @@ */ namespace btau_dummy { - struct Null {}; - constexpr const char none[] = ""; -} + struct Null {}; + constexpr const char none[] = ""; +} // namespace btau_dummy // 4 named TagInfos -template -class GenericMVAJetTagComputerWrapper : - public GenericMVAJetTagComputer, private Provider { - - public: - GenericMVAJetTagComputerWrapper(const edm::ParameterSet ¶ms) : - GenericMVAJetTagComputer(params), Provider(params) - { uses(0, ti1); uses(1, ti2); uses(2, ti3); uses(3, ti4); } - - protected: - reco::TaggingVariableList - taggingVariables(const TagInfoHelper &info) const override - { - return (static_cast(*this))(info.get(0), - info.get(1), info.get(2), info.get(3)); - } +template +class GenericMVAJetTagComputerWrapper : public GenericMVAJetTagComputer, private Provider { +public: + GenericMVAJetTagComputerWrapper(const edm::ParameterSet ¶ms) + : GenericMVAJetTagComputer(params), Provider(params) { + uses(0, ti1); + uses(1, ti2); + uses(2, ti3); + uses(3, ti4); + } + +protected: + reco::TaggingVariableList taggingVariables(const TagInfoHelper &info) const override { + return (static_cast(*this))( + info.get(0), info.get(1), info.get(2), info.get(3)); + } }; // 3 named TagInfos -template -class GenericMVAJetTagComputerWrapper : - public GenericMVAJetTagComputer, private Provider { - - public: - GenericMVAJetTagComputerWrapper(const edm::ParameterSet ¶ms) : - GenericMVAJetTagComputer(params), Provider(params) - { uses(0, ti1); uses(1, ti2); uses(2, ti3); } - - protected: - reco::TaggingVariableList - taggingVariables(const TagInfoHelper &info) const override - { - return (static_cast(*this))(info.get(0), - info.get(1), info.get(2)); - } +template +class GenericMVAJetTagComputerWrapper + : public GenericMVAJetTagComputer, private Provider { +public: + GenericMVAJetTagComputerWrapper(const edm::ParameterSet ¶ms) + : GenericMVAJetTagComputer(params), Provider(params) { + uses(0, ti1); + uses(1, ti2); + uses(2, ti3); + } + +protected: + reco::TaggingVariableList taggingVariables(const TagInfoHelper &info) const override { + return (static_cast(*this))(info.get(0), info.get(1), info.get(2)); + } }; // 2 named TagInfos -template -class GenericMVAJetTagComputerWrapper : - public GenericMVAJetTagComputer, private Provider { - - public: - GenericMVAJetTagComputerWrapper(const edm::ParameterSet ¶ms) : - GenericMVAJetTagComputer(params), Provider(params) - { uses(0, ti1); uses(1, ti2); } - - protected: - reco::TaggingVariableList - taggingVariables(const TagInfoHelper &info) const override - { - return (static_cast(*this))(info.get(0), - info.get(1)); - } +template +class GenericMVAJetTagComputerWrapper : public GenericMVAJetTagComputer, + private Provider { +public: + GenericMVAJetTagComputerWrapper(const edm::ParameterSet ¶ms) + : GenericMVAJetTagComputer(params), Provider(params) { + uses(0, ti1); + uses(1, ti2); + } + +protected: + reco::TaggingVariableList taggingVariables(const TagInfoHelper &info) const override { + return (static_cast(*this))(info.get(0), info.get(1)); + } }; // 1 named TagInfo -template -class GenericMVAJetTagComputerWrapper : - public GenericMVAJetTagComputer, private Provider { - - public: - GenericMVAJetTagComputerWrapper(const edm::ParameterSet ¶ms) : - GenericMVAJetTagComputer(params), Provider(params) - { uses(0, ti1); } - - protected: - reco::TaggingVariableList - taggingVariables(const TagInfoHelper &info) const override - { return (static_cast(*this))(info.get(0)); } +template +class GenericMVAJetTagComputerWrapper : public GenericMVAJetTagComputer, + private Provider { +public: + GenericMVAJetTagComputerWrapper(const edm::ParameterSet ¶ms) + : GenericMVAJetTagComputer(params), Provider(params) { + uses(0, ti1); + } + +protected: + reco::TaggingVariableList taggingVariables(const TagInfoHelper &info) const override { + return (static_cast(*this))(info.get(0)); + } }; // default TagInfo -template -class GenericMVAJetTagComputerWrapper : - public GenericMVAJetTagComputer, private Provider { - - public: - GenericMVAJetTagComputerWrapper(const edm::ParameterSet ¶ms) : - GenericMVAJetTagComputer(params), Provider(params) - {} - - protected: - reco::TaggingVariableList - taggingVariables(const TagInfoHelper &info) const override - { return (static_cast(*this))(info.get(0)); } +template +class GenericMVAJetTagComputerWrapper : public GenericMVAJetTagComputer, + private Provider { +public: + GenericMVAJetTagComputerWrapper(const edm::ParameterSet ¶ms) + : GenericMVAJetTagComputer(params), Provider(params) {} + +protected: + reco::TaggingVariableList taggingVariables(const TagInfoHelper &info) const override { + return (static_cast(*this))(info.get(0)); + } }; -#endif // RecoBTau_JetTagComputer_GenericMVAJetTagComputerWrapper_h +#endif // RecoBTau_JetTagComputer_GenericMVAJetTagComputerWrapper_h diff --git a/RecoBTau/JetTagComputer/interface/JetTagComputer.h b/RecoBTau/JetTagComputer/interface/JetTagComputer.h index 35f42064a2ce0..e4022d0f16ae7 100644 --- a/RecoBTau/JetTagComputer/interface/JetTagComputer.h +++ b/RecoBTau/JetTagComputer/interface/JetTagComputer.h @@ -12,103 +12,90 @@ class JetTagComputerRecord; class JetTagComputer { - public: - class TagInfoHelper { - public: - TagInfoHelper(const std::vector &infos, std::vector &labels) : - m_tagInfos(infos), - m_labels(labels) {} - - TagInfoHelper(const std::vector &infos): - m_tagInfos(infos), - m_labels() - {} - - - ~TagInfoHelper() {} - - const reco::BaseTagInfo &getBase(unsigned int index) const - { - if (index >= m_tagInfos.size()) - throw cms::Exception("InvalidIndex") - << "Invalid index " << index << " " - "in call to JetTagComputer::get." - << std::endl; - - const reco::BaseTagInfo *info = m_tagInfos[index]; - if (!info) - throw cms::Exception("ProductMissing") - << "Missing TagInfo " - "in call to JetTagComputer::get." - << std::endl; - - return *info; - } - - template - const T &get(unsigned int index = 0) const - { - const reco::BaseTagInfo *info = &getBase(index); - const T *castInfo = dynamic_cast(info); - if (!castInfo) - throw cms::Exception("InvalidCast") - << "Invalid TagInfo cast " - "in call to JetTagComputer::get( index="<< index <<" )." - << std::endl; - - return *castInfo; - } - - template - const T &get(std::string label) const - { - size_t idx=0; - for(; idx <= m_labels.size(); idx++){ - if(idx < m_labels.size() && m_labels[idx] == label) break; - } - - if(idx == m_labels.size()) { - throw cms::Exception("ProductMissing") - << "Missing TagInfo with label: " << label << - " in call to JetTagComputer::get." << std::endl; - } - return get(idx); - } - - private: - const std::vector &m_tagInfos; - std::vector m_labels; - }; - - // default constructor - JetTagComputer() : m_setupDone(false) {} - virtual ~JetTagComputer() {} - - // explicit constructor accepting a ParameterSet for configuration - explicit JetTagComputer(const edm::ParameterSet& configuration) : - m_setupDone(false) {} - - virtual void initialize(const JetTagComputerRecord &) {} - - float operator () (const reco::BaseTagInfo& info) const; - inline float operator () (const TagInfoHelper &helper) const - { return discriminator(helper); } - - inline const std::vector &getInputLabels() const - { return m_inputLabels; } - - void setupDone() { m_setupDone = true; } - - protected: - void uses(unsigned int id, const std::string &label); - void uses(const std::string &label) { uses(0, label); } - - virtual float discriminator(const reco::BaseTagInfo&) const; - virtual float discriminator(const TagInfoHelper&) const; - - private: - std::vector m_inputLabels; - bool m_setupDone; +public: + class TagInfoHelper { + public: + TagInfoHelper(const std::vector &infos, std::vector &labels) + : m_tagInfos(infos), m_labels(labels) {} + + TagInfoHelper(const std::vector &infos) : m_tagInfos(infos), m_labels() {} + + ~TagInfoHelper() {} + + const reco::BaseTagInfo &getBase(unsigned int index) const { + if (index >= m_tagInfos.size()) + throw cms::Exception("InvalidIndex") << "Invalid index " << index + << " " + "in call to JetTagComputer::get." + << std::endl; + + const reco::BaseTagInfo *info = m_tagInfos[index]; + if (!info) + throw cms::Exception("ProductMissing") << "Missing TagInfo " + "in call to JetTagComputer::get." + << std::endl; + + return *info; + } + + template + const T &get(unsigned int index = 0) const { + const reco::BaseTagInfo *info = &getBase(index); + const T *castInfo = dynamic_cast(info); + if (!castInfo) + throw cms::Exception("InvalidCast") << "Invalid TagInfo cast " + "in call to JetTagComputer::get( index=" + << index << " )." << std::endl; + + return *castInfo; + } + + template + const T &get(std::string label) const { + size_t idx = 0; + for (; idx <= m_labels.size(); idx++) { + if (idx < m_labels.size() && m_labels[idx] == label) + break; + } + + if (idx == m_labels.size()) { + throw cms::Exception("ProductMissing") + << "Missing TagInfo with label: " << label << " in call to JetTagComputer::get." << std::endl; + } + return get(idx); + } + + private: + const std::vector &m_tagInfos; + std::vector m_labels; + }; + + // default constructor + JetTagComputer() : m_setupDone(false) {} + virtual ~JetTagComputer() {} + + // explicit constructor accepting a ParameterSet for configuration + explicit JetTagComputer(const edm::ParameterSet &configuration) : m_setupDone(false) {} + + virtual void initialize(const JetTagComputerRecord &) {} + + float operator()(const reco::BaseTagInfo &info) const; + inline float operator()(const TagInfoHelper &helper) const { return discriminator(helper); } + + inline const std::vector &getInputLabels() const { return m_inputLabels; } + + void setupDone() { m_setupDone = true; } + +protected: + void uses(unsigned int id, const std::string &label); + void uses(const std::string &label) { uses(0, label); } + + virtual float discriminator(const reco::BaseTagInfo &) const; + virtual float discriminator(const TagInfoHelper &) const; + +private: + std::vector m_inputLabels; + bool m_setupDone; }; -#endif // RecoBTau_JetTagComputer_h +#endif // RecoBTau_JetTagComputer_h diff --git a/RecoBTau/JetTagComputer/interface/JetTagComputerESProducer.h b/RecoBTau/JetTagComputer/interface/JetTagComputerESProducer.h index 65f76fbfacb85..36562a01f6e97 100644 --- a/RecoBTau/JetTagComputer/interface/JetTagComputerESProducer.h +++ b/RecoBTau/JetTagComputer/interface/JetTagComputerESProducer.h @@ -12,21 +12,19 @@ #include "RecoBTau/JetTagComputer/interface/JetTagComputer.h" template -class JetTagComputerESProducer: public edm::ESProducer { +class JetTagComputerESProducer : public edm::ESProducer { private: // check that the template parameter inherits from JetTagComputer - static_assert((boost::is_convertible::value)); - -public: - JetTagComputerESProducer(const edm::ParameterSet & pset) : m_pset(pset) { - setWhatProduced(this, m_pset.getParameter("@module_label") ); + static_assert((boost::is_convertible::value)); +public: + JetTagComputerESProducer(const edm::ParameterSet& pset) : m_pset(pset) { + setWhatProduced(this, m_pset.getParameter("@module_label")); } - - ~JetTagComputerESProducer() override { - } - std::unique_ptr produce(const JetTagComputerRecord & record) { + ~JetTagComputerESProducer() override {} + + std::unique_ptr produce(const JetTagComputerRecord& record) { std::unique_ptr jetTagComputer = std::make_unique(m_pset); jetTagComputer->initialize(record); jetTagComputer->setupDone(); @@ -37,4 +35,4 @@ class JetTagComputerESProducer: public edm::ESProducer { edm::ParameterSet m_pset; }; -#endif // RecoBTau_JetTagComputerESProducer_h +#endif // RecoBTau_JetTagComputerESProducer_h diff --git a/RecoBTau/JetTagComputer/interface/JetTagComputerRecord.h b/RecoBTau/JetTagComputer/interface/JetTagComputerRecord.h index 9472ceba48444..472d2af47e5db 100644 --- a/RecoBTau/JetTagComputer/interface/JetTagComputerRecord.h +++ b/RecoBTau/JetTagComputer/interface/JetTagComputerRecord.h @@ -7,9 +7,8 @@ class BTauGenericMVAJetTagComputerRcd; class GBRWrapperRcd; -class JetTagComputerRecord : - public edm::eventsetup::DependentRecordImplementation< - JetTagComputerRecord, - boost::mpl::vector > {}; +class JetTagComputerRecord : public edm::eventsetup::DependentRecordImplementation< + JetTagComputerRecord, + boost::mpl::vector > {}; #endif diff --git a/RecoBTau/JetTagComputer/interface/TagInfoMVACategorySelector.h b/RecoBTau/JetTagComputer/interface/TagInfoMVACategorySelector.h index 8d3c6df0b678f..c7ac5f747f3e0 100644 --- a/RecoBTau/JetTagComputer/interface/TagInfoMVACategorySelector.h +++ b/RecoBTau/JetTagComputer/interface/TagInfoMVACategorySelector.h @@ -9,19 +9,17 @@ #include "PhysicsTools/MVAComputer/interface/Calibration.h" class TagInfoMVACategorySelector { - public: - TagInfoMVACategorySelector(const edm::ParameterSet ¶ms); - ~TagInfoMVACategorySelector(); +public: + TagInfoMVACategorySelector(const edm::ParameterSet ¶ms); + ~TagInfoMVACategorySelector(); - inline const std::vector &getCategoryLabels() const - { return categoryLabels; } + inline const std::vector &getCategoryLabels() const { return categoryLabels; } - int - findCategory(const reco::TaggingVariableList &taggingVariables) const; + int findCategory(const reco::TaggingVariableList &taggingVariables) const; - private: - reco::TaggingVariableName categoryVariable; - std::vector categoryLabels; +private: + reco::TaggingVariableName categoryVariable; + std::vector categoryLabels; }; -#endif // RecoBTau_JetTagComputer_TagInfoMVACategorySelector_h +#endif // RecoBTau_JetTagComputer_TagInfoMVACategorySelector_h diff --git a/RecoBTau/JetTagComputer/plugins/JetTagProducer.cc b/RecoBTau/JetTagComputer/plugins/JetTagProducer.cc index 2198efeb69e92..dafc797188e0c 100644 --- a/RecoBTau/JetTagComputer/plugins/JetTagProducer.cc +++ b/RecoBTau/JetTagComputer/plugins/JetTagProducer.cc @@ -2,7 +2,7 @@ // // Package: JetTagProducer // Class: JetTagProducer -// +// /**\class JetTagProducer JetTagProducer.cc RecoBTag/JetTagProducer/src/JetTagProducer.cc Description: Uses a JetTagComputer to produce JetTags from TagInfos @@ -16,7 +16,6 @@ // // - // system include files #include #include @@ -48,21 +47,18 @@ using namespace edm; // // constructors and destructor // -JetTagProducer::JetTagProducer(const ParameterSet& iConfig) : - m_jetTagComputer(iConfig.getParameter("jetTagComputer")) -{ - std::vector m_tagInfos = iConfig.getParameter< vector >("tagInfos"); +JetTagProducer::JetTagProducer(const ParameterSet &iConfig) + : m_jetTagComputer(iConfig.getParameter("jetTagComputer")) { + std::vector m_tagInfos = iConfig.getParameter >("tagInfos"); nTagInfos = m_tagInfos.size(); - for(unsigned int i = 0; i < nTagInfos; i++) { - token_tagInfos.push_back( consumes >(m_tagInfos[i]) ); + for (unsigned int i = 0; i < nTagInfos; i++) { + token_tagInfos.push_back(consumes >(m_tagInfos[i])); } produces(); } -JetTagProducer::~JetTagProducer() -{ -} +JetTagProducer::~JetTagProducer() {} // // member functions @@ -71,32 +67,30 @@ JetTagProducer::~JetTagProducer() // map helper - for some reason RefToBase lacks operator < (...) namespace { struct JetRefCompare { - inline bool operator () (const RefToBase &j1, - const RefToBase &j2) const - { return j1.id() < j2.id() || (j1.id() == j2.id() && j1.key() < j2.key()); } + inline bool operator()(const RefToBase &j1, const RefToBase &j2) const { + return j1.id() < j2.id() || (j1.id() == j2.id() && j1.key() < j2.key()); + } }; -} +} // namespace // ------------ method called to produce the data ------------ -void -JetTagProducer::produce(Event& iEvent, const EventSetup& iSetup) -{ +void JetTagProducer::produce(Event &iEvent, const EventSetup &iSetup) { edm::ESHandle computer; - iSetup.get().get( m_jetTagComputer, computer ); + iSetup.get().get(m_jetTagComputer, computer); - if (recordWatcher_.check(iSetup) ) { + if (recordWatcher_.check(iSetup)) { unsigned int nLabels = computer->getInputLabels().size(); - if (nLabels == 0) ++nLabels; + if (nLabels == 0) + ++nLabels; if (nTagInfos != nLabels) { - vector inputLabels(computer->getInputLabels()); // backward compatible case, use default tagInfo if (inputLabels.empty()) inputLabels.push_back("tagInfo"); - std::string message("VInputTag size mismatch - the following taginfo " - "labels are needed:\n"); - for(vector::const_iterator iter = inputLabels.begin(); - iter != inputLabels.end(); ++iter) + std::string message( + "VInputTag size mismatch - the following taginfo " + "labels are needed:\n"); + for (vector::const_iterator iter = inputLabels.begin(); iter != inputLabels.end(); ++iter) message += "\"" + *iter + "\"\n"; throw edm::Exception(errors::Configuration) << message; } @@ -105,20 +99,19 @@ JetTagProducer::produce(Event& iEvent, const EventSetup& iSetup) // now comes the tricky part: // we need to collect all requested TagInfos belonging to the same jet - typedef vector TagInfoPtrs; + typedef vector TagInfoPtrs; typedef RefToBase JetRef; typedef map JetToTagInfoMap; JetToTagInfoMap jetToTagInfos; // retrieve all requested TagInfos - vector< Handle< View > > tagInfoHandles(nTagInfos); - for(unsigned int i = 0; i < nTagInfos; i++) { - Handle< View > &tagInfoHandle = tagInfoHandles[i]; + vector > > tagInfoHandles(nTagInfos); + for (unsigned int i = 0; i < nTagInfos; i++) { + Handle > &tagInfoHandle = tagInfoHandles[i]; iEvent.getByToken(token_tagInfos[i], tagInfoHandle); - for(View::const_iterator iter = tagInfoHandle->begin(); - iter != tagInfoHandle->end(); iter++) { + for (View::const_iterator iter = tagInfoHandle->begin(); iter != tagInfoHandle->end(); iter++) { TagInfoPtrs &tagInfos = jetToTagInfos[iter->jet()]; if (tagInfos.empty()) tagInfos.resize(nTagInfos); @@ -128,7 +121,7 @@ JetTagProducer::produce(Event& iEvent, const EventSetup& iSetup) } // take first tagInfo - Handle< View > &tagInfoHandle = tagInfoHandles[0]; + Handle > &tagInfoHandle = tagInfoHandles[0]; std::unique_ptr jetTagCollection; if (!tagInfoHandle.product()->empty()) { RefToBase jj = tagInfoHandle->begin()->jet(); @@ -137,8 +130,7 @@ JetTagProducer::produce(Event& iEvent, const EventSetup& iSetup) jetTagCollection = std::make_unique(); // now loop over the map and compute all JetTags - for(JetToTagInfoMap::const_iterator iter = jetToTagInfos.begin(); - iter != jetToTagInfos.end(); iter++) { + for (JetToTagInfoMap::const_iterator iter = jetToTagInfos.begin(); iter != jetToTagInfos.end(); iter++) { const TagInfoPtrs &tagInfoPtrs = iter->second; JetTagComputer::TagInfoHelper helper(tagInfoPtrs); @@ -151,18 +143,16 @@ JetTagProducer::produce(Event& iEvent, const EventSetup& iSetup) } // ------------ method fills 'descriptions' with the allowed parameters for the module ------------ -void -JetTagProducer::fillDescriptions(edm::ConfigurationDescriptions & descriptions) { - +void JetTagProducer::fillDescriptions(edm::ConfigurationDescriptions &descriptions) { edm::ParameterSetDescription desc; - desc.add("jetTagComputer","combinedMVAComputer"); + desc.add("jetTagComputer", "combinedMVAComputer"); { std::vector tagInfos; tagInfos.push_back(edm::InputTag("impactParameterTagInfos")); tagInfos.push_back(edm::InputTag("inclusiveSecondaryVertexFinderTagInfos")); tagInfos.push_back(edm::InputTag("softPFMuonsTagInfos")); tagInfos.push_back(edm::InputTag("softPFElectronsTagInfos")); - desc.add >("tagInfos",tagInfos); + desc.add >("tagInfos", tagInfos); } descriptions.addDefault(desc); } diff --git a/RecoBTau/JetTagComputer/plugins/JetTagProducer.h b/RecoBTau/JetTagComputer/plugins/JetTagProducer.h index 1ec4e8fee60ee..abd9b7520ca9b 100644 --- a/RecoBTau/JetTagComputer/plugins/JetTagProducer.h +++ b/RecoBTau/JetTagComputer/plugins/JetTagProducer.h @@ -20,18 +20,18 @@ #include "DataFormats/BTauReco/interface/BaseTagInfo.h" class JetTagProducer : public edm::stream::EDProducer<> { - public: - explicit JetTagProducer(const edm::ParameterSet&); - ~JetTagProducer() override; - static void fillDescriptions(edm::ConfigurationDescriptions & descriptions); +public: + explicit JetTagProducer(const edm::ParameterSet&); + ~JetTagProducer() override; + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); - private: - void produce(edm::Event&, const edm::EventSetup&) override; +private: + void produce(edm::Event&, const edm::EventSetup&) override; - std::string m_jetTagComputer; - std::vector > > token_tagInfos; - unsigned int nTagInfos; - edm::ESWatcher recordWatcher_; + std::string m_jetTagComputer; + std::vector > > token_tagInfos; + unsigned int nTagInfos; + edm::ESWatcher recordWatcher_; }; -#endif // RecoBTag_JetTagComputer_JetTagProducer_h +#endif // RecoBTag_JetTagComputer_JetTagProducer_h diff --git a/RecoBTau/JetTagComputer/src/GenericMVAComputer.cc b/RecoBTau/JetTagComputer/src/GenericMVAComputer.cc index 3ce32004546c4..68ddcee449149 100644 --- a/RecoBTau/JetTagComputer/src/GenericMVAComputer.cc +++ b/RecoBTau/JetTagComputer/src/GenericMVAComputer.cc @@ -11,27 +11,19 @@ using namespace PhysicsTools; // static cache const GenericMVAComputer::TaggingVariableMapping GenericMVAComputer::mapping; -GenericMVAComputer::TaggingVariableMapping::TaggingVariableMapping() -{ - for(unsigned int i = 0; i < btau::lastTaggingVariable; i++) { - const char *name = TaggingVariableTokens[i]; - AtomicId id(name); - - taggingVarToAtomicId.push_back(id); - } +GenericMVAComputer::TaggingVariableMapping::TaggingVariableMapping() { + for (unsigned int i = 0; i < btau::lastTaggingVariable; i++) { + const char *name = TaggingVariableTokens[i]; + AtomicId id(name); + + taggingVarToAtomicId.push_back(id); + } } // explicit instantiation the common case of reco::TaggingVariableList -template -double GenericMVAComputer::eval( - reco::TaggingVariableList::const_iterator, - reco::TaggingVariableList::const_iterator) const; - -template -double GenericMVAComputer::eval( - const reco::TaggingVariableList&) const; +template double GenericMVAComputer::eval( + reco::TaggingVariableList::const_iterator, reco::TaggingVariableList::const_iterator) const; -template -class GenericMVAComputer::TaggingVariableIterator< - reco::TaggingVariableList::const_iterator>; +template double GenericMVAComputer::eval(const reco::TaggingVariableList &) const; +template class GenericMVAComputer::TaggingVariableIterator; diff --git a/RecoBTau/JetTagComputer/src/GenericMVAComputerCache.cc b/RecoBTau/JetTagComputer/src/GenericMVAComputerCache.cc index a0ccc58cb27c5..065268021af2b 100644 --- a/RecoBTau/JetTagComputer/src/GenericMVAComputerCache.cc +++ b/RecoBTau/JetTagComputer/src/GenericMVAComputerCache.cc @@ -9,115 +9,96 @@ using namespace PhysicsTools::Calibration; -inline GenericMVAComputerCache::IndividualComputer::IndividualComputer() -{ -} - -inline GenericMVAComputerCache::IndividualComputer::IndividualComputer( - const IndividualComputer &orig) : - label(orig.label) -{ -} - -inline GenericMVAComputerCache::IndividualComputer::~IndividualComputer() -{ -} - -GenericMVAComputerCache::GenericMVAComputerCache( - const std::vector &labels) : - computers(labels.size()), - cacheId(MVAComputerContainer::CacheId()), - initialized(false), - empty(true), - errorUpdatingLabel() -{ - std::vector::iterator computer = computers.begin(); - for(std::vector::const_iterator iter = labels.begin(); - iter != labels.end(); iter++) { - computer->label = *iter; - computer->cacheId = MVAComputer::CacheId(); - computer++; - } +inline GenericMVAComputerCache::IndividualComputer::IndividualComputer() {} + +inline GenericMVAComputerCache::IndividualComputer::IndividualComputer(const IndividualComputer &orig) + : label(orig.label) {} + +inline GenericMVAComputerCache::IndividualComputer::~IndividualComputer() {} + +GenericMVAComputerCache::GenericMVAComputerCache(const std::vector &labels) + : computers(labels.size()), + cacheId(MVAComputerContainer::CacheId()), + initialized(false), + empty(true), + errorUpdatingLabel() { + std::vector::iterator computer = computers.begin(); + for (std::vector::const_iterator iter = labels.begin(); iter != labels.end(); iter++) { + computer->label = *iter; + computer->cacheId = MVAComputer::CacheId(); + computer++; + } } -GenericMVAComputerCache::~GenericMVAComputerCache() -{ -} +GenericMVAComputerCache::~GenericMVAComputerCache() {} -GenericMVAComputer const* GenericMVAComputerCache::getComputer(int index) const -{ - if(!errorUpdatingLabel.empty()) { +GenericMVAComputer const *GenericMVAComputerCache::getComputer(int index) const { + if (!errorUpdatingLabel.empty()) { throw cms::Exception("MVAComputerCalibration") - << "GenericMVAComputerCache::getComputer Error occurred during update.\n" - << "Calibration record " << errorUpdatingLabel - << " not found in MVAComputerContainer." << std::endl; + << "GenericMVAComputerCache::getComputer Error occurred during update.\n" + << "Calibration record " << errorUpdatingLabel << " not found in MVAComputerContainer." << std::endl; } return index >= 0 ? computers[index].computer.get() : nullptr; } bool GenericMVAComputerCache::isEmpty() const { - if(!errorUpdatingLabel.empty()) { + if (!errorUpdatingLabel.empty()) { throw cms::Exception("MVAComputerCalibration") - << "GenericMVAComputerCache::isEmpty Error occurred during update.\n" - << "Calibration record " << errorUpdatingLabel - << " not found in MVAComputerContainer." << std::endl; + << "GenericMVAComputerCache::isEmpty Error occurred during update.\n" + << "Calibration record " << errorUpdatingLabel << " not found in MVAComputerContainer." << std::endl; } return empty; } -bool GenericMVAComputerCache::update(const MVAComputerContainer *calib) -{ - // check container for changes - if (initialized && !calib->changed(cacheId)) - return false; - - empty = true; - - bool changed = false; - for(std::vector::iterator iter = computers.begin(); - iter != computers.end(); iter++) { - // empty labels means we don't want a computer - if (iter->label.empty()) - continue; - - // Delay throwing if the label cannot be found until getComputer is called - // Sometimes this cache is updated and never used. - if (!calib->contains(iter->label)) { - errorUpdatingLabel = iter->label; - continue; - } - - const MVAComputer *computerCalib = &calib->find(iter->label); - if (!computerCalib) { - iter->computer.reset(); - continue; - } - - // check container content for changes - if (iter->computer.get() && - !computerCalib->changed(iter->cacheId)) { - empty = false; - continue; - } - - // drop old computer - iter->computer.reset(); - - if (!computerCalib) - continue; - - // instantiate new MVAComputer with uptodate calibration - iter->computer = std::unique_ptr( - new GenericMVAComputer(computerCalib)); - - iter->cacheId = computerCalib->getCacheId(); - - changed = true; - empty = false; - } - - cacheId = calib->getCacheId(); - initialized = true; - - return changed; +bool GenericMVAComputerCache::update(const MVAComputerContainer *calib) { + // check container for changes + if (initialized && !calib->changed(cacheId)) + return false; + + empty = true; + + bool changed = false; + for (std::vector::iterator iter = computers.begin(); iter != computers.end(); iter++) { + // empty labels means we don't want a computer + if (iter->label.empty()) + continue; + + // Delay throwing if the label cannot be found until getComputer is called + // Sometimes this cache is updated and never used. + if (!calib->contains(iter->label)) { + errorUpdatingLabel = iter->label; + continue; + } + + const MVAComputer *computerCalib = &calib->find(iter->label); + if (!computerCalib) { + iter->computer.reset(); + continue; + } + + // check container content for changes + if (iter->computer.get() && !computerCalib->changed(iter->cacheId)) { + empty = false; + continue; + } + + // drop old computer + iter->computer.reset(); + + if (!computerCalib) + continue; + + // instantiate new MVAComputer with uptodate calibration + iter->computer = std::unique_ptr(new GenericMVAComputer(computerCalib)); + + iter->cacheId = computerCalib->getCacheId(); + + changed = true; + empty = false; + } + + cacheId = calib->getCacheId(); + initialized = true; + + return changed; } diff --git a/RecoBTau/JetTagComputer/src/GenericMVAJetTagComputer.cc b/RecoBTau/JetTagComputer/src/GenericMVAJetTagComputer.cc index 450fd032ee256..bab3eded08088 100644 --- a/RecoBTau/JetTagComputer/src/GenericMVAJetTagComputer.cc +++ b/RecoBTau/JetTagComputer/src/GenericMVAJetTagComputer.cc @@ -18,84 +18,69 @@ using namespace reco; using namespace PhysicsTools; -static std::vector -getCalibrationLabels(const edm::ParameterSet ¶ms, - std::unique_ptr &selector) -{ - if (params.getParameter("useCategories")) { - selector = std::unique_ptr( - new TagInfoMVACategorySelector(params)); - - return selector->getCategoryLabels(); - } else { - std::string calibrationRecord = - params.getParameter("calibrationRecord"); - - std::vector calibrationLabels; - calibrationLabels.push_back(calibrationRecord); - return calibrationLabels; - } +static std::vector getCalibrationLabels(const edm::ParameterSet ¶ms, + std::unique_ptr &selector) { + if (params.getParameter("useCategories")) { + selector = std::unique_ptr(new TagInfoMVACategorySelector(params)); + + return selector->getCategoryLabels(); + } else { + std::string calibrationRecord = params.getParameter("calibrationRecord"); + + std::vector calibrationLabels; + calibrationLabels.push_back(calibrationRecord); + return calibrationLabels; + } } -GenericMVAJetTagComputer::GenericMVAJetTagComputer( - const edm::ParameterSet ¶ms) : - computerCache_(getCalibrationLabels(params, categorySelector_)), - recordLabel_(params.getParameter("recordLabel")) -{ -} - -GenericMVAJetTagComputer::~GenericMVAJetTagComputer() -{ -} +GenericMVAJetTagComputer::GenericMVAJetTagComputer(const edm::ParameterSet ¶ms) + : computerCache_(getCalibrationLabels(params, categorySelector_)), + recordLabel_(params.getParameter("recordLabel")) {} -void GenericMVAJetTagComputer::initialize(const JetTagComputerRecord & record) { +GenericMVAJetTagComputer::~GenericMVAJetTagComputer() {} - const BTauGenericMVAJetTagComputerRcd& dependentRecord = record.getRecord(); +void GenericMVAJetTagComputer::initialize(const JetTagComputerRecord &record) { + const BTauGenericMVAJetTagComputerRcd &dependentRecord = record.getRecord(); - // retrieve MVAComputer calibration container - edm::ESHandle calibHandle; - dependentRecord.get(recordLabel_, calibHandle); - const Calibration::MVAComputerContainer *calib = calibHandle.product(); + // retrieve MVAComputer calibration container + edm::ESHandle calibHandle; + dependentRecord.get(recordLabel_, calibHandle); + const Calibration::MVAComputerContainer *calib = calibHandle.product(); - // check for updates - computerCache_.update(calib); + // check for updates + computerCache_.update(calib); } -float GenericMVAJetTagComputer::discriminator(const TagInfoHelper &info) const -{ - TaggingVariableList variables = taggingVariables(info); +float GenericMVAJetTagComputer::discriminator(const TagInfoHelper &info) const { + TaggingVariableList variables = taggingVariables(info); - // retrieve index of computer in case categories are used - int index = 0; - if (categorySelector_.get()) { - index = categorySelector_->findCategory(variables); - if (index < 0) - return -10.0; - } + // retrieve index of computer in case categories are used + int index = 0; + if (categorySelector_.get()) { + index = categorySelector_->findCategory(variables); + if (index < 0) + return -10.0; + } - GenericMVAComputer const* computer = computerCache_.getComputer(index); + GenericMVAComputer const *computer = computerCache_.getComputer(index); - if (!computer) - return -10.0; + if (!computer) + return -10.0; - return computer->eval(variables); + return computer->eval(variables); } -TaggingVariableList -GenericMVAJetTagComputer::taggingVariables(const BaseTagInfo &baseTag) const -{ - TaggingVariableList variables = baseTag.taggingVariables(); +TaggingVariableList GenericMVAJetTagComputer::taggingVariables(const BaseTagInfo &baseTag) const { + TaggingVariableList variables = baseTag.taggingVariables(); - // add jet pt and jet eta variables (ordering irrelevant) - edm::RefToBase jet = baseTag.jet(); - variables.push_back(TaggingVariable(btau::jetPt, jet->pt())); - variables.push_back(TaggingVariable(btau::jetEta, jet->eta())); + // add jet pt and jet eta variables (ordering irrelevant) + edm::RefToBase jet = baseTag.jet(); + variables.push_back(TaggingVariable(btau::jetPt, jet->pt())); + variables.push_back(TaggingVariable(btau::jetEta, jet->eta())); - return variables; + return variables; } -TaggingVariableList -GenericMVAJetTagComputer::taggingVariables(const TagInfoHelper &info) const -{ - return taggingVariables(info.getBase(0)); +TaggingVariableList GenericMVAJetTagComputer::taggingVariables(const TagInfoHelper &info) const { + return taggingVariables(info.getBase(0)); } diff --git a/RecoBTau/JetTagComputer/src/JetTagComputer.cc b/RecoBTau/JetTagComputer/src/JetTagComputer.cc index 19db0bb858d9b..c74ab8cd837a5 100644 --- a/RecoBTau/JetTagComputer/src/JetTagComputer.cc +++ b/RecoBTau/JetTagComputer/src/JetTagComputer.cc @@ -8,41 +8,36 @@ #include "RecoBTau/JetTagComputer/interface/JetTagComputer.h" -float JetTagComputer::operator () (const reco::BaseTagInfo& info) const -{ - std::vector helper; - helper.push_back(&info); - return discriminator(TagInfoHelper(helper)); +float JetTagComputer::operator()(const reco::BaseTagInfo &info) const { + std::vector helper; + helper.push_back(&info); + return discriminator(TagInfoHelper(helper)); } -void JetTagComputer::uses(unsigned int id, const std::string &label) -{ - if (m_setupDone) - throw cms::Exception("InvalidState") - << "JetTagComputer::uses called outside of " - "constructor" << std::endl; +void JetTagComputer::uses(unsigned int id, const std::string &label) { + if (m_setupDone) + throw cms::Exception("InvalidState") << "JetTagComputer::uses called outside of " + "constructor" + << std::endl; - if (id >= m_inputLabels.size()) - m_inputLabels.resize(id + 1); + if (id >= m_inputLabels.size()) + m_inputLabels.resize(id + 1); - if (!m_inputLabels[id].empty()) - throw cms::Exception("InvalidIndex") - << "JetTagComputer::uses called with duplicate " - "or invalid index" << std::endl; + if (!m_inputLabels[id].empty()) + throw cms::Exception("InvalidIndex") << "JetTagComputer::uses called with duplicate " + "or invalid index" + << std::endl; - m_inputLabels[id] = label; + m_inputLabels[id] = label; } -float JetTagComputer::discriminator(const reco::BaseTagInfo &info) const -{ - throw cms::Exception("VirtualMethodMissing") - << "No virtual method implementation for " - << "JetTagComputer::discriminator() defined." << std::endl; +float JetTagComputer::discriminator(const reco::BaseTagInfo &info) const { + throw cms::Exception("VirtualMethodMissing") << "No virtual method implementation for " + << "JetTagComputer::discriminator() defined." << std::endl; } -float JetTagComputer::discriminator(const JetTagComputer::TagInfoHelper &info) const -{ - return discriminator(info.getBase(0)); +float JetTagComputer::discriminator(const JetTagComputer::TagInfoHelper &info) const { + return discriminator(info.getBase(0)); } TYPELOOKUP_DATA_REG(JetTagComputer); diff --git a/RecoBTau/JetTagComputer/src/TagInfoMVACategorySelector.cc b/RecoBTau/JetTagComputer/src/TagInfoMVACategorySelector.cc index 48f77e9ccb856..7c222887cd87f 100644 --- a/RecoBTau/JetTagComputer/src/TagInfoMVACategorySelector.cc +++ b/RecoBTau/JetTagComputer/src/TagInfoMVACategorySelector.cc @@ -11,37 +11,27 @@ using namespace reco; -TagInfoMVACategorySelector::TagInfoMVACategorySelector( - const edm::ParameterSet ¶ms) -{ - std::string variableName = - params.getParameter("categoryVariableName"); - - categoryVariable = getTaggingVariableName(variableName); - if (categoryVariable >= btau::lastTaggingVariable) - throw cms::Exception("TagInfoMVACategorySelector") - << "No such tagging variable \"" - << categoryVariable << "\"." << std::endl; - - categoryLabels = params.getParameter >( - "calibrationRecords"); - for(std::vector::iterator iter = categoryLabels.begin(); - iter != categoryLabels.end(); iter++) - if (*iter == " " || *iter == "-" || *iter == "*") - *iter = ""; +TagInfoMVACategorySelector::TagInfoMVACategorySelector(const edm::ParameterSet ¶ms) { + std::string variableName = params.getParameter("categoryVariableName"); + + categoryVariable = getTaggingVariableName(variableName); + if (categoryVariable >= btau::lastTaggingVariable) + throw cms::Exception("TagInfoMVACategorySelector") + << "No such tagging variable \"" << categoryVariable << "\"." << std::endl; + + categoryLabels = params.getParameter >("calibrationRecords"); + for (std::vector::iterator iter = categoryLabels.begin(); iter != categoryLabels.end(); iter++) + if (*iter == " " || *iter == "-" || *iter == "*") + *iter = ""; } -TagInfoMVACategorySelector::~TagInfoMVACategorySelector() -{ -} +TagInfoMVACategorySelector::~TagInfoMVACategorySelector() {} -int TagInfoMVACategorySelector::findCategory( - const TaggingVariableList &taggingVariables) const -{ - int index = (int)taggingVariables.get(categoryVariable, -1); +int TagInfoMVACategorySelector::findCategory(const TaggingVariableList &taggingVariables) const { + int index = (int)taggingVariables.get(categoryVariable, -1); - if (index < 0 || (unsigned int)index >= categoryLabels.size()) - return -1; + if (index < 0 || (unsigned int)index >= categoryLabels.size()) + return -1; - return index; + return index; } diff --git a/RecoJets/JetAlgorithms/interface/CATopJetAlgorithm.h b/RecoJets/JetAlgorithms/interface/CATopJetAlgorithm.h index 42d9f27a2780c..ed553b547ed5a 100644 --- a/RecoJets/JetAlgorithms/interface/CATopJetAlgorithm.h +++ b/RecoJets/JetAlgorithms/interface/CATopJetAlgorithm.h @@ -1,8 +1,6 @@ #ifndef RecoJets_JetAlgorithms_CATopJetAlgorithm_h #define RecoJets_JetAlgorithms_CATopJetAlgorithm_h - - /* ********************************************************* * \class CATopJetAlgorithm * Jet producer to produce top jets using the C-A algorithm to break @@ -36,99 +34,97 @@ #include "RecoJets/JetAlgorithms/interface/CompoundPseudoJet.h" - #include #include #include #include #include -class CATopJetAlgorithm{ - public: +class CATopJetAlgorithm { +public: /** Constructor */ CATopJetAlgorithm(const edm::InputTag& mSrc, - bool verbose, - int algorithm, - int useAdjacency, - double centralEtaCut, - double ptMin, - const std::vector & sumEtBins, - const std::vector & rBins, - const std::vector & ptFracBins, - const std::vector & deltarBins, - const std::vector & nCellBins, - double seedThreshold, - bool useMaxTower, - double sumEtEtaCut, - double etFrac) : - mSrc_ (mSrc ), - verbose_ (verbose ), - algorithm_ (algorithm ), - useAdjacency_ (useAdjacency ), - centralEtaCut_ (centralEtaCut ), - ptMin_ (ptMin ), - sumEtBins_ (sumEtBins ), - rBins_ (rBins ), - ptFracBins_ (ptFracBins ), - deltarBins_ (deltarBins ), - nCellBins_ (nCellBins ), - seedThreshold_ (seedThreshold ), - useMaxTower_ (useMaxTower ), - sumEtEtaCut_ (sumEtEtaCut ), - etFrac_ (etFrac ) - - { } - - /// Find the ProtoJets from the collection of input Candidates. - void run( const std::vector & cell_particles, - std::vector & hardjetsOutput , - boost::shared_ptr & fjClusterSeq - ); - - private: - - edm::InputTag mSrc_; // sumEtBins_; // rBins_; // ptFracBins_; // deltarBins_; // nCellBins_; //& sumEtBins, + const std::vector& rBins, + const std::vector& ptFracBins, + const std::vector& deltarBins, + const std::vector& nCellBins, + double seedThreshold, + bool useMaxTower, + double sumEtEtaCut, + double etFrac) + : mSrc_(mSrc), + verbose_(verbose), + algorithm_(algorithm), + useAdjacency_(useAdjacency), + centralEtaCut_(centralEtaCut), + ptMin_(ptMin), + sumEtBins_(sumEtBins), + rBins_(rBins), + ptFracBins_(ptFracBins), + deltarBins_(deltarBins), + nCellBins_(nCellBins), + seedThreshold_(seedThreshold), + useMaxTower_(useMaxTower), + sumEtEtaCut_(sumEtEtaCut), + etFrac_(etFrac) + + {} + + /// Find the ProtoJets from the collection of input Candidates. + void run(const std::vector& cell_particles, + std::vector& hardjetsOutput, + boost::shared_ptr& fjClusterSeq); + +private: + edm::InputTag mSrc_; // + sumEtBins_; // rBins_; // ptFracBins_; // deltarBins_; // + nCellBins_; // & cell_particles, - const fastjet::ClusterSequence & theClusterSequence, - double nCellMin ) const; - + double seedThreshold_; //& cell_particles, + const fastjet::ClusterSequence& theClusterSequence, + double nCellMin) const; // Attempt to break up one "hard" jet into two "soft" jets - bool decomposeJet(const fastjet::PseudoJet & theJet, - const fastjet::ClusterSequence & theClusterSequence, - const std::vector & cell_particles, - double ptHard, double nCellMin, double deltarcut, - fastjet::PseudoJet & ja, fastjet::PseudoJet & jb, - std::vector & leftovers) const; - + bool decomposeJet(const fastjet::PseudoJet& theJet, + const fastjet::ClusterSequence& theClusterSequence, + const std::vector& cell_particles, + double ptHard, + double nCellMin, + double deltarcut, + fastjet::PseudoJet& ja, + fastjet::PseudoJet& jb, + std::vector& leftovers) const; }; - - #endif diff --git a/RecoJets/JetAlgorithms/interface/CATopJetHelper.h b/RecoJets/JetAlgorithms/interface/CATopJetHelper.h index 1de4ea6c929a2..aae63f6a6872a 100644 --- a/RecoJets/JetAlgorithms/interface/CATopJetHelper.h +++ b/RecoJets/JetAlgorithms/interface/CATopJetHelper.h @@ -1,12 +1,11 @@ #ifndef TopQuarkAnalysis_TopPairBSM_interface_CATopJetHelper_h #define TopQuarkAnalysis_TopPairBSM_interface_CATopJetHelper_h - // \class CATopJetHelper -// +// // \short Create tag info properties for CATopTags that can be computed -// "on the fly". -// +// "on the fly". +// // // \author Salvatore Rappoccio // \version first version on 1-May-2011 @@ -15,19 +14,14 @@ #include "DataFormats/BTauReco/interface/CATopJetTagInfo.h" class CATopJetHelper { - public: +public: + CATopJetHelper(double TopMass, double WMass) : TopMass_(TopMass), WMass_(WMass) {} - CATopJetHelper(double TopMass, double WMass) : - TopMass_(TopMass), WMass_(WMass) - {} - - reco::CATopJetProperties operator()( reco::Jet const & ihardJet ) const; - - protected: - double TopMass_; - double WMass_; + reco::CATopJetProperties operator()(reco::Jet const& ihardJet) const; +protected: + double TopMass_; + double WMass_; }; - #endif diff --git a/RecoJets/JetAlgorithms/interface/CMSBoostedTauSeedingAlgorithm.h b/RecoJets/JetAlgorithms/interface/CMSBoostedTauSeedingAlgorithm.h index 1fa4ddb628468..9f763163715e0 100644 --- a/RecoJets/JetAlgorithms/interface/CMSBoostedTauSeedingAlgorithm.h +++ b/RecoJets/JetAlgorithms/interface/CMSBoostedTauSeedingAlgorithm.h @@ -6,7 +6,7 @@ // Find subjets corresponding to decay products of tau lepton pair // and produce data-formats neccessary to seed tau reconstruction. // -// Questions/Comments? +// Questions/Comments? // for physics : Christian.Veelken@cern.ch // for implementation : Salvatore.Rappoccio@cern.ch // @@ -40,10 +40,9 @@ #include #include -FASTJET_BEGIN_NAMESPACE // defined in fastjet/internal/base.hh - -namespace contrib{ +FASTJET_BEGIN_NAMESPACE // defined in fastjet/internal/base.hh + namespace contrib { class CMSBoostedTauSeedingAlgorithmStructure; //------------------------------------------------------------------------ @@ -51,40 +50,49 @@ namespace contrib{ /// This class implements the CMS boosted tau algorithm /// class CMSBoostedTauSeedingAlgorithm : public Transformer { - public: // constructors - CMSBoostedTauSeedingAlgorithm(double ptMin, double muMin, double muMax, double yMin, double yMax, double dRMin, double dRMax, int maxDepth, int verbosity = 0); + CMSBoostedTauSeedingAlgorithm(double ptMin, + double muMin, + double muMax, + double yMin, + double yMax, + double dRMin, + double dRMax, + int maxDepth, + int verbosity = 0); // destructor - ~CMSBoostedTauSeedingAlgorithm() override{} + ~CMSBoostedTauSeedingAlgorithm() override {} // standard usage std::string description() const override; - PseudoJet result(const PseudoJet & jet) const override; + PseudoJet result(const PseudoJet& jet) const override; // the type of the associated structure typedef CMSBoostedTauSeedingAlgorithmStructure StructureType; protected: - void dumpSubJetStructure(const fastjet::PseudoJet& jet, int depth, int maxDepth, const std::string& depth_and_idx_string) const; + void dumpSubJetStructure(const fastjet::PseudoJet& jet, + int depth, + int maxDepth, + const std::string& depth_and_idx_string) const; std::pair findSubjets(const PseudoJet& jet, int depth, bool& subjetsFound) const; - private: + private: double ptMin_; ///< minimum sub-jet pt double muMin_; ///< the min value of the mass-drop parameter double muMax_; ///< the max value of the mass-drop parameter double yMin_; ///< the min value of the asymmetry parameter - double yMax_; ///< the max value of the asymmetry parameter + double yMax_; ///< the max value of the asymmetry parameter double dRMin_; ///< the min value of the dR parameter double dRMax_; ///< the max value of the dR parameter int maxDepth_; ///< the max depth for descending into clustering sequence - int verbosity_; ///< flag to enable/disable debug output + int verbosity_; ///< flag to enable/disable debug output }; - //------------------------------------------------------------------------ /// @ingroup tools_taggers /// \class CMSBoostedTauSeedingAlgorithmStructure @@ -98,10 +106,8 @@ namespace contrib{ /// ctor with initialisation /// \param pieces the pieces of the created jet /// \param rec the recombiner from the underlying cluster sequence - CMSBoostedTauSeedingAlgorithmStructure(const PseudoJet& result_jet, const JetDefinition::Recombiner* rec = nullptr) - : CompositeJetStructure(result_jet.pieces(), rec), - _mu(0.0), _y(0.0), _dR(0.0), _pt(0.0) - {} + CMSBoostedTauSeedingAlgorithmStructure(const PseudoJet& result_jet, const JetDefinition::Recombiner* rec = nullptr) + : CompositeJetStructure(result_jet.pieces(), rec), _mu(0.0), _y(0.0), _dR(0.0), _pt(0.0) {} /// returns the mass-drop ratio, pieces[0].m()/jet.m() inline double mu() const { return _mu; } @@ -120,16 +126,15 @@ namespace contrib{ //const PseudoJet& original() const { return _original_jet; } protected: - double _mu; ///< the value of the mass-drop parameter - double _y; ///< the value of the asymmetry parameter - double _dR; ///< the value of the dR parameter - double _pt; ///< the value of the pt parameter + double _mu; ///< the value of the mass-drop parameter + double _y; ///< the value of the asymmetry parameter + double _dR; ///< the value of the dR parameter + double _pt; ///< the value of the pt parameter // allow the tagger to set these friend class CMSBoostedTauSeedingAlgorithm; }; - -} // namespace contrib +} // namespace contrib FASTJET_END_NAMESPACE diff --git a/RecoJets/JetAlgorithms/interface/CMSInsideOutAlgorithm.h b/RecoJets/JetAlgorithms/interface/CMSInsideOutAlgorithm.h index 5565df0f25f69..5d429c6a33b9b 100644 --- a/RecoJets/JetAlgorithms/interface/CMSInsideOutAlgorithm.h +++ b/RecoJets/JetAlgorithms/interface/CMSInsideOutAlgorithm.h @@ -9,7 +9,6 @@ * \some code adapted from RecoJets/JetAlgorithms/CMSIterativeConeAlgorithm ************************************************************/ - #include #include @@ -21,50 +20,47 @@ #include "fastjet/PseudoJet.hh" - - - class CMSInsideOutAlgorithm { - public: - typedef reco::Particle::LorentzVector LorentzVector; - typedef std::list::iterator inputListIter; - // binary predicate to sort a std::list of std::list iterators by increasing deltaR - // from a eta-phi point specified in the ctor - class ListIteratorLesserByDeltaR { - public: ListIteratorLesserByDeltaR(const double& eta, const double& phi):seedEta_(eta),seedPhi_(phi){} - bool operator()(const inputListIter& A, const inputListIter& B) const { - double deltaR2A = reco::deltaR2( (*A).eta(), seedEta_, (*A).phi(), seedPhi_ ); - double deltaR2B = reco::deltaR2( (*B).eta(), seedEta_, (*B).phi(), seedPhi_ ); - return - fabs(deltaR2A - deltaR2B) > std::numeric_limits::epsilon() ? deltaR2A < deltaR2B : - reco::deltaPhi((*A).phi(), seedPhi_) < reco::deltaPhi((*B).phi(), seedPhi_); - }; - private: - double seedEta_, seedPhi_; - }; +public: + typedef reco::Particle::LorentzVector LorentzVector; + typedef std::list::iterator inputListIter; + // binary predicate to sort a std::list of std::list iterators by increasing deltaR + // from a eta-phi point specified in the ctor + class ListIteratorLesserByDeltaR { + public: + ListIteratorLesserByDeltaR(const double& eta, const double& phi) : seedEta_(eta), seedPhi_(phi) {} + bool operator()(const inputListIter& A, const inputListIter& B) const { + double deltaR2A = reco::deltaR2((*A).eta(), seedEta_, (*A).phi(), seedPhi_); + double deltaR2B = reco::deltaR2((*B).eta(), seedEta_, (*B).phi(), seedPhi_); + return fabs(deltaR2A - deltaR2B) > std::numeric_limits::epsilon() + ? deltaR2A < deltaR2B + : reco::deltaPhi((*A).phi(), seedPhi_) < reco::deltaPhi((*B).phi(), seedPhi_); + }; - /** Constructor + private: + double seedEta_, seedPhi_; + }; + + /** Constructor \param seed defines the minimum ET in GeV of an object that can seed the jet \param growthparameter sets the growth parameter X, i.e. [dR < X/Et_jet] \param min/max size define the min/max size of jet in deltaR. Min is included for resolution effects \param seedCharge can be the following values; -1 [don't care], 0 neutral only, 1 [tracks only] */ - CMSInsideOutAlgorithm(double seedObjectPt, double growthParameter, double maxSize, double minSize): - seedThresholdPt_(seedObjectPt), - growthParameterSquared_(growthParameter*growthParameter), - maxSizeSquared_(maxSize*maxSize), - minSizeSquared_(minSize*minSize){}; - - + CMSInsideOutAlgorithm(double seedObjectPt, double growthParameter, double maxSize, double minSize) + : seedThresholdPt_(seedObjectPt), + growthParameterSquared_(growthParameter * growthParameter), + maxSizeSquared_(maxSize * maxSize), + minSizeSquared_(minSize * minSize){}; - /// Build from input candidate collection - void run(const std::vector& fInput, std::vector & fOutput); + /// Build from input candidate collection + void run(const std::vector& fInput, std::vector& fOutput); - private: - double seedThresholdPt_; - double growthParameterSquared_; - double maxSizeSquared_; - double minSizeSquared_; +private: + double seedThresholdPt_; + double growthParameterSquared_; + double maxSizeSquared_; + double minSizeSquared_; }; #endif diff --git a/RecoJets/JetAlgorithms/interface/CMSTopTagger.h b/RecoJets/JetAlgorithms/interface/CMSTopTagger.h index 62137adf62774..66e890792b055 100644 --- a/RecoJets/JetAlgorithms/interface/CMSTopTagger.h +++ b/RecoJets/JetAlgorithms/interface/CMSTopTagger.h @@ -50,7 +50,6 @@ FASTJET_BEGIN_NAMESPACE /// the JHTopTaggerStructure. class CMSTopTaggerStructure; - class CMSTopTagger : public TopTaggerBase { public: /// The parameters are the following: @@ -63,7 +62,7 @@ class CMSTopTagger : public TopTaggerBase { /// The default values of these parameters are taken from /// CMS-PAS-JME-10-013. For the older tagger described in CMS-PAS-JME-09-001, /// use delta_p=0.05, delta_r=0.0, A=0.0 - CMSTopTagger(double delta_p=0.05, double delta_r=0.4, double A=0.0004); + CMSTopTagger(double delta_p = 0.05, double delta_r = 0.4, double A = 0.0004); /// returns a textual description of the tagger std::string description() const override; @@ -72,15 +71,14 @@ class CMSTopTagger : public TopTaggerBase { /// returns the tagged PseudoJet if successful, or a PseudoJet==0 otherwise /// (standard access is through operator()). /// \param jet the PseudoJet to tag - PseudoJet result(const PseudoJet & jet) const override; + PseudoJet result(const PseudoJet& jet) const override; // the type of the associated structure typedef CMSTopTaggerStructure StructureType; - + protected: /// runs the Johns Hopkins decomposition procedure - std::vector _split_once(const PseudoJet & jet_to_split, - const PseudoJet & reference_jet) const; + std::vector _split_once(const PseudoJet& jet_to_split, const PseudoJet& reference_jet) const; /// find the indices corresponding to the minimum mass pairing in subjets /// only considers the hardest 3 @@ -94,52 +92,48 @@ class CMSTopTagger : public TopTaggerBase { /// be a friend. class CMSTopTaggerStructure : public JHTopTaggerStructure { public: - CMSTopTaggerStructure(const std::vector& pieces, - const JetDefinition::Recombiner *recombiner = nullptr) - : JHTopTaggerStructure(pieces, recombiner) {} + CMSTopTaggerStructure(const std::vector& pieces, const JetDefinition::Recombiner* recombiner = nullptr) + : JHTopTaggerStructure(pieces, recombiner) {} protected: friend class CMSTopTagger; }; - - - //---------------------------------------------------------------------- inline CMSTopTagger::CMSTopTagger(double delta_p, double delta_r, double A) - : _delta_p(delta_p), _delta_r(delta_r), _A(A) {} + : _delta_p(delta_p), _delta_r(delta_r), _A(A) {} //------------------------------------------------------------------------ // description of the tagger -inline std::string CMSTopTagger::description() const{ +inline std::string CMSTopTagger::description() const { std::ostringstream oss; - oss << "CMSTopTagger with delta_p=" << _delta_p << ", delta_r=" << _delta_r - << ", and A=" << _A; + oss << "CMSTopTagger with delta_p=" << _delta_p << ", delta_r=" << _delta_r << ", and A=" << _A; oss << description_of_selectors(); return oss.str(); } - //------------------------------------------------------------------------ // returns the tagged PseudoJet if successful, 0 otherwise // - jet the PseudoJet to tag -inline PseudoJet CMSTopTagger::result(const PseudoJet & jet) const{ +inline PseudoJet CMSTopTagger::result(const PseudoJet& jet) const { // make sure that there is a "regular" cluster sequence associated // with the jet. Note that we also check it is valid (to avoid a // more criptic error later on) - if (!jet.has_valid_cluster_sequence()){ + if (!jet.has_valid_cluster_sequence()) { throw Error("CMSTopTagger can only be applied on jets having an associated (and valid) ClusterSequence"); } // warn if the jet has not been clustered with a Cambridge/Aachen // algorithm if (jet.validated_cs()->jet_def().jet_algorithm() != cambridge_algorithm) - _warnings_nonca.warn("CMSTopTagger should only be applied on jets from a Cambridge/Aachen clustering; use it with other algorithms at your own risk."); - + _warnings_nonca.warn( + "CMSTopTagger should only be applied on jets from a Cambridge/Aachen clustering; use it with other algorithms " + "at your own risk."); // do the first splitting std::vector split0 = _split_once(jet, jet); - if (split0.empty()) return PseudoJet(); + if (split0.empty()) + return PseudoJet(); // now try a second splitting on each of the resulting objects std::vector subjets; @@ -154,10 +148,11 @@ inline PseudoJet CMSTopTagger::result(const PseudoJet & jet) const{ } // make sure things make sense - if (subjets.size() < 3) return PseudoJet(); + if (subjets.size() < 3) + return PseudoJet(); // now find the pair of subjets with minimum mass (only taking hardest three) - int ii=-1, jj=-1; + int ii = -1, jj = -1; _find_min_mass(subjets, ii, jj); // order the subjets in the following order: @@ -165,54 +160,59 @@ inline PseudoJet CMSTopTagger::result(const PseudoJet & jet) const{ // - softest of the W subjets // - hardest of the remaining subjets // - softest of the remaining subjets (if any) - if (ii>0) std::swap(subjets[ii], subjets[0]); - if (jj>1) std::swap(subjets[jj], subjets[1]); - if (subjets[0].perp2() < subjets[1].perp2()) std::swap(subjets[0], subjets[1]); - if ((subjets.size()>3) && (subjets[2].perp2() < subjets[3].perp2())) + if (ii > 0) + std::swap(subjets[ii], subjets[0]); + if (jj > 1) + std::swap(subjets[jj], subjets[1]); + if (subjets[0].perp2() < subjets[1].perp2()) + std::swap(subjets[0], subjets[1]); + if ((subjets.size() > 3) && (subjets[2].perp2() < subjets[3].perp2())) std::swap(subjets[2], subjets[3]); - + // create the result and its structure - const JetDefinition::Recombiner *rec - = jet.associated_cluster_sequence()->jet_def().recombiner(); + const JetDefinition::Recombiner* rec = jet.associated_cluster_sequence()->jet_def().recombiner(); PseudoJet W = join(subjets[0], subjets[1], *rec); PseudoJet non_W; - if (subjets.size()>3) { + if (subjets.size() > 3) { non_W = join(subjets[2], subjets[3], *rec); } else { non_W = join(subjets[2], *rec); } PseudoJet result = join(W, non_W, *rec); - CMSTopTaggerStructure *s = (CMSTopTaggerStructure*) result.structure_non_const_ptr(); + CMSTopTaggerStructure* s = (CMSTopTaggerStructure*)result.structure_non_const_ptr(); s->_cos_theta_w = _cos_theta_W(result); // Note that we could perhaps ensure this cut before constructing // the result structure but this has the advantage that the top // 4-vector is already available and does not have to de re-computed - if (!_top_selector.pass(result) || ! _W_selector.pass(W)) { + if (!_top_selector.pass(result) || !_W_selector.pass(W)) { result *= 0.0; } - result = join(subjets); //Added by J. Pilot to combine the (up to 4) subjets identified in the decomposition instead of just the W and non_W components + result = join( + subjets); //Added by J. Pilot to combine the (up to 4) subjets identified in the decomposition instead of just the W and non_W components return result; } - // runs the Johns Hopkins decomposition procedure -inline std::vector CMSTopTagger::_split_once(const PseudoJet & jet_to_split, - const PseudoJet & reference_jet) const{ +inline std::vector CMSTopTagger::_split_once(const PseudoJet& jet_to_split, + const PseudoJet& reference_jet) const { PseudoJet this_jet = jet_to_split; PseudoJet p1, p2; std::vector result; while (this_jet.has_parents(p1, p2)) { - if (p2.perp2() > p1.perp2()) std::swap(p1,p2); // order with hardness - if (p1.perp() < _delta_p * reference_jet.perp()) break; // harder is too soft wrt original jet + if (p2.perp2() > p1.perp2()) + std::swap(p1, p2); // order with hardness + if (p1.perp() < _delta_p * reference_jet.perp()) + break; // harder is too soft wrt original jet double DR = p1.delta_R(p2); - if (DR < _delta_r - _A * this_jet.perp()) break; // distance is too small + if (DR < _delta_r - _A * this_jet.perp()) + break; // distance is too small if (p2.perp() < _delta_p * reference_jet.perp()) { - this_jet = p1; // softer is too soft wrt original, so ignore it - continue; + this_jet = p1; // softer is too soft wrt original, so ignore it + continue; } //result.push_back(this_jet); result.push_back(p1); @@ -222,15 +222,15 @@ inline std::vector CMSTopTagger::_split_once(const PseudoJet & jet_to return result; } - // find the indices corresponding to the minimum mass pairing in subjets -inline void CMSTopTagger::_find_min_mass(const std::vector& subjets, int& i, int& j) const{ +inline void CMSTopTagger::_find_min_mass(const std::vector& subjets, int& i, int& j) const { assert(subjets.size() > 1 && subjets.size() < 5); - + // if four subjets found, only consider three hardest - unsigned softest = 5; // invalid value + unsigned softest = 5; // invalid value if (subjets.size() == 4) { - double min_pt = std::numeric_limits::max();; + double min_pt = std::numeric_limits::max(); + ; for (unsigned ii = 0; ii < subjets.size(); ++ii) { if (subjets[ii].perp() < min_pt) { min_pt = subjets[ii].perp(); @@ -238,14 +238,16 @@ inline void CMSTopTagger::_find_min_mass(const std::vector& subjets, } } } - + double min_mass = std::numeric_limits::max(); - for (unsigned ii = 0; ii+1 < subjets.size(); ++ii) { // don't do size()-1: (unsigned(0)-1 != -1) !! - if (ii == softest) continue; + for (unsigned ii = 0; ii + 1 < subjets.size(); ++ii) { // don't do size()-1: (unsigned(0)-1 != -1) !! + if (ii == softest) + continue; for (unsigned jj = ii + 1; jj < subjets.size(); ++jj) { - if (jj == softest) continue; - if ((subjets[ii]+subjets[jj]).m() < min_mass) { - min_mass = (subjets[ii]+subjets[jj]).m(); + if (jj == softest) + continue; + if ((subjets[ii] + subjets[jj]).m() < min_mass) { + min_mass = (subjets[ii] + subjets[jj]).m(); i = ii; j = jj; } @@ -253,7 +255,6 @@ inline void CMSTopTagger::_find_min_mass(const std::vector& subjets, } } - FASTJET_END_NAMESPACE -#endif // __CMSTOPTAGGER_HH__ +#endif // __CMSTOPTAGGER_HH__ diff --git a/RecoJets/JetAlgorithms/interface/CompoundPseudoJet.h b/RecoJets/JetAlgorithms/interface/CompoundPseudoJet.h index 3e898a97e975b..d2fc8fd519455 100644 --- a/RecoJets/JetAlgorithms/interface/CompoundPseudoJet.h +++ b/RecoJets/JetAlgorithms/interface/CompoundPseudoJet.h @@ -1,8 +1,6 @@ #ifndef RecoJets_JetAlgorithms_CompoundPseudoJet_h #define RecoJets_JetAlgorithms_CompoundPseudoJet_h - - // -*- C++ -*- //// -*- C++ -*- // @@ -25,9 +23,6 @@ // //------------------------------------------------------------------------------------- - - - #include #include @@ -35,76 +30,56 @@ #include class CompoundPseudoSubJet { - public: +public: CompoundPseudoSubJet() {} - CompoundPseudoSubJet(fastjet::PseudoJet const & subjet, - std::vector const & constituents ) : - subjet_(subjet), - subjetArea_(0.0), - constituents_(constituents.size() ) - { - copy( constituents.begin(), constituents.end(), constituents_.begin() ); + CompoundPseudoSubJet(fastjet::PseudoJet const& subjet, std::vector const& constituents) + : subjet_(subjet), subjetArea_(0.0), constituents_(constituents.size()) { + copy(constituents.begin(), constituents.end(), constituents_.begin()); } - CompoundPseudoSubJet(fastjet::PseudoJet const & subjet, - double subjetArea, - std::vector const & constituents ) : - subjet_(subjet), - subjetArea_(subjetArea), - constituents_(constituents.size() ) - { - copy( constituents.begin(), constituents.end(), constituents_.begin() ); + CompoundPseudoSubJet(fastjet::PseudoJet const& subjet, double subjetArea, std::vector const& constituents) + : subjet_(subjet), subjetArea_(subjetArea), constituents_(constituents.size()) { + copy(constituents.begin(), constituents.end(), constituents_.begin()); } - - ~CompoundPseudoSubJet() {} - - fastjet::PseudoJet const & subjet() const { return subjet_; } - double subjetArea() const { return subjetArea_; } - std::vector const & constituents() const { return constituents_; } - + + ~CompoundPseudoSubJet() {} + + fastjet::PseudoJet const& subjet() const { return subjet_; } + double subjetArea() const { return subjetArea_; } + std::vector const& constituents() const { return constituents_; } + protected: - fastjet::PseudoJet subjet_; - double subjetArea_; - std::vector constituents_; + fastjet::PseudoJet subjet_; + double subjetArea_; + std::vector constituents_; }; class CompoundPseudoJet { - public: CompoundPseudoJet() {} - CompoundPseudoJet(fastjet::PseudoJet const & hardJet, - std::vector const & subjets ) : - hardJet_(hardJet), - hardJetArea_(0.0), - subjets_(subjets.size()) - { - copy( subjets.begin(), subjets.end(), subjets_.begin() ); + CompoundPseudoJet(fastjet::PseudoJet const& hardJet, std::vector const& subjets) + : hardJet_(hardJet), hardJetArea_(0.0), subjets_(subjets.size()) { + copy(subjets.begin(), subjets.end(), subjets_.begin()); } - CompoundPseudoJet(fastjet::PseudoJet const & hardJet, - double hardJetArea, - std::vector const & subjets ) : - hardJet_(hardJet), - hardJetArea_(hardJetArea), - subjets_(subjets.size()) - { - copy( subjets.begin(), subjets.end(), subjets_.begin() ); + CompoundPseudoJet(fastjet::PseudoJet const& hardJet, + double hardJetArea, + std::vector const& subjets) + : hardJet_(hardJet), hardJetArea_(hardJetArea), subjets_(subjets.size()) { + copy(subjets.begin(), subjets.end(), subjets_.begin()); } - + ~CompoundPseudoJet() {} - - fastjet::PseudoJet const & hardJet() const {return hardJet_;} - double hardJetArea() const {return hardJetArea_;} - std::vectorconst& subjets() const {return subjets_; } - - + + fastjet::PseudoJet const& hardJet() const { return hardJet_; } + double hardJetArea() const { return hardJetArea_; } + std::vector const& subjets() const { return subjets_; } + protected: - fastjet::PseudoJet hardJet_; - double hardJetArea_; + fastjet::PseudoJet hardJet_; + double hardJetArea_; std::vector subjets_; }; - - -inline bool greaterByEtPseudoJet( fastjet::PseudoJet const & j1, fastjet::PseudoJet const & j2 ) { +inline bool greaterByEtPseudoJet(fastjet::PseudoJet const& j1, fastjet::PseudoJet const& j2) { return j1.perp() > j2.perp(); } diff --git a/RecoJets/JetAlgorithms/interface/FastPrunePlugin.hh b/RecoJets/JetAlgorithms/interface/FastPrunePlugin.hh index 0c3ddb7eb756f..60cb631de2ad5 100644 --- a/RecoJets/JetAlgorithms/interface/FastPrunePlugin.hh +++ b/RecoJets/JetAlgorithms/interface/FastPrunePlugin.hh @@ -16,7 +16,7 @@ // original jet with certain branches removed. // 3) This creates a pruned jet. For each of these, the helper function // output_mergings takes the cluster sequence from the pruned jet and -// feeds it into the input ClusterSequence with the +// feeds it into the input ClusterSequence with the // plugin_record_{ij,iB}_recombination functions. This leaves the // ClusterSequence holding pruned versions of all the original jets. // 4) Pruned away branches are marked in the history as entries that are not @@ -48,158 +48,147 @@ #include -FASTJET_BEGIN_NAMESPACE // defined in fastjet/internal/base.hh +FASTJET_BEGIN_NAMESPACE // defined in fastjet/internal/base.hh - -class FastPrunePlugin : public JetDefinition::Plugin { + class FastPrunePlugin : public JetDefinition::Plugin { public: - - class CutSetter; - - /// Constructors for the FastPrunePlugin, whose arguments have the - /// following meaning: - /// - /// - find_definition, which is a JetDefinition object, specifies which - /// jet algorithm to run to find jets. - /// - /// - prune_definition is the algorithm used when pruning the found jet - /// (typically the same as find_algorithm). Also a JetDefinition. - /// The PrunedRecombiner will be used in this definition. - /// - /// - zcut and Rcut_factor are parameters to the pruning procedure. - /// Jet alg. prune_algorithm is run as normal, but with infinite R - /// (actually R = pi/2, since FastJet asserts that R <= pi/2), and - /// recombinations with DeltaR > Rcut and z < zcut are vetoed, and the - /// softer PseudoJet is discarded. (It will appear in the history as a - /// PJ that never merged again -- it is not merged with the beam! - /// inclusive_jets(ptCut) should be used to access the pruned jets. - /// Rcut is chosen for each jet according to - /// Rcut = Rcut_factor * 2*m/pT, - /// where m and pT correspond to the four-momentum of the found jet. - /// - /// - recomb specifies the user's own Recombiner class, useful for - /// implementing, say, flavor recombination. The internal PrunedRecombiner - /// class only checks if pruning should be done. If this is not passed, - /// the Recombiner from prune_definition is used instead. - /// - /// Note that the PrunedRecombiner is set up in the constructor, but specific - /// values of Rcut are selected jet-by-jet in run_clustering(). - /// - FastPrunePlugin (const JetDefinition & find_definition, - const JetDefinition & prune_definition, - const double & zcut = 0.1, - const double & Rcut_factor = 0.5); - - FastPrunePlugin (const JetDefinition & find_definition, - const JetDefinition & prune_definition, - const JetDefinition::Recombiner* recomb, - const double & zcut = 0.1, - const double & Rcut_factor = 0.5); - - /// Two new constructors that allow you to pass your own CutSetter. - /// This lets you define zcut and Rcut on a jet-by-jet basis. - /// See below for CutSetter definition. - FastPrunePlugin (const JetDefinition & find_definition, - const JetDefinition & prune_definition, - CutSetter* const cut_setter); - - FastPrunePlugin (const JetDefinition & find_definition, - const JetDefinition & prune_definition, - CutSetter* const cut_setter, - const JetDefinition::Recombiner* recomb); - - - // Get the set of pruned away PseudoJets (valid in pruned ClusterSequence) - // Each vector corresponds to one of the unpruned jets, in pT order - virtual std::vector > pruned_subjets() const {return _pruned_subjets;} - - // The things that are required by base class. - virtual std::string description () const; - virtual void run_clustering(ClusterSequence &) const; - - // Sets minimum pT for unpruned jets (default is 20 GeV) - // (Just to save time by not pruning jets we don't care about) - virtual void set_unpruned_minpT(double pt) {_minpT = pt;} - - // Access to parameters. - virtual double R() const {return _find_definition.R();} - virtual double zcut() const {return _cut_setter->zcut;} - virtual double Rcut() const {return _cut_setter->Rcut;} - // only meaningful for DefaultCutSetter: - virtual double Rcut_factor() const { - if (DefaultCutSetter *cs = dynamic_cast(_cut_setter)) - return cs->Rcut_factor; - else return -1.0; - } - - // ***** DEPRECATED **** -- use FastPruneTool instead; this will be removed - // in a future release! - // Access to unpruned cluster sequence that gets made along the way - // This should only be used after run_clustering() has been called, - // i.e., after the plugin has been used to find jets. I've added - // this for speed, so you don't have to duplicate the effort of - // finding unpruned jets. - virtual ClusterSequence *get_unpruned_sequence() const {return _unpruned_seq;} - - virtual ~FastPrunePlugin() {delete _unpruned_seq; delete _pruned_recombiner; - delete _cut_setter;} + class CutSetter; + + /// Constructors for the FastPrunePlugin, whose arguments have the + /// following meaning: + /// + /// - find_definition, which is a JetDefinition object, specifies which + /// jet algorithm to run to find jets. + /// + /// - prune_definition is the algorithm used when pruning the found jet + /// (typically the same as find_algorithm). Also a JetDefinition. + /// The PrunedRecombiner will be used in this definition. + /// + /// - zcut and Rcut_factor are parameters to the pruning procedure. + /// Jet alg. prune_algorithm is run as normal, but with infinite R + /// (actually R = pi/2, since FastJet asserts that R <= pi/2), and + /// recombinations with DeltaR > Rcut and z < zcut are vetoed, and the + /// softer PseudoJet is discarded. (It will appear in the history as a + /// PJ that never merged again -- it is not merged with the beam! + /// inclusive_jets(ptCut) should be used to access the pruned jets. + /// Rcut is chosen for each jet according to + /// Rcut = Rcut_factor * 2*m/pT, + /// where m and pT correspond to the four-momentum of the found jet. + /// + /// - recomb specifies the user's own Recombiner class, useful for + /// implementing, say, flavor recombination. The internal PrunedRecombiner + /// class only checks if pruning should be done. If this is not passed, + /// the Recombiner from prune_definition is used instead. + /// + /// Note that the PrunedRecombiner is set up in the constructor, but specific + /// values of Rcut are selected jet-by-jet in run_clustering(). + /// + FastPrunePlugin(const JetDefinition &find_definition, + const JetDefinition &prune_definition, + const double &zcut = 0.1, + const double &Rcut_factor = 0.5); + + FastPrunePlugin(const JetDefinition &find_definition, + const JetDefinition &prune_definition, + const JetDefinition::Recombiner *recomb, + const double &zcut = 0.1, + const double &Rcut_factor = 0.5); + + /// Two new constructors that allow you to pass your own CutSetter. + /// This lets you define zcut and Rcut on a jet-by-jet basis. + /// See below for CutSetter definition. + FastPrunePlugin(const JetDefinition &find_definition, + const JetDefinition &prune_definition, + CutSetter *const cut_setter); + + FastPrunePlugin(const JetDefinition &find_definition, + const JetDefinition &prune_definition, + CutSetter *const cut_setter, + const JetDefinition::Recombiner *recomb); + + // Get the set of pruned away PseudoJets (valid in pruned ClusterSequence) + // Each vector corresponds to one of the unpruned jets, in pT order + virtual std::vector > pruned_subjets() const { return _pruned_subjets; } + + // The things that are required by base class. + std::string description() const override; + void run_clustering(ClusterSequence &) const override; + + // Sets minimum pT for unpruned jets (default is 20 GeV) + // (Just to save time by not pruning jets we don't care about) + virtual void set_unpruned_minpT(double pt) { _minpT = pt; } + + // Access to parameters. + double R() const override { return _find_definition.R(); } + virtual double zcut() const { return _cut_setter->zcut; } + virtual double Rcut() const { return _cut_setter->Rcut; } + // only meaningful for DefaultCutSetter: + virtual double Rcut_factor() const { + if (DefaultCutSetter *cs = dynamic_cast(_cut_setter)) + return cs->Rcut_factor; + else + return -1.0; + } + + // ***** DEPRECATED **** -- use FastPruneTool instead; this will be removed + // in a future release! + // Access to unpruned cluster sequence that gets made along the way + // This should only be used after run_clustering() has been called, + // i.e., after the plugin has been used to find jets. I've added + // this for speed, so you don't have to duplicate the effort of + // finding unpruned jets. + virtual ClusterSequence *get_unpruned_sequence() const { return _unpruned_seq; } + + ~FastPrunePlugin() override { + delete _unpruned_seq; + delete _pruned_recombiner; + delete _cut_setter; + } protected: + JetDefinition _find_definition; + mutable JetDefinition _prune_definition; // mutable: we change its Recombiner* + double _minpT; // minimum pT for unpruned jets - JetDefinition _find_definition; - mutable JetDefinition _prune_definition; // mutable: we change its Recombiner* - double _minpT; // minimum pT for unpruned jets - - mutable std::vector > _pruned_subjets; - mutable ClusterSequence* _unpruned_seq; - - mutable PrunedRecombiner* _pruned_recombiner; - - // Takes the merging structure of "in_seq" and feeds this into - // "out_seq" using _plugin_record_{ij,iB}_recombination() - void _output_mergings(ClusterSequence & in_seq, - std::vector & pruned_pseudojets, - ClusterSequence & out_seq) const; - - // this class stores info on how to dynamically set zcut and Rcut - // const because we won't change it - CutSetter* _cut_setter; - -public: - - /// A helper class to define cuts, possibly on a jet-by-jet basis - class CutSetter { - public: - CutSetter(const double & z = 0.1, const double & R = 0.5) - : zcut(z), Rcut(R) {} - double zcut, Rcut; - virtual void SetCuts(const PseudoJet &jet, - const ClusterSequence &clust_seq) = 0; - virtual ~CutSetter() {} - }; - - /// Default CutSetter implementation: never changes zcut, - /// and Rcut = Rcut_factor * 2m/pT for a given jet - class DefaultCutSetter : public CutSetter { - public: - DefaultCutSetter(const double & z = 0.1, const double &Rcut_fact = 0.5) - : CutSetter(z), Rcut_factor(Rcut_fact) {} - double Rcut_factor; - virtual void SetCuts(const PseudoJet &jet, - const ClusterSequence &clust_seq) { - PseudoJet p1, p2; - if (! clust_seq.has_parents(jet, p1, p2)) - Rcut = 0.0; - else - Rcut = Rcut_factor*2.0*jet.m()/jet.perp(); - } - }; + mutable std::vector > _pruned_subjets; + mutable ClusterSequence *_unpruned_seq; -}; + mutable PrunedRecombiner *_pruned_recombiner; + // Takes the merging structure of "in_seq" and feeds this into + // "out_seq" using _plugin_record_{ij,iB}_recombination() + void _output_mergings(ClusterSequence &in_seq, std::vector &pruned_pseudojets, ClusterSequence &out_seq) const; -FASTJET_END_NAMESPACE // defined in fastjet/internal/base.hh + // this class stores info on how to dynamically set zcut and Rcut + // const because we won't change it + CutSetter *_cut_setter; +public: + /// A helper class to define cuts, possibly on a jet-by-jet basis + class CutSetter { + public: + CutSetter(const double &z = 0.1, const double &R = 0.5) : zcut(z), Rcut(R) {} + double zcut, Rcut; + virtual void SetCuts(const PseudoJet &jet, const ClusterSequence &clust_seq) = 0; + virtual ~CutSetter() {} + }; + + /// Default CutSetter implementation: never changes zcut, + /// and Rcut = Rcut_factor * 2m/pT for a given jet + class DefaultCutSetter : public CutSetter { + public: + DefaultCutSetter(const double &z = 0.1, const double &Rcut_fact = 0.5) : CutSetter(z), Rcut_factor(Rcut_fact) {} + double Rcut_factor; + void SetCuts(const PseudoJet &jet, const ClusterSequence &clust_seq) override { + PseudoJet p1, p2; + if (!clust_seq.has_parents(jet, p1, p2)) + Rcut = 0.0; + else + Rcut = Rcut_factor * 2.0 * jet.m() / jet.perp(); + } + }; +}; +FASTJET_END_NAMESPACE // defined in fastjet/internal/base.hh #endif // __FASTPRUNEPLUGIN_HH__ diff --git a/RecoJets/JetAlgorithms/interface/FixedGridEnergyDensity.h b/RecoJets/JetAlgorithms/interface/FixedGridEnergyDensity.h index 6fd992bf3ff7e..1e506a8955b50 100644 --- a/RecoJets/JetAlgorithms/interface/FixedGridEnergyDensity.h +++ b/RecoJets/JetAlgorithms/interface/FixedGridEnergyDensity.h @@ -4,17 +4,15 @@ #include "DataFormats/ParticleFlowCandidate/interface/PFCandidateFwd.h" class FixedGridEnergyDensity { - - public: - FixedGridEnergyDensity(const reco::PFCandidateCollection *input){pfCandidates=input;} +public: + FixedGridEnergyDensity(const reco::PFCandidateCollection* input) { pfCandidates = input; } ~FixedGridEnergyDensity(){}; - enum EtaRegion {Central,Forward,All}; - float fixedGridRho(EtaRegion etaRegion=Central); - float fixedGridRho(std::vector& etabins,std::vector& phibins); - - private: - const reco::PFCandidateCollection *pfCandidates; + enum EtaRegion { Central, Forward, All }; + float fixedGridRho(EtaRegion etaRegion = Central); + float fixedGridRho(std::vector& etabins, std::vector& phibins); +private: + const reco::PFCandidateCollection* pfCandidates; }; #endif diff --git a/RecoJets/JetAlgorithms/interface/HEPTopTaggerV2.h b/RecoJets/JetAlgorithms/interface/HEPTopTaggerV2.h index 08a30eba4bc0b..a51fe292eb411 100644 --- a/RecoJets/JetAlgorithms/interface/HEPTopTaggerV2.h +++ b/RecoJets/JetAlgorithms/interface/HEPTopTaggerV2.h @@ -19,331 +19,388 @@ // Do not change next line, it's needed by the sed-code that makes the tagger CMSSW-compatible. namespace external { -using namespace std; -using namespace fastjet; - - enum Mode {EARLY_MASSRATIO_SORT_MASS, - LATE_MASSRATIO_SORT_MASS, - EARLY_MASSRATIO_SORT_MODDJADE, - LATE_MASSRATIO_SORT_MODDJADE, - TWO_STEP_FILTER}; - - -class HEPTopTaggerV2_fixed_R { -public: - typedef fastjet::ClusterSequence ClusterSequence; - typedef fastjet::JetAlgorithm JetAlgorithm; - typedef fastjet::JetDefinition JetDefinition; - typedef fastjet::PseudoJet PseudoJet; - - HEPTopTaggerV2_fixed_R(); - - HEPTopTaggerV2_fixed_R(fastjet::PseudoJet jet); - - HEPTopTaggerV2_fixed_R(fastjet::PseudoJet jet, - double mtmass, double mwmass); - - //run tagger - void run(); - - //settings - void do_qjets(bool qjets) {_do_qjets = qjets;} - - void set_mass_drop_threshold(double x) {_mass_drop_threshold = x;} - void set_max_subjet_mass(double x) {_max_subjet_mass = x;} - - void set_filtering_n(unsigned nfilt) {_nfilt = nfilt;} - void set_filtering_R(double Rfilt) {_Rfilt = Rfilt;} - void set_filtering_minpt_subjet(double x) {_minpt_subjet = x;} - void set_filtering_jetalgorithm(JetAlgorithm jet_algorithm) {_jet_algorithm_filter = jet_algorithm;} - - void set_reclustering_jetalgorithm(JetAlgorithm jet_algorithm) {_jet_algorithm_recluster = jet_algorithm;} - - void set_mode(enum Mode mode) {_mode = mode;} - void set_mt(double x) {_mtmass = x;} - void set_mw(double x) {_mwmass = x;} - void set_top_mass_range(double xmin, double xmax) {_mtmin = xmin; _mtmax = xmax;} - void set_fw(double fw) {_rmin = (1.-fw)*_mwmass/_mtmass; _rmax=(1.+fw)*_mwmass/_mtmass;} - void set_mass_ratio_range(double rmin, double rmax) {_rmin = rmin; _rmax = rmax;} - void set_mass_ratio_cut(double m23cut, double m13cutmin,double m13cutmax) {_m23cut = m23cut; _m13cutmin = m13cutmin; _m13cutmax = m13cutmax;} - void set_top_minpt(double x) {_minpt_tag = x;} - - void set_pruning_zcut(double zcut) {_zcut = zcut;} - void set_pruning_rcut_factor(double rcut_factor) {_rcut_factor = rcut_factor;} - - void set_debug(bool debug) {_debug = debug;} - void set_qjets(double q_zcut, double q_dcut_fctr, double q_exp_min, double q_exp_max, double q_rigidity, double q_truncation_fctr) { - _q_zcut = q_zcut; _q_dcut_fctr = q_dcut_fctr; _q_exp_min = q_exp_min; _q_exp_max = q_exp_max; _q_rigidity = q_rigidity; _q_truncation_fctr = q_truncation_fctr; - } - void set_qjets_rng(CLHEP::HepRandomEngine* engine){ _rnEngine = engine;} - - //get information - bool is_maybe_top() const {return _is_maybe_top;} - bool is_masscut_passed() const {return _is_masscut_passed;} - bool is_minptcut_passed() const {return _is_ptmincut_passed;} - bool is_tagged() const {return (_is_masscut_passed && _is_ptmincut_passed);} - - double delta_top() const {return _delta_top;} - double djsum() const {return _djsum;} - double pruned_mass() const {return _pruned_mass;} - double unfiltered_mass() const {return _unfiltered_mass;} - - double f_rec(); - const PseudoJet & t() const {return _top_candidate;} - const PseudoJet & b() const {return _top_subjets[0];} - const PseudoJet & W() const {return _W;} - const PseudoJet & W1() const {return _top_subjets[1];} - const PseudoJet & W2() const {return _top_subjets[2];} - const std::vector & top_subjets() const {return _top_subjets;} - const PseudoJet & j1() const {return _top_subs[0];} - const PseudoJet & j2() const {return _top_subs[1];} - const PseudoJet & j3() const {return _top_subs[2];} - const std::vector & top_hadrons() const {return _top_hadrons;} - const std::vector & hardparts() const {return _top_parts;} - const PseudoJet & fat_initial() {return _fat;} - - void get_setting() const; - void get_info() const; - - double nsub(fastjet::PseudoJet jet, int order, fastjet::contrib::Njettiness::AxesMode axes = fastjet::contrib::Njettiness::kt_axes, double beta = 1., double R0 = 1.); - double q_weight() {return _qweight;} - -private: - bool _do_qjets; - - PseudoJet _jet; - PseudoJet _initial_jet; - - double _mass_drop_threshold; - double _max_subjet_mass; - - Mode _mode; - double _mtmass, _mwmass; - double _mtmin, _mtmax; - double _rmin, _rmax; - double _m23cut, _m13cutmin, _m13cutmax; - double _minpt_tag; - - unsigned _nfilt; - double _Rfilt; - JetAlgorithm _jet_algorithm_filter; - double _minpt_subjet; - - JetAlgorithm _jet_algorithm_recluster; - - double _zcut; - double _rcut_factor; - - double _q_zcut, _q_dcut_fctr, _q_exp_min, _q_exp_max, _q_rigidity, _q_truncation_fctr; - JetDefinition _qjet_def; - - PseudoJet _fat; - - CLHEP::HepRandomEngine* _rnEngine; - - bool _debug; - - bool _is_masscut_passed; - bool _is_ptmincut_passed; - bool _is_maybe_top; - - double _delta_top; - double _djsum; - - double _pruned_mass; - double _unfiltered_mass; - - double _fw; - unsigned _parts_size; - - PseudoJet _top_candidate; - PseudoJet _W; - std::vector _top_subs; - std::vector _top_subjets; - std::vector _top_hadrons; - std::vector _top_parts; - - bool _first_time; - double _qweight; - - //internal functions - void FindHardSubst(const PseudoJet& jet, std::vector& t_parts); - std::vector Filtering(const std::vector & top_constits, const JetDefinition & filtering_def); - void store_topsubjets(const std::vector& top_subs); - bool check_mass_criteria(const std::vector & top_subs) const; - double perp(const PseudoJet & vec, const fastjet::PseudoJet & ref); - double djademod (const fastjet::PseudoJet & subjet_i, const fastjet::PseudoJet & subjet_j, const fastjet::PseudoJet & ref); - - void print_banner(); - -}; - -class HEPTopTaggerV2 { -public: - HEPTopTaggerV2(); - - HEPTopTaggerV2(const fastjet::PseudoJet & jet); - - - HEPTopTaggerV2(const fastjet::PseudoJet & jet, - double mtmass, double mwmass - ); - - ~HEPTopTaggerV2(); - - //run tagger - void run(); - - //get information - bool is_maybe_top() const {return _HEPTopTaggerV2_opt.is_maybe_top();} - bool is_masscut_passed() const {return _HEPTopTaggerV2_opt.is_masscut_passed();} - bool is_minptcut_passed() const {return _HEPTopTaggerV2_opt.is_minptcut_passed();} - bool is_tagged() const {return _HEPTopTaggerV2_opt.is_tagged();} - - double delta_top() const {return _HEPTopTaggerV2_opt.delta_top();} - double djsum() const {return _HEPTopTaggerV2_opt.djsum();} - double pruned_mass() const {return _HEPTopTaggerV2_opt.pruned_mass();} - double unfiltered_mass() const {return _HEPTopTaggerV2_opt.unfiltered_mass();} - - double f_rec() {return _HEPTopTaggerV2_opt.f_rec();} - const PseudoJet & t() const {return _HEPTopTaggerV2_opt.t();} - const PseudoJet & b() const {return _HEPTopTaggerV2_opt.b();} - const PseudoJet & W() const {return _HEPTopTaggerV2_opt.W();} - const PseudoJet & W1() const {return _HEPTopTaggerV2_opt.W1();} - const PseudoJet & W2() const {return _HEPTopTaggerV2_opt.W2();} - const std::vector & top_subjets() const {return _HEPTopTaggerV2_opt.top_subjets();} - const PseudoJet & j1() const {return _HEPTopTaggerV2_opt.j1();} - const PseudoJet & j2() const {return _HEPTopTaggerV2_opt.j2();} - const PseudoJet & j3() const {return _HEPTopTaggerV2_opt.j3();} - const std::vector & top_hadrons() const {return _HEPTopTaggerV2_opt.top_hadrons();} - const std::vector & hardparts() const {return _HEPTopTaggerV2_opt.hardparts();} - const PseudoJet & fat_initial() {return _fat;} - const PseudoJet & fat_Ropt() {return _HEPTopTaggerV2_opt.fat_initial();} - //HEPTopTaggerV2_fixed_R cand_Ropt(){return _HEPTopTaggerV2[_Ropt];} - HEPTopTaggerV2_fixed_R HEPTopTaggerV2agger(int i) {return _HEPTopTaggerV2[i];} - - double Ropt() const {return _Ropt/10.;} - double Ropt_calc() const {return _R_opt_calc;} - double pt_for_Ropt_calc() const {return _pt_for_R_opt_calc;} - - int optimalR_type(); - double nsub_unfiltered(int order, fastjet::contrib::Njettiness::AxesMode axes = fastjet::contrib::Njettiness::kt_axes, double beta = 1., double R0 = 1.); - double nsub_filtered(int order, fastjet::contrib::Njettiness::AxesMode axes = fastjet::contrib::Njettiness::kt_axes, double beta = 1., double R0 = 1.); - - void get_setting() const {return _HEPTopTaggerV2_opt.get_setting();}; - void get_info() const {return _HEPTopTaggerV2_opt.get_info();}; - - double q_weight() {return _qweight;} - - //settings - void do_optimalR(bool optimalR) {_do_optimalR = optimalR;} - - void set_mass_drop_threshold(double x) {_mass_drop_threshold = x;} - void set_max_subjet_mass(double x) {_max_subjet_mass = x;} - - void set_filtering_n(unsigned nfilt) {_nfilt = nfilt;} - void set_filtering_R(double Rfilt) {_Rfilt = Rfilt;} - void set_filtering_minpt_subjet(double x) {_minpt_subjet = x;} - void set_filtering_jetalgorithm(JetAlgorithm jet_algorithm) {_jet_algorithm_filter = jet_algorithm;} - - void set_reclustering_jetalgorithm(JetAlgorithm jet_algorithm) {_jet_algorithm_recluster = jet_algorithm;} - - void set_mode(enum Mode mode) {_mode = mode;} - void set_mt(double x) {_mtmass = x;} - void set_mw(double x) {_mwmass = x;} - void set_top_mass_range(double xmin, double xmax) {_mtmin = xmin; _mtmax = xmax;} - void set_fw(double fw) {_rmin = (1.-fw)*_mwmass/_mtmass; _rmax=(1.+fw)*_mwmass/_mtmass;} - void set_mass_ratio_range(double rmin, double rmax) {_rmin = rmin; _rmax = rmax;} - void set_mass_ratio_cut(double m23cut, double m13cutmin,double m13cutmax) {_m23cut = m23cut; _m13cutmin = m13cutmin; _m13cutmax = m13cutmax;} - void set_top_minpt(double x) {_minpt_tag = x;} - - void set_optimalR_max(double x) {_max_fatjet_R = x;} - void set_optimalR_min(double x) {_min_fatjet_R = x;} - void set_optimalR_step(double x) {_step_R = x;} - void set_optimalR_threshold(double x) {_optimalR_threshold = x;} - - void set_filtering_optimalR_calc_R(double x) {_R_filt_optimalR_calc = x;} - void set_filtering_optimalR_calc_n(unsigned x) {_N_filt_optimalR_calc = x;} - void set_optimalR_calc_fun(double (*f)(double)) {_r_min_exp_function = f;} - - void set_optimalR_type_top_mass_range(double x, double y) {_optimalR_mmin = x; _optimalR_mmax = y;} - void set_optimalR_type_fw(double x) {_optimalR_fw = x;} - void set_optimalR_type_max_diff(double x) {_R_opt_diff = x;} - - void set_optimalR_reject_minimum(bool x) {_R_opt_reject_min = x;} - - void set_filtering_optimalR_pass_R(double x) {_R_filt_optimalR_pass = x;} - void set_filtering_optimalR_pass_n(unsigned x) {_N_filt_optimalR_pass = x;} - void set_filtering_optimalR_fail_R(double x) {_R_filt_optimalR_fail = x;} - void set_filtering_optimalR_fail_n(unsigned x) {_N_filt_optimalR_fail = x;} - - void set_pruning_zcut(double zcut) {_zcut = zcut;} - void set_pruning_rcut_factor(double rcut_factor) {_rcut_factor = rcut_factor;} - - void set_debug(bool debug) {_debug = debug;} - void do_qjets(bool qjets) {_do_qjets = qjets;} - void set_qjets(double q_zcut, double q_dcut_fctr, double q_exp_min, double q_exp_max, double q_rigidity, double q_truncation_fctr) { - _q_zcut = q_zcut; _q_dcut_fctr = q_dcut_fctr; _q_exp_min = q_exp_min; _q_exp_max = q_exp_max; _q_rigidity = q_rigidity; _q_truncation_fctr = q_truncation_fctr; - } - void set_qjets_rng(CLHEP::HepRandomEngine* engine){ _rnEngine = engine;} - - -private: - bool _do_optimalR, _do_qjets; - - PseudoJet _jet; - PseudoJet _initial_jet; - - double _mass_drop_threshold; - double _max_subjet_mass; - - Mode _mode; - double _mtmass, _mwmass; - double _mtmin, _mtmax; - double _rmin, _rmax; - double _m23cut, _m13cutmin, _m13cutmax; - double _minpt_tag; - - unsigned _nfilt; - double _Rfilt; - fastjet::JetAlgorithm _jet_algorithm_filter; - double _minpt_subjet; - - fastjet::JetAlgorithm _jet_algorithm_recluster; - - double _zcut; - double _rcut_factor; - - double _max_fatjet_R, _min_fatjet_R, _step_R, _optimalR_threshold; - - double _R_filt_optimalR_calc, _N_filt_optimalR_calc; - double (*_r_min_exp_function)(double); - - double _optimalR_mmin, _optimalR_mmax, _optimalR_fw, _R_opt_calc, _pt_for_R_opt_calc, _R_opt_diff; - bool _R_opt_reject_min; - double _R_filt_optimalR_pass, _N_filt_optimalR_pass, _R_filt_optimalR_fail, _N_filt_optimalR_fail; - - double _q_zcut, _q_dcut_fctr, _q_exp_min, _q_exp_max, _q_rigidity, _q_truncation_fctr; - JetDefinition _qjet_def; - - PseudoJet _fat, _filt_fat; - map _n_small_fatjets; - map _HEPTopTaggerV2; - HEPTopTaggerV2_fixed_R _HEPTopTaggerV2_opt; - - int _Ropt; - - CLHEP::HepRandomEngine* _rnEngine; - - bool _debug; - double _qweight; - - void UnclusterFatjets(const vector & big_fatjets, vector & small_fatjets, const ClusterSequence & cs, const double small_radius); - -}; -//-------------------------------------------------------------------- -// Do not change next line, it's needed by the sed-code that makes the tagger CMSSW-compatible. -}; - -#endif // __HEPTOPTAGGERV2_HH__ - + using namespace std; + using namespace fastjet; + + enum Mode { + EARLY_MASSRATIO_SORT_MASS, + LATE_MASSRATIO_SORT_MASS, + EARLY_MASSRATIO_SORT_MODDJADE, + LATE_MASSRATIO_SORT_MODDJADE, + TWO_STEP_FILTER + }; + + class HEPTopTaggerV2_fixed_R { + public: + typedef fastjet::ClusterSequence ClusterSequence; + typedef fastjet::JetAlgorithm JetAlgorithm; + typedef fastjet::JetDefinition JetDefinition; + typedef fastjet::PseudoJet PseudoJet; + + HEPTopTaggerV2_fixed_R(); + + HEPTopTaggerV2_fixed_R(fastjet::PseudoJet jet); + + HEPTopTaggerV2_fixed_R(fastjet::PseudoJet jet, double mtmass, double mwmass); + + //run tagger + void run(); + + //settings + void do_qjets(bool qjets) { _do_qjets = qjets; } + + void set_mass_drop_threshold(double x) { _mass_drop_threshold = x; } + void set_max_subjet_mass(double x) { _max_subjet_mass = x; } + + void set_filtering_n(unsigned nfilt) { _nfilt = nfilt; } + void set_filtering_R(double Rfilt) { _Rfilt = Rfilt; } + void set_filtering_minpt_subjet(double x) { _minpt_subjet = x; } + void set_filtering_jetalgorithm(JetAlgorithm jet_algorithm) { _jet_algorithm_filter = jet_algorithm; } + + void set_reclustering_jetalgorithm(JetAlgorithm jet_algorithm) { _jet_algorithm_recluster = jet_algorithm; } + + void set_mode(enum Mode mode) { _mode = mode; } + void set_mt(double x) { _mtmass = x; } + void set_mw(double x) { _mwmass = x; } + void set_top_mass_range(double xmin, double xmax) { + _mtmin = xmin; + _mtmax = xmax; + } + void set_fw(double fw) { + _rmin = (1. - fw) * _mwmass / _mtmass; + _rmax = (1. + fw) * _mwmass / _mtmass; + } + void set_mass_ratio_range(double rmin, double rmax) { + _rmin = rmin; + _rmax = rmax; + } + void set_mass_ratio_cut(double m23cut, double m13cutmin, double m13cutmax) { + _m23cut = m23cut; + _m13cutmin = m13cutmin; + _m13cutmax = m13cutmax; + } + void set_top_minpt(double x) { _minpt_tag = x; } + + void set_pruning_zcut(double zcut) { _zcut = zcut; } + void set_pruning_rcut_factor(double rcut_factor) { _rcut_factor = rcut_factor; } + + void set_debug(bool debug) { _debug = debug; } + void set_qjets(double q_zcut, + double q_dcut_fctr, + double q_exp_min, + double q_exp_max, + double q_rigidity, + double q_truncation_fctr) { + _q_zcut = q_zcut; + _q_dcut_fctr = q_dcut_fctr; + _q_exp_min = q_exp_min; + _q_exp_max = q_exp_max; + _q_rigidity = q_rigidity; + _q_truncation_fctr = q_truncation_fctr; + } + void set_qjets_rng(CLHEP::HepRandomEngine* engine) { _rnEngine = engine; } + + //get information + bool is_maybe_top() const { return _is_maybe_top; } + bool is_masscut_passed() const { return _is_masscut_passed; } + bool is_minptcut_passed() const { return _is_ptmincut_passed; } + bool is_tagged() const { return (_is_masscut_passed && _is_ptmincut_passed); } + + double delta_top() const { return _delta_top; } + double djsum() const { return _djsum; } + double pruned_mass() const { return _pruned_mass; } + double unfiltered_mass() const { return _unfiltered_mass; } + + double f_rec(); + const PseudoJet& t() const { return _top_candidate; } + const PseudoJet& b() const { return _top_subjets[0]; } + const PseudoJet& W() const { return _W; } + const PseudoJet& W1() const { return _top_subjets[1]; } + const PseudoJet& W2() const { return _top_subjets[2]; } + const std::vector& top_subjets() const { return _top_subjets; } + const PseudoJet& j1() const { return _top_subs[0]; } + const PseudoJet& j2() const { return _top_subs[1]; } + const PseudoJet& j3() const { return _top_subs[2]; } + const std::vector& top_hadrons() const { return _top_hadrons; } + const std::vector& hardparts() const { return _top_parts; } + const PseudoJet& fat_initial() { return _fat; } + + void get_setting() const; + void get_info() const; + + double nsub(fastjet::PseudoJet jet, + int order, + fastjet::contrib::Njettiness::AxesMode axes = fastjet::contrib::Njettiness::kt_axes, + double beta = 1., + double R0 = 1.); + double q_weight() { return _qweight; } + + private: + bool _do_qjets; + + PseudoJet _jet; + PseudoJet _initial_jet; + + double _mass_drop_threshold; + double _max_subjet_mass; + + Mode _mode; + double _mtmass, _mwmass; + double _mtmin, _mtmax; + double _rmin, _rmax; + double _m23cut, _m13cutmin, _m13cutmax; + double _minpt_tag; + + unsigned _nfilt; + double _Rfilt; + JetAlgorithm _jet_algorithm_filter; + double _minpt_subjet; + + JetAlgorithm _jet_algorithm_recluster; + + double _zcut; + double _rcut_factor; + + double _q_zcut, _q_dcut_fctr, _q_exp_min, _q_exp_max, _q_rigidity, _q_truncation_fctr; + JetDefinition _qjet_def; + + PseudoJet _fat; + + CLHEP::HepRandomEngine* _rnEngine; + + bool _debug; + + bool _is_masscut_passed; + bool _is_ptmincut_passed; + bool _is_maybe_top; + + double _delta_top; + double _djsum; + + double _pruned_mass; + double _unfiltered_mass; + + double _fw; + unsigned _parts_size; + + PseudoJet _top_candidate; + PseudoJet _W; + std::vector _top_subs; + std::vector _top_subjets; + std::vector _top_hadrons; + std::vector _top_parts; + + bool _first_time; + double _qweight; + + //internal functions + void FindHardSubst(const PseudoJet& jet, std::vector& t_parts); + std::vector Filtering(const std::vector& top_constits, const JetDefinition& filtering_def); + void store_topsubjets(const std::vector& top_subs); + bool check_mass_criteria(const std::vector& top_subs) const; + double perp(const PseudoJet& vec, const fastjet::PseudoJet& ref); + double djademod(const fastjet::PseudoJet& subjet_i, + const fastjet::PseudoJet& subjet_j, + const fastjet::PseudoJet& ref); + + void print_banner(); + }; + + class HEPTopTaggerV2 { + public: + HEPTopTaggerV2(); + + HEPTopTaggerV2(const fastjet::PseudoJet& jet); + + HEPTopTaggerV2(const fastjet::PseudoJet& jet, double mtmass, double mwmass); + + ~HEPTopTaggerV2(); + + //run tagger + void run(); + + //get information + bool is_maybe_top() const { return _HEPTopTaggerV2_opt.is_maybe_top(); } + bool is_masscut_passed() const { return _HEPTopTaggerV2_opt.is_masscut_passed(); } + bool is_minptcut_passed() const { return _HEPTopTaggerV2_opt.is_minptcut_passed(); } + bool is_tagged() const { return _HEPTopTaggerV2_opt.is_tagged(); } + + double delta_top() const { return _HEPTopTaggerV2_opt.delta_top(); } + double djsum() const { return _HEPTopTaggerV2_opt.djsum(); } + double pruned_mass() const { return _HEPTopTaggerV2_opt.pruned_mass(); } + double unfiltered_mass() const { return _HEPTopTaggerV2_opt.unfiltered_mass(); } + + double f_rec() { return _HEPTopTaggerV2_opt.f_rec(); } + const PseudoJet& t() const { return _HEPTopTaggerV2_opt.t(); } + const PseudoJet& b() const { return _HEPTopTaggerV2_opt.b(); } + const PseudoJet& W() const { return _HEPTopTaggerV2_opt.W(); } + const PseudoJet& W1() const { return _HEPTopTaggerV2_opt.W1(); } + const PseudoJet& W2() const { return _HEPTopTaggerV2_opt.W2(); } + const std::vector& top_subjets() const { return _HEPTopTaggerV2_opt.top_subjets(); } + const PseudoJet& j1() const { return _HEPTopTaggerV2_opt.j1(); } + const PseudoJet& j2() const { return _HEPTopTaggerV2_opt.j2(); } + const PseudoJet& j3() const { return _HEPTopTaggerV2_opt.j3(); } + const std::vector& top_hadrons() const { return _HEPTopTaggerV2_opt.top_hadrons(); } + const std::vector& hardparts() const { return _HEPTopTaggerV2_opt.hardparts(); } + const PseudoJet& fat_initial() { return _fat; } + const PseudoJet& fat_Ropt() { return _HEPTopTaggerV2_opt.fat_initial(); } + //HEPTopTaggerV2_fixed_R cand_Ropt(){return _HEPTopTaggerV2[_Ropt];} + HEPTopTaggerV2_fixed_R HEPTopTaggerV2agger(int i) { return _HEPTopTaggerV2[i]; } + + double Ropt() const { return _Ropt / 10.; } + double Ropt_calc() const { return _R_opt_calc; } + double pt_for_Ropt_calc() const { return _pt_for_R_opt_calc; } + + int optimalR_type(); + double nsub_unfiltered(int order, + fastjet::contrib::Njettiness::AxesMode axes = fastjet::contrib::Njettiness::kt_axes, + double beta = 1., + double R0 = 1.); + double nsub_filtered(int order, + fastjet::contrib::Njettiness::AxesMode axes = fastjet::contrib::Njettiness::kt_axes, + double beta = 1., + double R0 = 1.); + + void get_setting() const { return _HEPTopTaggerV2_opt.get_setting(); }; + void get_info() const { return _HEPTopTaggerV2_opt.get_info(); }; + + double q_weight() { return _qweight; } + + //settings + void do_optimalR(bool optimalR) { _do_optimalR = optimalR; } + + void set_mass_drop_threshold(double x) { _mass_drop_threshold = x; } + void set_max_subjet_mass(double x) { _max_subjet_mass = x; } + + void set_filtering_n(unsigned nfilt) { _nfilt = nfilt; } + void set_filtering_R(double Rfilt) { _Rfilt = Rfilt; } + void set_filtering_minpt_subjet(double x) { _minpt_subjet = x; } + void set_filtering_jetalgorithm(JetAlgorithm jet_algorithm) { _jet_algorithm_filter = jet_algorithm; } + + void set_reclustering_jetalgorithm(JetAlgorithm jet_algorithm) { _jet_algorithm_recluster = jet_algorithm; } + + void set_mode(enum Mode mode) { _mode = mode; } + void set_mt(double x) { _mtmass = x; } + void set_mw(double x) { _mwmass = x; } + void set_top_mass_range(double xmin, double xmax) { + _mtmin = xmin; + _mtmax = xmax; + } + void set_fw(double fw) { + _rmin = (1. - fw) * _mwmass / _mtmass; + _rmax = (1. + fw) * _mwmass / _mtmass; + } + void set_mass_ratio_range(double rmin, double rmax) { + _rmin = rmin; + _rmax = rmax; + } + void set_mass_ratio_cut(double m23cut, double m13cutmin, double m13cutmax) { + _m23cut = m23cut; + _m13cutmin = m13cutmin; + _m13cutmax = m13cutmax; + } + void set_top_minpt(double x) { _minpt_tag = x; } + + void set_optimalR_max(double x) { _max_fatjet_R = x; } + void set_optimalR_min(double x) { _min_fatjet_R = x; } + void set_optimalR_step(double x) { _step_R = x; } + void set_optimalR_threshold(double x) { _optimalR_threshold = x; } + + void set_filtering_optimalR_calc_R(double x) { _R_filt_optimalR_calc = x; } + void set_filtering_optimalR_calc_n(unsigned x) { _N_filt_optimalR_calc = x; } + void set_optimalR_calc_fun(double (*f)(double)) { _r_min_exp_function = f; } + + void set_optimalR_type_top_mass_range(double x, double y) { + _optimalR_mmin = x; + _optimalR_mmax = y; + } + void set_optimalR_type_fw(double x) { _optimalR_fw = x; } + void set_optimalR_type_max_diff(double x) { _R_opt_diff = x; } + + void set_optimalR_reject_minimum(bool x) { _R_opt_reject_min = x; } + + void set_filtering_optimalR_pass_R(double x) { _R_filt_optimalR_pass = x; } + void set_filtering_optimalR_pass_n(unsigned x) { _N_filt_optimalR_pass = x; } + void set_filtering_optimalR_fail_R(double x) { _R_filt_optimalR_fail = x; } + void set_filtering_optimalR_fail_n(unsigned x) { _N_filt_optimalR_fail = x; } + + void set_pruning_zcut(double zcut) { _zcut = zcut; } + void set_pruning_rcut_factor(double rcut_factor) { _rcut_factor = rcut_factor; } + + void set_debug(bool debug) { _debug = debug; } + void do_qjets(bool qjets) { _do_qjets = qjets; } + void set_qjets(double q_zcut, + double q_dcut_fctr, + double q_exp_min, + double q_exp_max, + double q_rigidity, + double q_truncation_fctr) { + _q_zcut = q_zcut; + _q_dcut_fctr = q_dcut_fctr; + _q_exp_min = q_exp_min; + _q_exp_max = q_exp_max; + _q_rigidity = q_rigidity; + _q_truncation_fctr = q_truncation_fctr; + } + void set_qjets_rng(CLHEP::HepRandomEngine* engine) { _rnEngine = engine; } + + private: + bool _do_optimalR, _do_qjets; + + PseudoJet _jet; + PseudoJet _initial_jet; + + double _mass_drop_threshold; + double _max_subjet_mass; + + Mode _mode; + double _mtmass, _mwmass; + double _mtmin, _mtmax; + double _rmin, _rmax; + double _m23cut, _m13cutmin, _m13cutmax; + double _minpt_tag; + + unsigned _nfilt; + double _Rfilt; + fastjet::JetAlgorithm _jet_algorithm_filter; + double _minpt_subjet; + + fastjet::JetAlgorithm _jet_algorithm_recluster; + + double _zcut; + double _rcut_factor; + + double _max_fatjet_R, _min_fatjet_R, _step_R, _optimalR_threshold; + + double _R_filt_optimalR_calc, _N_filt_optimalR_calc; + double (*_r_min_exp_function)(double); + + double _optimalR_mmin, _optimalR_mmax, _optimalR_fw, _R_opt_calc, _pt_for_R_opt_calc, _R_opt_diff; + bool _R_opt_reject_min; + double _R_filt_optimalR_pass, _N_filt_optimalR_pass, _R_filt_optimalR_fail, _N_filt_optimalR_fail; + + double _q_zcut, _q_dcut_fctr, _q_exp_min, _q_exp_max, _q_rigidity, _q_truncation_fctr; + JetDefinition _qjet_def; + + PseudoJet _fat, _filt_fat; + map _n_small_fatjets; + map _HEPTopTaggerV2; + HEPTopTaggerV2_fixed_R _HEPTopTaggerV2_opt; + + int _Ropt; + + CLHEP::HepRandomEngine* _rnEngine; + + bool _debug; + double _qweight; + + void UnclusterFatjets(const vector& big_fatjets, + vector& small_fatjets, + const ClusterSequence& cs, + const double small_radius); + }; + //-------------------------------------------------------------------- + // Do not change next line, it's needed by the sed-code that makes the tagger CMSSW-compatible. +}; // namespace external + +#endif // __HEPTOPTAGGERV2_HH__ diff --git a/RecoJets/JetAlgorithms/interface/HEPTopTaggerWrapperV2.h b/RecoJets/JetAlgorithms/interface/HEPTopTaggerWrapperV2.h index 72f257efa70e6..49b7f157cbfca 100644 --- a/RecoJets/JetAlgorithms/interface/HEPTopTaggerWrapperV2.h +++ b/RecoJets/JetAlgorithms/interface/HEPTopTaggerWrapperV2.h @@ -32,7 +32,7 @@ FASTJET_BEGIN_NAMESPACE /// Tilman Plehn, Gavin Salam, Michael Spannowsky, and Michihisa Takeuchi. The /// HEP top tagger was described in Phys. Rev. Lett. 104 (2010) 111801 /// [arXiv:0910.5472] and JHEP 1010 (2010) 078 [arXiv:1006.2833]. -/// +/// /// /// This code is based on JHTopTagger.{hh,cc}, part of the FastJet package, /// written by Matteo Cacciari, Gavin P. Salam and Gregory Soyez, and released @@ -45,42 +45,41 @@ FASTJET_BEGIN_NAMESPACE class HEPTopTaggerV2Structure; - class HEPTopTaggerV2 : public TopTaggerBase { public: - HEPTopTaggerV2(bool DoOptimalR, - bool DoQjets, - double minSubjetPt, - double minCandPt, - double subjetMass, - double muCut, - double filtR, - int filtN, - int mode, - double minCandMass, - double maxCandMass, - double massRatioWidth, - double minM23Cut, - double minM13Cut, - double maxM13Cut, - bool optRrejectMin) : DoOptimalR_(DoOptimalR), - DoQjets_(DoQjets), - minSubjetPt_(minSubjetPt), - minCandPt_(minCandPt), - subjetMass_(subjetMass), - muCut_(muCut), - filtR_(filtR), - filtN_(filtN), - mode_(mode), - minCandMass_(minCandMass), - maxCandMass_(maxCandMass), - massRatioWidth_(massRatioWidth), - minM23Cut_(minM23Cut), - minM13Cut_(minM13Cut), - maxM13Cut_(maxM13Cut), - optRrejectMin_(optRrejectMin), - engine_(nullptr) - {} + HEPTopTaggerV2(bool DoOptimalR, + bool DoQjets, + double minSubjetPt, + double minCandPt, + double subjetMass, + double muCut, + double filtR, + int filtN, + int mode, + double minCandMass, + double maxCandMass, + double massRatioWidth, + double minM23Cut, + double minM13Cut, + double maxM13Cut, + bool optRrejectMin) + : DoOptimalR_(DoOptimalR), + DoQjets_(DoQjets), + minSubjetPt_(minSubjetPt), + minCandPt_(minCandPt), + subjetMass_(subjetMass), + muCut_(muCut), + filtR_(filtR), + filtN_(filtN), + mode_(mode), + minCandMass_(minCandMass), + maxCandMass_(maxCandMass), + massRatioWidth_(massRatioWidth), + minM23Cut_(minM23Cut), + minM13Cut_(minM13Cut), + maxM13Cut_(maxM13Cut), + optRrejectMin_(optRrejectMin), + engine_(nullptr) {} /// returns a textual description of the tagger std::string description() const override; @@ -89,212 +88,195 @@ class HEPTopTaggerV2 : public TopTaggerBase { /// returns the tagged PseudoJet if successful, or a PseudoJet==0 otherwise /// (standard access is through operator()). /// \param jet the PseudoJet to tag - PseudoJet result(const PseudoJet & jet) const override; + PseudoJet result(const PseudoJet& jet) const override; - void set_rng(CLHEP::HepRandomEngine* engine){ engine_ = engine;} + void set_rng(CLHEP::HepRandomEngine* engine) { engine_ = engine; } // the type of the associated structure typedef HEPTopTaggerV2Structure StructureType; private: - bool DoOptimalR_; // Use optimalR mode - bool DoQjets_; // Use qjet mode - - double minSubjetPt_; // Minimal pT for subjets [GeV] - double minCandPt_; // Minimal pT to return a candidate [GeV] - - double subjetMass_; // Mass above which subjets are further unclustered - double muCut_; // Mass drop threshold - - double filtR_; // maximal filtering radius - int filtN_; // number of filtered subjets to use - - // HEPTopTagger Mode - // 0: do 2d-plane, return candidate with delta m_top minimal - // 1: return candidate with delta m_top minimal IF passes 2d plane - // 2: do 2d-plane, return candidate with max dj_sum - // 3: return candidate with max dj_sum IF passes 2d plane - // 4: return candidate built from leading three subjets after unclustering IF passes 2d plane - // Note: Original HTT was mode==1 - int mode_; - - // Top Quark mass window in GeV - double minCandMass_; - double maxCandMass_; - - double massRatioWidth_; // One sided width of the A-shaped window around m_W/m_top in % - double minM23Cut_; // minimal value of m23/m123 - double minM13Cut_; // minimal value of atan(m13/m12) - double maxM13Cut_; // maximal value of atan(m13/m12) - - bool optRrejectMin_; // set Ropt to zero for candidates that never leave the window around the initial mass - // otherwise (default) set them to R=0.5 - - // Random engine for Q-jet HTT - CLHEP::HepRandomEngine* engine_; -}; + bool DoOptimalR_; // Use optimalR mode + bool DoQjets_; // Use qjet mode + double minSubjetPt_; // Minimal pT for subjets [GeV] + double minCandPt_; // Minimal pT to return a candidate [GeV] -class HEPTopTaggerV2Structure : public CompositeJetStructure, public TopTaggerBaseStructure { + double subjetMass_; // Mass above which subjets are further unclustered + double muCut_; // Mass drop threshold - public: - /// ctor with pieces initialisation - HEPTopTaggerV2Structure(const std::vector& pieces_in, - const JetDefinition::Recombiner *recombiner = nullptr) : CompositeJetStructure(pieces_in, recombiner), - _fj_mass(0.0), - _fj_pt(0.0), - _fj_eta(0.0), - _fj_phi(0.0), - _top_mass(0.0), - _unfiltered_mass(0.0), - _pruned_mass(0.0), - _fRec(-1.), - _mass_ratio_passed(-1), - _ptForRoptCalc(-1), - _tau1Unfiltered(-1.), - _tau2Unfiltered(-1.), - _tau3Unfiltered(-1.), - _tau1Filtered(-1.), - _tau2Filtered(-1.), - _tau3Filtered(-1.), - _qweight(-1.), - _qepsilon(-1.), - _qsigmaM(-1.), - W_rec(recombiner), - rW_(){} - - // Return W subjet - inline PseudoJet const & W() const override{ - rW_ = join(_pieces[0], _pieces[1], *W_rec); - return rW_; - } - - // Return leading subjet in W - inline PseudoJet W1() const{ - assert(!W().pieces().empty()); - return W().pieces()[0]; - } - - /// returns the second W subjet - inline PseudoJet W2() const{ - assert(W().pieces().size()>1); - return W().pieces()[1]; - } - - - /// returns the non-W subjet - /// It will have 1 or 2 pieces depending on whether the tagger has - /// found 3 or 4 pieces - inline const PseudoJet & non_W() const override{ - return _pieces[2]; - } - - /// return the mass of the initial fatjet - inline double fj_mass() const {return _fj_mass;} - - /// return the pt of the initial fatjet - inline double fj_pt() const {return _fj_pt;} - - /// return the eta of the initial fatjet - inline double fj_eta() const {return _fj_eta;} - - /// return the phi of the initial fatjet - inline double fj_phi() const {return _fj_phi;} - - /// returns the candidate mass - inline double top_mass() const {return _top_mass;} - - /// returns the unfiltered mass - inline double unfiltered_mass() const {return _unfiltered_mass;} - - /// returns the pruned mass - inline double pruned_mass() const {return _pruned_mass;} - - /// returns fRec - inline double fRec() const {return _fRec;} - - /// returns if 2d-mass plane cuts were passed - inline double mass_ratio_passed() const {return _mass_ratio_passed;} - - /// returns Ropt - inline double ropt() const {return _ropt;} - - /// returns calculated Ropt - inline double roptCalc() const {return _roptCalc;} - - /// returns the filtered pT for calculating R_opt - inline double ptForRoptCalc() const {return _ptForRoptCalc;} - - // Nsubjettiness and Q-jet variables - inline double Tau1Unfiltered() const {return _tau1Unfiltered;} - inline double Tau2Unfiltered() const {return _tau2Unfiltered;} - inline double Tau3Unfiltered() const {return _tau3Unfiltered;} - inline double Tau1Filtered() const {return _tau1Filtered;} - inline double Tau2Filtered() const {return _tau2Filtered;} - inline double Tau3Filtered() const {return _tau3Filtered;} - - inline double qweight() const {return _qweight;} - inline double qepsilon() const {return _qepsilon;} - inline double qsigmaM() const {return _qsigmaM;} - - protected: - - double _fj_mass; - double _fj_pt; - double _fj_eta; - double _fj_phi; - - double _top_mass; - double _unfiltered_mass; - double _pruned_mass; - double _fRec; - int _mass_ratio_passed; - double _ptForRoptCalc; - double _ropt; - double _roptCalc; - - double _tau1Unfiltered; - double _tau2Unfiltered; - double _tau3Unfiltered; - double _tau1Filtered; - double _tau2Filtered; - double _tau3Filtered; - double _qweight; - double _qepsilon; - double _qsigmaM; - - const JetDefinition::Recombiner * W_rec; - - mutable PseudoJet rW_; - - // allow the tagger to set these - friend class HEPTopTaggerV2; - }; + double filtR_; // maximal filtering radius + int filtN_; // number of filtered subjets to use + // HEPTopTagger Mode + // 0: do 2d-plane, return candidate with delta m_top minimal + // 1: return candidate with delta m_top minimal IF passes 2d plane + // 2: do 2d-plane, return candidate with max dj_sum + // 3: return candidate with max dj_sum IF passes 2d plane + // 4: return candidate built from leading three subjets after unclustering IF passes 2d plane + // Note: Original HTT was mode==1 + int mode_; + + // Top Quark mass window in GeV + double minCandMass_; + double maxCandMass_; + + double massRatioWidth_; // One sided width of the A-shaped window around m_W/m_top in % + double minM23Cut_; // minimal value of m23/m123 + double minM13Cut_; // minimal value of atan(m13/m12) + double maxM13Cut_; // maximal value of atan(m13/m12) + + bool optRrejectMin_; // set Ropt to zero for candidates that never leave the window around the initial mass + // otherwise (default) set them to R=0.5 + + // Random engine for Q-jet HTT + CLHEP::HepRandomEngine* engine_; +}; + +class HEPTopTaggerV2Structure : public CompositeJetStructure, public TopTaggerBaseStructure { +public: + /// ctor with pieces initialisation + HEPTopTaggerV2Structure(const std::vector& pieces_in, + const JetDefinition::Recombiner* recombiner = nullptr) + : CompositeJetStructure(pieces_in, recombiner), + _fj_mass(0.0), + _fj_pt(0.0), + _fj_eta(0.0), + _fj_phi(0.0), + _top_mass(0.0), + _unfiltered_mass(0.0), + _pruned_mass(0.0), + _fRec(-1.), + _mass_ratio_passed(-1), + _ptForRoptCalc(-1), + _tau1Unfiltered(-1.), + _tau2Unfiltered(-1.), + _tau3Unfiltered(-1.), + _tau1Filtered(-1.), + _tau2Filtered(-1.), + _tau3Filtered(-1.), + _qweight(-1.), + _qepsilon(-1.), + _qsigmaM(-1.), + W_rec(recombiner), + rW_() {} + + // Return W subjet + inline PseudoJet const& W() const override { + rW_ = join(_pieces[0], _pieces[1], *W_rec); + return rW_; + } + + // Return leading subjet in W + inline PseudoJet W1() const { + assert(!W().pieces().empty()); + return W().pieces()[0]; + } + + /// returns the second W subjet + inline PseudoJet W2() const { + assert(W().pieces().size() > 1); + return W().pieces()[1]; + } + + /// returns the non-W subjet + /// It will have 1 or 2 pieces depending on whether the tagger has + /// found 3 or 4 pieces + inline const PseudoJet& non_W() const override { return _pieces[2]; } + + /// return the mass of the initial fatjet + inline double fj_mass() const { return _fj_mass; } + + /// return the pt of the initial fatjet + inline double fj_pt() const { return _fj_pt; } + + /// return the eta of the initial fatjet + inline double fj_eta() const { return _fj_eta; } + + /// return the phi of the initial fatjet + inline double fj_phi() const { return _fj_phi; } + + /// returns the candidate mass + inline double top_mass() const { return _top_mass; } + + /// returns the unfiltered mass + inline double unfiltered_mass() const { return _unfiltered_mass; } + + /// returns the pruned mass + inline double pruned_mass() const { return _pruned_mass; } + + /// returns fRec + inline double fRec() const { return _fRec; } + + /// returns if 2d-mass plane cuts were passed + inline double mass_ratio_passed() const { return _mass_ratio_passed; } + + /// returns Ropt + inline double ropt() const { return _ropt; } + + /// returns calculated Ropt + inline double roptCalc() const { return _roptCalc; } + + /// returns the filtered pT for calculating R_opt + inline double ptForRoptCalc() const { return _ptForRoptCalc; } + + // Nsubjettiness and Q-jet variables + inline double Tau1Unfiltered() const { return _tau1Unfiltered; } + inline double Tau2Unfiltered() const { return _tau2Unfiltered; } + inline double Tau3Unfiltered() const { return _tau3Unfiltered; } + inline double Tau1Filtered() const { return _tau1Filtered; } + inline double Tau2Filtered() const { return _tau2Filtered; } + inline double Tau3Filtered() const { return _tau3Filtered; } + + inline double qweight() const { return _qweight; } + inline double qepsilon() const { return _qepsilon; } + inline double qsigmaM() const { return _qsigmaM; } + +protected: + double _fj_mass; + double _fj_pt; + double _fj_eta; + double _fj_phi; + + double _top_mass; + double _unfiltered_mass; + double _pruned_mass; + double _fRec; + int _mass_ratio_passed; + double _ptForRoptCalc; + double _ropt; + double _roptCalc; + + double _tau1Unfiltered; + double _tau2Unfiltered; + double _tau3Unfiltered; + double _tau1Filtered; + double _tau2Filtered; + double _tau3Filtered; + double _qweight; + double _qepsilon; + double _qsigmaM; + + const JetDefinition::Recombiner* W_rec; + + mutable PseudoJet rW_; + + // allow the tagger to set these + friend class HEPTopTaggerV2; +}; //------------------------------------------------------------------------ // description of the tagger -inline std::string HEPTopTaggerV2::description() const{ - +inline std::string HEPTopTaggerV2::description() const { std::ostringstream oss; oss << "HEPTopTaggerV2 with: " - << "minSubjetPt = " << minSubjetPt_ - << "minCandPt = " << minCandPt_ - << "subjetMass = " << subjetMass_ - << "muCut = " << muCut_ - << "filtR = " << filtR_ - << "filtN = " << filtN_ - << "mode = " << mode_ - << "minCandMass = " << minCandMass_ - << "maxCandMass = " << maxCandMass_ - << "massRatioWidth = " << massRatioWidth_ - << "minM23Cut = " << minM23Cut_ - << "minM13Cut = " << minM13Cut_ - << "maxM13Cut = " << maxM13Cut_ << std::endl; + << "minSubjetPt = " << minSubjetPt_ << "minCandPt = " << minCandPt_ << "subjetMass = " << subjetMass_ + << "muCut = " << muCut_ << "filtR = " << filtR_ << "filtN = " << filtN_ << "mode = " << mode_ + << "minCandMass = " << minCandMass_ << "maxCandMass = " << maxCandMass_ << "massRatioWidth = " << massRatioWidth_ + << "minM23Cut = " << minM23Cut_ << "minM13Cut = " << minM13Cut_ << "maxM13Cut = " << maxM13Cut_ << std::endl; return oss.str(); } - FASTJET_END_NAMESPACE -#endif // __HEPTOPTAGGER_HH__ +#endif // __HEPTOPTAGGER_HH__ diff --git a/RecoJets/JetAlgorithms/interface/JetAlgoHelper.h b/RecoJets/JetAlgorithms/interface/JetAlgoHelper.h index 5b1164eb8c7f3..aee588a4f78ca 100644 --- a/RecoJets/JetAlgorithms/interface/JetAlgoHelper.h +++ b/RecoJets/JetAlgorithms/interface/JetAlgoHelper.h @@ -19,88 +19,106 @@ namespace { double value; unsigned index; }; - - inline bool so_lt (const SortObject& a, const SortObject& b) {return a.value < b.value;} - inline bool so_gt (const SortObject& a, const SortObject& b) {return a.value > b.value;} - - template struct GetPt {inline double getValue (const T& a) {return a.pt();}}; - template struct GetEt {inline double getValue (const T& a) {return a.et();}}; - template struct GetPtRef {inline double getValue (const T& a) {return a->pt();}}; - template struct GetEtRef {inline double getValue (const T& a) {return a->et();}}; - + + inline bool so_lt(const SortObject& a, const SortObject& b) { return a.value < b.value; } + inline bool so_gt(const SortObject& a, const SortObject& b) { return a.value > b.value; } + + template + struct GetPt { + inline double getValue(const T& a) { return a.pt(); } + }; + template + struct GetEt { + inline double getValue(const T& a) { return a.et(); } + }; + template + struct GetPtRef { + inline double getValue(const T& a) { return a->pt(); } + }; + template + struct GetEtRef { + inline double getValue(const T& a) { return a->et(); } + }; + template - inline void sortGreater (std::vector * container) { - std::vector sortable (container->size()); + inline void sortGreater(std::vector* container) { + std::vector sortable(container->size()); bool sorted = true; GetValue getter; for (unsigned i = 0; i < container->size(); i++) { - sortable[i].value = getter.getValue ((*container)[i]); + sortable[i].value = getter.getValue((*container)[i]); sortable[i].index = i; - if (sorted && i && so_lt (sortable[i-1], sortable[i])) sorted = false; + if (sorted && i && so_lt(sortable[i - 1], sortable[i])) + sorted = false; } - if (!sorted) { // needs sorting - std::sort (sortable.begin(), sortable.end(), so_gt); - std::vector result; + if (!sorted) { // needs sorting + std::sort(sortable.begin(), sortable.end(), so_gt); + std::vector result; result.reserve(container->size()); for (unsigned i = 0; i < container->size(); i++) { - result.push_back ((*container)[sortable[i].index]); + result.push_back((*container)[sortable[i].index]); } - container->swap (result); + container->swap(result); } } - + template - inline void sortByPt (std::vector * container) { - sortGreater > (container); + inline void sortByPt(std::vector* container) { + sortGreater >(container); } - + template - inline void sortByEt (std::vector * container) { - sortGreater > (container); + inline void sortByEt(std::vector* container) { + sortGreater >(container); } - - + template - inline void sortByPtRef (std::vector * container) { - sortGreater > (container); + inline void sortByPtRef(std::vector* container) { + sortGreater >(container); } - + template - inline void sortByEtRef (std::vector * container) { - sortGreater > (container); + inline void sortByEtRef(std::vector* container) { + sortGreater >(container); } - -} + +} // namespace template class GreaterByPtRef { - public: +public: int operator()(const T& a1, const T& a2) { - if (!a1) return 0; - if (!a2) return 1; - NumericSafeGreaterByPt comp; - return comp.operator () (*a1, *a2); + if (!a1) + return 0; + if (!a2) + return 1; + NumericSafeGreaterByPt comp; + return comp.operator()(*a1, *a2); } }; template class GreaterByPtPtr { - public: +public: int operator()(const T* a1, const T* a2) { - if (!a1) return 0; - if (!a2) return 1; - NumericSafeGreaterByPt comp; - return comp.operator () (*a1, *a2); + if (!a1) + return 0; + if (!a2) + return 1; + NumericSafeGreaterByPt comp; + return comp.operator()(*a1, *a2); } }; template class GreaterByEtRef { - public: +public: int operator()(const T& a1, const T& a2) { - if (!a1) return 0; - if (!a2) return 1; - NumericSafeGreaterByEt comp; - return comp.operator () (*a1, *a2); + if (!a1) + return 0; + if (!a2) + return 1; + NumericSafeGreaterByEt comp; + return comp.operator()(*a1, *a2); } }; diff --git a/RecoJets/JetAlgorithms/interface/PrunedRecombiner.hh b/RecoJets/JetAlgorithms/interface/PrunedRecombiner.hh index da1be9faa3303..98e21f9a9f4a3 100644 --- a/RecoJets/JetAlgorithms/interface/PrunedRecombiner.hh +++ b/RecoJets/JetAlgorithms/interface/PrunedRecombiner.hh @@ -21,57 +21,49 @@ #include -FASTJET_BEGIN_NAMESPACE // defined in fastjet/internal/base.hh +FASTJET_BEGIN_NAMESPACE // defined in fastjet/internal/base.hh - -class PrunedRecombiner : public JetDefinition::Recombiner { + class PrunedRecombiner : public JetDefinition::Recombiner { public: - PrunedRecombiner(const JetDefinition::Recombiner *recomb, - const double & zcut = 0.1, const double & Rcut = 0.5) : - _zcut(zcut), _Rcut(Rcut), _recombiner(recomb) {} - - PrunedRecombiner(const RecombinationScheme scheme, - const double & zcut = 0.1, const double & Rcut = 0.5) : - _zcut(zcut), _Rcut(Rcut), _recombiner(0), _default_recombiner(scheme) { - _recombiner = &_default_recombiner; - } - - virtual std::string description() const; - - // recombine pa and pb and put result into pab - virtual void recombine(const PseudoJet & pa, const PseudoJet & pb, - PseudoJet & pab) const; - - std::vector pruned_pseudojets() { return _pruned_pseudojets; } - - // resets pruned_pseudojets vector, parameters - void reset(const double & zcut, const double & Rcut); - - virtual ~PrunedRecombiner() {} - + PrunedRecombiner(const JetDefinition::Recombiner* recomb, const double& zcut = 0.1, const double& Rcut = 0.5) + : _zcut(zcut), _Rcut(Rcut), _recombiner(recomb) {} + + PrunedRecombiner(const RecombinationScheme scheme, const double& zcut = 0.1, const double& Rcut = 0.5) + : _zcut(zcut), _Rcut(Rcut), _recombiner(nullptr), _default_recombiner(scheme) { + _recombiner = &_default_recombiner; + } + + std::string description() const override; + + // recombine pa and pb and put result into pab + void recombine(const PseudoJet& pa, const PseudoJet& pb, PseudoJet& pab) const override; + + std::vector pruned_pseudojets() { return _pruned_pseudojets; } + + // resets pruned_pseudojets vector, parameters + void reset(const double& zcut, const double& Rcut); + + ~PrunedRecombiner() override {} + private: - // tests whether pa and pb should be recombined or vetoed - int _pruning_test(const PseudoJet & pa, const PseudoJet & pb) const; - - double _zcut; // zcut parameter to the pruning test - double _Rcut; // Rcut parameter to the pruning test - - // vector that holds cluster_history_indices of pruned pj's - mutable std::vector _pruned_pseudojets; - - // points to the "real" external recombiner - const JetDefinition::Recombiner* _recombiner; - - // Use this if we are only passed a recombination scheme. - // A DefaultRecombiner is so small it's not worth dealing with whether we own - // the recombiner or not... - JetDefinition::DefaultRecombiner _default_recombiner; -}; + // tests whether pa and pb should be recombined or vetoed + int _pruning_test(const PseudoJet& pa, const PseudoJet& pb) const; + double _zcut; // zcut parameter to the pruning test + double _Rcut; // Rcut parameter to the pruning test + // vector that holds cluster_history_indices of pruned pj's + mutable std::vector _pruned_pseudojets; -FASTJET_END_NAMESPACE // defined in fastjet/internal/base.hh + // points to the "real" external recombiner + const JetDefinition::Recombiner* _recombiner; + // Use this if we are only passed a recombination scheme. + // A DefaultRecombiner is so small it's not worth dealing with whether we own + // the recombiner or not... + JetDefinition::DefaultRecombiner _default_recombiner; +}; +FASTJET_END_NAMESPACE // defined in fastjet/internal/base.hh #endif // __PRUNEDRECOMBINER_HH__ diff --git a/RecoJets/JetAlgorithms/interface/QGLikelihoodCalculator.h b/RecoJets/JetAlgorithms/interface/QGLikelihoodCalculator.h index 4767114e39f5e..574136c8db39e 100644 --- a/RecoJets/JetAlgorithms/interface/QGLikelihoodCalculator.h +++ b/RecoJets/JetAlgorithms/interface/QGLikelihoodCalculator.h @@ -10,19 +10,29 @@ * The variables in the vars vector should match with the variables in the QGLikelihoodObject, in which they are identified by the varIndex * Authors: andrea.carlo.marini@cern.ch, tom.cornelis@cern.ch, cms-qg-workinggroup@cern.ch */ -class QGLikelihoodCalculator{ - - public: +class QGLikelihoodCalculator { +public: QGLikelihoodCalculator(){}; - ~QGLikelihoodCalculator(){}; + ~QGLikelihoodCalculator(){}; - float computeQGLikelihood(edm::ESHandle &QGLParamsColl, float pt, float eta, float rho, std::vector vars) const; - float systematicSmearing(edm::ESHandle &QGLParamsColl, float pt, float eta, float rho, float qgValue, int qgIndex) const; + float computeQGLikelihood( + edm::ESHandle &QGLParamsColl, float pt, float eta, float rho, std::vector vars) const; + float systematicSmearing(edm::ESHandle &QGLParamsColl, + float pt, + float eta, + float rho, + float qgValue, + int qgIndex) const; - private: - const QGLikelihoodObject::Entry* findEntry(std::vector const &data, float eta, float pt, float rho, int qgIndex, int varIndex) const; +private: + const QGLikelihoodObject::Entry *findEntry(std::vector const &data, + float eta, + float pt, + float rho, + int qgIndex, + int varIndex) const; bool isValidRange(float pt, float rho, float eta, const QGLikelihoodCategory &qgValidRange) const; - float smearingFunction(float x0, float a ,float b,float min,float max) const; + float smearingFunction(float x0, float a, float b, float min, float max) const; }; #endif diff --git a/RecoJets/JetAlgorithms/interface/Qjets.h b/RecoJets/JetAlgorithms/interface/Qjets.h index fe2406f065081..676b6a421b47a 100644 --- a/RecoJets/JetAlgorithms/interface/Qjets.h +++ b/RecoJets/JetAlgorithms/interface/Qjets.h @@ -13,67 +13,72 @@ #include "FWCore/ServiceRegistry/interface/Service.h" #include "CLHEP/Random/RandomEngine.h" -struct JetDistance{ +struct JetDistance { double dij; int j1; int j2; }; -class JetDistanceCompare{ - public: +class JetDistanceCompare { +public: JetDistanceCompare(){}; - bool operator() (const JetDistance& lhs, const JetDistance&rhs) const {return lhs.dij > rhs.dij;}; + bool operator()(const JetDistance& lhs, const JetDistance& rhs) const { return lhs.dij > rhs.dij; }; }; -class Qjets{ - private: +class Qjets { +private: double omega; bool _rand_seed_set; unsigned int _seed; double _zcut, _dcut, _dcut_fctr, _exp_min, _exp_max, _rigidity, _truncation_fctr; - std::map _merged_jets; - std::priority_queue , JetDistanceCompare> _distances; + std::map _merged_jets; + std::priority_queue, JetDistanceCompare> _distances; CLHEP::HepRandomEngine* _rnEngine; - double d_ij(const fastjet::PseudoJet& v1, const fastjet::PseudoJet& v2) const; - void computeDCut(fastjet::ClusterSequence & cs); + double d_ij(const fastjet::PseudoJet& v1, const fastjet::PseudoJet& v2) const; + void computeDCut(fastjet::ClusterSequence& cs); double Rand(); - bool Prune(JetDistance& jd,fastjet::ClusterSequence & cs); + bool Prune(JetDistance& jd, fastjet::ClusterSequence& cs); bool JetsUnmerged(const JetDistance& jd) const; bool JetUnmerged(int num) const; - void ComputeNewDistanceMeasures(fastjet::ClusterSequence & cs, unsigned int new_jet); - void ComputeAllDistances(const std::vector& inp); + void ComputeNewDistanceMeasures(fastjet::ClusterSequence& cs, unsigned int new_jet); + void ComputeAllDistances(const std::vector& inp); double ComputeMinimumDistance(); double ComputeNormalization(double dmin); JetDistance GetNextDistance(); bool Same(const JetDistance& lhs, const JetDistance& rhs); - public: - Qjets(double zcut, double dcut_fctr, double exp_min, double exp_max, double rigidity, double truncation_fctr, CLHEP::HepRandomEngine* rnEngine) : _rand_seed_set(false), - _zcut(zcut), - _dcut(-1.), - _dcut_fctr(dcut_fctr), - _exp_min(exp_min), - _exp_max(exp_max), - _rigidity(rigidity), - _truncation_fctr(truncation_fctr), - _rnEngine(rnEngine) - {}; - - void Cluster(fastjet::ClusterSequence & cs); +public: + Qjets(double zcut, + double dcut_fctr, + double exp_min, + double exp_max, + double rigidity, + double truncation_fctr, + CLHEP::HepRandomEngine* rnEngine) + : _rand_seed_set(false), + _zcut(zcut), + _dcut(-1.), + _dcut_fctr(dcut_fctr), + _exp_min(exp_min), + _exp_max(exp_max), + _rigidity(rigidity), + _truncation_fctr(truncation_fctr), + _rnEngine(rnEngine){}; + + void Cluster(fastjet::ClusterSequence& cs); void SetRandSeed(unsigned int seed); /* In case you want reproducible behavior */ }; - class QjetsBaseExtras : public fastjet::ClusterSequence::Extras { public: - QjetsBaseExtras():_wij(-1.) {} + QjetsBaseExtras() : _wij(-1.) {} ~QjetsBaseExtras() override {} - virtual double weight() const {return _wij;} + virtual double weight() const { return _wij; } friend class Qjets; - protected: +protected: double _wij; }; diff --git a/RecoJets/JetAlgorithms/interface/QjetsPlugin.h b/RecoJets/JetAlgorithms/interface/QjetsPlugin.h index 067587be126a0..dda5d968178a7 100644 --- a/RecoJets/JetAlgorithms/interface/QjetsPlugin.h +++ b/RecoJets/JetAlgorithms/interface/QjetsPlugin.h @@ -5,29 +5,29 @@ #include "fastjet/ClusterSequence.hh" #include "RecoJets/JetAlgorithms/interface/Qjets.h" -class QjetsPlugin: public fastjet::JetDefinition::Plugin{ - private: +class QjetsPlugin : public fastjet::JetDefinition::Plugin { +private: bool _rand_seed_set; unsigned int _seed; int _truncated_length; - double _zcut, _dcut_fctr, _exp_min, _exp_max, _rigidity,_truncation_fctr; + double _zcut, _dcut_fctr, _exp_min, _exp_max, _rigidity, _truncation_fctr; CLHEP::HepRandomEngine* _rnEngine; - public: - QjetsPlugin(double zcut, double dcut_fctr, double exp_min, double exp_max, double rigidity, double truncation_fctr = 0.) : _rand_seed_set(false), - _zcut(zcut), - _dcut_fctr(dcut_fctr), - _exp_min(exp_min), - _exp_max(exp_max), - _rigidity(rigidity), - _truncation_fctr(truncation_fctr), - _rnEngine(nullptr) - {}; + +public: + QjetsPlugin( + double zcut, double dcut_fctr, double exp_min, double exp_max, double rigidity, double truncation_fctr = 0.) + : _rand_seed_set(false), + _zcut(zcut), + _dcut_fctr(dcut_fctr), + _exp_min(exp_min), + _exp_max(exp_max), + _rigidity(rigidity), + _truncation_fctr(truncation_fctr), + _rnEngine(nullptr){}; void SetRandSeed(unsigned int seed); /* In case you want reproducible behavior */ - void SetRNEngine(CLHEP::HepRandomEngine* rnEngine){ - _rnEngine=rnEngine; - }; + void SetRNEngine(CLHEP::HepRandomEngine* rnEngine) { _rnEngine = rnEngine; }; double R() const override; std::string description() const override; - void run_clustering(fastjet::ClusterSequence & cs) const override; + void run_clustering(fastjet::ClusterSequence& cs) const override; }; #endif diff --git a/RecoJets/JetAlgorithms/interface/SubJetAlgorithm.h b/RecoJets/JetAlgorithms/interface/SubJetAlgorithm.h index 492844c7e8f4a..a9db53a0d4424 100644 --- a/RecoJets/JetAlgorithms/interface/SubJetAlgorithm.h +++ b/RecoJets/JetAlgorithms/interface/SubJetAlgorithm.h @@ -13,50 +13,42 @@ #include #include - -class SubJetAlgorithm{ - public: - SubJetAlgorithm( double ptMin, - unsigned int subjets, - double zcut, - double rcut_factor, - boost::shared_ptr fjJetDefinition, - bool doAreaFastjet, - boost::shared_ptr fjActiveArea, - double voronoiRfact - ) : - ptMin_ (ptMin ), - nSubjets_ (subjets ), - zcut_ (zcut ), - rcut_factor_ (rcut_factor ), - fjJetDefinition_(fjJetDefinition), - doAreaFastjet_ (doAreaFastjet), - fjActiveArea_ (fjActiveArea), - voronoiRfact_ (voronoiRfact) - { - - } +class SubJetAlgorithm { +public: + SubJetAlgorithm(double ptMin, + unsigned int subjets, + double zcut, + double rcut_factor, + boost::shared_ptr fjJetDefinition, + bool doAreaFastjet, + boost::shared_ptr fjActiveArea, + double voronoiRfact) + : ptMin_(ptMin), + nSubjets_(subjets), + zcut_(zcut), + rcut_factor_(rcut_factor), + fjJetDefinition_(fjJetDefinition), + doAreaFastjet_(doAreaFastjet), + fjActiveArea_(fjActiveArea), + voronoiRfact_(voronoiRfact) {} void set_zcut(double z); void set_rcut_factor(double r); - double zcut() const { return zcut_;} + double zcut() const { return zcut_; } double rcut_factor() const { return rcut_factor_; } /// Find the ProtoJets from the collection of input Candidates. - void run( const std::vector & cell_particles, - std::vector & hardjetsOutput); - - - private: - - double ptMin_; // fjJetDefinition_; // fjActiveArea_; //& cell_particles, std::vector& hardjetsOutput); + +private: + double ptMin_; // fjJetDefinition_; // fjActiveArea_; // #include "RecoJets/JetAlgorithms/interface/CompoundPseudoJet.h" @@ -23,64 +21,62 @@ #include #include - - - -class SubjetFilterAlgorithm -{ +class SubjetFilterAlgorithm { // // construction / destruction // public: SubjetFilterAlgorithm(const std::string& moduleLabel, - const std::string& jetAlgorithm, - unsigned nFatMax, double rParam, - double rFilt, double jetPtMin, - double massDropCut, double asymmCut, - bool asymmCutLater,bool doAreaFastjet, - double ghostEtaMax, int activeAreaRepeats, - double ghostArea, bool verbose); + const std::string& jetAlgorithm, + unsigned nFatMax, + double rParam, + double rFilt, + double jetPtMin, + double massDropCut, + double asymmCut, + bool asymmCutLater, + bool doAreaFastjet, + double ghostEtaMax, + int activeAreaRepeats, + double ghostArea, + bool verbose); virtual ~SubjetFilterAlgorithm(); - - + // // member functions // public: - void run(const std::vector& inputs, - std::vector& fatJets, - const edm::EventSetup& iSetup); - + void run(const std::vector& inputs, + std::vector& fatJets, + const edm::EventSetup& iSetup); + std::string summary() const; - - + // // member data // private: - std::string moduleLabel_; - std::string jetAlgorithm_; - unsigned nFatMax_; - double rParam_; - double rFilt_; - double jetPtMin_; - double massDropCut_; - double asymmCut2_; - bool asymmCutLater_; - bool doAreaFastjet_; - double ghostEtaMax_; - int activeAreaRepeats_; - double ghostArea_; - bool verbose_; - - unsigned nevents_; - unsigned ntotal_; - unsigned nfound_; - - fastjet::JetDefinition* fjJetDef_; - fastjet::AreaDefinition* fjAreaDef_; + std::string moduleLabel_; + std::string jetAlgorithm_; + unsigned nFatMax_; + double rParam_; + double rFilt_; + double jetPtMin_; + double massDropCut_; + double asymmCut2_; + bool asymmCutLater_; + bool doAreaFastjet_; + double ghostEtaMax_; + int activeAreaRepeats_; + double ghostArea_; + bool verbose_; -}; + unsigned nevents_; + unsigned ntotal_; + unsigned nfound_; + fastjet::JetDefinition* fjJetDef_; + fastjet::AreaDefinition* fjAreaDef_; +}; #endif diff --git a/RecoJets/JetAlgorithms/src/CATopJetAlgorithm.cc b/RecoJets/JetAlgorithms/src/CATopJetAlgorithm.cc index ecfd8dcd8199a..3023625810970 100644 --- a/RecoJets/JetAlgorithms/src/CATopJetAlgorithm.cc +++ b/RecoJets/JetAlgorithms/src/CATopJetAlgorithm.cc @@ -13,250 +13,278 @@ using namespace std; using namespace reco; using namespace edm; - // Run the algorithm // ------------------ -void CATopJetAlgorithm::run( const vector & cell_particles, - vector & hardjetsOutput, - boost::shared_ptr & fjClusterSeq - ) -{ - if ( verbose_ ) cout << "Welcome to CATopSubJetAlgorithm::run" << endl; - - // Sum Et of the event - double sumEt = 0.; - - //make a list of input objects ordered by ET and calculate sum et - // list of fastjet pseudojet constituents - for (unsigned i = 0; i < cell_particles.size(); ++i) { - sumEt += cell_particles[i].perp(); - } - - // Determine which bin we are in for et clustering - int sumEtBinId = -1; - for ( unsigned int i = 0; i < sumEtBins_.size(); ++i ) { - if ( sumEt > sumEtBins_[i] ) sumEtBinId = i; - } - if ( verbose_ ) cout << "Using sumEt = " << sumEt << ", bin = " << sumEtBinId << endl; - - // If the sum et is too low, exit - if ( sumEtBinId < 0 ) { - return; - } - - // empty 4-vector - fastjet::PseudoJet blankJetA(0,0,0,0); - blankJetA.set_user_index(-1); - const fastjet::PseudoJet blankJet = blankJetA; - - // Define adjacency variables which depend on which sumEtBin we are in - double deltarcut = deltarBins_[sumEtBinId]; - double nCellMin = nCellBins_[sumEtBinId]; - - if ( verbose_ )cout<<"useAdjacency_ = "< fjClusterSeq; - // if ( !doAreaFastjet_ ) { - // fjClusterSeq = boost::shared_ptr( new fastjet::ClusterSequence( cell_particles, jetDef ) ); - // } else if (voronoiRfact_ <= 0) { - // fjClusterSeq = boost::shared_ptr( new fastjet::ClusterSequenceArea( cell_particles, jetDef , *fjActiveArea_ ) ); - // } else { - // fjClusterSeq = boost::shared_ptr( new fastjet::ClusterSequenceVoronoiArea( cell_particles, jetDef , fastjet::VoronoiAreaSpec(voronoiRfact_) ) ); - // } - - if ( verbose_ ) cout << "Getting inclusive jets" << endl; - // Get the transient inclusive jets - vector inclusiveJets = fjClusterSeq->inclusive_jets(ptMin_); - - if ( verbose_ ) cout << "Getting central jets" << endl; - // Find the transient central jets - vector centralJets; - for (unsigned int i = 0; i < inclusiveJets.size(); i++) { - - if (inclusiveJets[i].perp() > ptMin_ && fabs(inclusiveJets[i].rapidity()) < centralEtaCut_) { - centralJets.push_back(inclusiveJets[i]); - } - } - // Sort the transient central jets in Et - sort( centralJets.begin(), centralJets.end(), greaterByEtPseudoJet ); - - // These will store the 4-vectors of each hard jet - vector p4_hardJets; - - // These will store the indices of each subjet that - // are present in each jet - vector > indices( centralJets.size() ); - - // Loop over central jets, attempt to find substructure - vector::iterator jetIt = centralJets.begin(), - centralJetsEnd = centralJets.end(); - if ( verbose_ )cout<<"Loop over jets"< leftovers1; - bool hardBreak1 = decomposeJet(localJet,*fjClusterSeq,cell_particles,ptHard,nCellMin,deltarcut,ja,jb,leftovers1); - leftoversAll.insert(leftoversAll.end(),leftovers1.begin(),leftovers1.end()); - - // stage 2: secondary decomposition. look for when the hard subjets found above further decluster into two hard sub-subjets - // - // ja -> jaa+jab ? - if ( verbose_ ) cout << "Doing decomposition 2. ja->jaa+jab?" << endl; - fastjet::PseudoJet jaa, jab; - vector leftovers2a; - bool hardBreak2a = false; - if (hardBreak1) hardBreak2a = decomposeJet(ja,*fjClusterSeq,cell_particles,ptHard,nCellMin,deltarcut,jaa,jab,leftovers2a); - leftoversAll.insert(leftoversAll.end(),leftovers2a.begin(),leftovers2a.end()); - // jb -> jba+jbb ? - if ( verbose_ ) cout << "Doing decomposition 2. ja->jba+jbb?" << endl; - fastjet::PseudoJet jba, jbb; - vector leftovers2b; - bool hardBreak2b = false; - if (hardBreak1) hardBreak2b = decomposeJet(jb,*fjClusterSeq,cell_particles,ptHard,nCellMin,deltarcut,jba,jbb,leftovers2b); - leftoversAll.insert(leftoversAll.end(),leftovers2b.begin(),leftovers2b.end()); - - // NOTE: it might be good to consider some checks for whether these subjets can be further decomposed. e.g., the above procedure leaves - // open the possibility of "subjets" that actually consist of two or more distinct hard clusters. however, this kind of thing - // is a rarity for the simulations so far considered. - - // proceed if one or both of the above hard subjets successfully decomposed - if ( verbose_ ) cout << "Done with decomposition" << endl; - - if ( verbose_ ) cout<<"hardBreak1 = "<= 3 hard subjets - fastjet::PseudoJet subjet1 = blankJet; - fastjet::PseudoJet subjet2 = blankJet; - fastjet::PseudoJet subjet3 = blankJet; - fastjet::PseudoJet subjet4 = blankJet; - subjet1 = hardA; subjet2 = hardB; subjet3 = hardC; subjet4 = hardD; - - // record the hard subjets - vector hardSubjets; - - if ( verbose_ ) { - std::cout << "HardA : user_index = " << hardA.user_index() << ", (Pt,Y,Phi,M) = (" - << hardA.pt() << ", " << hardA.rapidity() << ", " - << hardA.phi() << ", " << hardA.m() << ")" << std::endl; - - std::cout << "HardB : user_index = " << hardB.user_index() << ", (Pt,Y,Phi,M) = (" - << hardB.pt() << ", " << hardB.rapidity() << ", " - << hardB.phi() << ", " << hardB.m() << ")" << std::endl; - - std::cout << "HardC : user_index = " << hardC.user_index() << ", (Pt,Y,Phi,M) = (" - << hardC.pt() << ", " << hardC.rapidity() << ", " - << hardC.phi() << ", " << hardC.m() << ")" << std::endl; - - std::cout << "HardD : user_index = " << hardD.user_index() << ", (Pt,Y,Phi,M) = (" - << hardD.pt() << ", " << hardD.rapidity() << ", " - << hardD.phi() << ", " << hardD.m() << ")" << std::endl; - } - - // Check to see if any subjects are counted amongst the "hard" subjets from previous - // lines. NOTE: In Fastjet 3.0, the default "user_index" changed from 0 to -1, so - // this can no longer be used as a designator for the veto of "blankJet" subjets, - // and now switch to pt > some small value. - if ( subjet1.pt() > 0.0001 ) - hardSubjets.push_back(subjet1); - if ( subjet2.pt() > 0.0001 ) - hardSubjets.push_back(subjet2); - if ( subjet3.pt() > 0.0001 ) - hardSubjets.push_back(subjet3); - if ( subjet4.pt() > 0.0001 ) - hardSubjets.push_back(subjet4); - sort(hardSubjets.begin(), hardSubjets.end(), greaterByEtPseudoJet ); - - // Use new fastjet functionality to create a Pseudojet from constituents - fastjet::PseudoJet candidate = join(hardSubjets); - // Reset the jet's 4-vector to the "ungroomed" value - candidate.reset_momentum( jetIt->px(), jetIt->py(), jetIt->pz(), jetIt->e() ); - - if ( verbose_ ) { - std::cout << "Final top-jet candidate: (Pt,Y,Phi,M) = (" - << candidate.pt() << ", " << candidate.rapidity() << ", " - << candidate.phi() << ", " << candidate.m() << ")" << std::endl; - std::vector pieces = candidate.pieces(); - std::cout << "Number of pieces = " << pieces.size() << std::endl; - for ( std::vector::const_iterator ibegin = pieces.begin(), iend = pieces.end(), i = ibegin; - i != iend; ++i ) { - std::cout << " Piece : " << i - ibegin << ", (Pt,Y,Phi,M) = (" - << i->pt() << ", " << i->rapidity() << ", " - << i->phi() << ", " << i->m() << ")" << std::endl; - } - } - // Add to the list - hardjetsOutput.push_back( candidate ); - } -} +void CATopJetAlgorithm::run(const vector& cell_particles, + vector& hardjetsOutput, + boost::shared_ptr& fjClusterSeq) { + if (verbose_) + cout << "Welcome to CATopSubJetAlgorithm::run" << endl; + + // Sum Et of the event + double sumEt = 0.; + + //make a list of input objects ordered by ET and calculate sum et + // list of fastjet pseudojet constituents + for (unsigned i = 0; i < cell_particles.size(); ++i) { + sumEt += cell_particles[i].perp(); + } + + // Determine which bin we are in for et clustering + int sumEtBinId = -1; + for (unsigned int i = 0; i < sumEtBins_.size(); ++i) { + if (sumEt > sumEtBins_[i]) + sumEtBinId = i; + } + if (verbose_) + cout << "Using sumEt = " << sumEt << ", bin = " << sumEtBinId << endl; + + // If the sum et is too low, exit + if (sumEtBinId < 0) { + return; + } + + // empty 4-vector + fastjet::PseudoJet blankJetA(0, 0, 0, 0); + blankJetA.set_user_index(-1); + const fastjet::PseudoJet blankJet = blankJetA; + + // Define adjacency variables which depend on which sumEtBin we are in + double deltarcut = deltarBins_[sumEtBinId]; + double nCellMin = nCellBins_[sumEtBinId]; + + if (verbose_) + cout << "useAdjacency_ = " << useAdjacency_ << endl; + if (verbose_ && useAdjacency_ == 0) + cout << "No Adjacency" << endl; + if (verbose_ && useAdjacency_ == 1) + cout << "using deltar adjacency" << endl; + if (verbose_ && useAdjacency_ == 2) + cout << "using modified adjacency" << endl; + if (verbose_ && useAdjacency_ == 3) + cout << "using calorimeter nearest neighbor based adjacency" << endl; + if (verbose_ && useAdjacency_ == 1) + cout << "Using deltarcut = " << deltarcut << endl; + if (verbose_ && useAdjacency_ == 3) + cout << "Using nCellMin = " << nCellMin << endl; + + if (verbose_) + cout << "About to do jet clustering in CA" << endl; + // run the jet clustering + + //cluster the jets with the jet definition jetDef: + // run algorithm + // boost::shared_ptr fjClusterSeq; + // if ( !doAreaFastjet_ ) { + // fjClusterSeq = boost::shared_ptr( new fastjet::ClusterSequence( cell_particles, jetDef ) ); + // } else if (voronoiRfact_ <= 0) { + // fjClusterSeq = boost::shared_ptr( new fastjet::ClusterSequenceArea( cell_particles, jetDef , *fjActiveArea_ ) ); + // } else { + // fjClusterSeq = boost::shared_ptr( new fastjet::ClusterSequenceVoronoiArea( cell_particles, jetDef , fastjet::VoronoiAreaSpec(voronoiRfact_) ) ); + // } + + if (verbose_) + cout << "Getting inclusive jets" << endl; + // Get the transient inclusive jets + vector inclusiveJets = fjClusterSeq->inclusive_jets(ptMin_); + + if (verbose_) + cout << "Getting central jets" << endl; + // Find the transient central jets + vector centralJets; + for (unsigned int i = 0; i < inclusiveJets.size(); i++) { + if (inclusiveJets[i].perp() > ptMin_ && fabs(inclusiveJets[i].rapidity()) < centralEtaCut_) { + centralJets.push_back(inclusiveJets[i]); + } + } + // Sort the transient central jets in Et + sort(centralJets.begin(), centralJets.end(), greaterByEtPseudoJet); + + // These will store the 4-vectors of each hard jet + vector p4_hardJets; + + // These will store the indices of each subjet that + // are present in each jet + vector > indices(centralJets.size()); + + // Loop over central jets, attempt to find substructure + vector::iterator jetIt = centralJets.begin(), centralJetsEnd = centralJets.end(); + if (verbose_) + cout << "Loop over jets" << endl; + int i = 0; + for (; jetIt != centralJetsEnd; ++jetIt) { + if (verbose_) + cout << "\nJet " << i << endl; + i++; + fastjet::PseudoJet localJet = *jetIt; + + // Get the 4-vector for this jet + p4_hardJets.push_back(math::XYZTLorentzVector(localJet.px(), localJet.py(), localJet.pz(), localJet.e())); + + // jet decomposition. try to find 3 or 4 hard, well-localized subjets, characteristic of a boosted top. + if (verbose_) + cout << "local jet pt = " << localJet.perp() << endl; + if (verbose_) + cout << "deltap = " << ptFracBins_[sumEtBinId] << endl; + + double ptHard = ptFracBins_[sumEtBinId] * localJet.perp(); + vector leftoversAll; + + // stage 1: primary decomposition. look for when the jet declusters into two hard subjets + if (verbose_) + cout << "Doing decomposition 1" << endl; + fastjet::PseudoJet ja, jb; + vector leftovers1; + bool hardBreak1 = + decomposeJet(localJet, *fjClusterSeq, cell_particles, ptHard, nCellMin, deltarcut, ja, jb, leftovers1); + leftoversAll.insert(leftoversAll.end(), leftovers1.begin(), leftovers1.end()); + + // stage 2: secondary decomposition. look for when the hard subjets found above further decluster into two hard sub-subjets + // + // ja -> jaa+jab ? + if (verbose_) + cout << "Doing decomposition 2. ja->jaa+jab?" << endl; + fastjet::PseudoJet jaa, jab; + vector leftovers2a; + bool hardBreak2a = false; + if (hardBreak1) + hardBreak2a = decomposeJet(ja, *fjClusterSeq, cell_particles, ptHard, nCellMin, deltarcut, jaa, jab, leftovers2a); + leftoversAll.insert(leftoversAll.end(), leftovers2a.begin(), leftovers2a.end()); + // jb -> jba+jbb ? + if (verbose_) + cout << "Doing decomposition 2. ja->jba+jbb?" << endl; + fastjet::PseudoJet jba, jbb; + vector leftovers2b; + bool hardBreak2b = false; + if (hardBreak1) + hardBreak2b = decomposeJet(jb, *fjClusterSeq, cell_particles, ptHard, nCellMin, deltarcut, jba, jbb, leftovers2b); + leftoversAll.insert(leftoversAll.end(), leftovers2b.begin(), leftovers2b.end()); + + // NOTE: it might be good to consider some checks for whether these subjets can be further decomposed. e.g., the above procedure leaves + // open the possibility of "subjets" that actually consist of two or more distinct hard clusters. however, this kind of thing + // is a rarity for the simulations so far considered. + + // proceed if one or both of the above hard subjets successfully decomposed + if (verbose_) + cout << "Done with decomposition" << endl; + + if (verbose_) + cout << "hardBreak1 = " << hardBreak1 << endl; + if (verbose_) + cout << "hardBreak2a = " << hardBreak2a << endl; + if (verbose_) + cout << "hardBreak2b = " << hardBreak2b << endl; + + fastjet::PseudoJet hardA = blankJet, hardB = blankJet, hardC = blankJet, hardD = blankJet; + if (!hardBreak1) { + hardA = localJet; + hardB = blankJet; + hardC = blankJet; + hardD = blankJet; + if (verbose_) + cout << "Hardbreak failed. Save subjet1=localJet" << endl; + } + if (hardBreak1 && !hardBreak2a && !hardBreak2b) { + hardA = ja; + hardB = jb; + hardC = blankJet; + hardD = blankJet; + if (verbose_) + cout << "First decomposition succeeded, both second decompositions failed. Save subjet1=ja subjet2=jb" << endl; + } + if (hardBreak1 && hardBreak2a && !hardBreak2b) { + hardA = jaa; + hardB = jab; + hardC = jb; + hardD = blankJet; + if (verbose_) + cout << "First decomposition succeeded, ja split succesfully, jb did not split. Save subjet1=jaa subjet2=jab " + "subjet3=jb" + << endl; + } + if (hardBreak1 && !hardBreak2a && hardBreak2b) { + hardA = jba; + hardB = jbb; + hardC = ja; + hardD = blankJet; + if (verbose_) + cout << "First decomposition succeeded, jb split succesfully, ja did not split. Save subjet1=jba subjet2=jbb " + "subjet3=ja" + << endl; + } + if (hardBreak1 && hardBreak2a && hardBreak2b) { + hardA = jaa; + hardB = jab; + hardC = jba; + hardD = jbb; + if (verbose_) + cout << "First decomposition and both secondary decompositions succeeded. Save subjet1=jaa subjet2=jab " + "subjet3=jba subjet4=jbb" + << endl; + } + + // check if we are left with >= 3 hard subjets + fastjet::PseudoJet subjet1 = blankJet; + fastjet::PseudoJet subjet2 = blankJet; + fastjet::PseudoJet subjet3 = blankJet; + fastjet::PseudoJet subjet4 = blankJet; + subjet1 = hardA; + subjet2 = hardB; + subjet3 = hardC; + subjet4 = hardD; + // record the hard subjets + vector hardSubjets; + if (verbose_) { + std::cout << "HardA : user_index = " << hardA.user_index() << ", (Pt,Y,Phi,M) = (" << hardA.pt() << ", " + << hardA.rapidity() << ", " << hardA.phi() << ", " << hardA.m() << ")" << std::endl; + std::cout << "HardB : user_index = " << hardB.user_index() << ", (Pt,Y,Phi,M) = (" << hardB.pt() << ", " + << hardB.rapidity() << ", " << hardB.phi() << ", " << hardB.m() << ")" << std::endl; + + std::cout << "HardC : user_index = " << hardC.user_index() << ", (Pt,Y,Phi,M) = (" << hardC.pt() << ", " + << hardC.rapidity() << ", " << hardC.phi() << ", " << hardC.m() << ")" << std::endl; + + std::cout << "HardD : user_index = " << hardD.user_index() << ", (Pt,Y,Phi,M) = (" << hardD.pt() << ", " + << hardD.rapidity() << ", " << hardD.phi() << ", " << hardD.m() << ")" << std::endl; + } + + // Check to see if any subjects are counted amongst the "hard" subjets from previous + // lines. NOTE: In Fastjet 3.0, the default "user_index" changed from 0 to -1, so + // this can no longer be used as a designator for the veto of "blankJet" subjets, + // and now switch to pt > some small value. + if (subjet1.pt() > 0.0001) + hardSubjets.push_back(subjet1); + if (subjet2.pt() > 0.0001) + hardSubjets.push_back(subjet2); + if (subjet3.pt() > 0.0001) + hardSubjets.push_back(subjet3); + if (subjet4.pt() > 0.0001) + hardSubjets.push_back(subjet4); + sort(hardSubjets.begin(), hardSubjets.end(), greaterByEtPseudoJet); + + // Use new fastjet functionality to create a Pseudojet from constituents + fastjet::PseudoJet candidate = join(hardSubjets); + // Reset the jet's 4-vector to the "ungroomed" value + candidate.reset_momentum(jetIt->px(), jetIt->py(), jetIt->pz(), jetIt->e()); + + if (verbose_) { + std::cout << "Final top-jet candidate: (Pt,Y,Phi,M) = (" << candidate.pt() << ", " << candidate.rapidity() << ", " + << candidate.phi() << ", " << candidate.m() << ")" << std::endl; + std::vector pieces = candidate.pieces(); + std::cout << "Number of pieces = " << pieces.size() << std::endl; + for (std::vector::const_iterator ibegin = pieces.begin(), iend = pieces.end(), i = ibegin; + i != iend; + ++i) { + std::cout << " Piece : " << i - ibegin << ", (Pt,Y,Phi,M) = (" << i->pt() << ", " << i->rapidity() << ", " + << i->phi() << ", " << i->m() << ")" << std::endl; + } + } + // Add to the list + hardjetsOutput.push_back(candidate); + } +} //----------------------------------------------------------------------- // determine whether two clusters (made of calorimeter towers) are living on "adjacent" cells. if they are, then @@ -264,117 +292,133 @@ void CATopJetAlgorithm::run( const vector & cell_particles, // // From Sal: Ignoring genjet case // -bool CATopJetAlgorithm::adjacentCells(const fastjet::PseudoJet & jet1, const fastjet::PseudoJet & jet2, - const vector & cell_particles, - const fastjet::ClusterSequence & theClusterSequence, - double nCellMin ) const { - - - double eta1 = jet1.rapidity(); - double phi1 = jet1.phi(); - double eta2 = jet2.rapidity(); - double phi2 = jet2.phi(); - - double deta = abs(eta2 - eta1) / 0.087; - double dphi = fabs( reco::deltaPhi(phi2,phi1) ) / 0.087; - - return ( ( deta + dphi ) <= nCellMin ); -} +bool CATopJetAlgorithm::adjacentCells(const fastjet::PseudoJet& jet1, + const fastjet::PseudoJet& jet2, + const vector& cell_particles, + const fastjet::ClusterSequence& theClusterSequence, + double nCellMin) const { + double eta1 = jet1.rapidity(); + double phi1 = jet1.phi(); + double eta2 = jet2.rapidity(); + double phi2 = jet2.phi(); + double deta = abs(eta2 - eta1) / 0.087; + double dphi = fabs(reco::deltaPhi(phi2, phi1)) / 0.087; + return ((deta + dphi) <= nCellMin); +} //------------------------------------------------------------------------- // attempt to decompose a jet into "hard" subjets, where hardness is set by ptHard // -bool CATopJetAlgorithm::decomposeJet(const fastjet::PseudoJet & theJet, - const fastjet::ClusterSequence & theClusterSequence, - const vector & cell_particles, - double ptHard, double nCellMin, double deltarcut, - fastjet::PseudoJet & ja, fastjet::PseudoJet & jb, - vector & leftovers) const { - - bool goodBreak; - fastjet::PseudoJet j = theJet; - double InputObjectPt = j.perp(); - if ( verbose_ )cout<<"Input Object Pt = "< shouldn't have decomposed - } - - if ( verbose_ )cout<<"clusters pass distance cut"< ptHard && jb.perp() > ptHard){ - if ( verbose_ )cout<<"two hard clusters. done"< jb.perp()) { // broke into one hard and one soft, ditch the soft one and try again - if ( verbose_ )cout<<"ja hard jb soft. try to split hard. j = ja"< particles = theClusterSequence.constituents(jb); - leftovers.insert(leftovers.end(),particles.begin(),particles.end()); - } - else { - if ( verbose_ )cout<<"ja hard jb soft. try to split hard. j = jb"< particles = theClusterSequence.constituents(ja); - leftovers.insert(leftovers.end(),particles.begin(),particles.end()); - } - } - - if ( verbose_ )cout<<"did not decluster."<& cell_particles, + double ptHard, + double nCellMin, + double deltarcut, + fastjet::PseudoJet& ja, + fastjet::PseudoJet& jb, + vector& leftovers) const { + bool goodBreak; + fastjet::PseudoJet j = theJet; + double InputObjectPt = j.perp(); + if (verbose_) + cout << "Input Object Pt = " << InputObjectPt << endl; + if (verbose_) + cout << "ptHard = " << ptHard << endl; + leftovers.clear(); + if (verbose_) + cout << "start while loop" << endl; + + while (true) { // watch out for infinite loop! + goodBreak = theClusterSequence.has_parents(j, ja, jb); + if (!goodBreak) { + if (verbose_) + cout << "bad break. this is one cell. can't decluster anymore." << endl; + break; // this is one cell, can't decluster anymore + } + + if (verbose_) + cout << "good break. ja Pt = " << ja.perp() << " jb Pt = " << jb.perp() << endl; + + /// Adjacency Requirement /// + + // check if clusters are adjacent using a constant deltar adjacency. + double clusters_deltar = fabs(ja.eta() - jb.eta()) + fabs(deltaPhi(ja.phi(), jb.phi())); + + if (verbose_ && useAdjacency_ == 1) + cout << "clusters_deltar = " << clusters_deltar << endl; + if (verbose_ && useAdjacency_ == 1) + cout << "deltar cut = " << deltarcut << endl; + + if (useAdjacency_ == 1 && clusters_deltar < deltarcut) { + if (verbose_) + cout << "clusters too close. consant adj. break." << endl; + break; + } + + // Check if clusters are adjacent using a DeltaR adjacency which is a function of pT. + double clusters_deltaR = deltaR(ja.rapidity(), ja.phi(), jb.rapidity(), jb.phi()); + + if (verbose_ && useAdjacency_ == 2) + cout << "clusters_deltaR = " << clusters_deltaR << endl; + if (verbose_ && useAdjacency_ == 2) + cout << "0.4-0.0004*InputObjectPt = " << 0.4 - 0.0004 * InputObjectPt << endl; + + if (useAdjacency_ == 2 && clusters_deltaR < 0.4 - 0.0004 * InputObjectPt) { + if (verbose_) + cout << "clusters too close. modified adj. break." << endl; + break; + } + + // Check if clusters are adjacent in the calorimeter. + if (useAdjacency_ == 3 && adjacentCells(ja, jb, cell_particles, theClusterSequence, nCellMin)) { + if (verbose_) + cout << "clusters too close in the calorimeter. calorimeter adj. break." << endl; + break; // the clusters are "adjacent" in the calorimeter => shouldn't have decomposed + } + + if (verbose_) + cout << "clusters pass distance cut" << endl; + + /// Pt Fraction Requirement /// + + if (verbose_) + cout << "ptHard = " << ptHard << endl; + + if (ja.perp() < ptHard && jb.perp() < ptHard) { + if (verbose_) + cout << "two soft clusters. dead end" << endl; + break; // broke into two soft clusters, dead end + } + + if (ja.perp() > ptHard && jb.perp() > ptHard) { + if (verbose_) + cout << "two hard clusters. done" << endl; + return true; // broke into two hard clusters, we're done! + } + + else if (ja.perp() > jb.perp()) { // broke into one hard and one soft, ditch the soft one and try again + if (verbose_) + cout << "ja hard jb soft. try to split hard. j = ja" << endl; + j = ja; + vector particles = theClusterSequence.constituents(jb); + leftovers.insert(leftovers.end(), particles.begin(), particles.end()); + } else { + if (verbose_) + cout << "ja hard jb soft. try to split hard. j = jb" << endl; + j = jb; + vector particles = theClusterSequence.constituents(ja); + leftovers.insert(leftovers.end(), particles.begin(), particles.end()); + } + } + + if (verbose_) + cout << "did not decluster." << endl; // did not decluster into hard subjets + + ja.reset(0, 0, 0, 0); + jb.reset(0, 0, 0, 0); + leftovers.clear(); + return false; } diff --git a/RecoJets/JetAlgorithms/src/CATopJetHelper.cc b/RecoJets/JetAlgorithms/src/CATopJetHelper.cc index 5d3f533191ea1..3c1ef096a6b34 100644 --- a/RecoJets/JetAlgorithms/src/CATopJetHelper.cc +++ b/RecoJets/JetAlgorithms/src/CATopJetHelper.cc @@ -1,59 +1,56 @@ #include "RecoJets/JetAlgorithms/interface/CATopJetHelper.h" - struct GreaterByPtCandPtr { - bool operator()( const edm::Ptr & t1, const edm::Ptr & t2 ) const { + bool operator()(const edm::Ptr& t1, const edm::Ptr& t2) const { return t1->pt() > t2->pt(); } }; - -reco::CATopJetProperties CATopJetHelper::operator()( reco::Jet const & ihardJet ) const { +reco::CATopJetProperties CATopJetHelper::operator()(reco::Jet const& ihardJet) const { reco::CATopJetProperties properties; // Get subjets reco::Jet::Constituents subjets = ihardJet.getJetConstituents(); properties.nSubJets = subjets.size(); // number of subjets - properties.topMass = ihardJet.mass(); // jet mass - properties.wMass = 99999.; // best W mass - properties.minMass = 999999.; // minimum mass pairing + properties.topMass = ihardJet.mass(); // jet mass + properties.wMass = 99999.; // best W mass + properties.minMass = 999999.; // minimum mass pairing // Require at least three subjets in all cases, if not, untagged - if ( properties.nSubJets >= 3 ) { - + if (properties.nSubJets >= 3) { // Take the highest 3 pt subjets for cuts - sort ( subjets.begin(), subjets.end(), GreaterByPtCandPtr() ); - - // Now look at the subjets that were formed - for ( int isub = 0; isub < 2; ++isub ) { + sort(subjets.begin(), subjets.end(), GreaterByPtCandPtr()); + // Now look at the subjets that were formed + for (int isub = 0; isub < 2; ++isub) { // Get this subjet reco::Jet::Constituent icandJet = subjets[isub]; // Now look at the "other" subjets than this one, form the minimum invariant mass // pairing, as well as the "closest" combination to the W mass - for ( int jsub = isub + 1; jsub < 3; ++jsub ) { - - // Get the second subjet - reco::Jet::Constituent jcandJet = subjets[jsub]; - - reco::Candidate::LorentzVector wCand = icandJet->p4() + jcandJet->p4(); - - // Get the candidate mass - double imw = wCand.mass(); - - // Find the combination closest to the W mass - if ( fabs( imw - WMass_ ) < fabs(properties.wMass - WMass_) ) { - properties.wMass = imw; - } - // Find the minimum mass pairing. - if ( fabs( imw ) < properties.minMass ) { - properties.minMass = imw; - } - }// end second loop over subjets - }// end first loop over subjets - }// endif 3 subjets - - if (properties.minMass == 999999){properties.minMass=-1;} + for (int jsub = isub + 1; jsub < 3; ++jsub) { + // Get the second subjet + reco::Jet::Constituent jcandJet = subjets[jsub]; + + reco::Candidate::LorentzVector wCand = icandJet->p4() + jcandJet->p4(); + + // Get the candidate mass + double imw = wCand.mass(); + + // Find the combination closest to the W mass + if (fabs(imw - WMass_) < fabs(properties.wMass - WMass_)) { + properties.wMass = imw; + } + // Find the minimum mass pairing. + if (fabs(imw) < properties.minMass) { + properties.minMass = imw; + } + } // end second loop over subjets + } // end first loop over subjets + } // endif 3 subjets + + if (properties.minMass == 999999) { + properties.minMass = -1; + } return properties; } diff --git a/RecoJets/JetAlgorithms/src/CMSBoostedTauSeedingAlgorithm.cc b/RecoJets/JetAlgorithms/src/CMSBoostedTauSeedingAlgorithm.cc index c2e6993106776..dd07224634883 100644 --- a/RecoJets/JetAlgorithms/src/CMSBoostedTauSeedingAlgorithm.cc +++ b/RecoJets/JetAlgorithms/src/CMSBoostedTauSeedingAlgorithm.cc @@ -16,32 +16,35 @@ // You should have received a copy of the GNU General Public License // along with this code. If not, see . -//CG: From CMSSW 8_0_X cut on eta subjets <3. Anyways taus are cut at 2.3 +//CG: From CMSSW 8_0_X cut on eta subjets <3. Anyways taus are cut at 2.3 //---------------------------------------------------------------------- #include "RecoJets/JetAlgorithms/interface/CMSBoostedTauSeedingAlgorithm.h" -FASTJET_BEGIN_NAMESPACE // defined in fastjet/internal/base.hh - -namespace contrib{ - +FASTJET_BEGIN_NAMESPACE // defined in fastjet/internal/base.hh + namespace contrib { ///////////////////////////// // constructor - CMSBoostedTauSeedingAlgorithm::CMSBoostedTauSeedingAlgorithm(double iminPt, - double iminMassDrop, double imaxMassDrop, - double iminY, double imaxY, - double iminDeltaR, double imaxDeltaR, - int maxDepth, - int verbosity) - : ptMin_(iminPt), - muMin_(iminMassDrop), muMax_(imaxMassDrop), - yMin_(iminY), yMax_(imaxY), - dRMin_(iminDeltaR), dRMax_(imaxDeltaR), - maxDepth_(maxDepth), - verbosity_(verbosity) - {} + CMSBoostedTauSeedingAlgorithm::CMSBoostedTauSeedingAlgorithm(double iminPt, + double iminMassDrop, + double imaxMassDrop, + double iminY, + double imaxY, + double iminDeltaR, + double imaxDeltaR, + int maxDepth, + int verbosity) + : ptMin_(iminPt), + muMin_(iminMassDrop), + muMax_(imaxMassDrop), + yMin_(iminY), + yMax_(imaxY), + dRMin_(iminDeltaR), + dRMax_(imaxDeltaR), + maxDepth_(maxDepth), + verbosity_(verbosity) {} ///////////////////////////// // description @@ -51,141 +54,154 @@ namespace contrib{ return oss.str(); } - ///////////////////////////// - void CMSBoostedTauSeedingAlgorithm::dumpSubJetStructure(const fastjet::PseudoJet& jet, int depth, int maxDepth, const std::string& depth_and_idx_string) const - { - if ( maxDepth != -1 && depth > maxDepth ) return; - fastjet::PseudoJet subjet1, subjet2; + void CMSBoostedTauSeedingAlgorithm::dumpSubJetStructure( + const fastjet::PseudoJet& jet, int depth, int maxDepth, const std::string& depth_and_idx_string) const { + if (maxDepth != -1 && depth > maxDepth) + return; + fastjet::PseudoJet subjet1, subjet2; bool hasSubjets = jet.has_parents(subjet1, subjet2); - if ( !hasSubjets ) return; + if (!hasSubjets) + return; std::string depth_and_idx_string_subjet1 = depth_and_idx_string; - if ( depth_and_idx_string_subjet1.length() > 0 ) depth_and_idx_string_subjet1.append("."); + if (depth_and_idx_string_subjet1.length() > 0) + depth_and_idx_string_subjet1.append("."); depth_and_idx_string_subjet1.append("0"); - for ( int iSpace = 0; iSpace < depth; ++iSpace ) { + for (int iSpace = 0; iSpace < depth; ++iSpace) { std::cout << " "; } - std::cout << " jetConstituent #" << depth_and_idx_string_subjet1 << " (depth = " << depth << "): Pt = " << subjet1.pt() << "," - << " eta = " << subjet1.eta() << ", phi = " << subjet1.phi() << ", mass = " << subjet1.m() - << " (constituents = " << subjet1.constituents().size() << ")" << std::endl; + std::cout << " jetConstituent #" << depth_and_idx_string_subjet1 << " (depth = " << depth + << "): Pt = " << subjet1.pt() << "," + << " eta = " << subjet1.eta() << ", phi = " << subjet1.phi() << ", mass = " << subjet1.m() + << " (constituents = " << subjet1.constituents().size() << ")" << std::endl; dumpSubJetStructure(subjet1, depth + 1, maxDepth, depth_and_idx_string_subjet1); std::string depth_and_idx_string_subjet2 = depth_and_idx_string; - if ( depth_and_idx_string_subjet2.length() > 0 ) depth_and_idx_string_subjet2.append("."); + if (depth_and_idx_string_subjet2.length() > 0) + depth_and_idx_string_subjet2.append("."); depth_and_idx_string_subjet2.append("1"); - for ( int iSpace = 0; iSpace < depth; ++iSpace ) { + for (int iSpace = 0; iSpace < depth; ++iSpace) { std::cout << " "; } - std::cout << " jetConstituent #" << depth_and_idx_string_subjet2 << " (depth = " << depth << "): Pt = " << subjet2.pt() << "," - << " eta = " << subjet2.eta() << ", phi = " << subjet2.phi() << ", mass = " << subjet2.m() - << " (constituents = " << subjet2.constituents().size() << ")" << std::endl; + std::cout << " jetConstituent #" << depth_and_idx_string_subjet2 << " (depth = " << depth + << "): Pt = " << subjet2.pt() << "," + << " eta = " << subjet2.eta() << ", phi = " << subjet2.phi() << ", mass = " << subjet2.m() + << " (constituents = " << subjet2.constituents().size() << ")" << std::endl; dumpSubJetStructure(subjet2, depth + 1, maxDepth, depth_and_idx_string_subjet2); - for ( int iSpace = 0; iSpace < depth; ++iSpace ) { + for (int iSpace = 0; iSpace < depth; ++iSpace) { std::cout << " "; } double dR = subjet1.delta_R(subjet2); - std::cout << " (mass-drop @ " << depth_and_idx_string << " = " << std::max(subjet1.m(), subjet2.m())/jet.m() << ", dR = " << dR << ")" << std::endl; + std::cout << " (mass-drop @ " << depth_and_idx_string << " = " << std::max(subjet1.m(), subjet2.m()) / jet.m() + << ", dR = " << dR << ")" << std::endl; } - std::pair CMSBoostedTauSeedingAlgorithm::findSubjets(const PseudoJet& jet, int depth, bool& subjetsFound) const - { - const float etaMax_ = 3.0; // cut on eta subjets <3. Anyway taus are cut at 2.3 - if ( verbosity_ >= 2 ) { + std::pair CMSBoostedTauSeedingAlgorithm::findSubjets( + const PseudoJet& jet, int depth, bool& subjetsFound) const { + const float etaMax_ = 3.0; // cut on eta subjets <3. Anyway taus are cut at 2.3 + if (verbosity_ >= 2) { std::cout << ":" << std::endl; - std::cout << " jet: Pt = " << jet.pt() << ", eta = " << jet.eta() << ", phi = " << jet.phi() << ", mass = " << jet.m() << std::endl; + std::cout << " jet: Pt = " << jet.pt() << ", eta = " << jet.eta() << ", phi = " << jet.phi() + << ", mass = " << jet.m() << std::endl; } PseudoJet subjet1, subjet2; bool hasSubjets = jet.has_parents(subjet1, subjet2); - if ( hasSubjets && (maxDepth_ == -1 || depth <= maxDepth_) ) { + if (hasSubjets && (maxDepth_ == -1 || depth <= maxDepth_)) { // make subjet1 the more massive jet - if ( subjet1.m2() < subjet2.m2() ) { - std::swap(subjet1, subjet2); + if (subjet1.m2() < subjet2.m2()) { + std::swap(subjet1, subjet2); } double dR = subjet1.delta_R(subjet2); double kT = subjet1.kt_distance(subjet2); - double mu = ( jet.m() > 0. ) ? - sqrt(std::max(subjet1.m2(), subjet2.m2())/jet.m2()) : -1.; + double mu = (jet.m() > 0.) ? sqrt(std::max(subjet1.m2(), subjet2.m2()) / jet.m2()) : -1.; // check if subjets pass selection required for seeding boosted tau reconstruction - if ( subjet1.pt() > ptMin_ && fabs(subjet1.eta()) < etaMax_ && subjet2.pt() > ptMin_ && fabs(subjet2.eta()) < etaMax_ && dR > dRMin_ && dR < dRMax_ && mu > muMin_ && mu < muMax_ && kT < (yMax_*jet.m2()) && kT > (yMin_*jet.m2()) ) { - subjetsFound = true; - return std::make_pair(subjet1, subjet2); - } else if ( subjet1.pt() > ptMin_ ) { - return findSubjets(subjet1, depth + 1, subjetsFound); - } else if ( subjet2.pt() > ptMin_ ) { - return findSubjets(subjet2, depth + 1, subjetsFound); - } + if (subjet1.pt() > ptMin_ && fabs(subjet1.eta()) < etaMax_ && subjet2.pt() > ptMin_ && + fabs(subjet2.eta()) < etaMax_ && dR > dRMin_ && dR < dRMax_ && mu > muMin_ && mu < muMax_ && + kT < (yMax_ * jet.m2()) && kT > (yMin_ * jet.m2())) { + subjetsFound = true; + return std::make_pair(subjet1, subjet2); + } else if (subjet1.pt() > ptMin_) { + return findSubjets(subjet1, depth + 1, subjetsFound); + } else if (subjet2.pt() > ptMin_) { + return findSubjets(subjet2, depth + 1, subjetsFound); + } } subjetsFound = false; PseudoJet dummy_subjet1, dummy_subjet2; - return std::make_pair(dummy_subjet1, dummy_subjet2); + return std::make_pair(dummy_subjet1, dummy_subjet2); } - PseudoJet CMSBoostedTauSeedingAlgorithm::result(const PseudoJet& jet) const - { - if ( verbosity_ >= 1 ) { + PseudoJet CMSBoostedTauSeedingAlgorithm::result(const PseudoJet& jet) const { + if (verbosity_ >= 1) { std::cout << ":" << std::endl; - std::cout << " jet: Pt = " << jet.pt() << ", eta = " << jet.eta() << ", phi = " << jet.phi() << ", mass = " << jet.m() << std::endl; + std::cout << " jet: Pt = " << jet.pt() << ", eta = " << jet.eta() << ", phi = " << jet.phi() + << ", mass = " << jet.m() << std::endl; } - if ( verbosity_ >= 2 ) { + if (verbosity_ >= 2) { dumpSubJetStructure(jet, 0, maxDepth_, ""); } bool subjetsFound = false; std::pair subjets = findSubjets(jet, 0, subjetsFound); - if ( subjetsFound ) { + if (subjetsFound) { // fill structure for returning result PseudoJet subjet1 = subjets.first; PseudoJet subjet2 = subjets.second; - if ( verbosity_ >= 1 ) { - std::cout << "before recombination:" << std::endl; - std::cout << " subjet #1: Pt = " << subjet1.pt() << ", eta = " << subjet1.eta() << ", phi = " << subjet1.phi() << ", mass = " << subjet1.m() << std::endl; - std::cout << " subjet #2: Pt = " << subjet2.pt() << ", eta = " << subjet2.eta() << ", phi = " << subjet2.phi() << ", mass = " << subjet2.m() << std::endl; + if (verbosity_ >= 1) { + std::cout << "before recombination:" << std::endl; + std::cout << " subjet #1: Pt = " << subjet1.pt() << ", eta = " << subjet1.eta() << ", phi = " << subjet1.phi() + << ", mass = " << subjet1.m() << std::endl; + std::cout << " subjet #2: Pt = " << subjet2.pt() << ", eta = " << subjet2.eta() << ", phi = " << subjet2.phi() + << ", mass = " << subjet2.m() << std::endl; } const JetDefinition::Recombiner* rec = jet.associated_cluster_sequence()->jet_def().recombiner(); PseudoJet result_local = join(subjet1, subjet2, *rec); - if ( verbosity_ >= 1 ) { - std::cout << "after recombination:" << std::endl; - std::vector subjets = result_local.pieces(); - int idx_subjet = 0; - for ( std::vector::const_iterator subjet = subjets.begin(); - subjet != subjets.end(); ++subjet ) { - std::cout << " subjet #" << idx_subjet << ": Pt = " << subjet->pt() << ", eta = " << subjet->eta() << ", phi = " << subjet->phi() << ", mass = " << subjet->m() - << " (#constituents = " << subjet->constituents().size() << ")" << std::endl; - std::vector constituents = subjet->constituents(); - int idx_constituent = 0; - for ( std::vector::const_iterator constituent = constituents.begin(); - constituent != constituents.end(); ++constituent ) { - if ( constituent->pt() < 1.e-3 ) continue; // CV: skip ghosts - std::cout << " constituent #" << idx_constituent << ": Pt = " << constituent->pt() << ", eta = " << constituent->eta() << ", phi = " << constituent->phi() << "," - << " mass = " << constituent->m() << std::endl; - ++idx_constituent; - } - ++idx_subjet; - } + if (verbosity_ >= 1) { + std::cout << "after recombination:" << std::endl; + std::vector subjets = result_local.pieces(); + int idx_subjet = 0; + for (std::vector::const_iterator subjet = subjets.begin(); subjet != subjets.end(); + ++subjet) { + std::cout << " subjet #" << idx_subjet << ": Pt = " << subjet->pt() << ", eta = " << subjet->eta() + << ", phi = " << subjet->phi() << ", mass = " << subjet->m() + << " (#constituents = " << subjet->constituents().size() << ")" << std::endl; + std::vector constituents = subjet->constituents(); + int idx_constituent = 0; + for (std::vector::const_iterator constituent = constituents.begin(); + constituent != constituents.end(); + ++constituent) { + if (constituent->pt() < 1.e-3) + continue; // CV: skip ghosts + std::cout << " constituent #" << idx_constituent << ": Pt = " << constituent->pt() + << ", eta = " << constituent->eta() << ", phi = " << constituent->phi() << "," + << " mass = " << constituent->m() << std::endl; + ++idx_constituent; + } + ++idx_subjet; + } } CMSBoostedTauSeedingAlgorithmStructure* s = new CMSBoostedTauSeedingAlgorithmStructure(result_local); //s->_original_jet = jet; - s->_mu = ( jet.m2() > 0. ) ? sqrt(std::max(subjet1.m2(), subjet2.m2())/jet.m2()) : 0.; - s->_y = ( jet.m2() > 0. ) ? subjet1.kt_distance(subjet2)/jet.m2() : 0.; + s->_mu = (jet.m2() > 0.) ? sqrt(std::max(subjet1.m2(), subjet2.m2()) / jet.m2()) : 0.; + s->_y = (jet.m2() > 0.) ? subjet1.kt_distance(subjet2) / jet.m2() : 0.; s->_dR = subjet1.delta_R(subjet2); s->_pt = subjet2.pt(); - + result_local.set_structure_shared_ptr(SharedPtr(s)); return result_local; } else { // no subjets for seeding boosted tau reconstruction found, return an empty PseudoJet - if ( verbosity_ >= 1 ) { - std::cout << "No subjets found." << std::endl; + if (verbosity_ >= 1) { + std::cout << "No subjets found." << std::endl; } return PseudoJet(); } } +} // namespace contrib -} // namespace contrib - FASTJET_END_NAMESPACE diff --git a/RecoJets/JetAlgorithms/src/CMSInsideOutAlgorithm.cc b/RecoJets/JetAlgorithms/src/CMSInsideOutAlgorithm.cc index 98b57f1fe23ca..d2057cfbcc914 100644 --- a/RecoJets/JetAlgorithms/src/CMSInsideOutAlgorithm.cc +++ b/RecoJets/JetAlgorithms/src/CMSInsideOutAlgorithm.cc @@ -2,67 +2,55 @@ #include "RecoJets/JetAlgorithms/interface/CompoundPseudoJet.h" - using namespace std; -void -CMSInsideOutAlgorithm::run(const std::vector& fInput, std::vector & fOutput) -{ - - //make a list of input objects - list input; - for (std::vector::const_iterator candIter = fInput.begin(); - candIter != fInput.end(); - ++candIter) { - input.push_back(*candIter); - } - - while( !input.empty() && input.front().perp() > seedThresholdPt_ ) - { - //get seed eta/phi - double seedEta = input.front().eta(); - double seedPhi = input.front().phi(); - - //find iterators to those objects that are in the max cone size - list maxCone; - // add seed, then test elements after seed - inputListIter iCand = input.begin(); - maxCone.push_back(iCand++); - for(; iCand != input.end(); ++iCand) - { - const fastjet::PseudoJet& candidate = *iCand; - if( reco::deltaR2(seedEta, candidate.eta(), seedPhi, candidate.phi()) < maxSizeSquared_ ) - maxCone.push_back(iCand); - } - //sort objects by increasing DR about the seed directions - maxCone.sort(ListIteratorLesserByDeltaR(seedEta, seedPhi)); - list::const_iterator position = maxCone.begin(); - bool limitReached = false; - double totalET = (**position).perp(); +void CMSInsideOutAlgorithm::run(const std::vector& fInput, + std::vector& fOutput) { + //make a list of input objects + list input; + for (std::vector::const_iterator candIter = fInput.begin(); candIter != fInput.end(); + ++candIter) { + input.push_back(*candIter); + } + + while (!input.empty() && input.front().perp() > seedThresholdPt_) { + //get seed eta/phi + double seedEta = input.front().eta(); + double seedPhi = input.front().phi(); + + //find iterators to those objects that are in the max cone size + list maxCone; + // add seed, then test elements after seed + inputListIter iCand = input.begin(); + maxCone.push_back(iCand++); + for (; iCand != input.end(); ++iCand) { + const fastjet::PseudoJet& candidate = *iCand; + if (reco::deltaR2(seedEta, candidate.eta(), seedPhi, candidate.phi()) < maxSizeSquared_) + maxCone.push_back(iCand); + } + //sort objects by increasing DR about the seed directions + maxCone.sort(ListIteratorLesserByDeltaR(seedEta, seedPhi)); + list::const_iterator position = maxCone.begin(); + bool limitReached = false; + double totalET = (**position).perp(); + ++position; + while (position != maxCone.end() && !limitReached) { + const fastjet::PseudoJet& theCandidate = **position; + double candidateET = theCandidate.perp() + totalET; + double candDR2 = reco::deltaR2(seedEta, theCandidate.eta(), seedPhi, theCandidate.phi()); + if (candDR2 < minSizeSquared_ || candDR2 * candidateET * candidateET < growthParameterSquared_) + totalET = candidateET; + else + limitReached = true; ++position; - while(position != maxCone.end() && !limitReached) - { - const fastjet::PseudoJet& theCandidate = **position; - double candidateET = theCandidate.perp() + totalET; - double candDR2 = reco::deltaR2(seedEta, theCandidate.eta(), seedPhi, theCandidate.phi()); - if( candDR2 < minSizeSquared_ || candDR2*candidateET*candidateET < growthParameterSquared_ ) - totalET = candidateET; - else - limitReached = true; - ++position; - } - //turn this into a final jet - fastjet::PseudoJet final; - for(list::const_iterator iNewJet = maxCone.begin(); - iNewJet != position; - ++iNewJet) - { - final += **iNewJet; - input.erase(*iNewJet); - } - fOutput.push_back(final); - } // end loop over seeds - sort (fOutput.begin (), fOutput.end (), greaterByEtPseudoJet); + } + //turn this into a final jet + fastjet::PseudoJet final; + for (list::const_iterator iNewJet = maxCone.begin(); iNewJet != position; ++iNewJet) { + final += **iNewJet; + input.erase(*iNewJet); + } + fOutput.push_back(final); + } // end loop over seeds + sort(fOutput.begin(), fOutput.end(), greaterByEtPseudoJet); } - - diff --git a/RecoJets/JetAlgorithms/src/FastPrunePlugin.cc b/RecoJets/JetAlgorithms/src/FastPrunePlugin.cc index b42472f92df87..e0a845e2e8200 100644 --- a/RecoJets/JetAlgorithms/src/FastPrunePlugin.cc +++ b/RecoJets/JetAlgorithms/src/FastPrunePlugin.cc @@ -15,93 +15,87 @@ using namespace std; using namespace fastjet; -FastPrunePlugin::FastPrunePlugin (const JetDefinition & find_definition, - const JetDefinition & prune_definition, - const double & zcut, - const double & Rcut_factor) : - _find_definition(find_definition), - _prune_definition(prune_definition), - _minpT(20.), - _unpruned_seq(nullptr), - _pruned_recombiner(nullptr), - _cut_setter(new DefaultCutSetter(zcut, Rcut_factor)) -{ - // If the passed prune_definition (copied into _prune_def) has an external - // recombiner, use it. Otherwise, create our own DefaultRecombiner. We - // could just point to _prune_definition's DefaultRecombiner, but FastJet - // actually sets this to use external_scheme later when we set - // _prune_definition's Recombiner to be a PrunedRecombiner. (Calling - // JetDefinition::set_recombiner() also calls jetdef._default_recombiner = - // DefaultRecombiner(external_scheme) as a sanity check to keep you from - // using it.) - RecombinationScheme scheme = _prune_definition.recombination_scheme(); - if (scheme == external_scheme) - _pruned_recombiner = new PrunedRecombiner(_prune_definition.recombiner(), zcut, 0.0); - else - _pruned_recombiner = new PrunedRecombiner(scheme, zcut, 0.0); +FastPrunePlugin::FastPrunePlugin(const JetDefinition& find_definition, + const JetDefinition& prune_definition, + const double& zcut, + const double& Rcut_factor) + : _find_definition(find_definition), + _prune_definition(prune_definition), + _minpT(20.), + _unpruned_seq(nullptr), + _pruned_recombiner(nullptr), + _cut_setter(new DefaultCutSetter(zcut, Rcut_factor)) { + // If the passed prune_definition (copied into _prune_def) has an external + // recombiner, use it. Otherwise, create our own DefaultRecombiner. We + // could just point to _prune_definition's DefaultRecombiner, but FastJet + // actually sets this to use external_scheme later when we set + // _prune_definition's Recombiner to be a PrunedRecombiner. (Calling + // JetDefinition::set_recombiner() also calls jetdef._default_recombiner = + // DefaultRecombiner(external_scheme) as a sanity check to keep you from + // using it.) + RecombinationScheme scheme = _prune_definition.recombination_scheme(); + if (scheme == external_scheme) + _pruned_recombiner = new PrunedRecombiner(_prune_definition.recombiner(), zcut, 0.0); + else + _pruned_recombiner = new PrunedRecombiner(scheme, zcut, 0.0); } -FastPrunePlugin::FastPrunePlugin (const JetDefinition & find_definition, - const JetDefinition & prune_definition, - const JetDefinition::Recombiner* recomb, - const double & zcut, - const double & Rcut_factor) : - _find_definition(find_definition), - _prune_definition(prune_definition), - _minpT(20.), - _unpruned_seq(nullptr), - _pruned_recombiner(new PrunedRecombiner(recomb, zcut, 0.0)), - _cut_setter(new DefaultCutSetter(zcut, Rcut_factor)) -{} - -FastPrunePlugin::FastPrunePlugin (const JetDefinition & find_definition, - const JetDefinition & prune_definition, - CutSetter* const cut_setter) : - _find_definition(find_definition), - _prune_definition(prune_definition), - _minpT(20.), - _unpruned_seq(nullptr), - _pruned_recombiner(nullptr), - _cut_setter(cut_setter) -{ - // See comments in first constructor - RecombinationScheme scheme = _prune_definition.recombination_scheme(); - if (scheme == external_scheme) - _pruned_recombiner = new PrunedRecombiner(_prune_definition.recombiner()); - else - _pruned_recombiner = new PrunedRecombiner(scheme); +FastPrunePlugin::FastPrunePlugin(const JetDefinition& find_definition, + const JetDefinition& prune_definition, + const JetDefinition::Recombiner* recomb, + const double& zcut, + const double& Rcut_factor) + : _find_definition(find_definition), + _prune_definition(prune_definition), + _minpT(20.), + _unpruned_seq(nullptr), + _pruned_recombiner(new PrunedRecombiner(recomb, zcut, 0.0)), + _cut_setter(new DefaultCutSetter(zcut, Rcut_factor)) {} + +FastPrunePlugin::FastPrunePlugin(const JetDefinition& find_definition, + const JetDefinition& prune_definition, + CutSetter* const cut_setter) + : _find_definition(find_definition), + _prune_definition(prune_definition), + _minpT(20.), + _unpruned_seq(nullptr), + _pruned_recombiner(nullptr), + _cut_setter(cut_setter) { + // See comments in first constructor + RecombinationScheme scheme = _prune_definition.recombination_scheme(); + if (scheme == external_scheme) + _pruned_recombiner = new PrunedRecombiner(_prune_definition.recombiner()); + else + _pruned_recombiner = new PrunedRecombiner(scheme); } -FastPrunePlugin::FastPrunePlugin (const JetDefinition & find_definition, - const JetDefinition & prune_definition, - CutSetter* const cut_setter, - const JetDefinition::Recombiner* recomb) : - _find_definition(find_definition), - _prune_definition(prune_definition), - _minpT(20.), - _unpruned_seq(nullptr), - _pruned_recombiner(new PrunedRecombiner(recomb)), - _cut_setter(cut_setter) -{} - -string FastPrunePlugin::description () const { - ostringstream desc; - - desc << "Pruned jet algorithm \n" - << "----------------------- \n" - << "Jet finder: " << _find_definition.description() - << "\n----------------------- \n" - << "Prune jets with: " << _prune_definition.description() - << "\n----------------------- \n" - << "Pruning parameters: " - << "zcut = " << _cut_setter->zcut << ", " - << "Rcut_factor = "; - if (DefaultCutSetter *cs = dynamic_cast(_cut_setter)) - desc << cs->Rcut_factor; - else - desc << "[dynamic]"; - desc << "\n" - << "----------------------- \n" ; +FastPrunePlugin::FastPrunePlugin(const JetDefinition& find_definition, + const JetDefinition& prune_definition, + CutSetter* const cut_setter, + const JetDefinition::Recombiner* recomb) + : _find_definition(find_definition), + _prune_definition(prune_definition), + _minpT(20.), + _unpruned_seq(nullptr), + _pruned_recombiner(new PrunedRecombiner(recomb)), + _cut_setter(cut_setter) {} + +string FastPrunePlugin::description() const { + ostringstream desc; + + desc << "Pruned jet algorithm \n" + << "----------------------- \n" + << "Jet finder: " << _find_definition.description() << "\n----------------------- \n" + << "Prune jets with: " << _prune_definition.description() << "\n----------------------- \n" + << "Pruning parameters: " + << "zcut = " << _cut_setter->zcut << ", " + << "Rcut_factor = "; + if (DefaultCutSetter* cs = dynamic_cast(_cut_setter)) + desc << cs->Rcut_factor; + else + desc << "[dynamic]"; + desc << "\n" + << "----------------------- \n"; return desc.str(); } @@ -118,112 +112,104 @@ string FastPrunePlugin::description () const { // children. For this reason, only inclusive_jets() is sensible to use with // the final ClusterSequence. The substructure, e.g., constituents() of a // pruned jet will not include the pruned away branchings. -void FastPrunePlugin::run_clustering(ClusterSequence & input_seq) const { - - // this will be filled in the output_mergings() step - _pruned_subjets.clear(); - - vector inputs = input_seq.jets(); - // Record user_index's so we can match PJ's in pruned jets to PJ's in - // input_seq. - // Use i+1 to distinguish from the default, which in some places appears to - // be 0. - // Note that we're working with a local copy of the input jets, so we don't - // change the indices in input_seq. - for (unsigned int i = 0; i < inputs.size(); i++) - inputs[i].set_user_index(i+1); - - // ClusterSequence for initial (unpruned) jet finding - if(_unpruned_seq) delete _unpruned_seq; - _unpruned_seq = new ClusterSequence(inputs, _find_definition); - - // now, for each jet, construct a pruned version: - vector unpruned_jets = - sorted_by_pt(_unpruned_seq->inclusive_jets(_minpT)); - - for (unsigned int i = 0; i < unpruned_jets.size(); i++) { - _cut_setter->SetCuts(unpruned_jets[i], *_unpruned_seq); - _pruned_recombiner->reset(_cut_setter->zcut, _cut_setter->Rcut); - _prune_definition.set_recombiner(_pruned_recombiner); - - // temp way to get constituents, to compare to new version - vector constituents; - for (size_t j = 0; j < inputs.size(); ++j) - if (_unpruned_seq->object_in_jet(inputs[j], unpruned_jets[i])) { - constituents.push_back(inputs[j]); - } - ClusterSequence pruned_seq(constituents, _prune_definition); - - vector pruned_PJs = _pruned_recombiner->pruned_pseudojets(); - _output_mergings(pruned_seq, pruned_PJs, input_seq); - } +void FastPrunePlugin::run_clustering(ClusterSequence& input_seq) const { + // this will be filled in the output_mergings() step + _pruned_subjets.clear(); + + vector inputs = input_seq.jets(); + // Record user_index's so we can match PJ's in pruned jets to PJ's in + // input_seq. + // Use i+1 to distinguish from the default, which in some places appears to + // be 0. + // Note that we're working with a local copy of the input jets, so we don't + // change the indices in input_seq. + for (unsigned int i = 0; i < inputs.size(); i++) + inputs[i].set_user_index(i + 1); + + // ClusterSequence for initial (unpruned) jet finding + if (_unpruned_seq) + delete _unpruned_seq; + _unpruned_seq = new ClusterSequence(inputs, _find_definition); + + // now, for each jet, construct a pruned version: + vector unpruned_jets = sorted_by_pt(_unpruned_seq->inclusive_jets(_minpT)); + + for (unsigned int i = 0; i < unpruned_jets.size(); i++) { + _cut_setter->SetCuts(unpruned_jets[i], *_unpruned_seq); + _pruned_recombiner->reset(_cut_setter->zcut, _cut_setter->Rcut); + _prune_definition.set_recombiner(_pruned_recombiner); + + // temp way to get constituents, to compare to new version + vector constituents; + for (size_t j = 0; j < inputs.size(); ++j) + if (_unpruned_seq->object_in_jet(inputs[j], unpruned_jets[i])) { + constituents.push_back(inputs[j]); + } + ClusterSequence pruned_seq(constituents, _prune_definition); + + vector pruned_PJs = _pruned_recombiner->pruned_pseudojets(); + _output_mergings(pruned_seq, pruned_PJs, input_seq); + } } - -// Takes the merging structure of "in_seq" and feeds this into "out_seq" using +// Takes the merging structure of "in_seq" and feeds this into "out_seq" using // _plugin_record_{ij,iB}_recombination(). -// PJ's in the input CS should have user_index's that are their (index+1) in +// PJ's in the input CS should have user_index's that are their (index+1) in // _jets() in the output CS (the output CS should be the input CS to // run_clustering()). // This allows us to build up the same jet in out_seq as already exists in -// in_seq. -void FastPrunePlugin::_output_mergings(ClusterSequence & in_seq, - vector & pruned_pseudojets, - ClusterSequence & out_seq) const { - // vector to store the pruned subjets for this jet - vector temp_pruned_subjets; - - vector p = in_seq.jets(); - - // sort this vector so we can binary search it - sort(pruned_pseudojets.begin(), pruned_pseudojets.end()); - - // get the history from in_seq - const vector & hist = in_seq.history(); - vector::const_iterator - iter = hist.begin(); - - // skip particle input elements - while (iter->parent1 == ClusterSequence::InexistentParent) - iter++; - - // Walk through history. PseudoJets in in_seq should have a user_index - // corresponding to their index in out_seq. Note that when we create a - // new PJ via record_ij we need to set the user_index of our local copy. - for (; iter != hist.end(); iter++) { - int new_jet_index = -1; - int jet_index = iter->jetp_index; - int parent1 = iter->parent1; - int parent2 = iter->parent2; - int parent1_index = p[hist[iter->parent1].jetp_index].user_index() - 1; - - if (parent2 == ClusterSequence::BeamJet) { - out_seq.plugin_record_iB_recombination(parent1_index, iter->dij); - } else { - int parent2_index = p[hist[parent2].jetp_index].user_index() - 1; - - // Check if either parent is stored in pruned_pseudojets - // Note that it is the history index that is stored - if (binary_search(pruned_pseudojets.begin(), pruned_pseudojets.end(), - parent2)) { - // pruned away parent2 -- just give child parent1's index - p[jet_index].set_user_index(p[hist[parent1].jetp_index].user_index()); - temp_pruned_subjets.push_back(out_seq.jets()[parent2_index]); - } else if (binary_search(pruned_pseudojets.begin(), pruned_pseudojets.end(), - parent1)) { - // pruned away parent1 -- just give child parent2's index - p[jet_index].set_user_index(p[hist[parent2].jetp_index].user_index()); - temp_pruned_subjets.push_back(out_seq.jets()[parent1_index]); - } else { - // no pruning -- record combination and index for child - out_seq.plugin_record_ij_recombination(parent1_index, parent2_index, - iter->dij, new_jet_index); - p[jet_index].set_user_index(new_jet_index + 1); - } - } - } - - _pruned_subjets.push_back(temp_pruned_subjets); +// in_seq. +void FastPrunePlugin::_output_mergings(ClusterSequence& in_seq, + vector& pruned_pseudojets, + ClusterSequence& out_seq) const { + // vector to store the pruned subjets for this jet + vector temp_pruned_subjets; + + vector p = in_seq.jets(); + + // sort this vector so we can binary search it + sort(pruned_pseudojets.begin(), pruned_pseudojets.end()); + + // get the history from in_seq + const vector& hist = in_seq.history(); + vector::const_iterator iter = hist.begin(); + + // skip particle input elements + while (iter->parent1 == ClusterSequence::InexistentParent) + iter++; + + // Walk through history. PseudoJets in in_seq should have a user_index + // corresponding to their index in out_seq. Note that when we create a + // new PJ via record_ij we need to set the user_index of our local copy. + for (; iter != hist.end(); iter++) { + int new_jet_index = -1; + int jet_index = iter->jetp_index; + int parent1 = iter->parent1; + int parent2 = iter->parent2; + int parent1_index = p[hist[iter->parent1].jetp_index].user_index() - 1; + + if (parent2 == ClusterSequence::BeamJet) { + out_seq.plugin_record_iB_recombination(parent1_index, iter->dij); + } else { + int parent2_index = p[hist[parent2].jetp_index].user_index() - 1; + + // Check if either parent is stored in pruned_pseudojets + // Note that it is the history index that is stored + if (binary_search(pruned_pseudojets.begin(), pruned_pseudojets.end(), parent2)) { + // pruned away parent2 -- just give child parent1's index + p[jet_index].set_user_index(p[hist[parent1].jetp_index].user_index()); + temp_pruned_subjets.push_back(out_seq.jets()[parent2_index]); + } else if (binary_search(pruned_pseudojets.begin(), pruned_pseudojets.end(), parent1)) { + // pruned away parent1 -- just give child parent2's index + p[jet_index].set_user_index(p[hist[parent2].jetp_index].user_index()); + temp_pruned_subjets.push_back(out_seq.jets()[parent1_index]); + } else { + // no pruning -- record combination and index for child + out_seq.plugin_record_ij_recombination(parent1_index, parent2_index, iter->dij, new_jet_index); + p[jet_index].set_user_index(new_jet_index + 1); + } + } + } + + _pruned_subjets.push_back(temp_pruned_subjets); } - - diff --git a/RecoJets/JetAlgorithms/src/FixedGridEnergyDensity.cc b/RecoJets/JetAlgorithms/src/FixedGridEnergyDensity.cc index 5dd36a47cd575..c8a788a5a47dc 100644 --- a/RecoJets/JetAlgorithms/src/FixedGridEnergyDensity.cc +++ b/RecoJets/JetAlgorithms/src/FixedGridEnergyDensity.cc @@ -8,47 +8,55 @@ using namespace reco; using namespace edm; using namespace std; -float FixedGridEnergyDensity::fixedGridRho(EtaRegion etaRegion){ +float FixedGridEnergyDensity::fixedGridRho(EtaRegion etaRegion) { //define the phi bins vector phibins; - for (int i=0;i<10;i++) phibins.push_back(-TMath::Pi()+(2*i+1)*TMath::TwoPi()/20.); + for (int i = 0; i < 10; i++) + phibins.push_back(-TMath::Pi() + (2 * i + 1) * TMath::TwoPi() / 20.); //define the eta bins vector etabins; - if (etaRegion==Central) { - for (int i=0;i<8;++i) etabins.push_back(-2.1+0.6*i); - } else if (etaRegion==Forward) { - for (int i=0;i<10;++i) { - if (i<5) etabins.push_back(-5.1+0.6*i); - else etabins.push_back(2.7+0.6*(i-5)); - } - } else if (etaRegion==All) { - for (int i=0;i<18;++i) etabins.push_back(-5.1+0.6*i); + if (etaRegion == Central) { + for (int i = 0; i < 8; ++i) + etabins.push_back(-2.1 + 0.6 * i); + } else if (etaRegion == Forward) { + for (int i = 0; i < 10; ++i) { + if (i < 5) + etabins.push_back(-5.1 + 0.6 * i); + else + etabins.push_back(2.7 + 0.6 * (i - 5)); + } + } else if (etaRegion == All) { + for (int i = 0; i < 18; ++i) + etabins.push_back(-5.1 + 0.6 * i); } - return fixedGridRho(etabins,phibins); + return fixedGridRho(etabins, phibins); } - -float FixedGridEnergyDensity::fixedGridRho(std::vector& etabins,std::vector& phibins) { - float etadist = etabins[1]-etabins[0]; - float phidist = phibins[1]-phibins[0]; - float etahalfdist = (etabins[1]-etabins[0])/2.; - float phihalfdist = (phibins[1]-phibins[0])/2.; - vector sumPFNallSMDQ; - sumPFNallSMDQ.reserve(etabins.size()*phibins.size()); - for (unsigned int ieta=0;ietabegin(); pf_it != pfCandidates->end(); pf_it++) { - if (fabs(etabins[ieta]-pf_it->eta())>etahalfdist) continue; - if (fabs(reco::deltaPhi(phibins[iphi],pf_it->phi()))>phihalfdist) continue; - pfniso_ieta_iphi+=pf_it->pt(); - } - sumPFNallSMDQ.push_back(pfniso_ieta_iphi); - } - } - float evt_smdq = 0; - sort(sumPFNallSMDQ.begin(),sumPFNallSMDQ.end()); - if (sumPFNallSMDQ.size()%2) evt_smdq = sumPFNallSMDQ[(sumPFNallSMDQ.size()-1)/2]; - else evt_smdq = (sumPFNallSMDQ[sumPFNallSMDQ.size()/2]+sumPFNallSMDQ[(sumPFNallSMDQ.size()-2)/2])/2.; - return evt_smdq/(etadist*phidist); +float FixedGridEnergyDensity::fixedGridRho(std::vector& etabins, std::vector& phibins) { + float etadist = etabins[1] - etabins[0]; + float phidist = phibins[1] - phibins[0]; + float etahalfdist = (etabins[1] - etabins[0]) / 2.; + float phihalfdist = (phibins[1] - phibins[0]) / 2.; + vector sumPFNallSMDQ; + sumPFNallSMDQ.reserve(etabins.size() * phibins.size()); + for (unsigned int ieta = 0; ieta < etabins.size(); ++ieta) { + for (unsigned int iphi = 0; iphi < phibins.size(); ++iphi) { + float pfniso_ieta_iphi = 0; + for (PFCandidateCollection::const_iterator pf_it = pfCandidates->begin(); pf_it != pfCandidates->end(); pf_it++) { + if (fabs(etabins[ieta] - pf_it->eta()) > etahalfdist) + continue; + if (fabs(reco::deltaPhi(phibins[iphi], pf_it->phi())) > phihalfdist) + continue; + pfniso_ieta_iphi += pf_it->pt(); + } + sumPFNallSMDQ.push_back(pfniso_ieta_iphi); + } + } + float evt_smdq = 0; + sort(sumPFNallSMDQ.begin(), sumPFNallSMDQ.end()); + if (sumPFNallSMDQ.size() % 2) + evt_smdq = sumPFNallSMDQ[(sumPFNallSMDQ.size() - 1) / 2]; + else + evt_smdq = (sumPFNallSMDQ[sumPFNallSMDQ.size() / 2] + sumPFNallSMDQ[(sumPFNallSMDQ.size() - 2) / 2]) / 2.; + return evt_smdq / (etadist * phidist); } diff --git a/RecoJets/JetAlgorithms/src/HEPTopTaggerV2.cc b/RecoJets/JetAlgorithms/src/HEPTopTaggerV2.cc index dd224056f34b3..d4dd807fe100f 100644 --- a/RecoJets/JetAlgorithms/src/HEPTopTaggerV2.cc +++ b/RecoJets/JetAlgorithms/src/HEPTopTaggerV2.cc @@ -3,654 +3,812 @@ // Do not change next line, it's needed by the sed-code that makes the tagger CMSSW-compatible. namespace external { -//optimal_R fit -double R_opt_calc_funct(double pt_filt) { - return 327./pt_filt; -} - -void HEPTopTaggerV2_fixed_R::print_banner() { - if (!_first_time) {return;} - _first_time = false; - - - edm::LogInfo("HEPTopTaggerV2") << "#--------------------------------------------------------------------------\n"; - edm::LogInfo("HEPTopTaggerV2") << "# HEPTopTaggerV2 - under construction \n"; - edm::LogInfo("HEPTopTaggerV2") << "# \n"; - edm::LogInfo("HEPTopTaggerV2") << "# Please cite JHEP 1010 (2010) 078 [arXiv:1006.2833 [hep-ph]] \n"; - edm::LogInfo("HEPTopTaggerV2") << "# and Phys.Rev. D89 (2014) 074047 [arXiv:1312.1504 [hep-ph]] \n"; - edm::LogInfo("HEPTopTaggerV2") << "#--------------------------------------------------------------------------\n"; -} - -//pt wrt a reference vector -double HEPTopTaggerV2_fixed_R::perp(const fastjet::PseudoJet & vec, const fastjet::PseudoJet & ref) { - double ref_ref = ref.px() * ref.px() + ref.py() * ref.py() + ref.pz() * ref.pz(); - double vec_ref = vec.px() * ref.px() + vec.py() * ref.py() + vec.pz() * ref.pz(); - double per_per = vec.px() * vec.px() + vec.py() * vec.py() + vec.pz() * vec.pz(); - if (ref_ref > 0.) - per_per -= vec_ref * vec_ref / ref_ref; - if (per_per < 0.) - per_per = 0.; - return sqrt(per_per); -} - -//modified Jade distance -double HEPTopTaggerV2_fixed_R::djademod (const fastjet::PseudoJet& subjet_i, const fastjet::PseudoJet& subjet_j, const fastjet::PseudoJet& ref) { - double dj = -1.0; - double delta_phi = subjet_i.delta_phi_to(subjet_j); - double delta_eta = subjet_i.eta() - subjet_j.eta(); - double delta_R = sqrt(delta_eta * delta_eta + delta_phi * delta_phi); - dj = perp(subjet_i, ref) * perp(subjet_j, ref) * pow(delta_R, 4.); - return dj; -} - -//minimal |(m_ij / m_123) / (m_w/ m_t) - 1| -double HEPTopTaggerV2_fixed_R::f_rec() { - double m12 = (_top_subs[0] + _top_subs[1]).m(); - double m13 = (_top_subs[0] + _top_subs[2]).m(); - double m23 = (_top_subs[1] + _top_subs[2]).m(); - double m123 = (_top_subs[0] + _top_subs[1] + _top_subs[2]).m(); - - double fw12 = fabs( (m12/m123) / (_mwmass/_mtmass) - 1); - double fw13 = fabs( (m13/m123) / (_mwmass/_mtmass) - 1); - double fw23 = fabs( (m23/m123) / (_mwmass/_mtmass) - 1); - - return std::min(fw12, std::min(fw13, fw23)); -} - -//find hard substructures -void HEPTopTaggerV2_fixed_R::FindHardSubst(const PseudoJet & this_jet, std::vector & t_parts) { - PseudoJet parent1(0, 0, 0, 0), parent2(0, 0, 0, 0); - if (this_jet.m() < _max_subjet_mass || !this_jet.validated_cs()->has_parents(this_jet, parent1, parent2)) { - t_parts.push_back(this_jet); - } else { - if (parent1.m() < parent2.m()) - std::swap(parent1, parent2); - FindHardSubst(parent1, t_parts); - if (parent1.m() < _mass_drop_threshold * this_jet.m()) - FindHardSubst(parent2, t_parts); - } -} - -//store subjets as vector with [0]->b [1]->W-jet 1 [2]->W-jet 2 -void HEPTopTaggerV2_fixed_R::store_topsubjets(const std::vector& top_subs) { - _top_subjets.resize(0); - double m12 = (top_subs[0] + top_subs[1]).m(); - double m13 = (top_subs[0] + top_subs[2]).m(); - double m23 = (top_subs[1] + top_subs[2]).m(); - double dm12 = fabs(m12 - _mwmass); - double dm13 = fabs(m13 - _mwmass); - double dm23 = fabs(m23 - _mwmass); - - if (dm23 <= dm12 && dm23 <= dm13) { - _top_subjets.push_back(top_subs[0]); - _top_subjets.push_back(top_subs[1]); - _top_subjets.push_back(top_subs[2]); - } else if (dm13 <= dm12 && dm13 < dm23) { - _top_subjets.push_back(top_subs[1]); - _top_subjets.push_back(top_subs[0]); - _top_subjets.push_back(top_subs[2]); - } else if (dm12 < dm23 && dm12 < dm13) { - _top_subjets.push_back(top_subs[2]); - _top_subjets.push_back(top_subs[0]); - _top_subjets.push_back(top_subs[1]); + //optimal_R fit + double R_opt_calc_funct(double pt_filt) { return 327. / pt_filt; } + + void HEPTopTaggerV2_fixed_R::print_banner() { + if (!_first_time) { + return; + } + _first_time = false; + + edm::LogInfo("HEPTopTaggerV2") << "#--------------------------------------------------------------------------\n"; + edm::LogInfo("HEPTopTaggerV2") << "# HEPTopTaggerV2 - under construction \n"; + edm::LogInfo("HEPTopTaggerV2") << "# \n"; + edm::LogInfo("HEPTopTaggerV2") << "# Please cite JHEP 1010 (2010) 078 [arXiv:1006.2833 [hep-ph]] \n"; + edm::LogInfo("HEPTopTaggerV2") << "# and Phys.Rev. D89 (2014) 074047 [arXiv:1312.1504 [hep-ph]] \n"; + edm::LogInfo("HEPTopTaggerV2") << "#--------------------------------------------------------------------------\n"; } - _W = _top_subjets[1] + _top_subjets[2]; - return; -} - -//check mass plane cuts -bool HEPTopTaggerV2_fixed_R::check_mass_criteria(const std::vector & top_subs) const { - bool is_passed = false; - double m12 = (top_subs[0] + top_subs[1]).m(); - double m13 = (top_subs[0] + top_subs[2]).m(); - double m23 = (top_subs[1] + top_subs[2]).m(); - double m123 = (top_subs[0] + top_subs[1] + top_subs[2]).m(); - double atan1312 = atan(m13/m12); - double m23_over_m123 = m23/m123; - double m23_over_m123_square = m23_over_m123 * m23_over_m123; - double rmin_square = _rmin * _rmin; - double rmax_square = _rmax * _rmax; - double m13m12_square_p1 = (1 + (m13/m12) * (m13/m12)); - double m12m13_square_p1 = (1 + (m12/m13) * (m12/m13)); - if ( - (atan1312 > _m13cutmin && _m13cutmax > atan1312 - && (m23_over_m123 > _rmin && _rmax > m23_over_m123)) - || - ((m23_over_m123_square < 1 - rmin_square * m13m12_square_p1) - && - (m23_over_m123_square > 1 - rmax_square * m13m12_square_p1) - && - (m23_over_m123 > _m23cut)) - || - ((m23_over_m123_square < 1 - rmin_square * m12m13_square_p1) - && - (m23_over_m123_square > 1 - rmax_square * m12m13_square_p1) - && - (m23_over_m123 > _m23cut)) - ) { - is_passed = true; + + //pt wrt a reference vector + double HEPTopTaggerV2_fixed_R::perp(const fastjet::PseudoJet& vec, const fastjet::PseudoJet& ref) { + double ref_ref = ref.px() * ref.px() + ref.py() * ref.py() + ref.pz() * ref.pz(); + double vec_ref = vec.px() * ref.px() + vec.py() * ref.py() + vec.pz() * ref.pz(); + double per_per = vec.px() * vec.px() + vec.py() * vec.py() + vec.pz() * vec.pz(); + if (ref_ref > 0.) + per_per -= vec_ref * vec_ref / ref_ref; + if (per_per < 0.) + per_per = 0.; + return sqrt(per_per); } - return is_passed; -} - -double HEPTopTaggerV2_fixed_R::nsub(fastjet::PseudoJet jet, int order, fastjet::contrib::Njettiness::AxesMode axes, double beta, double R0) { - fastjet::contrib::Nsubjettiness nsub(order, axes, beta, R0); - return nsub.result(jet); -} - -HEPTopTaggerV2_fixed_R::HEPTopTaggerV2_fixed_R() : _do_qjets(false), - _mass_drop_threshold(0.8), _max_subjet_mass(30.), - _mode(Mode(0)), _mtmass(172.3), _mwmass(80.4), _mtmin(150.), _mtmax(200.), _rmin(0.85*80.4/172.3), _rmax(1.15*80.4/172.3), - _m23cut(0.35), _m13cutmin(0.2), _m13cutmax(1.3), _minpt_tag(200.), - _nfilt(5), _Rfilt(0.3), _jet_algorithm_filter(fastjet::cambridge_algorithm), _minpt_subjet(0.), - _jet_algorithm_recluster(fastjet::cambridge_algorithm), - _zcut(0.1), _rcut_factor(0.5), - _q_zcut(0.1), _q_dcut_fctr(0.5), _q_exp_min(0.), _q_exp_max(0.), _q_rigidity(0.1), _q_truncation_fctr(0.0), _rnEngine(nullptr), - //_qjet_plugin(_q_zcut, _q_dcut_fctr, _q_exp_min, _q_exp_max, _q_rigidity, _q_truncation_fctr), - _debug(false),_first_time(true) -{ - _djsum = 0.; - _delta_top = 1000000000000.0; - _pruned_mass = 0.; - _unfiltered_mass = 0.; - _top_candidate.reset(0., 0., 0., 0.); - _parts_size = 0; - _is_maybe_top = _is_masscut_passed = _is_ptmincut_passed = false; - _top_subs.clear(); - _top_subjets.clear(); - _top_hadrons.clear(); - _top_parts.clear(); - _qweight= -1.; - -} - -HEPTopTaggerV2_fixed_R::HEPTopTaggerV2_fixed_R(const fastjet::PseudoJet jet) : _do_qjets(false), - _jet(jet), _initial_jet(jet), - _mass_drop_threshold(0.8), _max_subjet_mass(30.), - _mode(Mode(0)), _mtmass(172.3), _mwmass(80.4), _mtmin(150.), _mtmax(200.), _rmin(0.85*80.4/172.3), _rmax(1.15*80.4/172.3), - _m23cut(0.35), _m13cutmin(0.2), _m13cutmax(1.3), _minpt_tag(200.), - _nfilt(5), _Rfilt(0.3), _jet_algorithm_filter(fastjet::cambridge_algorithm), _minpt_subjet(0.), - _jet_algorithm_recluster(fastjet::cambridge_algorithm), - _zcut(0.1), _rcut_factor(0.5), - _q_zcut(0.1), _q_dcut_fctr(0.5), _q_exp_min(0.), _q_exp_max(0.), _q_rigidity(0.1), _q_truncation_fctr(0.0), - _fat(jet), _rnEngine(nullptr), - _debug(false),_first_time(true) -{} - -HEPTopTaggerV2_fixed_R::HEPTopTaggerV2_fixed_R(const fastjet::PseudoJet jet, - double mtmass, double mwmass) : _do_qjets(false), - _jet(jet), _initial_jet(jet), - _mass_drop_threshold(0.8), _max_subjet_mass(30.), - _mode(Mode(0)), _mtmass(mtmass), _mwmass(mwmass), _rmin(0.85*80.4/172.3), _rmax(1.15*80.4/172.3), - _m23cut(0.35), _m13cutmin(0.2), _m13cutmax(1.3), _minpt_tag(200.), - _nfilt(5), _Rfilt(0.3), _jet_algorithm_filter(fastjet::cambridge_algorithm), _minpt_subjet(0.), - _jet_algorithm_recluster(fastjet::cambridge_algorithm), - _zcut(0.1), _rcut_factor(0.5), - _q_zcut(0.1), _q_dcut_fctr(0.5), _q_exp_min(0.), _q_exp_max(0.), _q_rigidity(0.1), _q_truncation_fctr(0.0), - _fat(jet), _rnEngine(nullptr), - _debug(false),_first_time(true) -{} - -void HEPTopTaggerV2_fixed_R::run() { - print_banner(); - - if ((_mode != EARLY_MASSRATIO_SORT_MASS) - && (_mode != LATE_MASSRATIO_SORT_MASS) - && (_mode != EARLY_MASSRATIO_SORT_MODDJADE) - && (_mode != LATE_MASSRATIO_SORT_MODDJADE) - && (_mode != TWO_STEP_FILTER) ) { - edm::LogError("HEPTopTaggerV2") << "ERROR: UNKNOWN MODE" << std::endl; - return; + + //modified Jade distance + double HEPTopTaggerV2_fixed_R::djademod(const fastjet::PseudoJet& subjet_i, + const fastjet::PseudoJet& subjet_j, + const fastjet::PseudoJet& ref) { + double dj = -1.0; + double delta_phi = subjet_i.delta_phi_to(subjet_j); + double delta_eta = subjet_i.eta() - subjet_j.eta(); + double delta_R = sqrt(delta_eta * delta_eta + delta_phi * delta_phi); + dj = perp(subjet_i, ref) * perp(subjet_j, ref) * pow(delta_R, 4.); + return dj; } - - //Qjets - QjetsPlugin _qjet_plugin(_q_zcut, _q_dcut_fctr, _q_exp_min, _q_exp_max, _q_rigidity, _q_truncation_fctr); - _qjet_def = fastjet::JetDefinition(&_qjet_plugin); - _qweight=-1; - vector _q_constits; - ClusterSequence* _qjet_seq; - PseudoJet _qjet; - if (_do_qjets){ - _q_constits = _initial_jet.associated_cluster_sequence()->constituents(_initial_jet); - _qjet_seq = new ClusterSequence(_q_constits, _qjet_def); - _qjet = sorted_by_pt(_qjet_seq->inclusive_jets())[0]; - _qjet_seq->delete_self_when_unused(); - const QjetsBaseExtras* ext = - dynamic_cast(_qjet_seq->extras()); - _qweight=ext->weight(); - _jet = _qjet; - _fat = _qjet; - _qjet_plugin.SetRNEngine(_rnEngine); + + //minimal |(m_ij / m_123) / (m_w/ m_t) - 1| + double HEPTopTaggerV2_fixed_R::f_rec() { + double m12 = (_top_subs[0] + _top_subs[1]).m(); + double m13 = (_top_subs[0] + _top_subs[2]).m(); + double m23 = (_top_subs[1] + _top_subs[2]).m(); + double m123 = (_top_subs[0] + _top_subs[1] + _top_subs[2]).m(); + + double fw12 = fabs((m12 / m123) / (_mwmass / _mtmass) - 1); + double fw13 = fabs((m13 / m123) / (_mwmass / _mtmass) - 1); + double fw23 = fabs((m23 / m123) / (_mwmass / _mtmass) - 1); + + return std::min(fw12, std::min(fw13, fw23)); } - - //initialization - _djsum = 0.; - _delta_top = 1000000000000.0; - _pruned_mass = 0.; - _unfiltered_mass = 0.; - _top_candidate.reset(0., 0., 0., 0.); - _parts_size = 0; - _is_maybe_top = _is_masscut_passed = _is_ptmincut_passed = false; - _top_subs.clear(); - _top_subjets.clear(); - _top_hadrons.clear(); - _top_parts.clear(); - + //find hard substructures - FindHardSubst(_jet, _top_parts); - - if (_top_parts.size() < 3) { - if (_debug) {edm::LogInfo("HEPTopTaggerV2") << "< 3 hard substructures " << std::endl;} - return; //such events are not interesting - } - - // Sort subjets-after-unclustering by pT. - // Necessary so that two-step-filtering can use the leading-three. - _top_parts=sorted_by_pt(_top_parts); - - // loop over triples - _top_parts = sorted_by_pt(_top_parts); - for (unsigned rr = 0; rr < _top_parts.size(); rr++) { - for (unsigned ll = rr + 1; ll < _top_parts.size(); ll++) { - for (unsigned kk = ll + 1; kk < _top_parts.size(); kk++) { - - // two-step filtering - // This means that we only look at the triplet formed by the - // three leading-in-pT subjets-after-unclustering. - if((_mode==TWO_STEP_FILTER) && rr>0) - continue; - if((_mode==TWO_STEP_FILTER) && ll>1) - continue; - if((_mode==TWO_STEP_FILTER) && kk>2) - continue; - - //pick triple - PseudoJet triple = join(_top_parts[rr], _top_parts[ll], _top_parts[kk]); - - //filtering - double filt_top_R - = std::min(_Rfilt, 0.5*sqrt(std::min(_top_parts[kk].squared_distance(_top_parts[ll]), - std::min(_top_parts[rr].squared_distance(_top_parts[ll]), - _top_parts[kk].squared_distance(_top_parts[rr]))))); - JetDefinition filtering_def(_jet_algorithm_filter, filt_top_R); - fastjet::Filter filter(filtering_def, fastjet::SelectorNHardest(_nfilt) * fastjet::SelectorPtMin(_minpt_subjet)); - PseudoJet topcandidate = filter(triple); - - //mass window cut - if (topcandidate.m() < _mtmin || _mtmax < topcandidate.m()) continue; - - // Sanity cut: can't recluster less than 3 objects into three subjets - if (topcandidate.pieces().size() < 3) - continue; - - // Recluster to 3 subjets and apply mass plane cuts - JetDefinition reclustering(_jet_algorithm_recluster, 3.14); - ClusterSequence * cs_top_sub = new ClusterSequence(topcandidate.constituents(), reclustering); - std::vector top_subs = sorted_by_pt(cs_top_sub->exclusive_jets(3)); - cs_top_sub->delete_self_when_unused(); - - // Require the third subjet to be above the pT threshold - if (top_subs[2].perp() < _minpt_subjet) - continue; - - // Modes with early 2d-massplane cuts - if (_mode == EARLY_MASSRATIO_SORT_MASS && !check_mass_criteria(top_subs)) {continue;} - if (_mode == EARLY_MASSRATIO_SORT_MODDJADE && !check_mass_criteria(top_subs)) {continue;} - - //is this candidate better than the other? -> update - double deltatop = fabs(topcandidate.m() - _mtmass); - double djsum = djademod(top_subs[0], top_subs[1], topcandidate) - + djademod(top_subs[0], top_subs[2], topcandidate) - + djademod(top_subs[1], top_subs[2], topcandidate); - bool better = false; - - // Modes 0 and 1 sort by top mass - if ( (_mode == EARLY_MASSRATIO_SORT_MASS) - || (_mode == LATE_MASSRATIO_SORT_MASS)) { - if (deltatop < _delta_top) - better = true; - } - // Modes 2 and 3 sort by modified jade distance - else if ( (_mode == EARLY_MASSRATIO_SORT_MODDJADE) - || (_mode == LATE_MASSRATIO_SORT_MODDJADE)) { - if (djsum > _djsum) - better = true; - } - // Mode 4 is the two-step filtering. No sorting necessary as - // we just look at the triplet of highest pT objects after - // unclustering - else if (_mode == TWO_STEP_FILTER) { - better = true; - } - else { - edm::LogError("HEPTopTaggerV2") << "ERROR: UNKNOWN MODE (IN DISTANCE MEASURE SELECTION)" << std::endl; - return; - } - - if (better) { - _djsum = djsum; - _delta_top = deltatop; - _is_maybe_top = true; - _top_candidate = topcandidate; - _top_subs = top_subs; - store_topsubjets(top_subs); - _top_hadrons = topcandidate.constituents(); - // Pruning - double _Rprun = _initial_jet.validated_cluster_sequence()->jet_def().R(); - JetDefinition jet_def_prune(fastjet::cambridge_algorithm, _Rprun); - fastjet::Pruner pruner(jet_def_prune, _zcut, _rcut_factor); - PseudoJet prunedjet = pruner(triple); - _pruned_mass = prunedjet.m(); - _unfiltered_mass = triple.m(); - - //are all criteria fulfilled? - _is_masscut_passed = false; - if (check_mass_criteria(top_subs)) { - _is_masscut_passed = true; - } - _is_ptmincut_passed = false; - if (_top_candidate.pt() > _minpt_tag) { - _is_ptmincut_passed = true; - } - }//end better - }//end kk - }//end ll - }//end rr - - return; -} - -void HEPTopTaggerV2_fixed_R::get_info() const { - edm::LogInfo("HEPTopTaggerV2") << "#--------------------------------------------------------------------------\n"; - edm::LogInfo("HEPTopTaggerV2") << "# HEPTopTaggerV2 Result" << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "#" << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# is top candidate: " << _is_maybe_top << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# mass plane cuts passed: " << _is_masscut_passed << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# top candidate mass: " << _top_candidate.m() << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# top candidate (pt, eta, phi): (" - << _top_candidate.perp() << ", " - << _top_candidate.eta() << ", " - << _top_candidate.phi_std() << ")" << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# top hadrons: " << _top_hadrons.size() << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# hard substructures: " << _parts_size << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# |m - mtop| : " << _delta_top << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# djsum : " << _djsum << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# is consistency cut passed: " << _is_ptmincut_passed << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "#--------------------------------------------------------------------------\n"; - return; -} - -void HEPTopTaggerV2_fixed_R::get_setting() const { - edm::LogInfo("HEPTopTaggerV2") << "#--------------------------------------------------------------------------\n"; - edm::LogInfo("HEPTopTaggerV2") << "# HEPTopTaggerV2 Settings" << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "#" << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# mode: " << _mode << " (0 = EARLY_MASSRATIO_SORT_MASS) " << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# " << " (1 = LATE_MASSRATIO_SORT_MASS) " << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# " << " (2 = EARLY_MASSRATIO_SORT_MODDJADE) " << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# " << " (3 = LATE_MASSRATIO_SORT_MODDJADE) " << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# " << " (4 = TWO_STEP_FILTER) " << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# top mass: " << _mtmass << " "; - edm::LogInfo("HEPTopTaggerV2") << "W mass: " << _mwmass << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# top mass window: [" << _mtmin << ", " << _mtmax << "]" << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# W mass ratio: [" << _rmin << ", " << _rmax << "] ([" - <<_rmin*_mtmass/_mwmass<< "%, "<< _rmax*_mtmass/_mwmass << "%])"<< std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# mass plane cuts: (m23cut, m13min, m13max) = (" - << _m23cut << ", " << _m13cutmin << ", " << _m13cutmax << ")" << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# mass_drop_threshold: " << _mass_drop_threshold << " "; - edm::LogInfo("HEPTopTaggerV2") << "max_subjet_mass: " << _max_subjet_mass << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# R_filt: " << _Rfilt << " "; - edm::LogInfo("HEPTopTaggerV2") << "n_filt: " << _nfilt << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# minimal subjet pt: " << _minpt_subjet << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# minimal reconstructed pt: " << _minpt_tag << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# internal jet algorithms (0 = kt, 1 = C/A, 2 = anti-kt): " << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# filtering: "<< _jet_algorithm_filter << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "# reclustering: "<< _jet_algorithm_recluster << std::endl; - edm::LogInfo("HEPTopTaggerV2") << "#--------------------------------------------------------------------------\n"; - - return; -} - -//uncluster a fat jet to subjets of given cone size -void HEPTopTaggerV2::UnclusterFatjets(const vector & big_fatjets, - vector & small_fatjets, - const ClusterSequence & cseq, - const double small_radius) { - for (unsigned i=0; i < big_fatjets.size(); i++) { - PseudoJet this_jet = big_fatjets[i]; + void HEPTopTaggerV2_fixed_R::FindHardSubst(const PseudoJet& this_jet, std::vector& t_parts) { PseudoJet parent1(0, 0, 0, 0), parent2(0, 0, 0, 0); - bool test = cseq.has_parents(this_jet, parent1, parent2); - double dR = 100; + if (this_jet.m() < _max_subjet_mass || !this_jet.validated_cs()->has_parents(this_jet, parent1, parent2)) { + t_parts.push_back(this_jet); + } else { + if (parent1.m() < parent2.m()) + std::swap(parent1, parent2); + FindHardSubst(parent1, t_parts); + if (parent1.m() < _mass_drop_threshold * this_jet.m()) + FindHardSubst(parent2, t_parts); + } + } - if(test) dR = sqrt(parent1.squared_distance(parent2)); + //store subjets as vector with [0]->b [1]->W-jet 1 [2]->W-jet 2 + void HEPTopTaggerV2_fixed_R::store_topsubjets(const std::vector& top_subs) { + _top_subjets.resize(0); + double m12 = (top_subs[0] + top_subs[1]).m(); + double m13 = (top_subs[0] + top_subs[2]).m(); + double m23 = (top_subs[1] + top_subs[2]).m(); + double dm12 = fabs(m12 - _mwmass); + double dm13 = fabs(m13 - _mwmass); + double dm23 = fabs(m23 - _mwmass); + + if (dm23 <= dm12 && dm23 <= dm13) { + _top_subjets.push_back(top_subs[0]); + _top_subjets.push_back(top_subs[1]); + _top_subjets.push_back(top_subs[2]); + } else if (dm13 <= dm12 && dm13 < dm23) { + _top_subjets.push_back(top_subs[1]); + _top_subjets.push_back(top_subs[0]); + _top_subjets.push_back(top_subs[2]); + } else if (dm12 < dm23 && dm12 < dm13) { + _top_subjets.push_back(top_subs[2]); + _top_subjets.push_back(top_subs[0]); + _top_subjets.push_back(top_subs[1]); + } + _W = _top_subjets[1] + _top_subjets[2]; + return; + } - if (!test || dR parents; - parents.push_back(parent1); - parents.push_back(parent2); - UnclusterFatjets(parents, small_fatjets, cseq, small_radius); + //check mass plane cuts + bool HEPTopTaggerV2_fixed_R::check_mass_criteria(const std::vector& top_subs) const { + bool is_passed = false; + double m12 = (top_subs[0] + top_subs[1]).m(); + double m13 = (top_subs[0] + top_subs[2]).m(); + double m23 = (top_subs[1] + top_subs[2]).m(); + double m123 = (top_subs[0] + top_subs[1] + top_subs[2]).m(); + double atan1312 = atan(m13 / m12); + double m23_over_m123 = m23 / m123; + double m23_over_m123_square = m23_over_m123 * m23_over_m123; + double rmin_square = _rmin * _rmin; + double rmax_square = _rmax * _rmax; + double m13m12_square_p1 = (1 + (m13 / m12) * (m13 / m12)); + double m12m13_square_p1 = (1 + (m12 / m13) * (m12 / m13)); + if ((atan1312 > _m13cutmin && _m13cutmax > atan1312 && (m23_over_m123 > _rmin && _rmax > m23_over_m123)) || + ((m23_over_m123_square < 1 - rmin_square * m13m12_square_p1) && + (m23_over_m123_square > 1 - rmax_square * m13m12_square_p1) && (m23_over_m123 > _m23cut)) || + ((m23_over_m123_square < 1 - rmin_square * m12m13_square_p1) && + (m23_over_m123_square > 1 - rmax_square * m12m13_square_p1) && (m23_over_m123 > _m23cut))) { + is_passed = true; } + return is_passed; + } + + double HEPTopTaggerV2_fixed_R::nsub( + fastjet::PseudoJet jet, int order, fastjet::contrib::Njettiness::AxesMode axes, double beta, double R0) { + fastjet::contrib::Nsubjettiness nsub(order, axes, beta, R0); + return nsub.result(jet); + } + + HEPTopTaggerV2_fixed_R::HEPTopTaggerV2_fixed_R() + : _do_qjets(false), + _mass_drop_threshold(0.8), + _max_subjet_mass(30.), + _mode(Mode(0)), + _mtmass(172.3), + _mwmass(80.4), + _mtmin(150.), + _mtmax(200.), + _rmin(0.85 * 80.4 / 172.3), + _rmax(1.15 * 80.4 / 172.3), + _m23cut(0.35), + _m13cutmin(0.2), + _m13cutmax(1.3), + _minpt_tag(200.), + _nfilt(5), + _Rfilt(0.3), + _jet_algorithm_filter(fastjet::cambridge_algorithm), + _minpt_subjet(0.), + _jet_algorithm_recluster(fastjet::cambridge_algorithm), + _zcut(0.1), + _rcut_factor(0.5), + _q_zcut(0.1), + _q_dcut_fctr(0.5), + _q_exp_min(0.), + _q_exp_max(0.), + _q_rigidity(0.1), + _q_truncation_fctr(0.0), + _rnEngine(nullptr), + //_qjet_plugin(_q_zcut, _q_dcut_fctr, _q_exp_min, _q_exp_max, _q_rigidity, _q_truncation_fctr), + _debug(false), + _first_time(true) { + _djsum = 0.; + _delta_top = 1000000000000.0; + _pruned_mass = 0.; + _unfiltered_mass = 0.; + _top_candidate.reset(0., 0., 0., 0.); + _parts_size = 0; + _is_maybe_top = _is_masscut_passed = _is_ptmincut_passed = false; + _top_subs.clear(); + _top_subjets.clear(); + _top_hadrons.clear(); + _top_parts.clear(); + _qweight = -1.; } -} - -HEPTopTaggerV2::HEPTopTaggerV2() : _do_optimalR(false), _do_qjets(false), - _mass_drop_threshold(0.8), _max_subjet_mass(30.), - _mode(Mode(0)), _mtmass(172.3), _mwmass(80.4), _mtmin(150.), _mtmax(200.), _rmin(0.85*80.4/172.3), _rmax(1.15*80.4/172.3), - _m23cut(0.35), _m13cutmin(0.2), _m13cutmax(1.3), _minpt_tag(200.), - _nfilt(5), _Rfilt(0.3), _jet_algorithm_filter(fastjet::cambridge_algorithm), _minpt_subjet(0.), - _jet_algorithm_recluster(fastjet::cambridge_algorithm), - _zcut(0.1), _rcut_factor(0.5), - _max_fatjet_R(1.8), _min_fatjet_R(0.5), _step_R(0.1), _optimalR_threshold(0.2), - _R_filt_optimalR_calc(0.2), _N_filt_optimalR_calc(10), _r_min_exp_function(&R_opt_calc_funct), - _optimalR_mmin(150.), _optimalR_mmax(200.), _optimalR_fw(0.175), _R_opt_diff(0.3), _R_opt_reject_min(false), - _R_filt_optimalR_pass(0.2), _N_filt_optimalR_pass(5), _R_filt_optimalR_fail(0.3), _N_filt_optimalR_fail(3), - _q_zcut(0.1), _q_dcut_fctr(0.5), _q_exp_min(0.), _q_exp_max(0.), _q_rigidity(0.1), _q_truncation_fctr(0.0), _rnEngine(nullptr), - _debug(false) -{} - -HEPTopTaggerV2::HEPTopTaggerV2(const fastjet::PseudoJet & jet - ) : _do_optimalR(false), _do_qjets(false), - _jet(jet), _initial_jet(jet), - _mass_drop_threshold(0.8), _max_subjet_mass(30.), - _mode(Mode(0)), _mtmass(172.3), _mwmass(80.4), _mtmin(150.), _mtmax(200.), _rmin(0.85*80.4/172.3), _rmax(1.15*80.4/172.3), - _m23cut(0.35), _m13cutmin(0.2), _m13cutmax(1.3), _minpt_tag(200.), - _nfilt(5), _Rfilt(0.3), _jet_algorithm_filter(fastjet::cambridge_algorithm), _minpt_subjet(0.), - _jet_algorithm_recluster(fastjet::cambridge_algorithm), - _zcut(0.1), _rcut_factor(0.5), - _max_fatjet_R(jet.validated_cluster_sequence()->jet_def().R()), _min_fatjet_R(0.5), _step_R(0.1), _optimalR_threshold(0.2), - _R_filt_optimalR_calc(0.2), _N_filt_optimalR_calc(10), _r_min_exp_function(&R_opt_calc_funct), - _optimalR_mmin(150.), _optimalR_mmax(200.), _optimalR_fw(0.175), _R_opt_diff(0.3), _R_opt_reject_min(false), - _R_filt_optimalR_pass(0.2), _N_filt_optimalR_pass(5), _R_filt_optimalR_fail(0.3), _N_filt_optimalR_fail(3), - _q_zcut(0.1), _q_dcut_fctr(0.5), _q_exp_min(0.), _q_exp_max(0.), _q_rigidity(0.1), _q_truncation_fctr(0.0), - _fat(jet),_rnEngine(nullptr), - _debug(false) -{} - -HEPTopTaggerV2::HEPTopTaggerV2(const fastjet::PseudoJet & jet, - double mtmass, double mwmass - ) : _do_optimalR(false), _do_qjets(false), - _jet(jet), _initial_jet(jet), - _mass_drop_threshold(0.8), _max_subjet_mass(30.), - _mode(Mode(0)), _mtmass(mtmass), _mwmass(mwmass), _mtmin(150.), _mtmax(200.), _rmin(0.85*80.4/172.3), _rmax(1.15*80.4/172.3), - _m23cut(0.35), _m13cutmin(0.2), _m13cutmax(1.3), _minpt_tag(200.), - _nfilt(5), _Rfilt(0.3), _jet_algorithm_filter(fastjet::cambridge_algorithm), _minpt_subjet(0.), - _jet_algorithm_recluster(fastjet::cambridge_algorithm), - _zcut(0.1), _rcut_factor(0.5), - _max_fatjet_R(jet.validated_cluster_sequence()->jet_def().R()), _min_fatjet_R(0.5), _step_R(0.1), _optimalR_threshold(0.2), - _R_filt_optimalR_calc(0.2), _N_filt_optimalR_calc(10), _r_min_exp_function(&R_opt_calc_funct), - _optimalR_mmin(150.), _optimalR_mmax(200.), _optimalR_fw(0.175), _R_opt_diff(0.3), _R_opt_reject_min(false), - _R_filt_optimalR_pass(0.2), _N_filt_optimalR_pass(5), _R_filt_optimalR_fail(0.3), _N_filt_optimalR_fail(3), - _q_zcut(0.1), _q_dcut_fctr(0.5), _q_exp_min(0.), _q_exp_max(0.), _q_rigidity(0.1), _q_truncation_fctr(0.0), - _fat(jet), _rnEngine(nullptr), - _debug(false) -{} - -void HEPTopTaggerV2::run() { - - QjetsPlugin _qjet_plugin(_q_zcut, _q_dcut_fctr, _q_exp_min, _q_exp_max, _q_rigidity, _q_truncation_fctr); - int maxR = int(_max_fatjet_R * 10); - int minR = int(_min_fatjet_R * 10); - int stepR = int(_step_R * 10); - _qweight=-1; - _qjet_plugin.SetRNEngine(_rnEngine); - - if (!_do_optimalR) { - HEPTopTaggerV2_fixed_R htt(_jet); - htt.set_mass_drop_threshold(_mass_drop_threshold); - htt.set_max_subjet_mass(_max_subjet_mass); - htt.set_filtering_n(_nfilt); - htt.set_filtering_R(_Rfilt); - htt.set_filtering_minpt_subjet(_minpt_subjet); - htt.set_filtering_jetalgorithm(_jet_algorithm_filter); - htt.set_reclustering_jetalgorithm(_jet_algorithm_recluster); - htt.set_mode(_mode ); - htt.set_mt(_mtmass); - htt.set_mw(_mwmass); - htt.set_top_mass_range(_mtmin, _mtmax); - htt.set_mass_ratio_range(_rmin, _rmax); - htt.set_mass_ratio_cut(_m23cut, _m13cutmin, _m13cutmax); - htt.set_top_minpt(_minpt_tag); - htt.set_pruning_zcut(_zcut); - htt.set_pruning_rcut_factor(_rcut_factor); - htt.set_debug(_debug); - htt.set_qjets(_q_zcut, _q_dcut_fctr, _q_exp_min, _q_exp_max, _q_rigidity, _q_truncation_fctr); - htt.run(); - - _HEPTopTaggerV2[maxR] = htt; - _Ropt = maxR; - _qweight = htt.q_weight(); - _HEPTopTaggerV2_opt = _HEPTopTaggerV2[_Ropt]; - } else { + + HEPTopTaggerV2_fixed_R::HEPTopTaggerV2_fixed_R(const fastjet::PseudoJet jet) + : _do_qjets(false), + _jet(jet), + _initial_jet(jet), + _mass_drop_threshold(0.8), + _max_subjet_mass(30.), + _mode(Mode(0)), + _mtmass(172.3), + _mwmass(80.4), + _mtmin(150.), + _mtmax(200.), + _rmin(0.85 * 80.4 / 172.3), + _rmax(1.15 * 80.4 / 172.3), + _m23cut(0.35), + _m13cutmin(0.2), + _m13cutmax(1.3), + _minpt_tag(200.), + _nfilt(5), + _Rfilt(0.3), + _jet_algorithm_filter(fastjet::cambridge_algorithm), + _minpt_subjet(0.), + _jet_algorithm_recluster(fastjet::cambridge_algorithm), + _zcut(0.1), + _rcut_factor(0.5), + _q_zcut(0.1), + _q_dcut_fctr(0.5), + _q_exp_min(0.), + _q_exp_max(0.), + _q_rigidity(0.1), + _q_truncation_fctr(0.0), + _fat(jet), + _rnEngine(nullptr), + _debug(false), + _first_time(true) {} + + HEPTopTaggerV2_fixed_R::HEPTopTaggerV2_fixed_R(const fastjet::PseudoJet jet, double mtmass, double mwmass) + : _do_qjets(false), + _jet(jet), + _initial_jet(jet), + _mass_drop_threshold(0.8), + _max_subjet_mass(30.), + _mode(Mode(0)), + _mtmass(mtmass), + _mwmass(mwmass), + _rmin(0.85 * 80.4 / 172.3), + _rmax(1.15 * 80.4 / 172.3), + _m23cut(0.35), + _m13cutmin(0.2), + _m13cutmax(1.3), + _minpt_tag(200.), + _nfilt(5), + _Rfilt(0.3), + _jet_algorithm_filter(fastjet::cambridge_algorithm), + _minpt_subjet(0.), + _jet_algorithm_recluster(fastjet::cambridge_algorithm), + _zcut(0.1), + _rcut_factor(0.5), + _q_zcut(0.1), + _q_dcut_fctr(0.5), + _q_exp_min(0.), + _q_exp_max(0.), + _q_rigidity(0.1), + _q_truncation_fctr(0.0), + _fat(jet), + _rnEngine(nullptr), + _debug(false), + _first_time(true) {} + + void HEPTopTaggerV2_fixed_R::run() { + print_banner(); + + if ((_mode != EARLY_MASSRATIO_SORT_MASS) && (_mode != LATE_MASSRATIO_SORT_MASS) && + (_mode != EARLY_MASSRATIO_SORT_MODDJADE) && (_mode != LATE_MASSRATIO_SORT_MODDJADE) && + (_mode != TWO_STEP_FILTER)) { + edm::LogError("HEPTopTaggerV2") << "ERROR: UNKNOWN MODE" << std::endl; + return; + } + + //Qjets + QjetsPlugin _qjet_plugin(_q_zcut, _q_dcut_fctr, _q_exp_min, _q_exp_max, _q_rigidity, _q_truncation_fctr); _qjet_def = fastjet::JetDefinition(&_qjet_plugin); + _qweight = -1; vector _q_constits; ClusterSequence* _qjet_seq; PseudoJet _qjet; - const ClusterSequence* _seq; - _seq = _initial_jet.validated_cluster_sequence(); - if (_do_qjets){ + if (_do_qjets) { _q_constits = _initial_jet.associated_cluster_sequence()->constituents(_initial_jet); _qjet_seq = new ClusterSequence(_q_constits, _qjet_def); _qjet = sorted_by_pt(_qjet_seq->inclusive_jets())[0]; _qjet_seq->delete_self_when_unused(); - const QjetsBaseExtras* ext = - dynamic_cast(_qjet_seq->extras()); - _qweight=ext->weight(); + const QjetsBaseExtras* ext = dynamic_cast(_qjet_seq->extras()); + _qweight = ext->weight(); _jet = _qjet; - _seq = _qjet_seq; _fat = _qjet; + _qjet_plugin.SetRNEngine(_rnEngine); } - - // Do MultiR procedure - vector big_fatjets; - vector small_fatjets; - - big_fatjets.push_back(_jet); - _Ropt = 0; - - for (int R = maxR; R >= minR; R -= stepR) { - UnclusterFatjets(big_fatjets, small_fatjets, *_seq, R / 10.); - - if (_debug) {edm::LogInfo("HEPTopTaggerV2") << "R = " << R << " -> n_small_fatjets = " << small_fatjets.size() << endl;} - - _n_small_fatjets[R] = small_fatjets.size(); - - // We are sorting by pt - so start with a negative dummy - double dummy = -99999; - - for (unsigned i = 0; i < small_fatjets.size(); i++) { - HEPTopTaggerV2_fixed_R htt(small_fatjets[i]); - htt.set_mass_drop_threshold(_mass_drop_threshold); - htt.set_max_subjet_mass(_max_subjet_mass); - htt.set_filtering_n(_nfilt); - htt.set_filtering_R(_Rfilt); - htt.set_filtering_minpt_subjet(_minpt_subjet); - htt.set_filtering_jetalgorithm(_jet_algorithm_filter); - htt.set_reclustering_jetalgorithm(_jet_algorithm_recluster); - htt.set_mode(_mode ); - htt.set_mt(_mtmass); - htt.set_mw(_mwmass); - htt.set_top_mass_range(_mtmin, _mtmax); - htt.set_mass_ratio_range(_rmin, _rmax); - htt.set_mass_ratio_cut(_m23cut, _m13cutmin, _m13cutmax); - htt.set_top_minpt(_minpt_tag); - htt.set_pruning_zcut(_zcut); - htt.set_pruning_rcut_factor(_rcut_factor); - htt.set_debug(_debug); - htt.set_qjets(_q_zcut, _q_dcut_fctr, _q_exp_min, _q_exp_max, _q_rigidity, _q_truncation_fctr); - - htt.run(); - - if (htt.t().perp() > dummy) { - dummy = htt.t().perp(); - _HEPTopTaggerV2[R] = htt; - } - } //End of loop over small_fatjets - - // Only check if we have not found Ropt yet - if (_Ropt == 0 && R < maxR) { - // If the new mass is OUTSIDE the window .. - if (_HEPTopTaggerV2[R].t().m() < (1-_optimalR_threshold)*_HEPTopTaggerV2[maxR].t().m()) - // .. set _Ropt to the previous mass - _Ropt = R + stepR; + + //initialization + _djsum = 0.; + _delta_top = 1000000000000.0; + _pruned_mass = 0.; + _unfiltered_mass = 0.; + _top_candidate.reset(0., 0., 0., 0.); + _parts_size = 0; + _is_maybe_top = _is_masscut_passed = _is_ptmincut_passed = false; + _top_subs.clear(); + _top_subjets.clear(); + _top_hadrons.clear(); + _top_parts.clear(); + + //find hard substructures + FindHardSubst(_jet, _top_parts); + + if (_top_parts.size() < 3) { + if (_debug) { + edm::LogInfo("HEPTopTaggerV2") << "< 3 hard substructures " << std::endl; + } + return; //such events are not interesting + } + + // Sort subjets-after-unclustering by pT. + // Necessary so that two-step-filtering can use the leading-three. + _top_parts = sorted_by_pt(_top_parts); + + // loop over triples + _top_parts = sorted_by_pt(_top_parts); + for (unsigned rr = 0; rr < _top_parts.size(); rr++) { + for (unsigned ll = rr + 1; ll < _top_parts.size(); ll++) { + for (unsigned kk = ll + 1; kk < _top_parts.size(); kk++) { + // two-step filtering + // This means that we only look at the triplet formed by the + // three leading-in-pT subjets-after-unclustering. + if ((_mode == TWO_STEP_FILTER) && rr > 0) + continue; + if ((_mode == TWO_STEP_FILTER) && ll > 1) + continue; + if ((_mode == TWO_STEP_FILTER) && kk > 2) + continue; + + //pick triple + PseudoJet triple = join(_top_parts[rr], _top_parts[ll], _top_parts[kk]); + + //filtering + double filt_top_R = std::min(_Rfilt, + 0.5 * sqrt(std::min(_top_parts[kk].squared_distance(_top_parts[ll]), + std::min(_top_parts[rr].squared_distance(_top_parts[ll]), + _top_parts[kk].squared_distance(_top_parts[rr]))))); + JetDefinition filtering_def(_jet_algorithm_filter, filt_top_R); + fastjet::Filter filter(filtering_def, + fastjet::SelectorNHardest(_nfilt) * fastjet::SelectorPtMin(_minpt_subjet)); + PseudoJet topcandidate = filter(triple); + + //mass window cut + if (topcandidate.m() < _mtmin || _mtmax < topcandidate.m()) + continue; + + // Sanity cut: can't recluster less than 3 objects into three subjets + if (topcandidate.pieces().size() < 3) + continue; + + // Recluster to 3 subjets and apply mass plane cuts + JetDefinition reclustering(_jet_algorithm_recluster, 3.14); + ClusterSequence* cs_top_sub = new ClusterSequence(topcandidate.constituents(), reclustering); + std::vector top_subs = sorted_by_pt(cs_top_sub->exclusive_jets(3)); + cs_top_sub->delete_self_when_unused(); + + // Require the third subjet to be above the pT threshold + if (top_subs[2].perp() < _minpt_subjet) + continue; + + // Modes with early 2d-massplane cuts + if (_mode == EARLY_MASSRATIO_SORT_MASS && !check_mass_criteria(top_subs)) { + continue; + } + if (_mode == EARLY_MASSRATIO_SORT_MODDJADE && !check_mass_criteria(top_subs)) { + continue; + } + + //is this candidate better than the other? -> update + double deltatop = fabs(topcandidate.m() - _mtmass); + double djsum = djademod(top_subs[0], top_subs[1], topcandidate) + + djademod(top_subs[0], top_subs[2], topcandidate) + + djademod(top_subs[1], top_subs[2], topcandidate); + bool better = false; + + // Modes 0 and 1 sort by top mass + if ((_mode == EARLY_MASSRATIO_SORT_MASS) || (_mode == LATE_MASSRATIO_SORT_MASS)) { + if (deltatop < _delta_top) + better = true; + } + // Modes 2 and 3 sort by modified jade distance + else if ((_mode == EARLY_MASSRATIO_SORT_MODDJADE) || (_mode == LATE_MASSRATIO_SORT_MODDJADE)) { + if (djsum > _djsum) + better = true; + } + // Mode 4 is the two-step filtering. No sorting necessary as + // we just look at the triplet of highest pT objects after + // unclustering + else if (_mode == TWO_STEP_FILTER) { + better = true; + } else { + edm::LogError("HEPTopTaggerV2") << "ERROR: UNKNOWN MODE (IN DISTANCE MEASURE SELECTION)" << std::endl; + return; + } + + if (better) { + _djsum = djsum; + _delta_top = deltatop; + _is_maybe_top = true; + _top_candidate = topcandidate; + _top_subs = top_subs; + store_topsubjets(top_subs); + _top_hadrons = topcandidate.constituents(); + // Pruning + double _Rprun = _initial_jet.validated_cluster_sequence()->jet_def().R(); + JetDefinition jet_def_prune(fastjet::cambridge_algorithm, _Rprun); + fastjet::Pruner pruner(jet_def_prune, _zcut, _rcut_factor); + PseudoJet prunedjet = pruner(triple); + _pruned_mass = prunedjet.m(); + _unfiltered_mass = triple.m(); + + //are all criteria fulfilled? + _is_masscut_passed = false; + if (check_mass_criteria(top_subs)) { + _is_masscut_passed = true; + } + _is_ptmincut_passed = false; + if (_top_candidate.pt() > _minpt_tag) { + _is_ptmincut_passed = true; + } + } //end better + } //end kk + } //end ll + } //end rr + + return; + } + + void HEPTopTaggerV2_fixed_R::get_info() const { + edm::LogInfo("HEPTopTaggerV2") << "#--------------------------------------------------------------------------\n"; + edm::LogInfo("HEPTopTaggerV2") << "# HEPTopTaggerV2 Result" << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "#" << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# is top candidate: " << _is_maybe_top << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# mass plane cuts passed: " << _is_masscut_passed << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# top candidate mass: " << _top_candidate.m() << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# top candidate (pt, eta, phi): (" << _top_candidate.perp() << ", " + << _top_candidate.eta() << ", " << _top_candidate.phi_std() << ")" << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# top hadrons: " << _top_hadrons.size() << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# hard substructures: " << _parts_size << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# |m - mtop| : " << _delta_top << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# djsum : " << _djsum << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# is consistency cut passed: " << _is_ptmincut_passed << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "#--------------------------------------------------------------------------\n"; + return; + } + + void HEPTopTaggerV2_fixed_R::get_setting() const { + edm::LogInfo("HEPTopTaggerV2") << "#--------------------------------------------------------------------------\n"; + edm::LogInfo("HEPTopTaggerV2") << "# HEPTopTaggerV2 Settings" << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "#" << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# mode: " << _mode << " (0 = EARLY_MASSRATIO_SORT_MASS) " << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# " + << " (1 = LATE_MASSRATIO_SORT_MASS) " << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# " + << " (2 = EARLY_MASSRATIO_SORT_MODDJADE) " << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# " + << " (3 = LATE_MASSRATIO_SORT_MODDJADE) " << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# " + << " (4 = TWO_STEP_FILTER) " << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# top mass: " << _mtmass << " "; + edm::LogInfo("HEPTopTaggerV2") << "W mass: " << _mwmass << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# top mass window: [" << _mtmin << ", " << _mtmax << "]" << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# W mass ratio: [" << _rmin << ", " << _rmax << "] ([" + << _rmin * _mtmass / _mwmass << "%, " << _rmax * _mtmass / _mwmass << "%])" + << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# mass plane cuts: (m23cut, m13min, m13max) = (" << _m23cut << ", " << _m13cutmin + << ", " << _m13cutmax << ")" << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# mass_drop_threshold: " << _mass_drop_threshold << " "; + edm::LogInfo("HEPTopTaggerV2") << "max_subjet_mass: " << _max_subjet_mass << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# R_filt: " << _Rfilt << " "; + edm::LogInfo("HEPTopTaggerV2") << "n_filt: " << _nfilt << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# minimal subjet pt: " << _minpt_subjet << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# minimal reconstructed pt: " << _minpt_tag << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# internal jet algorithms (0 = kt, 1 = C/A, 2 = anti-kt): " << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# filtering: " << _jet_algorithm_filter << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "# reclustering: " << _jet_algorithm_recluster << std::endl; + edm::LogInfo("HEPTopTaggerV2") << "#--------------------------------------------------------------------------\n"; + + return; + } + + //uncluster a fat jet to subjets of given cone size + void HEPTopTaggerV2::UnclusterFatjets(const vector& big_fatjets, + vector& small_fatjets, + const ClusterSequence& cseq, + const double small_radius) { + for (unsigned i = 0; i < big_fatjets.size(); i++) { + PseudoJet this_jet = big_fatjets[i]; + PseudoJet parent1(0, 0, 0, 0), parent2(0, 0, 0, 0); + bool test = cseq.has_parents(this_jet, parent1, parent2); + double dR = 100; + + if (test) + dR = sqrt(parent1.squared_distance(parent2)); + + if (!test || dR < small_radius) { + small_fatjets.push_back(this_jet); + } else { + vector parents; + parents.push_back(parent1); + parents.push_back(parent2); + UnclusterFatjets(parents, small_fatjets, cseq, small_radius); } - - big_fatjets = small_fatjets; - small_fatjets.clear(); - }//End of loop over R - - // if we did not find Ropt in the loop: - if (_Ropt == 0 && _HEPTopTaggerV2[maxR].t().m() > 0){ - // either pick the last value (_R_opt_reject_min=false) - // or leace Ropt at zero (_R_opt_reject_min=true) - if (_R_opt_reject_min==false) - _Ropt = minR; } + } - //for the case that there is no tag at all (< 3 hard substructures) - if (_Ropt == 0 && _HEPTopTaggerV2[maxR].t().m() == 0) + HEPTopTaggerV2::HEPTopTaggerV2() + : _do_optimalR(false), + _do_qjets(false), + _mass_drop_threshold(0.8), + _max_subjet_mass(30.), + _mode(Mode(0)), + _mtmass(172.3), + _mwmass(80.4), + _mtmin(150.), + _mtmax(200.), + _rmin(0.85 * 80.4 / 172.3), + _rmax(1.15 * 80.4 / 172.3), + _m23cut(0.35), + _m13cutmin(0.2), + _m13cutmax(1.3), + _minpt_tag(200.), + _nfilt(5), + _Rfilt(0.3), + _jet_algorithm_filter(fastjet::cambridge_algorithm), + _minpt_subjet(0.), + _jet_algorithm_recluster(fastjet::cambridge_algorithm), + _zcut(0.1), + _rcut_factor(0.5), + _max_fatjet_R(1.8), + _min_fatjet_R(0.5), + _step_R(0.1), + _optimalR_threshold(0.2), + _R_filt_optimalR_calc(0.2), + _N_filt_optimalR_calc(10), + _r_min_exp_function(&R_opt_calc_funct), + _optimalR_mmin(150.), + _optimalR_mmax(200.), + _optimalR_fw(0.175), + _R_opt_diff(0.3), + _R_opt_reject_min(false), + _R_filt_optimalR_pass(0.2), + _N_filt_optimalR_pass(5), + _R_filt_optimalR_fail(0.3), + _N_filt_optimalR_fail(3), + _q_zcut(0.1), + _q_dcut_fctr(0.5), + _q_exp_min(0.), + _q_exp_max(0.), + _q_rigidity(0.1), + _q_truncation_fctr(0.0), + _rnEngine(nullptr), + _debug(false) {} + + HEPTopTaggerV2::HEPTopTaggerV2(const fastjet::PseudoJet& jet) + : _do_optimalR(false), + _do_qjets(false), + _jet(jet), + _initial_jet(jet), + _mass_drop_threshold(0.8), + _max_subjet_mass(30.), + _mode(Mode(0)), + _mtmass(172.3), + _mwmass(80.4), + _mtmin(150.), + _mtmax(200.), + _rmin(0.85 * 80.4 / 172.3), + _rmax(1.15 * 80.4 / 172.3), + _m23cut(0.35), + _m13cutmin(0.2), + _m13cutmax(1.3), + _minpt_tag(200.), + _nfilt(5), + _Rfilt(0.3), + _jet_algorithm_filter(fastjet::cambridge_algorithm), + _minpt_subjet(0.), + _jet_algorithm_recluster(fastjet::cambridge_algorithm), + _zcut(0.1), + _rcut_factor(0.5), + _max_fatjet_R(jet.validated_cluster_sequence()->jet_def().R()), + _min_fatjet_R(0.5), + _step_R(0.1), + _optimalR_threshold(0.2), + _R_filt_optimalR_calc(0.2), + _N_filt_optimalR_calc(10), + _r_min_exp_function(&R_opt_calc_funct), + _optimalR_mmin(150.), + _optimalR_mmax(200.), + _optimalR_fw(0.175), + _R_opt_diff(0.3), + _R_opt_reject_min(false), + _R_filt_optimalR_pass(0.2), + _N_filt_optimalR_pass(5), + _R_filt_optimalR_fail(0.3), + _N_filt_optimalR_fail(3), + _q_zcut(0.1), + _q_dcut_fctr(0.5), + _q_exp_min(0.), + _q_exp_max(0.), + _q_rigidity(0.1), + _q_truncation_fctr(0.0), + _fat(jet), + _rnEngine(nullptr), + _debug(false) {} + + HEPTopTaggerV2::HEPTopTaggerV2(const fastjet::PseudoJet& jet, double mtmass, double mwmass) + : _do_optimalR(false), + _do_qjets(false), + _jet(jet), + _initial_jet(jet), + _mass_drop_threshold(0.8), + _max_subjet_mass(30.), + _mode(Mode(0)), + _mtmass(mtmass), + _mwmass(mwmass), + _mtmin(150.), + _mtmax(200.), + _rmin(0.85 * 80.4 / 172.3), + _rmax(1.15 * 80.4 / 172.3), + _m23cut(0.35), + _m13cutmin(0.2), + _m13cutmax(1.3), + _minpt_tag(200.), + _nfilt(5), + _Rfilt(0.3), + _jet_algorithm_filter(fastjet::cambridge_algorithm), + _minpt_subjet(0.), + _jet_algorithm_recluster(fastjet::cambridge_algorithm), + _zcut(0.1), + _rcut_factor(0.5), + _max_fatjet_R(jet.validated_cluster_sequence()->jet_def().R()), + _min_fatjet_R(0.5), + _step_R(0.1), + _optimalR_threshold(0.2), + _R_filt_optimalR_calc(0.2), + _N_filt_optimalR_calc(10), + _r_min_exp_function(&R_opt_calc_funct), + _optimalR_mmin(150.), + _optimalR_mmax(200.), + _optimalR_fw(0.175), + _R_opt_diff(0.3), + _R_opt_reject_min(false), + _R_filt_optimalR_pass(0.2), + _N_filt_optimalR_pass(5), + _R_filt_optimalR_fail(0.3), + _N_filt_optimalR_fail(3), + _q_zcut(0.1), + _q_dcut_fctr(0.5), + _q_exp_min(0.), + _q_exp_max(0.), + _q_rigidity(0.1), + _q_truncation_fctr(0.0), + _fat(jet), + _rnEngine(nullptr), + _debug(false) {} + + void HEPTopTaggerV2::run() { + QjetsPlugin _qjet_plugin(_q_zcut, _q_dcut_fctr, _q_exp_min, _q_exp_max, _q_rigidity, _q_truncation_fctr); + int maxR = int(_max_fatjet_R * 10); + int minR = int(_min_fatjet_R * 10); + int stepR = int(_step_R * 10); + _qweight = -1; + _qjet_plugin.SetRNEngine(_rnEngine); + + if (!_do_optimalR) { + HEPTopTaggerV2_fixed_R htt(_jet); + htt.set_mass_drop_threshold(_mass_drop_threshold); + htt.set_max_subjet_mass(_max_subjet_mass); + htt.set_filtering_n(_nfilt); + htt.set_filtering_R(_Rfilt); + htt.set_filtering_minpt_subjet(_minpt_subjet); + htt.set_filtering_jetalgorithm(_jet_algorithm_filter); + htt.set_reclustering_jetalgorithm(_jet_algorithm_recluster); + htt.set_mode(_mode); + htt.set_mt(_mtmass); + htt.set_mw(_mwmass); + htt.set_top_mass_range(_mtmin, _mtmax); + htt.set_mass_ratio_range(_rmin, _rmax); + htt.set_mass_ratio_cut(_m23cut, _m13cutmin, _m13cutmax); + htt.set_top_minpt(_minpt_tag); + htt.set_pruning_zcut(_zcut); + htt.set_pruning_rcut_factor(_rcut_factor); + htt.set_debug(_debug); + htt.set_qjets(_q_zcut, _q_dcut_fctr, _q_exp_min, _q_exp_max, _q_rigidity, _q_truncation_fctr); + htt.run(); + + _HEPTopTaggerV2[maxR] = htt; _Ropt = maxR; - - _HEPTopTaggerV2_opt = _HEPTopTaggerV2[_Ropt]; - - Filter filter_optimalR_calc(_R_filt_optimalR_calc, SelectorNHardest(_N_filt_optimalR_calc)); - _R_opt_calc = _r_min_exp_function(filter_optimalR_calc(_fat).pt()); - _pt_for_R_opt_calc = filter_optimalR_calc(_fat).pt(); - - Filter filter_optimalR_pass(_R_filt_optimalR_pass, SelectorNHardest(_N_filt_optimalR_pass)); - Filter filter_optimalR_fail(_R_filt_optimalR_fail, SelectorNHardest(_N_filt_optimalR_fail)); - if(optimalR_type() == 1) { - _filt_fat = filter_optimalR_pass(_fat); + _qweight = htt.q_weight(); + _HEPTopTaggerV2_opt = _HEPTopTaggerV2[_Ropt]; } else { - _filt_fat = filter_optimalR_fail(_fat); + _qjet_def = fastjet::JetDefinition(&_qjet_plugin); + vector _q_constits; + ClusterSequence* _qjet_seq; + PseudoJet _qjet; + const ClusterSequence* _seq; + _seq = _initial_jet.validated_cluster_sequence(); + if (_do_qjets) { + _q_constits = _initial_jet.associated_cluster_sequence()->constituents(_initial_jet); + _qjet_seq = new ClusterSequence(_q_constits, _qjet_def); + _qjet = sorted_by_pt(_qjet_seq->inclusive_jets())[0]; + _qjet_seq->delete_self_when_unused(); + const QjetsBaseExtras* ext = dynamic_cast(_qjet_seq->extras()); + _qweight = ext->weight(); + _jet = _qjet; + _seq = _qjet_seq; + _fat = _qjet; + } + + // Do MultiR procedure + vector big_fatjets; + vector small_fatjets; + + big_fatjets.push_back(_jet); + _Ropt = 0; + + for (int R = maxR; R >= minR; R -= stepR) { + UnclusterFatjets(big_fatjets, small_fatjets, *_seq, R / 10.); + + if (_debug) { + edm::LogInfo("HEPTopTaggerV2") << "R = " << R << " -> n_small_fatjets = " << small_fatjets.size() << endl; + } + + _n_small_fatjets[R] = small_fatjets.size(); + + // We are sorting by pt - so start with a negative dummy + double dummy = -99999; + + for (unsigned i = 0; i < small_fatjets.size(); i++) { + HEPTopTaggerV2_fixed_R htt(small_fatjets[i]); + htt.set_mass_drop_threshold(_mass_drop_threshold); + htt.set_max_subjet_mass(_max_subjet_mass); + htt.set_filtering_n(_nfilt); + htt.set_filtering_R(_Rfilt); + htt.set_filtering_minpt_subjet(_minpt_subjet); + htt.set_filtering_jetalgorithm(_jet_algorithm_filter); + htt.set_reclustering_jetalgorithm(_jet_algorithm_recluster); + htt.set_mode(_mode); + htt.set_mt(_mtmass); + htt.set_mw(_mwmass); + htt.set_top_mass_range(_mtmin, _mtmax); + htt.set_mass_ratio_range(_rmin, _rmax); + htt.set_mass_ratio_cut(_m23cut, _m13cutmin, _m13cutmax); + htt.set_top_minpt(_minpt_tag); + htt.set_pruning_zcut(_zcut); + htt.set_pruning_rcut_factor(_rcut_factor); + htt.set_debug(_debug); + htt.set_qjets(_q_zcut, _q_dcut_fctr, _q_exp_min, _q_exp_max, _q_rigidity, _q_truncation_fctr); + + htt.run(); + + if (htt.t().perp() > dummy) { + dummy = htt.t().perp(); + _HEPTopTaggerV2[R] = htt; + } + } //End of loop over small_fatjets + + // Only check if we have not found Ropt yet + if (_Ropt == 0 && R < maxR) { + // If the new mass is OUTSIDE the window .. + if (_HEPTopTaggerV2[R].t().m() < (1 - _optimalR_threshold) * _HEPTopTaggerV2[maxR].t().m()) + // .. set _Ropt to the previous mass + _Ropt = R + stepR; + } + + big_fatjets = small_fatjets; + small_fatjets.clear(); + } //End of loop over R + + // if we did not find Ropt in the loop: + if (_Ropt == 0 && _HEPTopTaggerV2[maxR].t().m() > 0) { + // either pick the last value (_R_opt_reject_min=false) + // or leace Ropt at zero (_R_opt_reject_min=true) + if (_R_opt_reject_min == false) + _Ropt = minR; + } + + //for the case that there is no tag at all (< 3 hard substructures) + if (_Ropt == 0 && _HEPTopTaggerV2[maxR].t().m() == 0) + _Ropt = maxR; + + _HEPTopTaggerV2_opt = _HEPTopTaggerV2[_Ropt]; + + Filter filter_optimalR_calc(_R_filt_optimalR_calc, SelectorNHardest(_N_filt_optimalR_calc)); + _R_opt_calc = _r_min_exp_function(filter_optimalR_calc(_fat).pt()); + _pt_for_R_opt_calc = filter_optimalR_calc(_fat).pt(); + + Filter filter_optimalR_pass(_R_filt_optimalR_pass, SelectorNHardest(_N_filt_optimalR_pass)); + Filter filter_optimalR_fail(_R_filt_optimalR_fail, SelectorNHardest(_N_filt_optimalR_fail)); + if (optimalR_type() == 1) { + _filt_fat = filter_optimalR_pass(_fat); + } else { + _filt_fat = filter_optimalR_fail(_fat); + } } } -} -//optimal_R type -int HEPTopTaggerV2::optimalR_type() { - if(_HEPTopTaggerV2_opt.t().m() < _optimalR_mmin || _HEPTopTaggerV2_opt.t().m() > _optimalR_mmax) { - return 0; - } - if(_HEPTopTaggerV2_opt.f_rec() > _optimalR_fw) { - return 0; - } - if(_Ropt/10. - _R_opt_calc > _R_opt_diff) { - return 0; + //optimal_R type + int HEPTopTaggerV2::optimalR_type() { + if (_HEPTopTaggerV2_opt.t().m() < _optimalR_mmin || _HEPTopTaggerV2_opt.t().m() > _optimalR_mmax) { + return 0; + } + if (_HEPTopTaggerV2_opt.f_rec() > _optimalR_fw) { + return 0; + } + if (_Ropt / 10. - _R_opt_calc > _R_opt_diff) { + return 0; + } + return 1; } - return 1; -} -double HEPTopTaggerV2::nsub_unfiltered(int order, fastjet::contrib::Njettiness::AxesMode axes, double beta, double R0) { - fastjet::contrib::Nsubjettiness nsub(order, axes, beta, R0); - return nsub.result(_fat); -} + double HEPTopTaggerV2::nsub_unfiltered(int order, + fastjet::contrib::Njettiness::AxesMode axes, + double beta, + double R0) { + fastjet::contrib::Nsubjettiness nsub(order, axes, beta, R0); + return nsub.result(_fat); + } -double HEPTopTaggerV2::nsub_filtered(int order, fastjet::contrib::Njettiness::AxesMode axes, double beta, double R0) { - fastjet::contrib::Nsubjettiness nsub(order, axes, beta, R0); - return nsub.result(_filt_fat); -} + double HEPTopTaggerV2::nsub_filtered(int order, fastjet::contrib::Njettiness::AxesMode axes, double beta, double R0) { + fastjet::contrib::Nsubjettiness nsub(order, axes, beta, R0); + return nsub.result(_filt_fat); + } -HEPTopTaggerV2::~HEPTopTaggerV2(){} -// Do not change next line, it's needed by the sed-code that makes the tagger CMSSW-compatible. -}; + HEPTopTaggerV2::~HEPTopTaggerV2() {} + // Do not change next line, it's needed by the sed-code that makes the tagger CMSSW-compatible. +}; // namespace external diff --git a/RecoJets/JetAlgorithms/src/HEPTopTaggerWrapperV2.cc b/RecoJets/JetAlgorithms/src/HEPTopTaggerWrapperV2.cc index c660d24a8a0bd..d885aad54369a 100644 --- a/RecoJets/JetAlgorithms/src/HEPTopTaggerWrapperV2.cc +++ b/RecoJets/JetAlgorithms/src/HEPTopTaggerWrapperV2.cc @@ -33,60 +33,53 @@ using namespace std; #include "RecoJets/JetAlgorithms/interface/HEPTopTaggerV2.h" - FASTJET_BEGIN_NAMESPACE - // Expected R_min for tops (as function of filtered initial fatjet pT in GeV (using CA, R=0.2, n=10) // From ttbar sample, phys14, n20, bx25 // matched to hadronically decaying top with delta R < 1.2 and true top pT > 200 // Cuts are: fW < 0.175 and m_top = 120..220 // Input objects are packed pfCandidates with CHS -double R_min_expected_function(double x){ +double R_min_expected_function(double x) { + if (x > 700) + x = 700; + double A = -9.42052; + double B = 0.202773; + double C = 4498.45; + double D = -1.05737e+06; + double E = 9.95494e+07; - if (x>700) - x=700; - - double A = -9.42052; - double B = 0.202773; - double C = 4498.45; - double D = -1.05737e+06; - double E = 9.95494e+07; - - return A+B*sqrt(x)+C/x+D/(x*x)+E/(x*x*x); + return A + B * sqrt(x) + C / x + D / (x * x) + E / (x * x * x); } - - //------------------------------------------------------------------------ // returns the tagged PseudoJet if successful, 0 otherwise // - jet the PseudoJet to tag -PseudoJet HEPTopTaggerV2::result(const PseudoJet & jet) const{ - +PseudoJet HEPTopTaggerV2::result(const PseudoJet &jet) const { // make sure that there is a "regular" cluster sequence associated // with the jet. Note that we also check it is valid (to avoid a // more criptic error later on) - if (!jet.has_valid_cluster_sequence()){ + if (!jet.has_valid_cluster_sequence()) { throw Error("HEPTopTagger can only be applied on jets having an associated (and valid) ClusterSequence"); } external::HEPTopTaggerV2 tagger(jet); - + external::HEPTopTaggerV2 best_tagger; - // translate the massRatioWidth (which should be the half-width given in %) + // translate the massRatioWidth (which should be the half-width given in %) // to values useful for the A-shape cuts - double mw_over_mt = 80.4/172.3; - double ratio_min = mw_over_mt * (100.-massRatioWidth_)/100.; - double ratio_max = mw_over_mt * (100.+massRatioWidth_)/100.; - + double mw_over_mt = 80.4 / 172.3; + double ratio_min = mw_over_mt * (100. - massRatioWidth_) / 100.; + double ratio_max = mw_over_mt * (100. + massRatioWidth_) / 100.; + // Unclustering, Filtering & Subjet Settings tagger.set_max_subjet_mass(subjetMass_); tagger.set_mass_drop_threshold(muCut_); tagger.set_filtering_R(filtR_); tagger.set_filtering_n(filtN_); - tagger.set_filtering_minpt_subjet(minSubjetPt_); + tagger.set_filtering_minpt_subjet(minSubjetPt_); // Optimal R tagger.do_optimalR(DoOptimalR_); @@ -94,23 +87,21 @@ PseudoJet HEPTopTaggerV2::result(const PseudoJet & jet) const{ // How to select among candidates tagger.set_mode((external::Mode)mode_); - + // Requirements to accept a candidate - tagger.set_top_minpt(minCandPt_); - tagger.set_top_mass_range(minCandMass_, maxCandMass_); + tagger.set_top_minpt(minCandPt_); + tagger.set_top_mass_range(minCandMass_, maxCandMass_); tagger.set_mass_ratio_cut(minM23Cut_, minM13Cut_, maxM13Cut_); tagger.set_mass_ratio_range(ratio_min, ratio_max); // Set function to calculate R_min_expected tagger.set_optimalR_calc_fun(R_min_expected_function); - - double qweight = -1; + double qweight = -1; double qepsilon = -1; - double qsigmaM = -1; + double qsigmaM = -1; - if (DoQjets_){ - + if (DoQjets_) { int niter(100); double q_zcut(0.1); double q_dcut_fctr(0.5); @@ -118,47 +109,41 @@ PseudoJet HEPTopTaggerV2::result(const PseudoJet & jet) const{ double q_exp_max(0.); double q_rigidity(0.1); double q_truncation_fctr(0.0); - + double weight_q1 = -1.; double m_sum = 0.; double m2_sum = 0.; int qtags = 0; - tagger.set_qjets(q_zcut, - q_dcut_fctr, - q_exp_min, - q_exp_max, - q_rigidity, - q_truncation_fctr); - tagger.set_qjets_rng(engine_); + tagger.set_qjets(q_zcut, q_dcut_fctr, q_exp_min, q_exp_max, q_rigidity, q_truncation_fctr); + tagger.set_qjets_rng(engine_); tagger.do_qjets(true); tagger.run(); for (int iq = 0; iq < niter; iq++) { tagger.run(); if (tagger.is_tagged()) { - qtags++; - m_sum += tagger.t().m(); - m2_sum += tagger.t().m() * tagger.t().m(); - if (tagger.q_weight() > weight_q1) { - best_tagger = tagger; - weight_q1=tagger.q_weight(); - } + qtags++; + m_sum += tagger.t().m(); + m2_sum += tagger.t().m() * tagger.t().m(); + if (tagger.q_weight() > weight_q1) { + best_tagger = tagger; + weight_q1 = tagger.q_weight(); + } } } - + tagger = best_tagger; qweight = weight_q1; - qepsilon = float(qtags)/float(niter); - + qepsilon = float(qtags) / float(niter); + // calculate width of tagged mass distribution if we have at least one candidate - if (qtags > 0){ + if (qtags > 0) { double mean_m = m_sum / qtags; double mean_m2 = m2_sum / qtags; - qsigmaM = sqrt(mean_m2 - mean_m*mean_m); + qsigmaM = sqrt(mean_m2 - mean_m * mean_m); } - } - else{ + } else { tagger.run(); } @@ -169,12 +154,11 @@ PseudoJet HEPTopTaggerV2::result(const PseudoJet & jet) const{ // If this is not intended: use loose top mass and ratio windows if (!tagger.is_tagged()) return PseudoJet(); - + // create the result and its structure - const JetDefinition::Recombiner *rec - = jet.associated_cluster_sequence()->jet_def().recombiner(); + const JetDefinition::Recombiner *rec = jet.associated_cluster_sequence()->jet_def().recombiner(); - const vector& subjets = tagger.top_subjets(); + const vector &subjets = tagger.top_subjets(); assert(subjets.size() == 3); PseudoJet non_W = subjets[0]; @@ -182,13 +166,13 @@ PseudoJet HEPTopTaggerV2::result(const PseudoJet & jet) const{ PseudoJet W2 = subjets[2]; PseudoJet W = join(subjets[1], subjets[2], *rec); - PseudoJet result = join( W1, W2, non_W, *rec); - HEPTopTaggerV2Structure *s = (HEPTopTaggerV2Structure*) result.structure_non_const_ptr(); + PseudoJet result = join(W1, W2, non_W, *rec); + HEPTopTaggerV2Structure *s = (HEPTopTaggerV2Structure *)result.structure_non_const_ptr(); - s->_fj_mass = jet.m(); - s->_fj_pt = jet.perp(); - s->_fj_eta = jet.eta(); - s->_fj_phi = jet.phi(); + s->_fj_mass = jet.m(); + s->_fj_pt = jet.perp(); + s->_fj_eta = jet.eta(); + s->_fj_phi = jet.phi(); s->_top_mass = tagger.t().m(); s->_pruned_mass = tagger.pruned_mass(); @@ -196,7 +180,7 @@ PseudoJet HEPTopTaggerV2::result(const PseudoJet & jet) const{ s->_fRec = tagger.f_rec(); s->_mass_ratio_passed = tagger.is_masscut_passed(); - if (DoOptimalR_){ + if (DoOptimalR_) { s->_tau1Unfiltered = tagger.nsub_unfiltered(1); s->_tau2Unfiltered = tagger.nsub_unfiltered(2); s->_tau3Unfiltered = tagger.nsub_unfiltered(3); @@ -209,13 +193,11 @@ PseudoJet HEPTopTaggerV2::result(const PseudoJet & jet) const{ s->_qepsilon = qepsilon; s->_qsigmaM = qsigmaM; - - if (DoOptimalR_){ + if (DoOptimalR_) { s->_ropt = tagger.Ropt(); s->_roptCalc = tagger.Ropt_calc(); s->_ptForRoptCalc = tagger.pt_for_Ropt_calc(); - } - else { + } else { s->_ropt = -1; s->_roptCalc = -1; s->_ptForRoptCalc = -1; diff --git a/RecoJets/JetAlgorithms/src/PrunedRecombiner.cc b/RecoJets/JetAlgorithms/src/PrunedRecombiner.cc index d07819cc2bf8d..58f7e4ff3032b 100644 --- a/RecoJets/JetAlgorithms/src/PrunedRecombiner.cc +++ b/RecoJets/JetAlgorithms/src/PrunedRecombiner.cc @@ -10,75 +10,66 @@ using namespace fastjet; -std::string PrunedRecombiner::description() const -{ - std::ostringstream s; - s << "Pruned " << _recombiner->description() - << ", with zcut = " << _zcut << " and Rcut = " << _Rcut; - return s.str(); -} - +std::string PrunedRecombiner::description() const { + std::ostringstream s; + s << "Pruned " << _recombiner->description() << ", with zcut = " << _zcut << " and Rcut = " << _Rcut; + return s.str(); +} + // Recombine pa and pb and put result into pab. // If pruning test is true (the recombination is vetoed) the harder // parent is merged with a 0 PseudoJet. (Check that this is an identity in // all recombination schemes!) -// When a branch is pruned, its cluster_hist_index is stored in +// When a branch is pruned, its cluster_hist_index is stored in // _pruned_pseudojets for later use. -void PrunedRecombiner::recombine(const PseudoJet & pa, const PseudoJet & pb, - PseudoJet & pab) const -{ - PseudoJet p0(0.0, 0.0, 0.0, 0.0); - // test if recombination should be pruned - switch ( _pruning_test(pa, pb) ) { - case 1: - _pruned_pseudojets.push_back(pb.cluster_hist_index()); - _recombiner->recombine(pa, p0, pab); - break; - case 2: - _pruned_pseudojets.push_back(pa.cluster_hist_index()); - _recombiner->recombine(pb, p0, pab); - break; - default: - // if no pruning, do regular combination - _recombiner->recombine(pa, pb, pab); - } +void PrunedRecombiner::recombine(const PseudoJet& pa, const PseudoJet& pb, PseudoJet& pab) const { + PseudoJet p0(0.0, 0.0, 0.0, 0.0); + // test if recombination should be pruned + switch (_pruning_test(pa, pb)) { + case 1: + _pruned_pseudojets.push_back(pb.cluster_hist_index()); + _recombiner->recombine(pa, p0, pab); + break; + case 2: + _pruned_pseudojets.push_back(pa.cluster_hist_index()); + _recombiner->recombine(pb, p0, pab); + break; + default: + // if no pruning, do regular combination + _recombiner->recombine(pa, pb, pab); + } } - // Function to test if two pseudojets should be merged -- ie, to selectively // veto mergings. Should provide possibility to provide this function... // Return codes: // // 0: Merge. (Currently, anything other than 1 or 2 will do.) // 1: Don't merge; keep pa -// 2: Don't merge; keep pb +// 2: Don't merge; keep pb // -int PrunedRecombiner::_pruning_test(const PseudoJet & pa, const PseudoJet & pb) const -{ - // create the new jet by recombining the first two, using the normal - // recombination scheme - PseudoJet newjet; - _recombiner->recombine(pa, pb, newjet); +int PrunedRecombiner::_pruning_test(const PseudoJet& pa, const PseudoJet& pb) const { + // create the new jet by recombining the first two, using the normal + // recombination scheme + PseudoJet newjet; + _recombiner->recombine(pa, pb, newjet); - double minpT = pa.perp(); - int hard = 2; // harder pj is pj2 - double tmp = pb.perp(); - if (tmp < minpT) { - minpT = tmp; - hard = 1; // harder pj is pj1 - } - - if ( pa.squared_distance(pb) < _Rcut*_Rcut - || minpT > _zcut * newjet.perp() ) - return 0; - else - return hard; -} + double minpT = pa.perp(); + int hard = 2; // harder pj is pj2 + double tmp = pb.perp(); + if (tmp < minpT) { + minpT = tmp; + hard = 1; // harder pj is pj1 + } + if (pa.squared_distance(pb) < _Rcut * _Rcut || minpT > _zcut * newjet.perp()) + return 0; + else + return hard; +} -void PrunedRecombiner::reset(const double & zcut, const double & Rcut) -{ - _pruned_pseudojets.clear(); - _zcut = zcut; - _Rcut = Rcut; +void PrunedRecombiner::reset(const double& zcut, const double& Rcut) { + _pruned_pseudojets.clear(); + _zcut = zcut; + _Rcut = Rcut; } diff --git a/RecoJets/JetAlgorithms/src/QGLikelihoodCalculator.cc b/RecoJets/JetAlgorithms/src/QGLikelihoodCalculator.cc index 735f87e3e0a8e..c7cd249db8a14 100644 --- a/RecoJets/JetAlgorithms/src/QGLikelihoodCalculator.cc +++ b/RecoJets/JetAlgorithms/src/QGLikelihoodCalculator.cc @@ -5,15 +5,17 @@ #include /// Compute likelihood for a jet using the QGLikelihoodObject information and a set of variables -float QGLikelihoodCalculator::computeQGLikelihood(edm::ESHandle &QGLParamsColl, float pt, float eta, float rho, std::vector vars) const{ - if(!isValidRange(pt, rho, eta, QGLParamsColl->qgValidRange)) return -1; - - float Q=1., G=1.; - for(unsigned int varIndex = 0; varIndex < vars.size(); ++varIndex){ +float QGLikelihoodCalculator::computeQGLikelihood( + edm::ESHandle &QGLParamsColl, float pt, float eta, float rho, std::vector vars) const { + if (!isValidRange(pt, rho, eta, QGLParamsColl->qgValidRange)) + return -1; + float Q = 1., G = 1.; + for (unsigned int varIndex = 0; varIndex < vars.size(); ++varIndex) { auto quarkEntry = findEntry(QGLParamsColl->data, eta, pt, rho, 0, varIndex); auto gluonEntry = findEntry(QGLParamsColl->data, eta, pt, rho, 1, varIndex); - if(!quarkEntry || !gluonEntry) return -2; + if (!quarkEntry || !gluonEntry) + return -2; int binQ = quarkEntry->histogram.findBin(vars[varIndex]); float Qi = quarkEntry->histogram.binContent(binQ); @@ -25,13 +27,18 @@ float QGLikelihoodCalculator::computeQGLikelihood(edm::ESHandle const &data, float eta, float pt, float rho, int qgIndex, int varIndex) const{ +const QGLikelihoodObject::Entry *QGLikelihoodCalculator::findEntry(std::vector const &data, + float eta, + float pt, + float rho, + int qgIndex, + int varIndex) const { QGLikelihoodParameters myParameters; myParameters.Rho = rho; myParameters.Pt = pt; @@ -40,46 +47,64 @@ const QGLikelihoodObject::Entry* QGLikelihoodCalculator::findEntry(std::vectorcategory)){ + while (!(myParameters == myDataObject->category)) { ++myDataObject; - if(myDataObject == data.end()){ - edm::LogWarning("QGLCategoryNotFound") << "Jet passed qgValidRange criteria, but no category found with rho=" << rho << ", pt=" << pt << ", eta=" << eta - << "\nPlease contact cms-qg-workinggroup@cern.ch" << std::endl; + if (myDataObject == data.end()) { + edm::LogWarning("QGLCategoryNotFound") + << "Jet passed qgValidRange criteria, but no category found with rho=" << rho << ", pt=" << pt + << ", eta=" << eta << "\nPlease contact cms-qg-workinggroup@cern.ch" << std::endl; return nullptr; } } return &*myDataObject; } - /// Check the valid range of this qg tagger -bool QGLikelihoodCalculator::isValidRange(float pt, float rho, float eta, const QGLikelihoodCategory &qgValidRange) const{ - if(pt < qgValidRange.PtMin) return false; - if(pt > qgValidRange.PtMax) return false; - if(rho < qgValidRange.RhoMin) return false; - if(rho > qgValidRange.RhoMax) return false; - if(fabs(eta) < qgValidRange.EtaMin) return false; - if(fabs(eta) > qgValidRange.EtaMax) return false; +bool QGLikelihoodCalculator::isValidRange(float pt, + float rho, + float eta, + const QGLikelihoodCategory &qgValidRange) const { + if (pt < qgValidRange.PtMin) + return false; + if (pt > qgValidRange.PtMax) + return false; + if (rho < qgValidRange.RhoMin) + return false; + if (rho > qgValidRange.RhoMax) + return false; + if (fabs(eta) < qgValidRange.EtaMin) + return false; + if (fabs(eta) > qgValidRange.EtaMax) + return false; return true; } - /// Return the smeared qgLikelihood value, given input x0 and parameters a, b, min and max -float QGLikelihoodCalculator::smearingFunction(float x0, float a ,float b,float min,float max) const{ - float x=(x0-min)/(max-min); - if(x<0.) x=0.; - if(x>1.) x=1.; - - float x1= tanh(a*atanh(2.*x-1.)+b)/2.+.5; - if(x<=0.) x1=0.; - if(x>=1.) x1=1.; - - return x1*(max-min)+min; +float QGLikelihoodCalculator::smearingFunction(float x0, float a, float b, float min, float max) const { + float x = (x0 - min) / (max - min); + if (x < 0.) + x = 0.; + if (x > 1.) + x = 1.; + + float x1 = tanh(a * atanh(2. * x - 1.) + b) / 2. + .5; + if (x <= 0.) + x1 = 0.; + if (x >= 1.) + x1 = 1.; + + return x1 * (max - min) + min; } // Get systematic smearing -float QGLikelihoodCalculator::systematicSmearing(edm::ESHandle &QGLSystematicsColl, float pt, float eta, float rho, float qgValue, int qgIndex) const{ - if(qgValue < 0 || qgValue > 1) return -1.; +float QGLikelihoodCalculator::systematicSmearing(edm::ESHandle &QGLSystematicsColl, + float pt, + float eta, + float rho, + float qgValue, + int qgIndex) const { + if (qgValue < 0 || qgValue > 1) + return -1.; QGLikelihoodParameters myParameters; myParameters.Rho = rho; @@ -89,9 +114,10 @@ float QGLikelihoodCalculator::systematicSmearing(edm::ESHandledata.begin(); - while(!(myParameters == myDataObject->systCategory)){ + while (!(myParameters == myDataObject->systCategory)) { ++myDataObject; - if(myDataObject == QGLSystematicsColl->data.end()) return -1; //Smearing not available in the whole qgValidRange: do not throw warnings or errors + if (myDataObject == QGLSystematicsColl->data.end()) + return -1; //Smearing not available in the whole qgValidRange: do not throw warnings or errors } return smearingFunction(qgValue, myDataObject->a, myDataObject->b, myDataObject->lmin, myDataObject->lmax); } diff --git a/RecoJets/JetAlgorithms/src/Qjets.cc b/RecoJets/JetAlgorithms/src/Qjets.cc index 2cea287794fd0..477eebb89ecb1 100644 --- a/RecoJets/JetAlgorithms/src/Qjets.cc +++ b/RecoJets/JetAlgorithms/src/Qjets.cc @@ -2,21 +2,17 @@ using namespace std; -void Qjets::SetRandSeed(unsigned int seed){ +void Qjets::SetRandSeed(unsigned int seed) { _rand_seed_set = true; _seed = seed; } -bool Qjets::JetUnmerged(int num) const{ - return _merged_jets.find(num) == _merged_jets.end(); -} +bool Qjets::JetUnmerged(int num) const { return _merged_jets.find(num) == _merged_jets.end(); } -bool Qjets::JetsUnmerged(const JetDistance& jd) const{ - return JetUnmerged(jd.j1) && JetUnmerged(jd.j2); -} +bool Qjets::JetsUnmerged(const JetDistance& jd) const { return JetUnmerged(jd.j1) && JetUnmerged(jd.j2); } -JetDistance Qjets::GetNextDistance(){ - vector< pair > popped_distances; +JetDistance Qjets::GetNextDistance() { + vector > popped_distances; double norm(0.); JetDistance ret; ret.j1 = -1; @@ -25,129 +21,131 @@ JetDistance Qjets::GetNextDistance(){ bool dmin_set(false); double dmin(0.); - while(!_distances.empty()){ + while (!_distances.empty()) { JetDistance dist = _distances.top(); _distances.pop(); - if(JetsUnmerged(dist)){ - if(!dmin_set){ - dmin = dist.dij; - dmin_set = true; + if (JetsUnmerged(dist)) { + if (!dmin_set) { + dmin = dist.dij; + dmin_set = true; } - double weight = exp(-_rigidity * (dist.dij-dmin) /dmin); - popped_distances.push_back(make_pair(dist,weight)); - norm += weight; - if(weight/norm < _truncation_fctr) - break; + double weight = exp(-_rigidity * (dist.dij - dmin) / dmin); + popped_distances.push_back(make_pair(dist, weight)); + norm += weight; + if (weight / norm < _truncation_fctr) + break; } } - + double rand(Rand()), tot_weight(0.); - for(vector >::iterator it = popped_distances.begin(); it != popped_distances.end(); it++){ - tot_weight += (*it).second/norm; - if(tot_weight >= rand){ + for (vector >::iterator it = popped_distances.begin(); it != popped_distances.end(); it++) { + tot_weight += (*it).second / norm; + if (tot_weight >= rand) { ret = (*it).first; omega *= ((*it).second); break; } } - + // repopulate in reverse (maybe quicker?) - for(vector >::reverse_iterator it = popped_distances.rbegin(); it != popped_distances.rend(); it++) - if(JetsUnmerged((*it).first)) + for (vector >::reverse_iterator it = popped_distances.rbegin(); + it != popped_distances.rend(); + it++) + if (JetsUnmerged((*it).first)) _distances.push((*it).first); return ret; } -void Qjets::Cluster(fastjet::ClusterSequence & cs){ +void Qjets::Cluster(fastjet::ClusterSequence& cs) { omega = 1.; - QjetsBaseExtras * extras = new QjetsBaseExtras(); + QjetsBaseExtras* extras = new QjetsBaseExtras(); computeDCut(cs); // Populate all the distances ComputeAllDistances(cs.jets()); JetDistance jd = GetNextDistance(); - while(!_distances.empty() && jd.dij != -1.){ - if(!Prune(jd,cs)){ + while (!_distances.empty() && jd.dij != -1.) { + if (!Prune(jd, cs)) { // _merged_jets.push_back(jd.j1); // _merged_jets.push_back(jd.j2); _merged_jets[jd.j1] = true; _merged_jets[jd.j2] = true; - int new_jet=-1; + int new_jet = -1; cs.plugin_record_ij_recombination(jd.j1, jd.j2, 1., new_jet); - if(!JetUnmerged(new_jet)) - edm::LogError("QJets Clustering") << "Problem with FastJet::plugin_record_ij_recombination"; - ComputeNewDistanceMeasures(cs,new_jet); + if (!JetUnmerged(new_jet)) + edm::LogError("QJets Clustering") << "Problem with FastJet::plugin_record_ij_recombination"; + ComputeNewDistanceMeasures(cs, new_jet); } else { double j1pt = cs.jets()[jd.j1].perp(); double j2pt = cs.jets()[jd.j2].perp(); - if(j1pt>j2pt){ - // _merged_jets.push_back(jd.j2); - _merged_jets[jd.j2] = true; - cs.plugin_record_iB_recombination(jd.j2, 1.); + if (j1pt > j2pt) { + // _merged_jets.push_back(jd.j2); + _merged_jets[jd.j2] = true; + cs.plugin_record_iB_recombination(jd.j2, 1.); } else { - // _merged_jets.push_back(jd.j1); - _merged_jets[jd.j1] = true; - cs.plugin_record_iB_recombination(jd.j1, 1.); + // _merged_jets.push_back(jd.j1); + _merged_jets[jd.j1] = true; + cs.plugin_record_iB_recombination(jd.j1, 1.); } } jd = GetNextDistance(); - } + } extras->_wij = omega; cs.plugin_associate_extras(extras); // merge remaining jets with beam int num_merged_final(0); - for(unsigned int i = 0 ; i < cs.jets().size(); i++) - if(JetUnmerged(i)){ + for (unsigned int i = 0; i < cs.jets().size(); i++) + if (JetUnmerged(i)) { num_merged_final++; - cs.plugin_record_iB_recombination(i,1.); + cs.plugin_record_iB_recombination(i, 1.); } - - if(!(num_merged_final < 2)) + + if (!(num_merged_final < 2)) edm::LogError("QJets Clustering") << "More than 1 jet remains after reclustering"; } -void Qjets::computeDCut(fastjet::ClusterSequence & cs){ +void Qjets::computeDCut(fastjet::ClusterSequence& cs) { // assume all jets in cs form a single jet. compute mass and pt - fastjet::PseudoJet sum(0.,0.,0.,0.); - for(vector::const_iterator it = cs.jets().begin(); it != cs.jets().end(); it++) + fastjet::PseudoJet sum(0., 0., 0., 0.); + for (vector::const_iterator it = cs.jets().begin(); it != cs.jets().end(); it++) sum += (*it); - _dcut = 2. * _dcut_fctr * sum.m()/sum.perp(); + _dcut = 2. * _dcut_fctr * sum.m() / sum.perp(); } -bool Qjets::Prune(JetDistance& jd,fastjet::ClusterSequence & cs){ +bool Qjets::Prune(JetDistance& jd, fastjet::ClusterSequence& cs) { double pt1 = cs.jets()[jd.j1].perp(); double pt2 = cs.jets()[jd.j2].perp(); - fastjet::PseudoJet sum_jet = cs.jets()[jd.j1]+cs.jets()[jd.j2]; + fastjet::PseudoJet sum_jet = cs.jets()[jd.j1] + cs.jets()[jd.j2]; double sum_pt = sum_jet.perp(); - double z = min(pt1,pt2)/sum_pt; + double z = min(pt1, pt2) / sum_pt; double d2 = cs.jets()[jd.j1].plain_distance(cs.jets()[jd.j2]); - return (d2 > _dcut*_dcut) && (z < _zcut); + return (d2 > _dcut * _dcut) && (z < _zcut); } -void Qjets::ComputeAllDistances(const vector& inp){ - for(unsigned int i = 0 ; i < inp.size()-1; i++){ +void Qjets::ComputeAllDistances(const vector& inp) { + for (unsigned int i = 0; i < inp.size() - 1; i++) { // jet-jet distances - for(unsigned int j = i+1 ; j < inp.size(); j++){ + for (unsigned int j = i + 1; j < inp.size(); j++) { JetDistance jd; jd.j1 = i; jd.j2 = j; - if(jd.j1 != jd.j2){ - jd.dij = d_ij(inp[i],inp[j]); - _distances.push(jd); + if (jd.j1 != jd.j2) { + jd.dij = d_ij(inp[i], inp[j]); + _distances.push(jd); } - } + } } } -void Qjets::ComputeNewDistanceMeasures(fastjet::ClusterSequence & cs, unsigned int new_jet){ +void Qjets::ComputeNewDistanceMeasures(fastjet::ClusterSequence& cs, unsigned int new_jet) { // jet-jet distances - for(unsigned int i = 0; i < cs.jets().size(); i++) - if(JetUnmerged(i) && i != new_jet){ + for (unsigned int i = 0; i < cs.jets().size(); i++) + if (JetUnmerged(i) && i != new_jet) { JetDistance jd; jd.j1 = new_jet; jd.j2 = i; @@ -156,20 +154,20 @@ void Qjets::ComputeNewDistanceMeasures(fastjet::ClusterSequence & cs, unsigned i } } -double Qjets::d_ij(const fastjet::PseudoJet& v1,const fastjet::PseudoJet& v2) const{ +double Qjets::d_ij(const fastjet::PseudoJet& v1, const fastjet::PseudoJet& v2) const { double p1 = v1.perp(); double p2 = v2.perp(); - double ret = pow(min(p1,p2),_exp_min) * pow(max(p1,p2),_exp_max) * v1.squared_distance(v2); - if(edm::isNotFinite(ret)) + double ret = pow(min(p1, p2), _exp_min) * pow(max(p1, p2), _exp_max) * v1.squared_distance(v2); + if (edm::isNotFinite(ret)) edm::LogError("QJets Clustering") << "d_ij is not finite"; - return ret; + return ret; } -double Qjets::Rand(){ +double Qjets::Rand() { double ret = 0.; //if(_rand_seed_set) // ret = rand_r(&_seed)/(double)RAND_MAX; - //else + //else //ret = rand()/(double)RAND_MAX; ret = _rnEngine->flat(); return ret; diff --git a/RecoJets/JetAlgorithms/src/QjetsPlugin.cc b/RecoJets/JetAlgorithms/src/QjetsPlugin.cc index 1a8d123200c4f..12e0e23fbe3c1 100644 --- a/RecoJets/JetAlgorithms/src/QjetsPlugin.cc +++ b/RecoJets/JetAlgorithms/src/QjetsPlugin.cc @@ -2,23 +2,21 @@ using namespace std; -void QjetsPlugin::SetRandSeed(unsigned int seed){ +void QjetsPlugin::SetRandSeed(unsigned int seed) { _rand_seed_set = true; _seed = seed; } -double QjetsPlugin::R()const{ - return 0.; -} +double QjetsPlugin::R() const { return 0.; } -string QjetsPlugin::description() const{ +string QjetsPlugin::description() const { string desc("Qjets pruning plugin"); return desc; } -void QjetsPlugin::run_clustering(fastjet::ClusterSequence & cs) const{ +void QjetsPlugin::run_clustering(fastjet::ClusterSequence& cs) const { Qjets qjets(_zcut, _dcut_fctr, _exp_min, _exp_max, _rigidity, _truncation_fctr, _rnEngine); - if(_rand_seed_set) + if (_rand_seed_set) qjets.SetRandSeed(_seed); qjets.Cluster(cs); } diff --git a/RecoJets/JetAlgorithms/src/SubJetAlgorithm.cc b/RecoJets/JetAlgorithms/src/SubJetAlgorithm.cc index 28024c2df4d1d..dea83821991ee 100644 --- a/RecoJets/JetAlgorithms/src/SubJetAlgorithm.cc +++ b/RecoJets/JetAlgorithms/src/SubJetAlgorithm.cc @@ -8,90 +8,69 @@ using namespace std; using namespace edm; -void SubJetAlgorithm::set_zcut(double z){ - zcut_ = z; -} - -void SubJetAlgorithm::set_rcut_factor(double r){ - rcut_factor_ = r; -} +void SubJetAlgorithm::set_zcut(double z) { zcut_ = z; } +void SubJetAlgorithm::set_rcut_factor(double r) { rcut_factor_ = r; } // Run the algorithm // ------------------ -void SubJetAlgorithm::run( const vector & cell_particles, - vector & hardjetsOutput ) { - +void SubJetAlgorithm::run(const vector& cell_particles, vector& hardjetsOutput) { //for actual jet clustering, either the pruned or the original version is used. //For the pruned version, a new jet definition using the PrunedRecombPlugin is required: - fastjet::FastPrunePlugin PRplugin(*fjJetDefinition_, - *fjJetDefinition_, - zcut_, - rcut_factor_); + fastjet::FastPrunePlugin PRplugin(*fjJetDefinition_, *fjJetDefinition_, zcut_, rcut_factor_); fastjet::JetDefinition pjetdef(&PRplugin); - - // cluster the jets with the jet definition jetDef: // run algorithm boost::shared_ptr fjClusterSeq; - if ( !doAreaFastjet_ ) { - fjClusterSeq = - boost::shared_ptr( new fastjet::ClusterSequence( cell_particles, - pjetdef ) ); + if (!doAreaFastjet_) { + fjClusterSeq = boost::shared_ptr(new fastjet::ClusterSequence(cell_particles, pjetdef)); } else if (voronoiRfact_ <= 0) { - fjClusterSeq = - boost::shared_ptr( new fastjet::ClusterSequenceActiveArea( cell_particles, - pjetdef , - *fjActiveArea_ ) ); + fjClusterSeq = boost::shared_ptr( + new fastjet::ClusterSequenceActiveArea(cell_particles, pjetdef, *fjActiveArea_)); } else { - fjClusterSeq = - boost::shared_ptr( new fastjet::ClusterSequenceVoronoiArea( cell_particles, - pjetdef , - fastjet::VoronoiAreaSpec(voronoiRfact_) ) ); + fjClusterSeq = boost::shared_ptr( + new fastjet::ClusterSequenceVoronoiArea(cell_particles, pjetdef, fastjet::VoronoiAreaSpec(voronoiRfact_))); } vector inclusiveJets = fjClusterSeq->inclusive_jets(ptMin_); - // These will store the indices of each subjet that + // These will store the indices of each subjet that // are present in each jet vector > indices(inclusiveJets.size()); // Loop over inclusive jets, attempt to find substructure vector::iterator jetIt = inclusiveJets.begin(); - for ( ; jetIt != inclusiveJets.end(); ++jetIt ) { + for (; jetIt != inclusiveJets.end(); ++jetIt) { //decompose into requested number of subjets: vector subjets = fjClusterSeq->exclusive_subjets(*jetIt, nSubjets_); //create the subjets objects to put into the "output" objects - vector subjetsOutput; - std::vector::const_iterator itSubJetBegin = subjets.begin(), - itSubJet = itSubJetBegin, itSubJetEnd = subjets.end(); - for (; itSubJet != itSubJetEnd; ++itSubJet ){ + vector subjetsOutput; + std::vector::const_iterator itSubJetBegin = subjets.begin(), itSubJet = itSubJetBegin, + itSubJetEnd = subjets.end(); + for (; itSubJet != itSubJetEnd; ++itSubJet) { // Get the transient subjet constituents from fastjet - vector subjetFastjetConstituents = fjClusterSeq->constituents( *itSubJet ); + vector subjetFastjetConstituents = fjClusterSeq->constituents(*itSubJet); // Get the indices of the constituents: vector constituents; vector::const_iterator fastSubIt = subjetFastjetConstituents.begin(), - transConstEnd = subjetFastjetConstituents.end(); - for ( ; fastSubIt != transConstEnd; ++fastSubIt ) { - if (fastSubIt->user_index() >= 0) { - constituents.push_back( fastSubIt->user_index() ); - } + transConstEnd = subjetFastjetConstituents.end(); + for (; fastSubIt != transConstEnd; ++fastSubIt) { + if (fastSubIt->user_index() >= 0) { + constituents.push_back(fastSubIt->user_index()); + } } - double subJetArea = (doAreaFastjet_) ? - dynamic_cast(*fjClusterSeq).area(*itSubJet) : 0.0; - + double subJetArea = + (doAreaFastjet_) ? dynamic_cast(*fjClusterSeq).area(*itSubJet) : 0.0; // Make a CompoundPseudoSubJet object to hold this subjet and the indices of its constituents - subjetsOutput.push_back( CompoundPseudoSubJet( *itSubJet, subJetArea, constituents ) ); - + subjetsOutput.push_back(CompoundPseudoSubJet(*itSubJet, subJetArea, constituents)); } - - double fatJetArea = (doAreaFastjet_) ? - dynamic_cast(*fjClusterSeq).area(*jetIt) : 0.0; + double fatJetArea = + (doAreaFastjet_) ? dynamic_cast(*fjClusterSeq).area(*jetIt) : 0.0; // Make a CompoundPseudoJet object to hold this hard jet, and the subjets that make it up - hardjetsOutput.push_back( CompoundPseudoJet( *jetIt,fatJetArea,subjetsOutput)); + hardjetsOutput.push_back(CompoundPseudoJet(*jetIt, fatJetArea, subjetsOutput)); } } diff --git a/RecoJets/JetAlgorithms/src/SubjetFilterAlgorithm.cc b/RecoJets/JetAlgorithms/src/SubjetFilterAlgorithm.cc index 3fe6022246e9a..51c0524df8679 100644 --- a/RecoJets/JetAlgorithms/src/SubjetFilterAlgorithm.cc +++ b/RecoJets/JetAlgorithms/src/SubjetFilterAlgorithm.cc @@ -15,7 +15,6 @@ // 25/11/2009 Philipp Schieferdecker //////////////////////////////////////////////////////////////////////////////// - #include "RecoJets/JetAlgorithms/interface/SubjetFilterAlgorithm.h" #include @@ -25,12 +24,9 @@ #include #include - using namespace std; - -ostream & operator<<(ostream & ostr, fastjet::PseudoJet & jet); - +ostream& operator<<(ostream& ostr, fastjet::PseudoJet& jet); //////////////////////////////////////////////////////////////////////////////// // construction / destruction @@ -38,226 +34,212 @@ ostream & operator<<(ostream & ostr, fastjet::PseudoJet & jet); //______________________________________________________________________________ SubjetFilterAlgorithm::SubjetFilterAlgorithm(const std::string& moduleLabel, - const std::string& jetAlgorithm, - unsigned nFatMax, - double rParam, - double rFilt, - double jetPtMin, - double massDropCut, - double asymmCut, - bool asymmCutLater, - bool doAreaFastjet, - double ghostEtaMax, - int activeAreaRepeats, - double ghostArea, - bool verbose) - : moduleLabel_(moduleLabel) - , jetAlgorithm_(jetAlgorithm) - , nFatMax_(nFatMax) - , rParam_(rParam) - , rFilt_(rFilt) - , jetPtMin_(jetPtMin) - , massDropCut_(massDropCut) - , asymmCut2_(asymmCut*asymmCut) - , asymmCutLater_(asymmCutLater) - , doAreaFastjet_(doAreaFastjet) - , ghostEtaMax_(ghostEtaMax) - , activeAreaRepeats_(activeAreaRepeats) - , ghostArea_(ghostArea) - , verbose_(verbose) - , nevents_(0) - , ntotal_(0) - , nfound_(0) - , fjJetDef_(nullptr) - , fjAreaDef_(nullptr) -{ + const std::string& jetAlgorithm, + unsigned nFatMax, + double rParam, + double rFilt, + double jetPtMin, + double massDropCut, + double asymmCut, + bool asymmCutLater, + bool doAreaFastjet, + double ghostEtaMax, + int activeAreaRepeats, + double ghostArea, + bool verbose) + : moduleLabel_(moduleLabel), + jetAlgorithm_(jetAlgorithm), + nFatMax_(nFatMax), + rParam_(rParam), + rFilt_(rFilt), + jetPtMin_(jetPtMin), + massDropCut_(massDropCut), + asymmCut2_(asymmCut * asymmCut), + asymmCutLater_(asymmCutLater), + doAreaFastjet_(doAreaFastjet), + ghostEtaMax_(ghostEtaMax), + activeAreaRepeats_(activeAreaRepeats), + ghostArea_(ghostArea), + verbose_(verbose), + nevents_(0), + ntotal_(0), + nfound_(0), + fjJetDef_(nullptr), + fjAreaDef_(nullptr) { // FASTJET JET DEFINITION - if (jetAlgorithm=="CambridgeAachen"||jetAlgorithm_=="ca") - fjJetDef_=new fastjet::JetDefinition(fastjet::cambridge_algorithm,rParam_); - else if (jetAlgorithm=="AntiKt"||jetAlgorithm_=="ak") - fjJetDef_=new fastjet::JetDefinition(fastjet::antikt_algorithm,rParam_); - else if (jetAlgorithm=="Kt"||jetAlgorithm_=="kt") - fjJetDef_=new fastjet::JetDefinition(fastjet::kt_algorithm,rParam_); + if (jetAlgorithm == "CambridgeAachen" || jetAlgorithm_ == "ca") + fjJetDef_ = new fastjet::JetDefinition(fastjet::cambridge_algorithm, rParam_); + else if (jetAlgorithm == "AntiKt" || jetAlgorithm_ == "ak") + fjJetDef_ = new fastjet::JetDefinition(fastjet::antikt_algorithm, rParam_); + else if (jetAlgorithm == "Kt" || jetAlgorithm_ == "kt") + fjJetDef_ = new fastjet::JetDefinition(fastjet::kt_algorithm, rParam_); else - throw cms::Exception("InvalidJetAlgo") - <<"Jet Algorithm for SubjetFilterAlgorithm is invalid: " - <& fjInputs, - std::vector& fjJets, - const edm::EventSetup& iSetup) -{ +void SubjetFilterAlgorithm::run(const std::vector& fjInputs, + std::vector& fjJets, + const edm::EventSetup& iSetup) { nevents_++; - - if (verbose_) cout< fjFatJets = - fastjet::sorted_by_pt(cs->inclusive_jets(jetPtMin_)); - - size_t nFat = - (nFatMax_==0) ? fjFatJets.size() : std::min(fjFatJets.size(),(size_t)nFatMax_); - - for (size_t iFat=0;iFat fjFatJets = fastjet::sorted_by_pt(cs->inclusive_jets(jetPtMin_)); + + size_t nFat = (nFatMax_ == 0) ? fjFatJets.size() : std::min(fjFatJets.size(), (size_t)nFatMax_); + + for (size_t iFat = 0; iFat < nFat; iFat++) { + if (verbose_) + cout << endl << iFat << ". FATJET: " << fjFatJets[iFat] << endl; + fastjet::PseudoJet fjFatJet = fjFatJets[iFat]; fastjet::PseudoJet fjCurrentJet(fjFatJet); - fastjet::PseudoJet fjSubJet1,fjSubJet2; + fastjet::PseudoJet fjSubJet1, fjSubJet2; bool hadSubJets; - + vector subJets; - - + // FIND SUBJETS PASSING MASSDROP [AND ASYMMETRY] CUT(S) - while ((hadSubJets = cs->has_parents(fjCurrentJet,fjSubJet1,fjSubJet2))) { - - if (fjSubJet1.m() < fjSubJet2.m()) swap(fjSubJet1,fjSubJet2); - - if (verbose_) cout<<"SUBJET CANDIDATES: "< fjFilterJets; - double Rbb = std::sqrt(fjSubJet1.squared_distance(fjSubJet2)); - double Rfilt = std::min(0.5*Rbb,rFilt_); - double dcut = Rfilt*Rfilt/rParam_/rParam_; - fjFilterJets=fastjet::sorted_by_pt(cs->exclusive_subjets(fjCurrentJet,dcut)); - - if (verbose_) { - cout<<"Rbb="<0) cout<<" "< fjSubJets; - fjSubJets.push_back(fjSubJet1); - fjSubJets.push_back(fjSubJet2); - size_t nFilter = fjFilterJets.size(); - for (size_t iFilter=0;iFilter fjConstituents= - cs->constituents(fjSubJets[iSub]); - vector constituents; - for (size_t iConst=0;iConst=0) constituents.push_back(userIndex); - } - - double subJetArea=(doAreaFastjet_) ? - ((fastjet::ClusterSequenceArea*)cs)->area(fjSubJets[iSub]) : 0.0; - - if (iSub<2||!constituents.empty()) - subJets.push_back(CompoundPseudoSubJet(fjSubJets[iSub], - subJetArea, - constituents)); - } - - } // PASSED Y CUT - - } // PASSED MASSDROP CUT - - if (verbose_) cout<<"write fatjet with "<area(fjFatJet) : 0.0; - - fjJets.push_back(CompoundPseudoJet(fjFatJet,fatJetArea,subJets)); - + if (verbose_) + cout << "PASSED y cut" << endl; + + vector fjFilterJets; + double Rbb = std::sqrt(fjSubJet1.squared_distance(fjSubJet2)); + double Rfilt = std::min(0.5 * Rbb, rFilt_); + double dcut = Rfilt * Rfilt / rParam_ / rParam_; + fjFilterJets = fastjet::sorted_by_pt(cs->exclusive_subjets(fjCurrentJet, dcut)); + + if (verbose_) { + cout << "Rbb=" << Rbb << ", Rfilt=" << Rfilt << endl; + cout << "FILTER JETS: " << flush; + for (size_t i = 0; i < fjFilterJets.size(); i++) { + if (i > 0) + cout << " " << flush; + cout << fjFilterJets[i] << endl; + } + } + + vector fjSubJets; + fjSubJets.push_back(fjSubJet1); + fjSubJets.push_back(fjSubJet2); + size_t nFilter = fjFilterJets.size(); + for (size_t iFilter = 0; iFilter < nFilter; iFilter++) + fjSubJets.push_back(fjFilterJets[iFilter]); + + for (size_t iSub = 0; iSub < fjSubJets.size(); iSub++) { + vector fjConstituents = cs->constituents(fjSubJets[iSub]); + vector constituents; + for (size_t iConst = 0; iConst < fjConstituents.size(); iConst++) { + int userIndex = fjConstituents[iConst].user_index(); + if (userIndex >= 0) + constituents.push_back(userIndex); + } + + double subJetArea = (doAreaFastjet_) ? ((fastjet::ClusterSequenceArea*)cs)->area(fjSubJets[iSub]) : 0.0; + + if (iSub < 2 || !constituents.empty()) + subJets.push_back(CompoundPseudoSubJet(fjSubJets[iSub], subJetArea, constituents)); + } + + } // PASSED Y CUT + + } // PASSED MASSDROP CUT + + if (verbose_) + cout << "write fatjet with " << subJets.size() << " sub+filter jets" << endl; + + double fatJetArea = (doAreaFastjet_) ? ((fastjet::ClusterSequenceArea*)cs)->area(fjFatJet) : 0.0; + + fjJets.push_back(CompoundPseudoJet(fjFatJet, fatJetArea, subJets)); + ntotal_++; - if (subJets.size()>3) nfound_++; - - } // LOOP OVER FATJETS - - if (verbose_) cout< 3) + nfound_++; + + } // LOOP OVER FATJETS + + if (verbose_) + cout << endl << fjJets.size() << " FATJETS written\n" << endl; + delete cs; - + return; } - //______________________________________________________________________________ -string SubjetFilterAlgorithm::summary() const -{ - double eff = (ntotal_>0) ? nfound_/(double)ntotal_ : 0; +string SubjetFilterAlgorithm::summary() const { + double eff = (ntotal_ > 0) ? nfound_ / (double)ntotal_ : 0; std::stringstream ss; - ss<<"************************************************************\n" - <<"* "< class NuclearInteractionFinder { private: - typedef TrajectoryStateOnSurface TSOS; typedef FreeTrajectoryState FTS; typedef TrajectoryMeasurement TM; typedef std::vector TrajectoryContainer; - typedef TrajectoryMeasurement::ConstRecHitPointer ConstRecHitPointer; + typedef TrajectoryMeasurement::ConstRecHitPointer ConstRecHitPointer; /// get the seeds at the interaction point - void fillSeeds( const std::pair >& tmPairs ); + void fillSeeds(const std::pair >& tmPairs); /// Find compatible TM of a TM with error rescaled by rescaleFactor - std::vector - findCompatibleMeasurements( const TM& lastMeas, double rescaleFactor, const LayerMeasurements & layerMeasurements) const; + std::vector findCompatibleMeasurements(const TM& lastMeas, + double rescaleFactor, + const LayerMeasurements& layerMeasurements) const; - std::vector - findMeasurementsFromTSOS(const TSOS& currentState, DetId detid, const LayerMeasurements & layerMeasurements) const; + std::vector findMeasurementsFromTSOS(const TSOS& currentState, + DetId detid, + const LayerMeasurements& layerMeasurements) const; /// Calculate the parameters of the circle representing the primary track at the interaction point void definePrimaryHelix(std::vector::const_iterator it_meas); public: - - NuclearInteractionFinder(){} + NuclearInteractionFinder() {} NuclearInteractionFinder(const edm::EventSetup& es, const edm::ParameterSet& iConfig); virtual ~NuclearInteractionFinder(); /// Run the Finder - bool run(const Trajectory& traj, const MeasurementTrackerEvent &event ); + bool run(const Trajectory& traj, const MeasurementTrackerEvent& event); /// Improve the seeds with a third RecHit - void improveSeeds( const MeasurementTrackerEvent &event ); + void improveSeeds(const MeasurementTrackerEvent& event); /// Fill 'output' with persistent nuclear seeds - std::unique_ptr getPersistentSeeds(); + std::unique_ptr getPersistentSeeds(); TrajectoryStateOnSurface rescaleError(float rescale, const TSOS& state) const; const NavigationSchool* nav() const { return theNavigationSchool; } private: - - const Propagator* thePropagator; - const MeasurementEstimator* theEstimator; - const MeasurementTracker* theMeasurementTracker; - const GeometricSearchTracker* theGeomSearchTracker; - const NavigationSchool* theNavigationSchool; - edm::ESHandle theMagField; - - NuclearTester* nuclTester; - SeedFromNuclearInteraction *currentSeed; - std::vector< SeedFromNuclearInteraction > allSeeds; - TangentHelix* thePrimaryHelix; + const Propagator* thePropagator; + const MeasurementEstimator* theEstimator; + const MeasurementTracker* theMeasurementTracker; + const GeometricSearchTracker* theGeomSearchTracker; + const NavigationSchool* theNavigationSchool; + edm::ESHandle theMagField; + + NuclearTester* nuclTester; + SeedFromNuclearInteraction* currentSeed; + std::vector allSeeds; + TangentHelix* thePrimaryHelix; // parameters - double ptMin; - unsigned int maxHits; - double rescaleErrorFactor; - bool checkCompletedTrack; /**< If set to true check all the tracks, even those reaching the edge of the tracker */ - std::string navigationSchoolName; - + double ptMin; + unsigned int maxHits; + double rescaleErrorFactor; + bool checkCompletedTrack; /**< If set to true check all the tracks, even those reaching the edge of the tracker */ + std::string navigationSchoolName; }; #endif diff --git a/RecoTracker/NuclearSeedGenerator/interface/NuclearSeedsEDProducer.h b/RecoTracker/NuclearSeedGenerator/interface/NuclearSeedsEDProducer.h index 836a8a7dc0516..1376a26ca009b 100644 --- a/RecoTracker/NuclearSeedGenerator/interface/NuclearSeedsEDProducer.h +++ b/RecoTracker/NuclearSeedGenerator/interface/NuclearSeedsEDProducer.h @@ -18,7 +18,6 @@ // // - // system include files #include @@ -38,7 +37,9 @@ #include "DataFormats/TrackReco/interface/TrackFwd.h" #include "RecoTracker/NuclearSeedGenerator/interface/TrajectoryToSeedMap.h" -namespace reco {class TransientTrack;} +namespace reco { + class TransientTrack; +} class Trajectory; @@ -47,21 +48,20 @@ class Trajectory; */ class NuclearSeedsEDProducer : public edm::stream::EDProducer<> { +public: + explicit NuclearSeedsEDProducer(const edm::ParameterSet&); + ~NuclearSeedsEDProducer() override; - public: - explicit NuclearSeedsEDProducer(const edm::ParameterSet&); - ~NuclearSeedsEDProducer() override; - - private: - void beginRun(edm::Run const& run, const edm::EventSetup&) override; - void produce(edm::Event&, const edm::EventSetup&) override; +private: + void beginRun(edm::Run const& run, const edm::EventSetup&) override; + void produce(edm::Event&, const edm::EventSetup&) override; - // ----------member data --------------------------- - edm::ParameterSet conf_; - std::unique_ptr theNuclearInteractionFinder; + // ----------member data --------------------------- + edm::ParameterSet conf_; + std::unique_ptr theNuclearInteractionFinder; - bool improveSeeds; - edm::EDGetTokenT producer_; - edm::EDGetTokenT mteToken_; + bool improveSeeds; + edm::EDGetTokenT producer_; + edm::EDGetTokenT mteToken_; }; #endif diff --git a/RecoTracker/NuclearSeedGenerator/interface/NuclearTester.h b/RecoTracker/NuclearSeedGenerator/interface/NuclearTester.h index 852a57bd60cd2..74dd68b01a3f8 100644 --- a/RecoTracker/NuclearSeedGenerator/interface/NuclearTester.h +++ b/RecoTracker/NuclearSeedGenerator/interface/NuclearTester.h @@ -3,7 +3,7 @@ //! \brief Class used to test if a track has interacted nuclearly //! //! \description Using the properties of all the compatible TMs of the TMs associated to a track, the method -//! isNuclearInteraction return 1 in case the track has interacted nuclearly, 0 else. +//! isNuclearInteraction return 1 in case the track has interacted nuclearly, 0 else. //----------------------------------------------------------------------------- #ifndef CD_NuclearTester_H_ #define CD_NuclearTester_H_ @@ -15,15 +15,14 @@ class NuclearTester { private: - typedef TrajectoryMeasurement TM; typedef std::vector TMContainer; - typedef TrajectoryMeasurement::ConstRecHitPointer ConstRecHitPointer; - typedef std::pair TMPair; - typedef std::vector< TMPair > TMPairVector; + typedef TrajectoryMeasurement::ConstRecHitPointer ConstRecHitPointer; + typedef std::pair TMPair; + typedef std::vector TMPairVector; -public : - NuclearTester(unsigned int max_hits, const MeasurementEstimator* est, const TrackerGeometry* track_geom); +public: + NuclearTester(unsigned int max_hits, const MeasurementEstimator* est, const TrackerGeometry* track_geom); bool isNuclearInteraction(); @@ -35,42 +34,41 @@ public : std::vector::const_iterator lastValidTM(const std::vector& vecTM) const; - void push_back(const TM & init_tm, const TMContainer & vecTM) { - allTM.push_back(std::make_pair(init_tm, vecTM) ); - compatible_hits.push_back(vecTM.size()); + void push_back(const TM& init_tm, const TMContainer& vecTM) { + allTM.push_back(std::make_pair(init_tm, vecTM)); + compatible_hits.push_back(vecTM.size()); } const TMContainer& back() const { return allTM.back().second; } - double meanHitDistance() const { return meanHitDistance( back() ); } + double meanHitDistance() const { return meanHitDistance(back()); } - double fwdEstimate() const { return fwdEstimate( back() ); } + double fwdEstimate() const { return fwdEstimate(back()); } - void reset(unsigned int nMeasurements) { - allTM.clear(); - compatible_hits.clear(); - maxHits = (nMeasurements < maxHits) ? nMeasurements : maxHits; + void reset(unsigned int nMeasurements) { + allTM.clear(); + compatible_hits.clear(); + maxHits = (nMeasurements < maxHits) ? nMeasurements : maxHits; } int nuclearIndex() const { return NuclearIndex; } - const TMPair& goodTMPair() const { return *(allTM.begin()+nuclearIndex()-1); } + const TMPair& goodTMPair() const { return *(allTM.begin() + nuclearIndex() - 1); } unsigned int nHitsChecked() const { return compatible_hits.size(); } std::vector compatibleHits() const { return compatible_hits; } - -private : +private: // data members TMPairVector allTM; - std::vector< int > compatible_hits; + std::vector compatible_hits; int NuclearIndex; // input parameters unsigned int maxHits; - const MeasurementEstimator* theEstimator; - const TrackerGeometry* trackerGeom; + const MeasurementEstimator* theEstimator; + const TrackerGeometry* trackerGeom; bool checkWithMultiplicity(); }; diff --git a/RecoTracker/NuclearSeedGenerator/interface/NuclearTrackCorrector.h b/RecoTracker/NuclearSeedGenerator/interface/NuclearTrackCorrector.h index 431e30f4fa955..db51c5f9ee152 100644 --- a/RecoTracker/NuclearSeedGenerator/interface/NuclearTrackCorrector.h +++ b/RecoTracker/NuclearSeedGenerator/interface/NuclearTrackCorrector.h @@ -1,12 +1,11 @@ #ifndef CD_NuclearTrackCorrector_H_ #define CD_NuclearTrackCorrector_H_ - // -*- C++ -*- // // Package: NuclearTrackCorrector // Class: NuclearTrackCorrector -// +// /**\class NuclearTrackCorrector NuclearTrackCorrector.h RecoTracker/NuclearSeedGenerator/interface/NuclearTrackCorrector.h Description: @@ -20,7 +19,6 @@ // // - // system include files #include #include @@ -61,72 +59,69 @@ #include "RecoTracker/TrackProducer/interface/TrackProducerAlgorithm.h" - - class TransientInitialStateEstimator; // // class decleration // -class NuclearTrackCorrector : public edm::EDProducer { - +class NuclearTrackCorrector : public edm::EDProducer { public: typedef edm::RefVector TrajectorySeedRefVector; typedef edm::Ref TrajectoryRef; typedef edm::Ref TrackCandidateRef; typedef TransientTrackingRecHit::ConstRecHitContainer ConstRecHitContainer; - using AlgoProductCollection = TrackProducerAlgorithm::AlgoProductCollection; + using AlgoProductCollection = TrackProducerAlgorithm::AlgoProductCollection; - public: - - explicit NuclearTrackCorrector(const edm::ParameterSet&); - ~NuclearTrackCorrector() override; +public: + explicit NuclearTrackCorrector(const edm::ParameterSet&); + ~NuclearTrackCorrector() override; - private: - void produce(edm::Event&, const edm::EventSetup&) override; - void endJob() override ; +private: + void produce(edm::Event&, const edm::EventSetup&) override; + void endJob() override; - /// check if the trajectory has to be refitted and get the new trajectory - bool newTrajNeeded(Trajectory& newtrajectory, const TrajectoryRef& trajRef, const reco::NuclearInteraction& ni); + /// check if the trajectory has to be refitted and get the new trajectory + bool newTrajNeeded(Trajectory& newtrajectory, const TrajectoryRef& trajRef, const reco::NuclearInteraction& ni); - /// get a new TrackExtra from an AlgoProductCollection - reco::TrackExtra getNewTrackExtra(const AlgoProductCollection& algoresults); + /// get a new TrackExtra from an AlgoProductCollection + reco::TrackExtra getNewTrackExtra(const AlgoProductCollection& algoresults); - /// Get the refitted track from the Trajectory - bool getTrackFromTrajectory(const Trajectory& newTraj , const TrajectoryRef& initialTrajRef, AlgoProductCollection& algoResults); + /// Get the refitted track from the Trajectory + bool getTrackFromTrajectory(const Trajectory& newTraj, + const TrajectoryRef& initialTrajRef, + AlgoProductCollection& algoResults); - /// Calculate the inital state to be used to buil the track - TrajectoryStateOnSurface getInitialState(const reco::Track * theT, - TransientTrackingRecHit::RecHitContainer& hits, - const TrackingGeometry * theG, - const MagneticField * theMF); + /// Calculate the inital state to be used to buil the track + TrajectoryStateOnSurface getInitialState(const reco::Track* theT, + TransientTrackingRecHit::RecHitContainer& hits, + const TrackingGeometry* theG, + const MagneticField* theMF); - void swap_map(const edm::Handle< TrajectoryCollection >& trajColl , std::map< reco::TrackRef, edm::Ref >& result); - - // ----------member data --------------------------- + void swap_map(const edm::Handle& trajColl, + std::map >& result); + // ----------member data --------------------------- - std::string str_Input_Trajectory; - std::string str_Input_NuclearInteraction; - int int_Input_Hit_Distance; + std::string str_Input_Trajectory; + std::string str_Input_NuclearInteraction; + int int_Input_Hit_Distance; - int verbosity; - int KeepOnlyCorrectedTracks; + int verbosity; + int KeepOnlyCorrectedTracks; - std::vector< std::pair > Indice_Map; + std::vector > Indice_Map; - - edm::ESHandle theG; - edm::ESHandle theMF; - edm::ESHandle theFitter; - edm::ESHandle thePropagator; - edm::ParameterSet conf_; - TransientInitialStateEstimator* theInitialState; + edm::ESHandle theG; + edm::ESHandle theMF; + edm::ESHandle theFitter; + edm::ESHandle thePropagator; + edm::ParameterSet conf_; + TransientInitialStateEstimator* theInitialState; - TrackProducerAlgorithm* theAlgo; - const TrajTrackAssociationCollection* m_TrajToTrackCollection; + TrackProducerAlgorithm* theAlgo; + const TrajTrackAssociationCollection* m_TrajToTrackCollection; }; #endif diff --git a/RecoTracker/NuclearSeedGenerator/interface/SeedFromNuclearInteraction.h b/RecoTracker/NuclearSeedGenerator/interface/SeedFromNuclearInteraction.h index f24d4ecfa037f..10049f981e942 100644 --- a/RecoTracker/NuclearSeedGenerator/interface/SeedFromNuclearInteraction.h +++ b/RecoTracker/NuclearSeedGenerator/interface/SeedFromNuclearInteraction.h @@ -19,25 +19,28 @@ class FreeTrajectoryState; class SeedFromNuclearInteraction { -private : - typedef TrajectoryMeasurement TM; - typedef TrajectoryStateOnSurface TSOS; - typedef edm::OwnVector recHitContainer; +private: + typedef TrajectoryMeasurement TM; + typedef TrajectoryStateOnSurface TSOS; + typedef edm::OwnVector recHitContainer; typedef TransientTrackingRecHit::ConstRecHitPointer ConstRecHitPointer; - typedef std::vector ConstRecHitContainer; + typedef std::vector ConstRecHitContainer; -public : +public: SeedFromNuclearInteraction(const Propagator* prop, const TrackerGeometry* geom, const edm::ParameterSet& iConfig); - virtual ~SeedFromNuclearInteraction(){} + virtual ~SeedFromNuclearInteraction() {} /// Fill all data members from 2 TM's where the first one is supposed to be at the interaction point void setMeasurements(const TSOS& tsosAtInteractionPoint, ConstRecHitPointer ihit, ConstRecHitPointer ohit); /// Fill all data members from 1 TSOS and 2 rec Hits and using the circle associated to the primary track as constraint - void setMeasurements(TangentHelix& primHelix, const TSOS& inner_TSOS, ConstRecHitPointer ihit, ConstRecHitPointer ohit); + void setMeasurements(TangentHelix& primHelix, + const TSOS& inner_TSOS, + ConstRecHitPointer ihit, + ConstRecHitPointer ohit); - PTrajectoryStateOnDet const & trajectoryState() const { return pTraj; } + PTrajectoryStateOnDet const& trajectoryState() const { return pTraj; } FreeTrajectoryState* stateWithError() const; @@ -45,10 +48,10 @@ public : PropagationDirection direction() const { return alongMomentum; } - recHitContainer hits() const; + recHitContainer hits() const; + + TrajectorySeed TrajSeed() const { return TrajectorySeed(trajectoryState(), hits(), direction()); } - TrajectorySeed TrajSeed() const { return TrajectorySeed(trajectoryState(),hits(),direction()); } - bool isValid() const { return isValid_; } const TSOS& updatedTSOS() const { return *updatedTSOS_; } @@ -56,43 +59,41 @@ public : const TSOS& initialTSOS() const { return *initialTSOS_; } GlobalPoint outerHitPosition() const { - return theTrackerGeom->idToDet(outerHitDetId())->surface().toGlobal(outerHit_->localPosition()); + return theTrackerGeom->idToDet(outerHitDetId())->surface().toGlobal(outerHit_->localPosition()); } DetId outerHitDetId() const { return outerHit_->geographicalId(); } ConstRecHitPointer outerHit() const { return outerHit_; } - /// Return the rotation matrix to be applied to get parameters in + /// Return the rotation matrix to be applied to get parameters in /// a framework where the z direction is along perp - AlgebraicMatrix33 rotationMatrix(const GlobalVector& perp) const; + AlgebraicMatrix33 rotationMatrix(const GlobalVector& perp) const; -private : - bool isValid_; /**< check if the seed is valid */ +private: + bool isValid_; /**< check if the seed is valid */ - ConstRecHitContainer theHits; /**< all the hits to be used to update the */ - /* initial freeTS and to be fitted */ + ConstRecHitContainer theHits; /**< all the hits to be used to update the */ + /* initial freeTS and to be fitted */ - ConstRecHitPointer innerHit_; /**< Pointer to the hit of the inner TM */ - ConstRecHitPointer outerHit_; /**< Pointer to the outer hit */ + ConstRecHitPointer innerHit_; /**< Pointer to the hit of the inner TM */ + ConstRecHitPointer outerHit_; /**< Pointer to the outer hit */ - boost::shared_ptr updatedTSOS_; /**< Final TSOS */ + boost::shared_ptr updatedTSOS_; /**< Final TSOS */ - boost::shared_ptr initialTSOS_; /**< Initial TSOS used as input */ - - boost::shared_ptr freeTS_; /**< Initial FreeTrajectoryState */ + boost::shared_ptr initialTSOS_; /**< Initial TSOS used as input */ - PTrajectoryStateOnDet pTraj; /**< the final persistent TSOS */ + boost::shared_ptr freeTS_; /**< Initial FreeTrajectoryState */ + PTrajectoryStateOnDet pTraj; /**< the final persistent TSOS */ // input parameters - double ptMin; /**< Minimum transverse momentum of the seed */ + double ptMin; /**< Minimum transverse momentum of the seed */ - const Propagator* thePropagator; - const TrackerGeometry* theTrackerGeom; + const Propagator* thePropagator; + const TrackerGeometry* theTrackerGeom; bool construct(); - }; #endif diff --git a/RecoTracker/NuclearSeedGenerator/interface/TangentCircle.h b/RecoTracker/NuclearSeedGenerator/interface/TangentCircle.h index 317d28f921cc5..c4db41faf5761 100644 --- a/RecoTracker/NuclearSeedGenerator/interface/TangentCircle.h +++ b/RecoTracker/NuclearSeedGenerator/interface/TangentCircle.h @@ -4,71 +4,78 @@ #include "RecoTracker/TkSeedGenerator/interface/FastCircle.h" #include "DataFormats/GeometryVector/interface/GlobalVector.h" -class TangentCircle -{ -// TODO : for speed-up : -// typedef Point2DBase< float, GlobalTag> Global2DPoint; -// typedef Vector2DBase< float, GlobalTag> Global2DVector; +class TangentCircle { + // TODO : for speed-up : + // typedef Point2DBase< float, GlobalTag> Global2DPoint; + // typedef Vector2DBase< float, GlobalTag> Global2DVector; - public : - TangentCircle() : - theInnerPoint(), theOuterPoint(), theVertexPoint(), theDirectionAtVertex(), - theX0(0), theY0(0), theRho(0), theVertexError(0), - valid(false), theCharge(0) {} +public: + TangentCircle() + : theInnerPoint(), + theOuterPoint(), + theVertexPoint(), + theDirectionAtVertex(), + theX0(0), + theY0(0), + theRho(0), + theVertexError(0), + valid(false), + theCharge(0) {} - /// Calculate the circle from 2 points on the circle (the vertex=innerPoint and the outerPoint) - /// and the tangent direction at the inner point - TangentCircle(const GlobalVector& direction, const GlobalPoint& innerPoint, const GlobalPoint& outerPoint); + /// Calculate the circle from 2 points on the circle (the vertex=innerPoint and the outerPoint) + /// and the tangent direction at the inner point + TangentCircle(const GlobalVector& direction, const GlobalPoint& innerPoint, const GlobalPoint& outerPoint); - /// Copy of FastCircle - TangentCircle(const GlobalPoint& outerPoint, const GlobalPoint& innerPoint, const GlobalPoint& vertexPoint); + /// Copy of FastCircle + TangentCircle(const GlobalPoint& outerPoint, const GlobalPoint& innerPoint, const GlobalPoint& vertexPoint); - /// Calculate the parameters of a circle which pass by 2 points (innerPoint and outerPoint) and which is tangent to primCircle - TangentCircle(const TangentCircle& primCircle, const GlobalPoint& outerPoint, const GlobalPoint& innerPoint); + /// Calculate the parameters of a circle which pass by 2 points (innerPoint and outerPoint) and which is tangent to primCircle + TangentCircle(const TangentCircle& primCircle, const GlobalPoint& outerPoint, const GlobalPoint& innerPoint); - /// Return the direction at the vertex - GlobalVector directionAtVertex(); + /// Return the direction at the vertex + GlobalVector directionAtVertex(); - double x0() const {return theX0;} - - double y0() const {return theY0;} - - double rho() const {return theRho;} + double x0() const { return theX0; } - GlobalPoint outerPoint() const { return theOuterPoint; } + double y0() const { return theY0; } - GlobalPoint innerPoint() const { return theInnerPoint; } + double rho() const { return theRho; } - GlobalPoint vertexPoint() const { return theVertexPoint; } + GlobalPoint outerPoint() const { return theOuterPoint; } - double vertexError() const { return theVertexError; } + GlobalPoint innerPoint() const { return theInnerPoint; } - double curvatureError(); + GlobalPoint vertexPoint() const { return theVertexPoint; } - int charge(float magz); + double vertexError() const { return theVertexError; } + double curvatureError(); - private : - GlobalPoint theInnerPoint; - GlobalPoint theOuterPoint; - GlobalPoint theVertexPoint; + int charge(float magz); - GlobalVector theDirectionAtVertex; - - double theX0; /**< x center of the circle */ - double theY0; /**< y center of the circle */ - double theRho; /**< Signed radius of the circle (=q*R) */ +private: + GlobalPoint theInnerPoint; + GlobalPoint theOuterPoint; + GlobalPoint theVertexPoint; - double theVertexError; /**< the error on the vertex position along the direction of the circle at this point */ + GlobalVector theDirectionAtVertex; - bool valid; - int theCharge; + double theX0; /**< x center of the circle */ + double theY0; /**< y center of the circle */ + double theRho; /**< Signed radius of the circle (=q*R) */ - double isTangent(const TangentCircle& primCircle, const TangentCircle& secCircle) const; - GlobalPoint getPosition(const TangentCircle& circle, const GlobalPoint& initalPosition, double theta, int direction) const; - int chargeLocally(float magz, GlobalVector v) const; - GlobalVector direction(const GlobalPoint& point) const; + double theVertexError; /**< the error on the vertex position along the direction of the circle at this point */ + bool valid; + int theCharge; + + double isTangent(const TangentCircle& primCircle, const TangentCircle& secCircle) const; + GlobalPoint getPosition(const TangentCircle& circle, + const GlobalPoint& initalPosition, + double theta, + int direction) const; + int chargeLocally(float magz, GlobalVector v) const; + GlobalVector direction(const GlobalPoint& point) const; }; #endif diff --git a/RecoTracker/NuclearSeedGenerator/interface/TangentHelix.h b/RecoTracker/NuclearSeedGenerator/interface/TangentHelix.h index 1b3c2875b507a..810aefdc2a480 100644 --- a/RecoTracker/NuclearSeedGenerator/interface/TangentHelix.h +++ b/RecoTracker/NuclearSeedGenerator/interface/TangentHelix.h @@ -4,51 +4,56 @@ #include "RecoTracker/NuclearSeedGenerator/interface/TangentCircle.h" class TangentHelix { +public: + TangentHelix() {} - public : - TangentHelix(){} + /// Calculate the helix from 2 points on the circle (the vertex=innerPoint and the outerPoint) + /// and the tangent direction at the inner point + TangentHelix(const GlobalVector& direction, const GlobalPoint& innerPoint, const GlobalPoint& outerPoint) + : theInnerPoint(innerPoint), + theOuterPoint(outerPoint), + theVertexPoint(innerPoint), + theCircle(direction, innerPoint, outerPoint), + theDirectionAtVertex(direction) {} - /// Calculate the helix from 2 points on the circle (the vertex=innerPoint and the outerPoint) - /// and the tangent direction at the inner point - TangentHelix(const GlobalVector& direction, const GlobalPoint& innerPoint, const GlobalPoint& outerPoint) : - theInnerPoint(innerPoint), theOuterPoint(outerPoint), theVertexPoint(innerPoint), theCircle(direction, innerPoint, outerPoint), - theDirectionAtVertex(direction) {} + /// Calculate Helix from 3 points + TangentHelix(const GlobalPoint& outerPoint, const GlobalPoint& innerPoint, const GlobalPoint& vertexPoint) + : theInnerPoint(innerPoint), + theOuterPoint(outerPoint), + theVertexPoint(vertexPoint), + theCircle(outerPoint, innerPoint, vertexPoint) { + theDirectionAtVertex = GlobalVector(1000, 1000, 1000); + } - /// Calculate Helix from 3 points - TangentHelix(const GlobalPoint& outerPoint, const GlobalPoint& innerPoint, const GlobalPoint& vertexPoint) : - theInnerPoint(innerPoint), theOuterPoint(outerPoint), theVertexPoint(vertexPoint), theCircle(outerPoint, innerPoint, vertexPoint) { - theDirectionAtVertex = GlobalVector(1000,1000,1000); - } + /// Calculate the parameters of the helix which pass by 2 points (innerPoint and outerPoint) and which is tangent to primHelix + TangentHelix(const TangentHelix& primCircle, const GlobalPoint& outerPoint, const GlobalPoint& innerPoint); - /// Calculate the parameters of the helix which pass by 2 points (innerPoint and outerPoint) and which is tangent to primHelix - TangentHelix(const TangentHelix& primCircle, const GlobalPoint& outerPoint, const GlobalPoint& innerPoint); + GlobalPoint outerPoint() const { return theOuterPoint; } - GlobalPoint outerPoint() const { return theOuterPoint; } + GlobalPoint innerPoint() const { return theInnerPoint; } - GlobalPoint innerPoint() const { return theInnerPoint; } + GlobalPoint vertexPoint() const { return theVertexPoint; } - GlobalPoint vertexPoint() const { return theVertexPoint; } + TangentCircle circle() const { return theCircle; } - TangentCircle circle() const { return theCircle; } + GlobalVector directionAtVertex(); - GlobalVector directionAtVertex() ; + int charge(float magz) { return theCircle.charge(magz); } - int charge(float magz) { return theCircle.charge(magz); } + double rho() const { return theCircle.rho(); } - double rho() const { return theCircle.rho(); } + double curvatureError() { return theCircle.curvatureError(); } - double curvatureError() { return theCircle.curvatureError(); } + double vertexError() { return theCircle.vertexError(); } - double vertexError() { return theCircle.vertexError(); } +private: + GlobalPoint theInnerPoint; + GlobalPoint theOuterPoint; + GlobalPoint theVertexPoint; - private : - GlobalPoint theInnerPoint; - GlobalPoint theOuterPoint; - GlobalPoint theVertexPoint; + TangentCircle theCircle; - TangentCircle theCircle; - - GlobalVector theDirectionAtVertex; + GlobalVector theDirectionAtVertex; }; #endif diff --git a/RecoTracker/NuclearSeedGenerator/interface/TrackCandidateToTrajectoryMap.h b/RecoTracker/NuclearSeedGenerator/interface/TrackCandidateToTrajectoryMap.h index f0daed8ef296c..93d97203caf6d 100644 --- a/RecoTracker/NuclearSeedGenerator/interface/TrackCandidateToTrajectoryMap.h +++ b/RecoTracker/NuclearSeedGenerator/interface/TrackCandidateToTrajectoryMap.h @@ -15,13 +15,11 @@ #include "RecoTracker/NuclearSeedGenerator/interface/TrajectoryToSeedMap.h" #include "DataFormats/TrackCandidate/interface/TrackCandidateCollection.h" - - // TrajectoryToTrajectoryMap /// association map typedef edm::AssociationMap > TrajectoryToTrajectoryMap; -typedef TrajectoryToTrajectoryMap::value_type TrajectoryToTrajectory; +typedef TrajectoryToTrajectoryMap::value_type TrajectoryToTrajectory; /// reference to an object in a collection of TrajectoryMap objects typedef edm::Ref TrajectoryToTrajectoryMapRef; @@ -32,13 +30,12 @@ typedef edm::RefProd TrajectoryToTrajectoryMapRefProd /// vector of references to objects in the same colletion of SeedMap objects typedef edm::RefVector TrajectoryToTrajectoryMapRefVector; - - // TrackCandidateToTrajectoryMap /// association map -typedef edm::AssociationMap > TrackCandidateToTrajectoryMap; -typedef TrackCandidateToTrajectoryMap::value_type TrackCandidateToTrajectory; +typedef edm::AssociationMap > + TrackCandidateToTrajectoryMap; +typedef TrackCandidateToTrajectoryMap::value_type TrackCandidateToTrajectory; /// reference to an object in a collection of TrajectoryMap objects typedef edm::Ref TrackCandidateToTrajectoryMapRef; @@ -49,13 +46,11 @@ typedef edm::RefProd TrackCandidateToTrajectoryMa /// vector of references to objects in the same colletion of SeedMap objects typedef edm::RefVector TrackCandidateToTrajectoryMapRefVector; - - // TrackToTrajectoryMap /// association map typedef edm::AssociationMap > TrackToTrajectoryMap; -typedef TrackToTrajectoryMap::value_type TrackToTrajectory; +typedef TrackToTrajectoryMap::value_type TrackToTrajectory; /// reference to an object in a collection of TrajectoryMap objects typedef edm::Ref TrackToTrajectoryMapRef; @@ -66,23 +61,17 @@ typedef edm::RefProd TrackToTrajectoryMapRefProd; /// vector of references to objects in the same colletion of SeedMap objects typedef edm::RefVector TrackToTrajectoryMapRefVector; - /// association map - typedef edm::AssociationMap > TrackToTrackMap; - typedef TrackToTrackMap::value_type TrackToTrack; - - /// reference to an object in a collection of SeedMap objects - typedef edm::Ref TrackToTrackMapRef; - - /// reference to a collection of SeedMap object - typedef edm::RefProd TrackToTrackMapRefProd; +typedef edm::AssociationMap > TrackToTrackMap; +typedef TrackToTrackMap::value_type TrackToTrack; - /// vector of references to objects in the same colletion of SeedMap objects - typedef edm::RefVector TrackToTrackMapRefVector; +/// reference to an object in a collection of SeedMap objects +typedef edm::Ref TrackToTrackMapRef; +/// reference to a collection of SeedMap object +typedef edm::RefProd TrackToTrackMapRefProd; +/// vector of references to objects in the same colletion of SeedMap objects +typedef edm::RefVector TrackToTrackMapRefVector; - #endif - - diff --git a/RecoTracker/NuclearSeedGenerator/interface/TrajectoryToSeedMap.h b/RecoTracker/NuclearSeedGenerator/interface/TrajectoryToSeedMap.h index b1d130a86e8ac..536c0b07a3c5f 100644 --- a/RecoTracker/NuclearSeedGenerator/interface/TrajectoryToSeedMap.h +++ b/RecoTracker/NuclearSeedGenerator/interface/TrajectoryToSeedMap.h @@ -14,47 +14,45 @@ #include "DataFormats/TrackReco/interface/TrackBase.h" #include "DataFormats/TrackReco/interface/TrackFwd.h" - typedef std::vector TrajectoryCollection; +typedef std::vector TrajectoryCollection; - /// association map - typedef edm::AssociationMap > TrajectoryToSeedsMap; - typedef TrajectoryToSeedsMap::value_type TrajectoryToSeeds; +/// association map +typedef edm::AssociationMap > TrajectoryToSeedsMap; +typedef TrajectoryToSeedsMap::value_type TrajectoryToSeeds; - /// reference to an object in a collection of SeedMap objects - typedef edm::Ref TrajectoryToSeedsMapRef; +/// reference to an object in a collection of SeedMap objects +typedef edm::Ref TrajectoryToSeedsMapRef; - /// reference to a collection of SeedMap object - typedef edm::RefProd TrajectoryToSeedsMapRefProd; +/// reference to a collection of SeedMap object +typedef edm::RefProd TrajectoryToSeedsMapRefProd; - /// vector of references to objects in the same colletion of SeedMap objects - typedef edm::RefVector TrajectoryToSeedsMapRefVector; +/// vector of references to objects in the same colletion of SeedMap objects +typedef edm::RefVector TrajectoryToSeedsMapRefVector; - /// association map - typedef edm::AssociationMap > TrackToSeedsMap; - typedef TrackToSeedsMap::value_type TrackToSeeds; +/// association map +typedef edm::AssociationMap > TrackToSeedsMap; +typedef TrackToSeedsMap::value_type TrackToSeeds; - /// reference to an object in a collection of SeedMap objects - typedef edm::Ref TrackToSeedsMapRef; +/// reference to an object in a collection of SeedMap objects +typedef edm::Ref TrackToSeedsMapRef; - /// reference to a collection of SeedMap object - typedef edm::RefProd TrackToSeedsMapRefProd; +/// reference to a collection of SeedMap object +typedef edm::RefProd TrackToSeedsMapRefProd; - /// vector of references to objects in the same colletion of SeedMap objects - typedef edm::RefVector TrackToSeedsMapRefVector; +/// vector of references to objects in the same colletion of SeedMap objects +typedef edm::RefVector TrackToSeedsMapRefVector; /// association map - typedef edm::AssociationMap > TrackToTracksMap; - typedef TrackToTracksMap::value_type TrackToTracks; +typedef edm::AssociationMap > TrackToTracksMap; +typedef TrackToTracksMap::value_type TrackToTracks; - /// reference to an object in a collection of SeedMap objects - typedef edm::Ref TrackToTracksMapRef; +/// reference to an object in a collection of SeedMap objects +typedef edm::Ref TrackToTracksMapRef; - /// reference to a collection of SeedMap object - typedef edm::RefProd TrackToTracksMapRefProd; +/// reference to a collection of SeedMap object +typedef edm::RefProd TrackToTracksMapRefProd; - /// vector of references to objects in the same colletion of SeedMap objects - typedef edm::RefVector TrackToTracksMapRefVector; +/// vector of references to objects in the same colletion of SeedMap objects +typedef edm::RefVector TrackToTracksMapRefVector; #endif - - diff --git a/RecoTracker/NuclearSeedGenerator/plugins/NuclearSeedsEDProducer.cc b/RecoTracker/NuclearSeedGenerator/plugins/NuclearSeedsEDProducer.cc index e7afce82a6c3b..598518443aa5d 100644 --- a/RecoTracker/NuclearSeedGenerator/plugins/NuclearSeedsEDProducer.cc +++ b/RecoTracker/NuclearSeedGenerator/plugins/NuclearSeedsEDProducer.cc @@ -11,86 +11,74 @@ using namespace edm; using namespace std; using namespace reco; - // // constructors and destructor // -NuclearSeedsEDProducer::NuclearSeedsEDProducer(const edm::ParameterSet& iConfig) : conf_(iConfig), -improveSeeds(iConfig.getParameter("improveSeeds")), -producer_(consumes(iConfig.getParameter("producer"))), -mteToken_(consumes(edm::InputTag("MeasurementTrackerEvents"))) -{ - produces(); - produces(); - - -} - - -NuclearSeedsEDProducer::~NuclearSeedsEDProducer() -{ +NuclearSeedsEDProducer::NuclearSeedsEDProducer(const edm::ParameterSet& iConfig) + : conf_(iConfig), + improveSeeds(iConfig.getParameter("improveSeeds")), + producer_(consumes(iConfig.getParameter("producer"))), + mteToken_(consumes(edm::InputTag("MeasurementTrackerEvents"))) { + produces(); + produces(); } +NuclearSeedsEDProducer::~NuclearSeedsEDProducer() {} // // member functions // // ------------ method called to produce the data ------------ -void -NuclearSeedsEDProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) -{ - typedef TrajectoryMeasurement TM; - - edm::Handle< TrajectoryCollection > m_TrajectoryCollection; - iEvent.getByToken( producer_, m_TrajectoryCollection ); - - LogDebug("NuclearSeedGenerator") << "Number of trajectory in event :" << m_TrajectoryCollection->size() << "\n"; +void NuclearSeedsEDProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { + typedef TrajectoryMeasurement TM; - auto output = std::make_unique(); - auto outAssoc = std::make_unique(); + edm::Handle m_TrajectoryCollection; + iEvent.getByToken(producer_, m_TrajectoryCollection); - - edm::Handle data; - iEvent.getByToken(mteToken_, data); + LogDebug("NuclearSeedGenerator") << "Number of trajectory in event :" << m_TrajectoryCollection->size() << "\n"; -// NavigationSetter setter( *(theNuclearInteractionFinder->nav()) ); why??? + auto output = std::make_unique(); + auto outAssoc = std::make_unique(); - std::vector > assocPair; - int i=0; + edm::Handle data; + iEvent.getByToken(mteToken_, data); - for(std::vector::const_iterator iTraj = m_TrajectoryCollection->begin(); iTraj != m_TrajectoryCollection->end(); iTraj++,i++) { + // NavigationSetter setter( *(theNuclearInteractionFinder->nav()) ); why??? - // run the finder - theNuclearInteractionFinder->run( *iTraj, *data ); + std::vector > assocPair; + int i = 0; - // improve seeds - if( improveSeeds == true ) theNuclearInteractionFinder->improveSeeds( *data ); + for (std::vector::const_iterator iTraj = m_TrajectoryCollection->begin(); + iTraj != m_TrajectoryCollection->end(); + iTraj++, i++) { + // run the finder + theNuclearInteractionFinder->run(*iTraj, *data); - // push back the new persistent seeds in output - std::unique_ptr newSeeds(theNuclearInteractionFinder->getPersistentSeeds()); - output->insert(output->end(), newSeeds->begin(), newSeeds->end()); + // improve seeds + if (improveSeeds == true) + theNuclearInteractionFinder->improveSeeds(*data); - // fill the id of the Trajectory and the if of the seed in assocPair - for(unsigned int j=0; jsize(); j++) { - assocPair.push_back( std::make_pair( i, output->size()-newSeeds->size()+j ) ); - } + // push back the new persistent seeds in output + std::unique_ptr newSeeds(theNuclearInteractionFinder->getPersistentSeeds()); + output->insert(output->end(), newSeeds->begin(), newSeeds->end()); - } + // fill the id of the Trajectory and the if of the seed in assocPair + for (unsigned int j = 0; j < newSeeds->size(); j++) { + assocPair.push_back(std::make_pair(i, output->size() - newSeeds->size() + j)); + } + } - const edm::OrphanHandle refprodTrajSeedColl = iEvent.put(std::move(output)); - - for(std::vector >::const_iterator iVecP = assocPair.begin(); iVecP != assocPair.end(); iVecP++) { - outAssoc->insert(edm::Ref(m_TrajectoryCollection,iVecP->first), edm::Ref(refprodTrajSeedColl, iVecP->second)); - } - iEvent.put(std::move(outAssoc)); + const edm::OrphanHandle refprodTrajSeedColl = iEvent.put(std::move(output)); + for (std::vector >::const_iterator iVecP = assocPair.begin(); iVecP != assocPair.end(); iVecP++) { + outAssoc->insert(edm::Ref(m_TrajectoryCollection, iVecP->first), + edm::Ref(refprodTrajSeedColl, iVecP->second)); + } + iEvent.put(std::move(outAssoc)); } // ------------ method called once each job just before starting event loop ------------ -void -NuclearSeedsEDProducer::beginRun(edm::Run const& run, const edm::EventSetup& es) -{ - theNuclearInteractionFinder = std::make_unique(es, conf_); - +void NuclearSeedsEDProducer::beginRun(edm::Run const& run, const edm::EventSetup& es) { + theNuclearInteractionFinder = std::make_unique(es, conf_); } diff --git a/RecoTracker/NuclearSeedGenerator/plugins/NuclearTrackCorrector.cc b/RecoTracker/NuclearSeedGenerator/plugins/NuclearTrackCorrector.cc index 343e316324ab6..9db679f0a99c0 100644 --- a/RecoTracker/NuclearSeedGenerator/plugins/NuclearTrackCorrector.cc +++ b/RecoTracker/NuclearSeedGenerator/plugins/NuclearTrackCorrector.cc @@ -2,7 +2,7 @@ // // Package: NuclearTrackCorrector // Class: NuclearTrackCorrector -// +// /**\class NuclearTrackCorrector NuclearTrackCorrector.cc RecoTracker/NuclearSeedGenerator/plugin/NuclearTrackCorrector.cc Description: @@ -21,7 +21,7 @@ #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h" #include "RecoTracker/CkfPattern/interface/TransientInitialStateEstimator.h" #include "TrackingTools/TrajectoryState/interface/TrajectoryStateTransform.h" -#include "TrackingTools/Records/interface/TrackingComponentsRecord.h" +#include "TrackingTools/Records/interface/TrackingComponentsRecord.h" #include "DataFormats/BeamSpot/interface/BeamSpot.h" @@ -31,131 +31,112 @@ using namespace edm; using namespace std; using namespace reco; +NuclearTrackCorrector::NuclearTrackCorrector(const edm::ParameterSet& iConfig) + : conf_(iConfig), theInitialState(nullptr) { + str_Input_Trajectory = iConfig.getParameter("InputTrajectory"); + str_Input_NuclearInteraction = iConfig.getParameter("InputNuclearInteraction"); + verbosity = iConfig.getParameter("Verbosity"); + KeepOnlyCorrectedTracks = iConfig.getParameter("KeepOnlyCorrectedTracks"); -NuclearTrackCorrector::NuclearTrackCorrector(const edm::ParameterSet& iConfig) : -conf_(iConfig), -theInitialState(nullptr) -{ - str_Input_Trajectory = iConfig.getParameter ("InputTrajectory"); - str_Input_NuclearInteraction = iConfig.getParameter ("InputNuclearInteraction"); - verbosity = iConfig.getParameter ("Verbosity"); - KeepOnlyCorrectedTracks = iConfig.getParameter ("KeepOnlyCorrectedTracks"); - - - theAlgo = new TrackProducerAlgorithm(iConfig); + theAlgo = new TrackProducerAlgorithm(iConfig); - produces< TrajectoryCollection >(); - produces< TrajectoryToTrajectoryMap >(); + produces(); + produces(); - produces< reco::TrackExtraCollection >(); - produces< reco::TrackCollection >(); - produces< TrackToTrajectoryMap >(); + produces(); + produces(); + produces(); - produces< TrackToTrackMap >(); + produces(); } +NuclearTrackCorrector::~NuclearTrackCorrector() {} -NuclearTrackCorrector::~NuclearTrackCorrector() -{ -} - -void -NuclearTrackCorrector::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) -{ +void NuclearTrackCorrector::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { // Create Output Collections // -------------------------------------------------------------------------------------------------- - auto Output_traj = std::make_unique(); - auto Output_trajmap = std::make_unique(); - - auto Output_trackextra = std::make_unique(); - auto Output_track = std::make_unique(); - auto Output_trackmap = std::make_unique(); - - - - + auto Output_traj = std::make_unique(); + auto Output_trajmap = std::make_unique(); + auto Output_trackextra = std::make_unique(); + auto Output_track = std::make_unique(); + auto Output_trackmap = std::make_unique(); // Load Reccord // -------------------------------------------------------------------------------------------------- - std::string fitterName = conf_.getParameter("Fitter"); - iSetup.get().get(fitterName,theFitter); + std::string fitterName = conf_.getParameter("Fitter"); + iSetup.get().get(fitterName, theFitter); - std::string propagatorName = conf_.getParameter("Propagator"); - iSetup.get().get(propagatorName,thePropagator); + std::string propagatorName = conf_.getParameter("Propagator"); + iSetup.get().get(propagatorName, thePropagator); iSetup.get().get(theG); reco::TrackExtraRefProd rTrackExtras = iEvent.getRefBeforePut(); - iSetup.get().get(theMF); + iSetup.get().get(theMF); // Load Inputs // -------------------------------------------------------------------------------------------------- - edm::Handle< TrajectoryCollection > temp_m_TrajectoryCollection; - iEvent.getByLabel( str_Input_Trajectory, temp_m_TrajectoryCollection ); + edm::Handle temp_m_TrajectoryCollection; + iEvent.getByLabel(str_Input_Trajectory, temp_m_TrajectoryCollection); const TrajectoryCollection m_TrajectoryCollection = *(temp_m_TrajectoryCollection.product()); - edm::Handle< NuclearInteractionCollection > temp_m_NuclearInteractionCollection; - iEvent.getByLabel( str_Input_NuclearInteraction, temp_m_NuclearInteractionCollection ); + edm::Handle temp_m_NuclearInteractionCollection; + iEvent.getByLabel(str_Input_NuclearInteraction, temp_m_NuclearInteractionCollection); const NuclearInteractionCollection m_NuclearInteractionCollection = *(temp_m_NuclearInteractionCollection.product()); - edm::Handle< TrajTrackAssociationCollection > h_TrajToTrackCollection; - iEvent.getByLabel( str_Input_Trajectory, h_TrajToTrackCollection ); + edm::Handle h_TrajToTrackCollection; + iEvent.getByLabel(str_Input_Trajectory, h_TrajToTrackCollection); m_TrajToTrackCollection = h_TrajToTrackCollection.product(); - // Correct the trajectories (Remove trajectory's hits that are located after the nuclear interacion) // -------------------------------------------------------------------------------------------------- - if(verbosity>=1){ - LogDebug("NuclearTrackCorrector") - <<"Number of trajectories = "<size() != Handle_traj->size() \n"); - return; + if (Handle_tracks->size() != Handle_traj->size()) { + printf("ERROR Handle_tracks->size() != Handle_traj->size() \n"); + return; } auto Output_tracktrackmap = std::make_unique(Handle_tracks, m_TrajToTrackCollection->refProd().val); - for(unsigned int i = 0 ; i < Indice_Map.size() ; i++) - { - TrajectoryRef InTrajRef ( temp_m_TrajectoryCollection, Indice_Map[i].second ); - TrajectoryRef OutTrajRef ( Handle_traj, Indice_Map[i].first ); - reco::TrackRef TrackRef ( Handle_tracks, Indice_Map[i].first ); + for (unsigned int i = 0; i < Indice_Map.size(); i++) { + TrajectoryRef InTrajRef(temp_m_TrajectoryCollection, Indice_Map[i].second); + TrajectoryRef OutTrajRef(Handle_traj, Indice_Map[i].first); + reco::TrackRef TrackRef(Handle_tracks, Indice_Map[i].first); - Output_trajmap ->insert(OutTrajRef,InTrajRef); - Output_trackmap->insert(TrackRef,InTrajRef); + Output_trajmap->insert(OutTrajRef, InTrajRef); + Output_trackmap->insert(TrackRef, InTrajRef); - try{ - reco::TrackRef PrimaryTrackRef = m_TrajToTrackCollection->operator[]( InTrajRef ); - Output_tracktrackmap->insert(TrackRef,PrimaryTrackRef); - }catch(edm::Exception const&){} - + try { + reco::TrackRef PrimaryTrackRef = m_TrajToTrackCollection->operator[](InTrajRef); + Output_tracktrackmap->insert(TrackRef, PrimaryTrackRef); + } catch (edm::Exception const&) { + } } iEvent.put(std::move(Output_trajmap)); iEvent.put(std::move(Output_trackmap)); iEvent.put(std::move(Output_tracktrackmap)); - - if(verbosity>=3)printf("-----------------------\n"); + if (verbosity >= 3) + printf("-----------------------\n"); } // ------------ method called once each job just after ending the event loop ------------ -void -NuclearTrackCorrector::endJob() { -} +void NuclearTrackCorrector::endJob() {} //---------------------------------------------------------------------------------------- -bool NuclearTrackCorrector::newTrajNeeded(Trajectory& newtrajectory, const TrajectoryRef& trajRef, const NuclearInteraction& ni) { - - bool needNewTraj=false; - reco::Vertex::Point vtx_pos = ni.vertex().position(); - double vtx_pos_mag = sqrt (vtx_pos.X()*vtx_pos.X()+vtx_pos.Y()*vtx_pos.Y()+vtx_pos.Z()*vtx_pos.Z()); - if(verbosity>=2) printf("Nuclear Interaction pos = %f\n",vtx_pos_mag ); - - - newtrajectory = Trajectory(trajRef->seed(), alongMomentum); - - // Look all the Hits of the trajectory and keep only Hits before seeds - Trajectory::DataContainer Measurements = trajRef->measurements(); - if(verbosity>=2)LogDebug("NuclearTrackCorrector")<<"Size of Measurements = "<isValid() )continue; - GlobalPoint hit_pos = theG->idToDet(Measurements[m].recHit()->geographicalId())->surface().toGlobal(Measurements[m].recHit()->localPosition()); - - if(verbosity>=2)printf("Hit pos = %f",hit_pos.mag() ); - - if(hit_pos.mag()>vtx_pos_mag){ - if(verbosity>=2)printf(" X "); - needNewTraj=true; - }else{ - newtrajectory.push(Measurements[m]); - } - if(verbosity>=2)printf("\n"); - } +bool NuclearTrackCorrector::newTrajNeeded(Trajectory& newtrajectory, + const TrajectoryRef& trajRef, + const NuclearInteraction& ni) { + bool needNewTraj = false; + reco::Vertex::Point vtx_pos = ni.vertex().position(); + double vtx_pos_mag = sqrt(vtx_pos.X() * vtx_pos.X() + vtx_pos.Y() * vtx_pos.Y() + vtx_pos.Z() * vtx_pos.Z()); + if (verbosity >= 2) + printf("Nuclear Interaction pos = %f\n", vtx_pos_mag); + + newtrajectory = Trajectory(trajRef->seed(), alongMomentum); + + // Look all the Hits of the trajectory and keep only Hits before seeds + Trajectory::DataContainer Measurements = trajRef->measurements(); + if (verbosity >= 2) + LogDebug("NuclearTrackCorrector") << "Size of Measurements = " << Measurements.size(); + + for (unsigned int m = Measurements.size() - 1; m != (unsigned int)-1; m--) { + if (!Measurements[m].recHit()->isValid()) + continue; + GlobalPoint hit_pos = theG->idToDet(Measurements[m].recHit()->geographicalId()) + ->surface() + .toGlobal(Measurements[m].recHit()->localPosition()); + + if (verbosity >= 2) + printf("Hit pos = %f", hit_pos.mag()); + + if (hit_pos.mag() > vtx_pos_mag) { + if (verbosity >= 2) + printf(" X "); + needNewTraj = true; + } else { + newtrajectory.push(Measurements[m]); + } + if (verbosity >= 2) + printf("\n"); + } - return needNewTraj; + return needNewTraj; } //---------------------------------------------------------------------------------------- -bool NuclearTrackCorrector::getTrackFromTrajectory(const Trajectory& newTraj , const TrajectoryRef& initialTrajRef, AlgoProductCollection& algoResults) { - - const Trajectory* it = &newTraj; - - TransientTrackingRecHit::RecHitContainer hits; - it->validRecHits( hits ); - - - float ndof=0; - for(unsigned int h=0 ; hisValid() ) - { - ndof = ndof + hits[h]->dimension() * hits[h]->weight(); - } - else { - LogDebug("NuclearSeedGenerator") << " HIT IS INVALID ???"; - } - } - - - ndof = ndof - 5; - reco::TrackRef theT = m_TrajToTrackCollection->operator[]( initialTrajRef ); - LogDebug("NuclearSeedGenerator") << " TrackCorrector - number of valid hits" << hits.size() << "\n" - << " - number of hits from Track " << theT->recHitsSize() << "\n" - << " - number of valid hits from initial track " << theT->numberOfValidHits(); - - - if( hits.size() > 1){ - - TrajectoryStateOnSurface theInitialStateForRefitting = getInitialState(&(*theT),hits,theG.product(),theMF.product() -); +bool NuclearTrackCorrector::getTrackFromTrajectory(const Trajectory& newTraj, + const TrajectoryRef& initialTrajRef, + AlgoProductCollection& algoResults) { + const Trajectory* it = &newTraj; + + TransientTrackingRecHit::RecHitContainer hits; + it->validRecHits(hits); + + float ndof = 0; + for (unsigned int h = 0; h < hits.size(); h++) { + if (hits[h]->isValid()) { + ndof = ndof + hits[h]->dimension() * hits[h]->weight(); + } else { + LogDebug("NuclearSeedGenerator") << " HIT IS INVALID ???"; + } + } - reco::BeamSpot bs; - return theAlgo->buildTrack(theFitter.product(), thePropagator.product(), algoResults, hits, theInitialStateForRefitting ,it->seed(), ndof, bs, theT->seedRef()); - } + ndof = ndof - 5; + reco::TrackRef theT = m_TrajToTrackCollection->operator[](initialTrajRef); + LogDebug("NuclearSeedGenerator") << " TrackCorrector - number of valid hits" << hits.size() << "\n" + << " - number of hits from Track " << theT->recHitsSize() << "\n" + << " - number of valid hits from initial track " + << theT->numberOfValidHits(); + + if (hits.size() > 1) { + TrajectoryStateOnSurface theInitialStateForRefitting = + getInitialState(&(*theT), hits, theG.product(), theMF.product()); + + reco::BeamSpot bs; + return theAlgo->buildTrack(theFitter.product(), + thePropagator.product(), + algoResults, + hits, + theInitialStateForRefitting, + it->seed(), + ndof, + bs, + theT->seedRef()); + } - return false; + return false; } //---------------------------------------------------------------------------------------- reco::TrackExtra NuclearTrackCorrector::getNewTrackExtra(const AlgoProductCollection& algoResults) { - Trajectory* theTraj = algoResults[0].trajectory; - PropagationDirection seedDir = algoResults[0].pDir; - - TrajectoryStateOnSurface outertsos; - TrajectoryStateOnSurface innertsos; - unsigned int innerId, outerId; - if (theTraj->direction() == alongMomentum) { - outertsos = theTraj->lastMeasurement().updatedState(); - innertsos = theTraj->firstMeasurement().updatedState(); - outerId = theTraj->lastMeasurement().recHit()->geographicalId().rawId(); - innerId = theTraj->firstMeasurement().recHit()->geographicalId().rawId(); - } else { - outertsos = theTraj->firstMeasurement().updatedState(); - innertsos = theTraj->lastMeasurement().updatedState(); - outerId = theTraj->firstMeasurement().recHit()->geographicalId().rawId(); - innerId = theTraj->lastMeasurement().recHit()->geographicalId().rawId(); - } - - GlobalPoint v = outertsos.globalParameters().position(); - GlobalVector p = outertsos.globalParameters().momentum(); - math::XYZVector outmom( p.x(), p.y(), p.z() ); - math::XYZPoint outpos( v.x(), v.y(), v.z() ); - v = innertsos.globalParameters().position(); - p = innertsos.globalParameters().momentum(); - math::XYZVector inmom( p.x(), p.y(), p.z() ); - math::XYZPoint inpos( v.x(), v.y(), v.z() ); - - return reco::TrackExtra (outpos, outmom, true, inpos, inmom, true, - outertsos.curvilinearError(), outerId, - innertsos.curvilinearError(), innerId, seedDir); + Trajectory* theTraj = algoResults[0].trajectory; + PropagationDirection seedDir = algoResults[0].pDir; + + TrajectoryStateOnSurface outertsos; + TrajectoryStateOnSurface innertsos; + unsigned int innerId, outerId; + if (theTraj->direction() == alongMomentum) { + outertsos = theTraj->lastMeasurement().updatedState(); + innertsos = theTraj->firstMeasurement().updatedState(); + outerId = theTraj->lastMeasurement().recHit()->geographicalId().rawId(); + innerId = theTraj->firstMeasurement().recHit()->geographicalId().rawId(); + } else { + outertsos = theTraj->firstMeasurement().updatedState(); + innertsos = theTraj->lastMeasurement().updatedState(); + outerId = theTraj->firstMeasurement().recHit()->geographicalId().rawId(); + innerId = theTraj->lastMeasurement().recHit()->geographicalId().rawId(); + } + GlobalPoint v = outertsos.globalParameters().position(); + GlobalVector p = outertsos.globalParameters().momentum(); + math::XYZVector outmom(p.x(), p.y(), p.z()); + math::XYZPoint outpos(v.x(), v.y(), v.z()); + v = innertsos.globalParameters().position(); + p = innertsos.globalParameters().momentum(); + math::XYZVector inmom(p.x(), p.y(), p.z()); + math::XYZPoint inpos(v.x(), v.y(), v.z()); + + return reco::TrackExtra(outpos, + outmom, + true, + inpos, + inmom, + true, + outertsos.curvilinearError(), + outerId, + innertsos.curvilinearError(), + innerId, + seedDir); } //---------------------------------------------------------------------------------------- -TrajectoryStateOnSurface NuclearTrackCorrector::getInitialState(const reco::Track * theT, - TransientTrackingRecHit::RecHitContainer& hits, - const TrackingGeometry * theG, - const MagneticField * theMF){ - +TrajectoryStateOnSurface NuclearTrackCorrector::getInitialState(const reco::Track* theT, + TransientTrackingRecHit::RecHitContainer& hits, + const TrackingGeometry* theG, + const MagneticField* theMF) { TrajectoryStateOnSurface theInitialStateForRefitting; //the starting state is the state closest to the first hit along seedDirection. - + //avoiding to use transientTrack, it should be faster; - TrajectoryStateOnSurface innerStateFromTrack=trajectoryStateTransform::innerStateOnSurface(*theT,*theG,theMF); - TrajectoryStateOnSurface outerStateFromTrack=trajectoryStateTransform::outerStateOnSurface(*theT,*theG,theMF); - TrajectoryStateOnSurface initialStateFromTrack = - ( (innerStateFromTrack.globalPosition()-hits.front()->globalPosition()).mag2() < - (outerStateFromTrack.globalPosition()-hits.front()->globalPosition()).mag2() ) ? - innerStateFromTrack: outerStateFromTrack; - + TrajectoryStateOnSurface innerStateFromTrack = trajectoryStateTransform::innerStateOnSurface(*theT, *theG, theMF); + TrajectoryStateOnSurface outerStateFromTrack = trajectoryStateTransform::outerStateOnSurface(*theT, *theG, theMF); + TrajectoryStateOnSurface initialStateFromTrack = + ((innerStateFromTrack.globalPosition() - hits.front()->globalPosition()).mag2() < + (outerStateFromTrack.globalPosition() - hits.front()->globalPosition()).mag2()) + ? innerStateFromTrack + : outerStateFromTrack; + // error is rescaled, but correlation are kept. initialStateFromTrack.rescaleError(100); theInitialStateForRefitting = TrajectoryStateOnSurface(initialStateFromTrack.localParameters(), - initialStateFromTrack.localError(), + initialStateFromTrack.localError(), initialStateFromTrack.surface(), - theMF); + theMF); return theInitialStateForRefitting; } //---------------------------------------------------------------------------------------- -void NuclearTrackCorrector::swap_map(const edm::Handle< TrajectoryCollection >& trajColl , std::map< reco::TrackRef, edm::Ref >& result) { - for(unsigned int i = 0 ; i < trajColl->size() ; i++) - { - TrajectoryRef InTrajRef ( trajColl, i); - reco::TrackRef PrimaryTrackRef = m_TrajToTrackCollection->operator[]( InTrajRef ); - result[ PrimaryTrackRef ] = InTrajRef; +void NuclearTrackCorrector::swap_map(const edm::Handle& trajColl, + std::map >& result) { + for (unsigned int i = 0; i < trajColl->size(); i++) { + TrajectoryRef InTrajRef(trajColl, i); + reco::TrackRef PrimaryTrackRef = m_TrajToTrackCollection->operator[](InTrajRef); + result[PrimaryTrackRef] = InTrajRef; } } diff --git a/RecoTracker/NuclearSeedGenerator/plugins/modules.cc b/RecoTracker/NuclearSeedGenerator/plugins/modules.cc index d9845692f069e..0fc6bc52d4036 100644 --- a/RecoTracker/NuclearSeedGenerator/plugins/modules.cc +++ b/RecoTracker/NuclearSeedGenerator/plugins/modules.cc @@ -4,6 +4,3 @@ DEFINE_FWK_MODULE(NuclearSeedsEDProducer); #include "RecoTracker/NuclearSeedGenerator/interface/NuclearTrackCorrector.h" DEFINE_FWK_MODULE(NuclearTrackCorrector); - - - diff --git a/RecoTracker/NuclearSeedGenerator/src/NuclearInteractionFinder.cc b/RecoTracker/NuclearSeedGenerator/src/NuclearInteractionFinder.cc index 6cafbef3364ae..fb4a35d400d37 100644 --- a/RecoTracker/NuclearSeedGenerator/src/NuclearInteractionFinder.cc +++ b/RecoTracker/NuclearSeedGenerator/src/NuclearInteractionFinder.cc @@ -8,7 +8,7 @@ #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "TrackingTools/KalmanUpdators/interface/Chi2MeasurementEstimatorBase.h" -#include "RecoTracker/Record/interface/NavigationSchoolRecord.h" +#include "RecoTracker/Record/interface/NavigationSchoolRecord.h" #include "RecoTracker/Record/interface/CkfComponentsRecord.h" @@ -16,49 +16,46 @@ #include "FWCore/Framework/interface/ESHandle.h" - -NuclearInteractionFinder::NuclearInteractionFinder(const edm::EventSetup& es, const edm::ParameterSet& iConfig) : -maxHits(iConfig.getParameter("maxHits")), -rescaleErrorFactor(iConfig.getParameter("rescaleErrorFactor")), -checkCompletedTrack(iConfig.getParameter("checkCompletedTrack")), -navigationSchoolName(iConfig.getParameter("NavigationSchool")) -{ - - std::string measurementTrackerName = iConfig.getParameter("MeasurementTrackerName"); - - edm::ESHandle prop; - edm::ESHandle upd; - edm::ESHandle est; - edm::ESHandle measurementTrackerHandle; - edm::ESHandle theGeomSearchTrackerHandle; - edm::ESHandle theTrackerGeom; - - es.get ().get (theTrackerGeom); - es.get().get("PropagatorWithMaterial",prop); - es.get().get("Chi2",est); - es.get().get(measurementTrackerName, measurementTrackerHandle); - es.get().get(theGeomSearchTrackerHandle ); - es.get().get(theMagField); - - edm::ESHandle nav; - es.get().get(navigationSchoolName, nav); - theNavigationSchool = nav.product(); - - thePropagator = prop.product(); - theEstimator = est.product(); - theMeasurementTracker = measurementTrackerHandle.product(); - theGeomSearchTracker = theGeomSearchTrackerHandle.product(); - - LogDebug("NuclearSeedGenerator") << "New NuclearInteractionFinder instance with parameters : \n" - << "maxHits : " << maxHits << "\n" - << "rescaleErrorFactor : " << rescaleErrorFactor << "\n" - << "checkCompletedTrack : " << checkCompletedTrack << "\n"; - - nuclTester = new NuclearTester(maxHits, theEstimator, theTrackerGeom.product() ); - - currentSeed = new SeedFromNuclearInteraction(thePropagator, theTrackerGeom.product(), iConfig) ; - - thePrimaryHelix = new TangentHelix(); +NuclearInteractionFinder::NuclearInteractionFinder(const edm::EventSetup& es, const edm::ParameterSet& iConfig) + : maxHits(iConfig.getParameter("maxHits")), + rescaleErrorFactor(iConfig.getParameter("rescaleErrorFactor")), + checkCompletedTrack(iConfig.getParameter("checkCompletedTrack")), + navigationSchoolName(iConfig.getParameter("NavigationSchool")) { + std::string measurementTrackerName = iConfig.getParameter("MeasurementTrackerName"); + + edm::ESHandle prop; + edm::ESHandle upd; + edm::ESHandle est; + edm::ESHandle measurementTrackerHandle; + edm::ESHandle theGeomSearchTrackerHandle; + edm::ESHandle theTrackerGeom; + + es.get().get(theTrackerGeom); + es.get().get("PropagatorWithMaterial", prop); + es.get().get("Chi2", est); + es.get().get(measurementTrackerName, measurementTrackerHandle); + es.get().get(theGeomSearchTrackerHandle); + es.get().get(theMagField); + + edm::ESHandle nav; + es.get().get(navigationSchoolName, nav); + theNavigationSchool = nav.product(); + + thePropagator = prop.product(); + theEstimator = est.product(); + theMeasurementTracker = measurementTrackerHandle.product(); + theGeomSearchTracker = theGeomSearchTrackerHandle.product(); + + LogDebug("NuclearSeedGenerator") << "New NuclearInteractionFinder instance with parameters : \n" + << "maxHits : " << maxHits << "\n" + << "rescaleErrorFactor : " << rescaleErrorFactor << "\n" + << "checkCompletedTrack : " << checkCompletedTrack << "\n"; + + nuclTester = new NuclearTester(maxHits, theEstimator, theTrackerGeom.product()); + + currentSeed = new SeedFromNuclearInteraction(thePropagator, theTrackerGeom.product(), iConfig); + + thePrimaryHelix = new TangentHelix(); } //---------------------------------------------------------------------- NuclearInteractionFinder::~NuclearInteractionFinder() { @@ -68,80 +65,82 @@ NuclearInteractionFinder::~NuclearInteractionFinder() { } //---------------------------------------------------------------------- -bool NuclearInteractionFinder::run(const Trajectory& traj, const MeasurementTrackerEvent &event) { - - if(traj.empty() || !traj.isValid()) return false; +bool NuclearInteractionFinder::run(const Trajectory& traj, const MeasurementTrackerEvent& event) { + if (traj.empty() || !traj.isValid()) + return false; - LogDebug("NuclearSeedGenerator") << "Analyzis of a new trajectory with a number of valid hits = " << traj.foundHits(); + LogDebug("NuclearSeedGenerator") << "Analyzis of a new trajectory with a number of valid hits = " << traj.foundHits(); - std::vector measurements = traj.measurements(); + std::vector measurements = traj.measurements(); - // initialization - nuclTester->reset( measurements.size() ); - allSeeds.clear(); + // initialization + nuclTester->reset(measurements.size()); + allSeeds.clear(); - LayerMeasurements layerMeasurements(*theMeasurementTracker, event); + LayerMeasurements layerMeasurements(*theMeasurementTracker, event); - if(traj.direction()==alongMomentum) { - std::reverse(measurements.begin(), measurements.end()); - } + if (traj.direction() == alongMomentum) { + std::reverse(measurements.begin(), measurements.end()); + } - std::vector::const_iterator it_meas = measurements.begin(); + std::vector::const_iterator it_meas = measurements.begin(); - std::vector ncompatibleHits; - bool NIfound = false; + std::vector ncompatibleHits; + bool NIfound = false; - // Loop on all the RecHits. - while(!NIfound) - { - if(it_meas == measurements.end()) break; + // Loop on all the RecHits. + while (!NIfound) { + if (it_meas == measurements.end()) + break; - // check only the maxHits outermost hits of the primary track - if(nuclTester->nHitsChecked() > maxHits) break; + // check only the maxHits outermost hits of the primary track + if (nuclTester->nHitsChecked() > maxHits) + break; - nuclTester->push_back(*it_meas, findCompatibleMeasurements(*it_meas, rescaleErrorFactor, layerMeasurements)); + nuclTester->push_back(*it_meas, findCompatibleMeasurements(*it_meas, rescaleErrorFactor, layerMeasurements)); - LogDebug("NuclearSeedGenerator") << "Number of compatible meas:" << (nuclTester->back()).size() << "\n" - << "Mean distance between hits :" << nuclTester->meanHitDistance() << "\n" - << "Forward estimate :" << nuclTester->fwdEstimate() << "\n"; + LogDebug("NuclearSeedGenerator") << "Number of compatible meas:" << (nuclTester->back()).size() << "\n" + << "Mean distance between hits :" << nuclTester->meanHitDistance() << "\n" + << "Forward estimate :" << nuclTester->fwdEstimate() << "\n"; - // don't check tracks which reach the end of the tracker if checkCompletedTrack==false - if( checkCompletedTrack==false && (nuclTester->compatibleHits()).front()==0 ) break; + // don't check tracks which reach the end of the tracker if checkCompletedTrack==false + if (checkCompletedTrack == false && (nuclTester->compatibleHits()).front() == 0) + break; - if(nuclTester->isNuclearInteraction()) NIfound=true; + if (nuclTester->isNuclearInteraction()) + NIfound = true; - ++it_meas; - } + ++it_meas; + } - if(NIfound) { - LogDebug("NuclearSeedGenerator") << "NUCLEAR INTERACTION FOUND at index : " << nuclTester->nuclearIndex() << "\n"; + if (NIfound) { + LogDebug("NuclearSeedGenerator") << "NUCLEAR INTERACTION FOUND at index : " << nuclTester->nuclearIndex() << "\n"; - // Get correct parametrization of the helix of the primary track at the interaction point (to be used by improveCurrentSeed) - definePrimaryHelix(measurements.begin()+nuclTester->nuclearIndex()-1); + // Get correct parametrization of the helix of the primary track at the interaction point (to be used by improveCurrentSeed) + definePrimaryHelix(measurements.begin() + nuclTester->nuclearIndex() - 1); - this->fillSeeds( nuclTester->goodTMPair()); + this->fillSeeds(nuclTester->goodTMPair()); - return true; - } + return true; + } - return false; + return false; } //---------------------------------------------------------------------- void NuclearInteractionFinder::definePrimaryHelix(std::vector::const_iterator it_meas) { - // This method uses the 3 last TM after the interaction point to calculate the helix parameters + // This method uses the 3 last TM after the interaction point to calculate the helix parameters - GlobalPoint pt[3]; - for(int i=0; i<3; i++) { - pt[i] = (it_meas->updatedState()).globalParameters().position(); - it_meas++; - } - delete thePrimaryHelix; - thePrimaryHelix = new TangentHelix( pt[0], pt[1], pt[2] ); + GlobalPoint pt[3]; + for (int i = 0; i < 3; i++) { + pt[i] = (it_meas->updatedState()).globalParameters().position(); + it_meas++; + } + delete thePrimaryHelix; + thePrimaryHelix = new TangentHelix(pt[0], pt[1], pt[2]); } //---------------------------------------------------------------------- -std::vector -NuclearInteractionFinder::findCompatibleMeasurements(const TM& lastMeas, double rescale, const LayerMeasurements & layerMeasurements) const -{ +std::vector NuclearInteractionFinder::findCompatibleMeasurements( + const TM& lastMeas, double rescale, const LayerMeasurements& layerMeasurements) const { const TSOS& currentState = lastMeas.updatedState(); LogDebug("NuclearSeedGenerator") << "currentState :" << currentState << "\n"; @@ -149,121 +148,123 @@ NuclearInteractionFinder::findCompatibleMeasurements(const TM& lastMeas, double return findMeasurementsFromTSOS(newState, lastMeas.recHit()->geographicalId(), layerMeasurements); } //---------------------------------------------------------------------- -std::vector -NuclearInteractionFinder::findMeasurementsFromTSOS(const TSOS& currentState, DetId detid, const LayerMeasurements & layerMeasurements) const { - +std::vector NuclearInteractionFinder::findMeasurementsFromTSOS( + const TSOS& currentState, DetId detid, const LayerMeasurements& layerMeasurements) const { using namespace std; int invalidHits = 0; vector result; - const DetLayer* lastLayer = theGeomSearchTracker->detLayer( detid ); + const DetLayer* lastLayer = theGeomSearchTracker->detLayer(detid); vector nl; - if(lastLayer) { - nl = theNavigationSchool->nextLayers(*lastLayer,*currentState.freeState(), alongMomentum); - } - else { - edm::LogError("NuclearInteractionFinder") << "In findCompatibleMeasurements : lastLayer not accessible"; - return result; + if (lastLayer) { + nl = theNavigationSchool->nextLayers(*lastLayer, *currentState.freeState(), alongMomentum); + } else { + edm::LogError("NuclearInteractionFinder") << "In findCompatibleMeasurements : lastLayer not accessible"; + return result; } if (nl.empty()) { - LogDebug("NuclearSeedGenerator") << "In findCompatibleMeasurements : no compatible layer found"; - return result; + LogDebug("NuclearSeedGenerator") << "In findCompatibleMeasurements : no compatible layer found"; + return result; } - for (vector::iterator il = nl.begin(); - il != nl.end(); il++) { - vector tmp = - layerMeasurements.measurements((**il),currentState, *thePropagator, *theEstimator); - if ( !tmp.empty()) { - if ( result.empty()) result = tmp; + for (vector::iterator il = nl.begin(); il != nl.end(); il++) { + vector tmp = layerMeasurements.measurements((**il), currentState, *thePropagator, *theEstimator); + if (!tmp.empty()) { + if (result.empty()) + result = tmp; else { // keep one dummy TM at the end, skip the others - result.insert( result.end()-invalidHits, tmp.begin(), tmp.end()); + result.insert(result.end() - invalidHits, tmp.begin(), tmp.end()); } invalidHits++; } } // sort the final result, keep dummy measurements at the end - if ( result.size() > 1) { - sort( result.begin(), result.end()-invalidHits, TrajMeasLessEstim()); + if (result.size() > 1) { + sort(result.begin(), result.end() - invalidHits, TrajMeasLessEstim()); } return result; } //---------------------------------------------------------------------- -void NuclearInteractionFinder::fillSeeds( const std::pair >& tmPairs ) { +void NuclearInteractionFinder::fillSeeds( + const std::pair >& tmPairs) { // This method returns the seeds calculated by the class SeedsFromNuclearInteraction - const TM& innerTM = tmPairs.first; - const std::vector& outerTMs = tmPairs.second; - - // Loop on all outer TM - for(std::vector::const_iterator outtm = outerTMs.begin(); outtm!=outerTMs.end(); outtm++) { - if((innerTM.recHit())->isValid() && (outtm->recHit())->isValid()) { - currentSeed->setMeasurements(innerTM.updatedState(), innerTM.recHit(), outtm->recHit()); - allSeeds.push_back(*currentSeed); - } - else LogDebug("NuclearSeedGenerator") << "The initial hits for seeding are invalid" << "\n"; - } - return; + const TM& innerTM = tmPairs.first; + const std::vector& outerTMs = tmPairs.second; + + // Loop on all outer TM + for (std::vector::const_iterator outtm = outerTMs.begin(); outtm != outerTMs.end(); outtm++) { + if ((innerTM.recHit())->isValid() && (outtm->recHit())->isValid()) { + currentSeed->setMeasurements(innerTM.updatedState(), innerTM.recHit(), outtm->recHit()); + allSeeds.push_back(*currentSeed); + } else + LogDebug("NuclearSeedGenerator") << "The initial hits for seeding are invalid" + << "\n"; + } + return; } //---------------------------------------------------------------------- std::unique_ptr NuclearInteractionFinder::getPersistentSeeds() { - auto output = std::make_unique(); - for(std::vector::const_iterator it_seed = allSeeds.begin(); it_seed != allSeeds.end(); it_seed++) { - if(it_seed->isValid()) { - output->push_back( it_seed->TrajSeed() ); - } - else LogDebug("NuclearSeedGenerator") << "The seed is invalid" << "\n"; - } - return output; + auto output = std::make_unique(); + for (std::vector::const_iterator it_seed = allSeeds.begin(); it_seed != allSeeds.end(); + it_seed++) { + if (it_seed->isValid()) { + output->push_back(it_seed->TrajSeed()); + } else + LogDebug("NuclearSeedGenerator") << "The seed is invalid" + << "\n"; + } + return output; } //---------------------------------------------------------------------- -void NuclearInteractionFinder::improveSeeds(const MeasurementTrackerEvent &event) { - std::vector newSeedCollection; - - LayerMeasurements layerMeasurements(*theMeasurementTracker, event); - - // loop on all actual seeds - for(std::vector::const_iterator it_seed = allSeeds.begin(); it_seed != allSeeds.end(); it_seed++) { +void NuclearInteractionFinder::improveSeeds(const MeasurementTrackerEvent& event) { + std::vector newSeedCollection; - if( !it_seed->isValid() ) continue; + LayerMeasurements layerMeasurements(*theMeasurementTracker, event); - // find compatible TM in an outer layer - std::vector thirdTMs = findMeasurementsFromTSOS( it_seed->updatedTSOS() , it_seed->outerHitDetId(), layerMeasurements ); + // loop on all actual seeds + for (std::vector::const_iterator it_seed = allSeeds.begin(); it_seed != allSeeds.end(); + it_seed++) { + if (!it_seed->isValid()) + continue; - // loop on those new TMs - for(std::vector::const_iterator tm = thirdTMs.begin(); tm!= thirdTMs.end(); tm++) { + // find compatible TM in an outer layer + std::vector thirdTMs = + findMeasurementsFromTSOS(it_seed->updatedTSOS(), it_seed->outerHitDetId(), layerMeasurements); - if( ! tm->recHit()->isValid() ) continue; + // loop on those new TMs + for (std::vector::const_iterator tm = thirdTMs.begin(); tm != thirdTMs.end(); tm++) { + if (!tm->recHit()->isValid()) + continue; - // create new seeds collection using the circle equation - currentSeed->setMeasurements(*thePrimaryHelix, it_seed->initialTSOS(), it_seed->outerHit(), tm->recHit() ); - newSeedCollection.push_back( *currentSeed ); - } - } - allSeeds.clear(); - allSeeds = newSeedCollection; + // create new seeds collection using the circle equation + currentSeed->setMeasurements(*thePrimaryHelix, it_seed->initialTSOS(), it_seed->outerHit(), tm->recHit()); + newSeedCollection.push_back(*currentSeed); + } + } + allSeeds.clear(); + allSeeds = newSeedCollection; } //---------------------------------------------------------------------- TrajectoryStateOnSurface NuclearInteractionFinder::rescaleError(float rescale, const TSOS& state) const { + AlgebraicSymMatrix55 m(state.localError().matrix()); + AlgebraicSymMatrix55 mr; + LocalTrajectoryParameters ltp = state.localParameters(); - AlgebraicSymMatrix55 m(state.localError().matrix()); - AlgebraicSymMatrix55 mr; - LocalTrajectoryParameters ltp = state.localParameters(); - - // we assume that the error on q/p is equal to 20% of q/p * rescale - mr(0,0) = (ltp.signedInverseMomentum()*0.2*rescale)*(ltp.signedInverseMomentum()*0.2*rescale); + // we assume that the error on q/p is equal to 20% of q/p * rescale + mr(0, 0) = (ltp.signedInverseMomentum() * 0.2 * rescale) * (ltp.signedInverseMomentum() * 0.2 * rescale); - // the error on dx/z and dy/dz is fixed to 10% (* rescale) - mr(1,1) = 1E-2*rescale*rescale; - mr(2,2) = 1E-2*rescale*rescale; + // the error on dx/z and dy/dz is fixed to 10% (* rescale) + mr(1, 1) = 1E-2 * rescale * rescale; + mr(2, 2) = 1E-2 * rescale * rescale; - // the error on the local x and y positions are not modified. - mr(3,3) = m(3,3); - mr(4,4) = m(4,4); + // the error on the local x and y positions are not modified. + mr(3, 3) = m(3, 3); + mr(4, 4) = m(4, 4); - return TSOS(ltp, mr, state.surface(), &(state.globalParameters().magneticField()), state.surfaceSide()); + return TSOS(ltp, mr, state.surface(), &(state.globalParameters().magneticField()), state.surfaceSide()); } diff --git a/RecoTracker/NuclearSeedGenerator/src/NuclearTester.cc b/RecoTracker/NuclearSeedGenerator/src/NuclearTester.cc index a2cd244f3b601..96bd22b29da3c 100644 --- a/RecoTracker/NuclearSeedGenerator/src/NuclearTester.cc +++ b/RecoTracker/NuclearSeedGenerator/src/NuclearTester.cc @@ -2,101 +2,118 @@ #include "FWCore/MessageLogger/interface/MessageLogger.h" //---------------------------------------------------------------------- -NuclearTester::NuclearTester(unsigned int max_hits, const MeasurementEstimator* est, const TrackerGeometry* track_geom) : - maxHits(max_hits), theEstimator(est), trackerGeom(track_geom) { NuclearIndex=0; } +NuclearTester::NuclearTester(unsigned int max_hits, const MeasurementEstimator* est, const TrackerGeometry* track_geom) + : maxHits(max_hits), theEstimator(est), trackerGeom(track_geom) { + NuclearIndex = 0; +} //---------------------------------------------------------------------- -bool NuclearTester::isNuclearInteraction( ) { -// TODO : if energy of primary track is below a threshold don't use checkWithMultiplicity but only checkwith compatible_hits.front - - // 1. if momentum of the primary track is below 5 GeV and if the number of compatible hits >0 - // assume that a nuclear interaction occured at the end of the track - if( allTM.front().first.updatedState().globalMomentum().mag() < 5.0 && compatible_hits.front()>0) { NuclearIndex=1; return true; } - - // 2. else to use multiplicity we require at least 3 TM vectors to check if nuclear interactions occurs - if(nHitsChecked()<3) return false; +bool NuclearTester::isNuclearInteraction() { + // TODO : if energy of primary track is below a threshold don't use checkWithMultiplicity but only checkwith compatible_hits.front + + // 1. if momentum of the primary track is below 5 GeV and if the number of compatible hits >0 + // assume that a nuclear interaction occured at the end of the track + if (allTM.front().first.updatedState().globalMomentum().mag() < 5.0 && compatible_hits.front() > 0) { + NuclearIndex = 1; + return true; + } + + // 2. else to use multiplicity we require at least 3 TM vectors to check if nuclear interactions occurs + if (nHitsChecked() < 3) + return false; - // 2. check with multiplicity : - if( checkWithMultiplicity() == true ) return true; - else { - // 3. last case : uncompleted track with at least 1 compatible hits in the last layer - if( nHitsChecked() >= maxHits && compatible_hits.front()>0) {NuclearIndex=1; return true; } - } + // 2. check with multiplicity : + if (checkWithMultiplicity() == true) + return true; + else { + // 3. last case : uncompleted track with at least 1 compatible hits in the last layer + if (nHitsChecked() >= maxHits && compatible_hits.front() > 0) { + NuclearIndex = 1; + return true; + } + } - return false; + return false; } //---------------------------------------------------------------------- bool NuclearTester::checkWithMultiplicity() { - //RQ: assume that the input vector of compatible hits has been filled from Outside to Inside the tracker ! - - // find the first min nb of compatible TM : - std::vector::iterator min_it = min_element(compatible_hits.begin(), compatible_hits.end()); + //RQ: assume that the input vector of compatible hits has been filled from Outside to Inside the tracker ! - // if the outermost hit has no compatible TM, min_it has to be recalculated : - if(min_it == compatible_hits.begin() && *min_it!=0) return false; - if(min_it == compatible_hits.begin() && *min_it==0) min_it=min_element(compatible_hits.begin()+1, compatible_hits.end()); + // find the first min nb of compatible TM : + std::vector::iterator min_it = min_element(compatible_hits.begin(), compatible_hits.end()); - // this first min cannot be the innermost TM : - if(min_it == compatible_hits.end()-1) return false; + // if the outermost hit has no compatible TM, min_it has to be recalculated : + if (min_it == compatible_hits.begin() && *min_it != 0) + return false; + if (min_it == compatible_hits.begin() && *min_it == 0) + min_it = min_element(compatible_hits.begin() + 1, compatible_hits.end()); - // if the previous nb of compatible TM is > min+2 and if the next compatible TM is min+-1 -> NUCLEAR - // example : Nhits = 5, 8, 2, 2, ... - if((*(min_it-1) - *min_it) > 2 && (*(min_it+1) - *min_it) < 2 ) { - NuclearIndex = min_it - compatible_hits.begin(); - return true; - } + // this first min cannot be the innermost TM : + if (min_it == compatible_hits.end() - 1) + return false; - // case of : Nhits = 5, 8, 3, 2, 2, ... - if(min_it-1 != compatible_hits.begin()) //because min_it must be at least at the third position - { - if(min_it-1 != compatible_hits.begin() && (*(min_it-1) - *min_it) < 2 && (*(min_it-2) - *(min_it-1)) > 2 ) { - NuclearIndex = min_it - 1 - compatible_hits.begin(); - return true; - } + // if the previous nb of compatible TM is > min+2 and if the next compatible TM is min+-1 -> NUCLEAR + // example : Nhits = 5, 8, 2, 2, ... + if ((*(min_it - 1) - *min_it) > 2 && (*(min_it + 1) - *min_it) < 2) { + NuclearIndex = min_it - compatible_hits.begin(); + return true; + } + + // case of : Nhits = 5, 8, 3, 2, 2, ... + if (min_it - 1 != compatible_hits.begin()) //because min_it must be at least at the third position + { + if (min_it - 1 != compatible_hits.begin() && (*(min_it - 1) - *min_it) < 2 && (*(min_it - 2) - *(min_it - 1)) > 2) { + NuclearIndex = min_it - 1 - compatible_hits.begin(); + return true; } + } - return false; + return false; } //---------------------------------------------------------------------- double NuclearTester::meanHitDistance(const std::vector& vecTM) const { - std::vector vgp = this->HitPositions(vecTM); - double mean_dist=0; - int ncomb=0; - if(vgp.size()<2) return 0; - for(std::vector::iterator itp = vgp.begin(); itp != vgp.end()-1; itp++) { - for(std::vector::iterator itq = itp+1; itq != vgp.end(); itq++) { - double dist = ((*itp) - (*itq)).mag(); - // to calculate mean distance between particles and not hits (to not take into account twice stereo hits) - if(dist > 1E-12) { - mean_dist += dist; - ncomb++; - } - } + std::vector vgp = this->HitPositions(vecTM); + double mean_dist = 0; + int ncomb = 0; + if (vgp.size() < 2) + return 0; + for (std::vector::iterator itp = vgp.begin(); itp != vgp.end() - 1; itp++) { + for (std::vector::iterator itq = itp + 1; itq != vgp.end(); itq++) { + double dist = ((*itp) - (*itq)).mag(); + // to calculate mean distance between particles and not hits (to not take into account twice stereo hits) + if (dist > 1E-12) { + mean_dist += dist; + ncomb++; + } } - return mean_dist/ncomb; + } + return mean_dist / ncomb; } //---------------------------------------------------------------------- std::vector NuclearTester::HitPositions(const std::vector& vecTM) const { - std::vector gp; + std::vector gp; - std::vector::const_iterator last = this->lastValidTM(vecTM); + std::vector::const_iterator last = this->lastValidTM(vecTM); - for(std::vector::const_iterator itm = vecTM.begin(); itm!=last; itm++) { - ConstRecHitPointer trh = itm->recHit(); - if(trh->isValid()) gp.push_back(trackerGeom->idToDet(trh->geographicalId())->surface().toGlobal(trh->localPosition())); - } - return gp; + for (std::vector::const_iterator itm = vecTM.begin(); itm != last; itm++) { + ConstRecHitPointer trh = itm->recHit(); + if (trh->isValid()) + gp.push_back(trackerGeom->idToDet(trh->geographicalId())->surface().toGlobal(trh->localPosition())); + } + return gp; } //---------------------------------------------------------------------- double NuclearTester::fwdEstimate(const std::vector& vecTM) const { - if(vecTM.empty()) return 0; - - auto hit = vecTM.front().recHit().get(); - if( hit->isValid() ) - return theEstimator->estimate( vecTM.front().forwardPredictedState(), *hit ).second; - else return -1; -/* + if (vecTM.empty()) + return 0; + + auto hit = vecTM.front().recHit().get(); + if (hit->isValid()) + return theEstimator->estimate(vecTM.front().forwardPredictedState(), *hit).second; + else + return -1; + /* double meanEst=0; int goodTM=0; std::vector::const_iterator last; @@ -113,10 +130,11 @@ double NuclearTester::fwdEstimate(const std::vector& vecT } //---------------------------------------------------------------------- std::vector::const_iterator NuclearTester::lastValidTM(const std::vector& vecTM) const { - if (vecTM.empty()) return vecTM.end(); - if (vecTM.front().recHit()->isValid()) - return std::find_if( vecTM.begin(), vecTM.end(), - [](auto const& meas){ return !meas.recHit()->isValid(); }); - else return vecTM.end(); + if (vecTM.empty()) + return vecTM.end(); + if (vecTM.front().recHit()->isValid()) + return std::find_if(vecTM.begin(), vecTM.end(), [](auto const& meas) { return !meas.recHit()->isValid(); }); + else + return vecTM.end(); } //---------------------------------------------------------------------- diff --git a/RecoTracker/NuclearSeedGenerator/src/SeedFromNuclearInteraction.cc b/RecoTracker/NuclearSeedGenerator/src/SeedFromNuclearInteraction.cc index db51abab43c88..5a7aa1fa3869f 100644 --- a/RecoTracker/NuclearSeedGenerator/src/SeedFromNuclearInteraction.cc +++ b/RecoTracker/NuclearSeedGenerator/src/SeedFromNuclearInteraction.cc @@ -9,186 +9,188 @@ #include "FWCore/MessageLogger/interface/MessageLogger.h" - -SeedFromNuclearInteraction::SeedFromNuclearInteraction(const Propagator* prop, const TrackerGeometry* geom, const edm::ParameterSet& iConfig): - ptMin(iConfig.getParameter("ptMin")), - thePropagator(prop), theTrackerGeom(geom) - { - isValid_=true; - initialTSOS_ = boost::shared_ptr(new TrajectoryStateOnSurface()); - updatedTSOS_ = boost::shared_ptr(new TrajectoryStateOnSurface()); - freeTS_ = boost::shared_ptr(new FreeTrajectoryState()); - } +SeedFromNuclearInteraction::SeedFromNuclearInteraction(const Propagator* prop, + const TrackerGeometry* geom, + const edm::ParameterSet& iConfig) + : ptMin(iConfig.getParameter("ptMin")), thePropagator(prop), theTrackerGeom(geom) { + isValid_ = true; + initialTSOS_ = boost::shared_ptr(new TrajectoryStateOnSurface()); + updatedTSOS_ = boost::shared_ptr(new TrajectoryStateOnSurface()); + freeTS_ = boost::shared_ptr(new FreeTrajectoryState()); +} //---------------------------------------------------------------------- -void SeedFromNuclearInteraction::setMeasurements(const TSOS& inner_TSOS, ConstRecHitPointer ihit, ConstRecHitPointer ohit) { - - // delete pointer to TrackingRecHits - theHits.clear(); - - // get the inner and outer transient TrackingRecHits - innerHit_ = ihit; - outerHit_ = ohit; - - //theHits.push_back( inner_TM.recHit() ); // put temporarily - TODO: remove this line - theHits.push_back( outerHit_ ); - - initialTSOS_.reset( new TrajectoryStateOnSurface(inner_TSOS) ); - - // calculate the initial FreeTrajectoryState. - freeTS_.reset(stateWithError()); - - // check transverse momentum - if(freeTS_->momentum().perp() < ptMin) { isValid_ = false; } - else { - // convert freeTS_ into a persistent TSOS on the outer surface - isValid_ = construct(); } +void SeedFromNuclearInteraction::setMeasurements(const TSOS& inner_TSOS, + ConstRecHitPointer ihit, + ConstRecHitPointer ohit) { + // delete pointer to TrackingRecHits + theHits.clear(); + + // get the inner and outer transient TrackingRecHits + innerHit_ = ihit; + outerHit_ = ohit; + + //theHits.push_back( inner_TM.recHit() ); // put temporarily - TODO: remove this line + theHits.push_back(outerHit_); + + initialTSOS_.reset(new TrajectoryStateOnSurface(inner_TSOS)); + + // calculate the initial FreeTrajectoryState. + freeTS_.reset(stateWithError()); + + // check transverse momentum + if (freeTS_->momentum().perp() < ptMin) { + isValid_ = false; + } else { + // convert freeTS_ into a persistent TSOS on the outer surface + isValid_ = construct(); + } } //---------------------------------------------------------------------- -void SeedFromNuclearInteraction::setMeasurements(TangentHelix& thePrimaryHelix, const TSOS& inner_TSOS, ConstRecHitPointer ihit, ConstRecHitPointer ohit) { - - // delete pointer to TrackingRecHits - theHits.clear(); - - // get the inner and outer transient TrackingRecHits - innerHit_ = ihit; - outerHit_ = ohit; - - GlobalPoint innerPos = theTrackerGeom->idToDet(innerHit_->geographicalId())->surface().toGlobal(innerHit_->localPosition()); - GlobalPoint outerPos = theTrackerGeom->idToDet(outerHit_->geographicalId())->surface().toGlobal(outerHit_->localPosition()); - - TangentHelix helix(thePrimaryHelix, outerPos, innerPos); - - theHits.push_back( innerHit_ ); - theHits.push_back( outerHit_ ); - - initialTSOS_.reset( new TrajectoryStateOnSurface(inner_TSOS) ); - - // calculate the initial FreeTrajectoryState from the inner and outer TM assuming that the helix equation is already known. - freeTS_.reset(stateWithError(helix)); - - if(freeTS_->momentum().perp() < ptMin) { isValid_ = false; } - else { - // convert freeTS_ into a persistent TSOS on the outer surface - isValid_ = construct(); } +void SeedFromNuclearInteraction::setMeasurements(TangentHelix& thePrimaryHelix, + const TSOS& inner_TSOS, + ConstRecHitPointer ihit, + ConstRecHitPointer ohit) { + // delete pointer to TrackingRecHits + theHits.clear(); + + // get the inner and outer transient TrackingRecHits + innerHit_ = ihit; + outerHit_ = ohit; + + GlobalPoint innerPos = + theTrackerGeom->idToDet(innerHit_->geographicalId())->surface().toGlobal(innerHit_->localPosition()); + GlobalPoint outerPos = + theTrackerGeom->idToDet(outerHit_->geographicalId())->surface().toGlobal(outerHit_->localPosition()); + + TangentHelix helix(thePrimaryHelix, outerPos, innerPos); + + theHits.push_back(innerHit_); + theHits.push_back(outerHit_); + + initialTSOS_.reset(new TrajectoryStateOnSurface(inner_TSOS)); + + // calculate the initial FreeTrajectoryState from the inner and outer TM assuming that the helix equation is already known. + freeTS_.reset(stateWithError(helix)); + + if (freeTS_->momentum().perp() < ptMin) { + isValid_ = false; + } else { + // convert freeTS_ into a persistent TSOS on the outer surface + isValid_ = construct(); + } } //---------------------------------------------------------------------- FreeTrajectoryState* SeedFromNuclearInteraction::stateWithError() const { + // Calculation of the helix assuming that the secondary track has the same direction + // than the primary track and pass through the inner and outer hits. + GlobalVector direction = initialTSOS_->globalDirection(); + GlobalPoint inner = initialTSOS_->globalPosition(); + TangentHelix helix(direction, inner, outerHitPosition()); - // Calculation of the helix assuming that the secondary track has the same direction - // than the primary track and pass through the inner and outer hits. - GlobalVector direction = initialTSOS_->globalDirection(); - GlobalPoint inner = initialTSOS_->globalPosition(); - TangentHelix helix(direction, inner, outerHitPosition()); - - return stateWithError(helix); + return stateWithError(helix); } //---------------------------------------------------------------------- FreeTrajectoryState* SeedFromNuclearInteraction::stateWithError(TangentHelix& helix) const { + // typedef TkRotation Rotation; -// typedef TkRotation Rotation; - - GlobalVector dirAtVtx = helix.directionAtVertex(); - const MagneticField& mag = initialTSOS_->globalParameters().magneticField(); + GlobalVector dirAtVtx = helix.directionAtVertex(); + const MagneticField& mag = initialTSOS_->globalParameters().magneticField(); - // Get the global parameters of the trajectory - // we assume that the magnetic field at the vertex is equal to the magnetic field at the inner TM. - GlobalTrajectoryParameters gtp(helix.vertexPoint(), dirAtVtx , helix.charge(mag.inTesla(helix.vertexPoint()).z())/helix.rho(), 0, &mag); + // Get the global parameters of the trajectory + // we assume that the magnetic field at the vertex is equal to the magnetic field at the inner TM. + GlobalTrajectoryParameters gtp( + helix.vertexPoint(), dirAtVtx, helix.charge(mag.inTesla(helix.vertexPoint()).z()) / helix.rho(), 0, &mag); - // Error matrix in a frame where z is in the direction of the track at the vertex - AlgebraicSymMatrix66 primaryError( initialTSOS_->cartesianError().matrix() ); - double p_max = initialTSOS_->globalParameters().momentum().mag(); - AlgebraicMatrix33 rot = this->rotationMatrix( dirAtVtx ); + // Error matrix in a frame where z is in the direction of the track at the vertex + AlgebraicSymMatrix66 primaryError(initialTSOS_->cartesianError().matrix()); + double p_max = initialTSOS_->globalParameters().momentum().mag(); + AlgebraicMatrix33 rot = this->rotationMatrix(dirAtVtx); - AlgebraicMatrix66 globalRotation; - globalRotation.Place_at(rot,0,0); - globalRotation.Place_at(rot,3,3); - AlgebraicSymMatrix66 primaryErrorInNewFrame = ROOT::Math::Similarity(globalRotation, primaryError); + AlgebraicMatrix66 globalRotation; + globalRotation.Place_at(rot, 0, 0); + globalRotation.Place_at(rot, 3, 3); + AlgebraicSymMatrix66 primaryErrorInNewFrame = ROOT::Math::Similarity(globalRotation, primaryError); - AlgebraicSymMatrix66 secondaryErrorInNewFrame = AlgebraicMatrixID(); - double p_perp_max = 2; // energy max of a secondary track emited perpendicularly to the + AlgebraicSymMatrix66 secondaryErrorInNewFrame = AlgebraicMatrixID(); + double p_perp_max = 2; // energy max of a secondary track emited perpendicularly to the // primary track is +/- 2 GeV - secondaryErrorInNewFrame(0,0) = primaryErrorInNewFrame(0,0)+helix.vertexError()*p_perp_max/p_max; - secondaryErrorInNewFrame(1,1) = primaryErrorInNewFrame(1,1)+helix.vertexError()*p_perp_max/p_max; - secondaryErrorInNewFrame(2,2) = helix.vertexError() * helix.vertexError(); - secondaryErrorInNewFrame(3,3) = p_perp_max*p_perp_max; - secondaryErrorInNewFrame(4,4) = p_perp_max*p_perp_max; - secondaryErrorInNewFrame(5,5) = p_max*p_max; + secondaryErrorInNewFrame(0, 0) = primaryErrorInNewFrame(0, 0) + helix.vertexError() * p_perp_max / p_max; + secondaryErrorInNewFrame(1, 1) = primaryErrorInNewFrame(1, 1) + helix.vertexError() * p_perp_max / p_max; + secondaryErrorInNewFrame(2, 2) = helix.vertexError() * helix.vertexError(); + secondaryErrorInNewFrame(3, 3) = p_perp_max * p_perp_max; + secondaryErrorInNewFrame(4, 4) = p_perp_max * p_perp_max; + secondaryErrorInNewFrame(5, 5) = p_max * p_max; - AlgebraicSymMatrix66 secondaryError = ROOT::Math::SimilarityT(globalRotation, secondaryErrorInNewFrame); + AlgebraicSymMatrix66 secondaryError = ROOT::Math::SimilarityT(globalRotation, secondaryErrorInNewFrame); - return new FreeTrajectoryState( gtp, CartesianTrajectoryError(secondaryError) ); + return new FreeTrajectoryState(gtp, CartesianTrajectoryError(secondaryError)); } //---------------------------------------------------------------------- bool SeedFromNuclearInteraction::construct() { + // loop on all hits in theHits + KFUpdator theUpdator; - // loop on all hits in theHits - KFUpdator theUpdator; + const TrackingRecHit* hit = nullptr; - const TrackingRecHit* hit = nullptr; + LogDebug("NuclearSeedGenerator") << "Seed ** initial state " << freeTS_->cartesianError().matrix(); - LogDebug("NuclearSeedGenerator") << "Seed ** initial state " << freeTS_->cartesianError().matrix(); + for (unsigned int iHit = 0; iHit < theHits.size(); iHit++) { + hit = theHits[iHit]->hit(); + TrajectoryStateOnSurface state = + (iHit == 0) + ? thePropagator->propagate(*freeTS_, theTrackerGeom->idToDet(hit->geographicalId())->surface()) + : thePropagator->propagate(*updatedTSOS_, theTrackerGeom->idToDet(hit->geographicalId())->surface()); - for ( unsigned int iHit = 0; iHit < theHits.size(); iHit++) { - hit = theHits[iHit]->hit(); - TrajectoryStateOnSurface state = (iHit==0) ? - thePropagator->propagate( *freeTS_, theTrackerGeom->idToDet(hit->geographicalId())->surface()) - : thePropagator->propagate( *updatedTSOS_, theTrackerGeom->idToDet(hit->geographicalId())->surface()); + if (!state.isValid()) + return false; - if (!state.isValid()) return false; + const TransientTrackingRecHit::ConstRecHitPointer& tth = theHits[iHit]; + updatedTSOS_.reset(new TrajectoryStateOnSurface(theUpdator.update(state, *tth))); + } - const TransientTrackingRecHit::ConstRecHitPointer& tth = theHits[iHit]; - updatedTSOS_.reset( new TrajectoryStateOnSurface(theUpdator.update(state, *tth)) ); + LogDebug("NuclearSeedGenerator") << "Seed ** updated state " << updatedTSOS_->cartesianError().matrix(); - } - - - - LogDebug("NuclearSeedGenerator") << "Seed ** updated state " << updatedTSOS_->cartesianError().matrix(); - - pTraj = trajectoryStateTransform::persistentState(*updatedTSOS_, outerHitDetId().rawId()); - return true; + pTraj = trajectoryStateTransform::persistentState(*updatedTSOS_, outerHitDetId().rawId()); + return true; } //---------------------------------------------------------------------- -edm::OwnVector SeedFromNuclearInteraction::hits() const { - recHitContainer _hits; - for( ConstRecHitContainer::const_iterator it = theHits.begin(); it!=theHits.end(); it++ ){ - _hits.push_back( it->get()->hit()->clone() ); - } - return _hits; +edm::OwnVector SeedFromNuclearInteraction::hits() const { + recHitContainer _hits; + for (ConstRecHitContainer::const_iterator it = theHits.begin(); it != theHits.end(); it++) { + _hits.push_back(it->get()->hit()->clone()); + } + return _hits; } //---------------------------------------------------------------------- AlgebraicMatrix33 SeedFromNuclearInteraction::rotationMatrix(const GlobalVector& perp) const { - - AlgebraicMatrix33 result; - - // z axis coincides with perp - GlobalVector zAxis = perp.unit(); - - // x axis has no global Z component - GlobalVector xAxis; - if ( zAxis.x() != 0 || zAxis.y() != 0) { - // precision is not an issue here, just protect against divizion by zero - xAxis = GlobalVector( -zAxis.y(), zAxis.x(), 0).unit(); - } - else { // perp coincides with global Z - xAxis = GlobalVector( 1, 0, 0); - } - - // y axis obtained by cross product - GlobalVector yAxis( zAxis.cross( xAxis)); - - result(0,0) = xAxis.x(); - result(0,1) = xAxis.y(); - result(0,2) = xAxis.z(); - result(1,0) = yAxis.x(); - result(1,1) = yAxis.y(); - result(1,2) = yAxis.z(); - result(2,0) = zAxis.x(); - result(2,1) = zAxis.y(); - result(2,2) = zAxis.z(); + AlgebraicMatrix33 result; + + // z axis coincides with perp + GlobalVector zAxis = perp.unit(); + + // x axis has no global Z component + GlobalVector xAxis; + if (zAxis.x() != 0 || zAxis.y() != 0) { + // precision is not an issue here, just protect against divizion by zero + xAxis = GlobalVector(-zAxis.y(), zAxis.x(), 0).unit(); + } else { // perp coincides with global Z + xAxis = GlobalVector(1, 0, 0); + } + + // y axis obtained by cross product + GlobalVector yAxis(zAxis.cross(xAxis)); + + result(0, 0) = xAxis.x(); + result(0, 1) = xAxis.y(); + result(0, 2) = xAxis.z(); + result(1, 0) = yAxis.x(); + result(1, 1) = yAxis.y(); + result(1, 2) = yAxis.z(); + result(2, 0) = zAxis.x(); + result(2, 1) = zAxis.y(); + result(2, 2) = zAxis.z(); return result; } - diff --git a/RecoTracker/NuclearSeedGenerator/src/TangentCircle.cc b/RecoTracker/NuclearSeedGenerator/src/TangentCircle.cc index 1b00ea8c49659..944dc1301ba94 100644 --- a/RecoTracker/NuclearSeedGenerator/src/TangentCircle.cc +++ b/RecoTracker/NuclearSeedGenerator/src/TangentCircle.cc @@ -4,205 +4,236 @@ #define PI 3.1415926 // TODO: is not valid don't do any calculations and return init values -TangentCircle::TangentCircle(const GlobalVector& direction, const GlobalPoint& inner, const GlobalPoint& outer) : - theInnerPoint(inner), theOuterPoint(outer), theVertexPoint(inner) { - - if(theInnerPoint.perp2() > theOuterPoint.perp2()) { valid = false; } - else valid=true; - - double x1 = inner.x(); - double y1 = inner.y(); - double x2 = outer.x(); - double y2 = outer.y(); - double alpha1 = (direction.y() != 0) ? atan(-direction.x()/direction.y()) : PI/2 ; - double denominator = 2*((x1-x2)*cos(alpha1)+(y1-y2)*sin(alpha1)); - theRho = (denominator != 0) ? ((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2))/denominator : 1E12; - - // TODO : variable not yet calculated look in nucl.C - theX0 = 1E10; - theY0 = 1E10; - - theDirectionAtVertex = direction; - theDirectionAtVertex/=theDirectionAtVertex.mag(); - - //theCharge = (theRho>0) ? -1 : 1; - - theCharge = 0; - theRho = fabs(theRho); - - theVertexError = (theInnerPoint-theOuterPoint).mag(); +TangentCircle::TangentCircle(const GlobalVector& direction, const GlobalPoint& inner, const GlobalPoint& outer) + : theInnerPoint(inner), theOuterPoint(outer), theVertexPoint(inner) { + if (theInnerPoint.perp2() > theOuterPoint.perp2()) { + valid = false; + } else + valid = true; + + double x1 = inner.x(); + double y1 = inner.y(); + double x2 = outer.x(); + double y2 = outer.y(); + double alpha1 = (direction.y() != 0) ? atan(-direction.x() / direction.y()) : PI / 2; + double denominator = 2 * ((x1 - x2) * cos(alpha1) + (y1 - y2) * sin(alpha1)); + theRho = (denominator != 0) ? ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) / denominator : 1E12; + + // TODO : variable not yet calculated look in nucl.C + theX0 = 1E10; + theY0 = 1E10; + + theDirectionAtVertex = direction; + theDirectionAtVertex /= theDirectionAtVertex.mag(); + + //theCharge = (theRho>0) ? -1 : 1; + + theCharge = 0; + theRho = fabs(theRho); + + theVertexError = (theInnerPoint - theOuterPoint).mag(); } -TangentCircle::TangentCircle(const GlobalPoint& outerPoint, const GlobalPoint& innerPoint, const GlobalPoint& vertexPoint) : - theInnerPoint(innerPoint), theOuterPoint(outerPoint), theVertexPoint(vertexPoint) { - FastCircle circle(outerPoint, innerPoint, vertexPoint); - theX0 = circle.x0(); - theY0 = circle.y0(); - theRho = circle.rho(); - theVertexError = 0; - theCharge = 0; - theDirectionAtVertex = GlobalVector(1000, 1000, 1000); - if(theInnerPoint.perp2() > theOuterPoint.perp2() || !circle.isValid()) { valid = false; } - else valid=true; +TangentCircle::TangentCircle(const GlobalPoint& outerPoint, + const GlobalPoint& innerPoint, + const GlobalPoint& vertexPoint) + : theInnerPoint(innerPoint), theOuterPoint(outerPoint), theVertexPoint(vertexPoint) { + FastCircle circle(outerPoint, innerPoint, vertexPoint); + theX0 = circle.x0(); + theY0 = circle.y0(); + theRho = circle.rho(); + theVertexError = 0; + theCharge = 0; + theDirectionAtVertex = GlobalVector(1000, 1000, 1000); + if (theInnerPoint.perp2() > theOuterPoint.perp2() || !circle.isValid()) { + valid = false; + } else + valid = true; } -TangentCircle::TangentCircle(const TangentCircle& primCircle, const GlobalPoint& outerPoint, const GlobalPoint& innerPoint) { - - if(theInnerPoint.perp2() > theOuterPoint.perp2()) { valid = false; } - else valid = true; - - int NITER = 10; - - // Initial vertex used = outerPoint of the primary circle (should be the first estimation of the nuclear interaction position) - GlobalPoint InitialVertex( primCircle.outerPoint().x() , primCircle.outerPoint().y(), 0); - GlobalPoint SecInnerPoint( innerPoint.x(), innerPoint.y(), 0); - GlobalPoint SecOuterPoint( outerPoint.x(), outerPoint.y(), 0); - - // distance between the initial vertex and the inner point of the secondary circle - double s = (SecInnerPoint - InitialVertex).mag(); - double deltaTheta = s/primCircle.rho(); - - double minTangentCondition = 1E12; - TangentCircle theCorrectSecCircle; - GlobalPoint vertex = InitialVertex; - int dir = 1; - double theta = deltaTheta/(NITER-1); - - for(int i=0; i 1) dirDiff = 2-dirDiff; - - if(minCond < minTangentCondition) { - minTangentCondition = minCond; - theCorrectSecCircle = secCircle; - vertex = getPosition( primCircle, secCircle.vertexPoint(), theta, dir ); - if( i==0 && ((vertex-SecInnerPoint).mag() > (InitialVertex-SecInnerPoint).mag()) ) { - dir=-1; - vertex = getPosition( primCircle, InitialVertex, theta, dir ); - LogDebug("NuclearSeedGenerator") << "Change direction to look for vertex" << "\n"; - } - } - else break; - - } - theInnerPoint = theCorrectSecCircle.innerPoint(); - theOuterPoint = theCorrectSecCircle.outerPoint(); - theVertexPoint = theCorrectSecCircle.vertexPoint(); - theX0 = theCorrectSecCircle.x0(); - theY0 = theCorrectSecCircle.y0(); - theRho = theCorrectSecCircle.rho(); - theCharge = 0; - theDirectionAtVertex = GlobalVector(1000, 1000, 1000); - - theVertexError = s/NITER; +TangentCircle::TangentCircle(const TangentCircle& primCircle, + const GlobalPoint& outerPoint, + const GlobalPoint& innerPoint) { + if (theInnerPoint.perp2() > theOuterPoint.perp2()) { + valid = false; + } else + valid = true; + + int NITER = 10; + + // Initial vertex used = outerPoint of the primary circle (should be the first estimation of the nuclear interaction position) + GlobalPoint InitialVertex(primCircle.outerPoint().x(), primCircle.outerPoint().y(), 0); + GlobalPoint SecInnerPoint(innerPoint.x(), innerPoint.y(), 0); + GlobalPoint SecOuterPoint(outerPoint.x(), outerPoint.y(), 0); + + // distance between the initial vertex and the inner point of the secondary circle + double s = (SecInnerPoint - InitialVertex).mag(); + double deltaTheta = s / primCircle.rho(); + + double minTangentCondition = 1E12; + TangentCircle theCorrectSecCircle; + GlobalPoint vertex = InitialVertex; + int dir = 1; + double theta = deltaTheta / (NITER - 1); + + for (int i = 0; i < NITER; i++) { + // get the circle which pass through outerPoint, innerPoint and the vertex + TangentCircle secCircle(SecOuterPoint, SecInnerPoint, vertex); + + // get a value relative to the tangentness of the 2 circles + double minCond = isTangent(primCircle, secCircle); + + // double dirDiff = (primCircle.direction(vertex) - secCircle.direction(vertex)).mag(); + // if( dirDiff > 1) dirDiff = 2-dirDiff; + + if (minCond < minTangentCondition) { + minTangentCondition = minCond; + theCorrectSecCircle = secCircle; + vertex = getPosition(primCircle, secCircle.vertexPoint(), theta, dir); + if (i == 0 && ((vertex - SecInnerPoint).mag() > (InitialVertex - SecInnerPoint).mag())) { + dir = -1; + vertex = getPosition(primCircle, InitialVertex, theta, dir); + LogDebug("NuclearSeedGenerator") << "Change direction to look for vertex" + << "\n"; + } + } else + break; + } + theInnerPoint = theCorrectSecCircle.innerPoint(); + theOuterPoint = theCorrectSecCircle.outerPoint(); + theVertexPoint = theCorrectSecCircle.vertexPoint(); + theX0 = theCorrectSecCircle.x0(); + theY0 = theCorrectSecCircle.y0(); + theRho = theCorrectSecCircle.rho(); + theCharge = 0; + theDirectionAtVertex = GlobalVector(1000, 1000, 1000); + + theVertexError = s / NITER; } double TangentCircle::isTangent(const TangentCircle& primCircle, const TangentCircle& secCircle) const { - // return a value that should be equal to 0 if primCircle and secCircle are tangent + // return a value that should be equal to 0 if primCircle and secCircle are tangent - double distanceBetweenCircle = (primCircle.x0() - secCircle.x0())*(primCircle.x0() - secCircle.x0()) - + (primCircle.y0() - secCircle.y0())*(primCircle.y0() - secCircle.y0()); - double RadiusSum = (primCircle.rho() + secCircle.rho())*(primCircle.rho() + secCircle.rho()); - double RadiusDifference = (primCircle.rho() - secCircle.rho())*(primCircle.rho() - secCircle.rho()); + double distanceBetweenCircle = (primCircle.x0() - secCircle.x0()) * (primCircle.x0() - secCircle.x0()) + + (primCircle.y0() - secCircle.y0()) * (primCircle.y0() - secCircle.y0()); + double RadiusSum = (primCircle.rho() + secCircle.rho()) * (primCircle.rho() + secCircle.rho()); + double RadiusDifference = (primCircle.rho() - secCircle.rho()) * (primCircle.rho() - secCircle.rho()); - return std::min( fabs(RadiusSum-distanceBetweenCircle), fabs(RadiusDifference-distanceBetweenCircle) ); + return std::min(fabs(RadiusSum - distanceBetweenCircle), fabs(RadiusDifference - distanceBetweenCircle)); } GlobalVector TangentCircle::direction(const GlobalPoint& point) const { + if (theY0 > 1E9 || theX0 > 1E9) { + LogDebug("NuclearSeedGenerator") << "Center of TangentCircle not calculated but used !!!" + << "\n"; + } - if(theY0 > 1E9 || theX0 > 1E9) { - LogDebug("NuclearSeedGenerator") << "Center of TangentCircle not calculated but used !!!" << "\n"; - } + // calculate the direction perpendicular to the vector v = point - center_of_circle + GlobalVector dir(point.y() - theY0, theX0 - point.x(), 0); - // calculate the direction perpendicular to the vector v = point - center_of_circle - GlobalVector dir(point.y() - theY0, theX0 - point.x(), 0); + dir /= dir.mag(); - dir/=dir.mag(); + // Check the sign : + GlobalVector fastDir = theOuterPoint - theInnerPoint; + double diff = (dir - fastDir).mag(); + double sum = (dir + fastDir).mag(); - // Check the sign : - GlobalVector fastDir = theOuterPoint - theInnerPoint; - double diff = (dir - fastDir).mag(); - double sum = (dir + fastDir).mag(); + if (sum < diff) + dir = (-1) * dir; - if( sum < diff ) dir = (-1)*dir; - - return dir; + return dir; } -GlobalVector TangentCircle::directionAtVertex() { - if(theDirectionAtVertex.x() > 999) - theDirectionAtVertex = direction(theVertexPoint); - return theDirectionAtVertex; +GlobalVector TangentCircle::directionAtVertex() { + if (theDirectionAtVertex.x() > 999) + theDirectionAtVertex = direction(theVertexPoint); + return theDirectionAtVertex; } -GlobalPoint TangentCircle::getPosition(const TangentCircle& circle, const GlobalPoint& initalPosition, double theta, int dir) const { - - int sign[3]; - double x2 = initalPosition.x(); - double y2 = initalPosition.y(); - - if( (x2>circle.x0()) && dir >0) { sign[0] = 1; sign[1] = -1; sign[2] = -1; } - if( (x2>circle.x0()) && dir <0) { sign[0] = 1; sign[1] = 1; sign[2] = 1; } - if( (x20) { sign[0] = -1; sign[1] = 1; sign[2] = -1; } - if( (x2 circle.x0()) && dir > 0) { + sign[0] = 1; + sign[1] = -1; + sign[2] = -1; + } + if ((x2 > circle.x0()) && dir < 0) { + sign[0] = 1; + sign[1] = 1; + sign[2] = 1; + } + if ((x2 < circle.x0()) && dir > 0) { + sign[0] = -1; + sign[1] = 1; + sign[2] = -1; + } + if ((x2 < circle.x0()) && dir < 0) { + sign[0] = -1; + sign[1] = -1; + sign[2] = 1; + } + + double l = 2 * circle.rho() * sin(theta / 2); + double alpha = atan((y2 - circle.y0()) / (x2 - circle.x0())); + double beta = PI / 2 - theta / 2; + double gamma = PI + sign[2] * alpha - beta; + + double xnew = x2 + sign[0] * l * cos(gamma); + double ynew = y2 + sign[1] * l * sin(gamma); + + return GlobalPoint(xnew, ynew, 0); } double TangentCircle::curvatureError() { - if( (theInnerPoint - theVertexPoint).mag() < theVertexError ) { - TangentCircle circle1( directionAtVertex() , theVertexPoint - theVertexError*directionAtVertex(), theOuterPoint); - TangentCircle circle2( directionAtVertex() , theVertexPoint + theVertexError*directionAtVertex(), theOuterPoint); - return fabs(1/circle1.rho() - 1/circle2.rho()); - } - else { - TangentCircle circle1( theOuterPoint, theInnerPoint, theVertexPoint - theVertexError*directionAtVertex()); - TangentCircle circle2( theOuterPoint, theInnerPoint, theVertexPoint + theVertexError*directionAtVertex()); - return fabs(1/circle1.rho() - 1/circle2.rho()); - } + if ((theInnerPoint - theVertexPoint).mag() < theVertexError) { + TangentCircle circle1(directionAtVertex(), theVertexPoint - theVertexError * directionAtVertex(), theOuterPoint); + TangentCircle circle2(directionAtVertex(), theVertexPoint + theVertexError * directionAtVertex(), theOuterPoint); + return fabs(1 / circle1.rho() - 1 / circle2.rho()); + } else { + TangentCircle circle1(theOuterPoint, theInnerPoint, theVertexPoint - theVertexError * directionAtVertex()); + TangentCircle circle2(theOuterPoint, theInnerPoint, theVertexPoint + theVertexError * directionAtVertex()); + return fabs(1 / circle1.rho() - 1 / circle2.rho()); + } } int TangentCircle::charge(float magz) { - - if(theCharge != 0) return theCharge; - - if(theX0 > 1E9 || theY0 > 1E9) theCharge = chargeLocally(magz, directionAtVertex()); - else { - GlobalPoint center(theX0, theY0, 0); - GlobalVector u = center - theVertexPoint; - GlobalVector v = directionAtVertex(); - - // F = force vector - GlobalVector F( v.y() * magz, -v.x() * magz, 0); - if( u.x() * F.x() + u.y() * F.y() > 0) theCharge=-1; - else theCharge=1; - - if(theCharge != chargeLocally(magz, v)) { - LogDebug("NuclearSeedGenerator") << "Inconsistency in calculation of the charge" << "\n"; - } - - } - return theCharge; + if (theCharge != 0) + return theCharge; + + if (theX0 > 1E9 || theY0 > 1E9) + theCharge = chargeLocally(magz, directionAtVertex()); + else { + GlobalPoint center(theX0, theY0, 0); + GlobalVector u = center - theVertexPoint; + GlobalVector v = directionAtVertex(); + + // F = force vector + GlobalVector F(v.y() * magz, -v.x() * magz, 0); + if (u.x() * F.x() + u.y() * F.y() > 0) + theCharge = -1; + else + theCharge = 1; + + if (theCharge != chargeLocally(magz, v)) { + LogDebug("NuclearSeedGenerator") << "Inconsistency in calculation of the charge" + << "\n"; + } + } + return theCharge; } int TangentCircle::chargeLocally(float magz, GlobalVector v) const { - GlobalVector u = theOuterPoint - theVertexPoint; - double tz = v.x() * u.y() - v.y() * u.x() ; + GlobalVector u = theOuterPoint - theVertexPoint; + double tz = v.x() * u.y() - v.y() * u.x(); - if(tz * magz > 0) return 1; else return -1; + if (tz * magz > 0) + return 1; + else + return -1; } diff --git a/RecoTracker/NuclearSeedGenerator/src/TangentHelix.cc b/RecoTracker/NuclearSeedGenerator/src/TangentHelix.cc index 7dd5710635b25..9f61d0a4bc7aa 100644 --- a/RecoTracker/NuclearSeedGenerator/src/TangentHelix.cc +++ b/RecoTracker/NuclearSeedGenerator/src/TangentHelix.cc @@ -1,33 +1,31 @@ #include "RecoTracker/NuclearSeedGenerator/interface/TangentHelix.h" -TangentHelix::TangentHelix(const TangentHelix& primCircle, const GlobalPoint& outerPoint, const GlobalPoint& innerPoint) : - theInnerPoint(innerPoint), theOuterPoint(outerPoint), theCircle(primCircle.circle(), outerPoint, innerPoint) { - - // Calculation of vertex.z : - GlobalPoint inner_T( innerPoint.x() , innerPoint.y() , 0.0 ); - GlobalPoint outer_T( outerPoint.x() , outerPoint.y() , 0.0 ); - GlobalPoint vtx_T( theCircle.vertexPoint().x() , theCircle.vertexPoint().y() , 0.0 ); - - double d1 = (inner_T - vtx_T).mag(); - double d = (inner_T - outer_T).mag(); - - theVertexPoint = GlobalPoint(vtx_T.x() , vtx_T.y(), innerPoint.z() - (outerPoint.z() - innerPoint.z()) * d1 / d ); - theDirectionAtVertex = GlobalVector(1000, 1000, 1000); +TangentHelix::TangentHelix(const TangentHelix& primCircle, const GlobalPoint& outerPoint, const GlobalPoint& innerPoint) + : theInnerPoint(innerPoint), theOuterPoint(outerPoint), theCircle(primCircle.circle(), outerPoint, innerPoint) { + // Calculation of vertex.z : + GlobalPoint inner_T(innerPoint.x(), innerPoint.y(), 0.0); + GlobalPoint outer_T(outerPoint.x(), outerPoint.y(), 0.0); + GlobalPoint vtx_T(theCircle.vertexPoint().x(), theCircle.vertexPoint().y(), 0.0); + + double d1 = (inner_T - vtx_T).mag(); + double d = (inner_T - outer_T).mag(); + + theVertexPoint = GlobalPoint(vtx_T.x(), vtx_T.y(), innerPoint.z() - (outerPoint.z() - innerPoint.z()) * d1 / d); + theDirectionAtVertex = GlobalVector(1000, 1000, 1000); } GlobalVector TangentHelix::directionAtVertex() { + if (theDirectionAtVertex.z() > 999) { + GlobalPoint inner_T(theInnerPoint.x(), theInnerPoint.y(), 0.0); + GlobalPoint outer_T(theOuterPoint.x(), theOuterPoint.y(), 0.0); + double p_z = (theOuterPoint.z() - theInnerPoint.z()) / (outer_T - inner_T).mag(); - if(theDirectionAtVertex.z() > 999) { - GlobalPoint inner_T( theInnerPoint.x() , theInnerPoint.y() , 0.0 ); - GlobalPoint outer_T( theOuterPoint.x() , theOuterPoint.y() , 0.0 ); - double p_z = (theOuterPoint.z() - theInnerPoint.z()) / (outer_T - inner_T).mag(); - - GlobalVector dir_T = theCircle.directionAtVertex(); - GlobalVector dir( dir_T.x(), dir_T.y(), p_z); + GlobalVector dir_T = theCircle.directionAtVertex(); + GlobalVector dir(dir_T.x(), dir_T.y(), p_z); - dir/=dir.mag(); - theDirectionAtVertex = dir; - } + dir /= dir.mag(); + theDirectionAtVertex = dir; + } - return theDirectionAtVertex; + return theDirectionAtVertex; } diff --git a/RecoVertex/VertexTools/interface/AbstractLTSFactory.h b/RecoVertex/VertexTools/interface/AbstractLTSFactory.h index 4a5e547a88cb5..f5fd06ca8c35c 100644 --- a/RecoVertex/VertexTools/interface/AbstractLTSFactory.h +++ b/RecoVertex/VertexTools/interface/AbstractLTSFactory.h @@ -4,29 +4,25 @@ #include "RecoVertex/VertexPrimitives/interface/LinearizedTrackState.h" #include "TrackingTools/TransientTrack/interface/TransientTrack.h" - /** * Abstract class that defines an LinearzedTrackStateFactory */ template class AbstractLTSFactory { - public: - typedef ReferenceCountingPointer > RefCountedLinearizedTrackState; - - virtual RefCountedLinearizedTrackState - linearizedTrackState(const GlobalPoint & linP, const reco::TransientTrack & track) const = 0; - virtual RefCountedLinearizedTrackState - linearizedTrackState(const GlobalPoint & linP, const reco::TransientTrack & track, - const TrajectoryStateOnSurface& tsos) const = 0; + virtual RefCountedLinearizedTrackState linearizedTrackState(const GlobalPoint& linP, + const reco::TransientTrack& track) const = 0; - virtual ~AbstractLTSFactory() {}; + virtual RefCountedLinearizedTrackState linearizedTrackState(const GlobalPoint& linP, + const reco::TransientTrack& track, + const TrajectoryStateOnSurface& tsos) const = 0; - virtual const AbstractLTSFactory * clone() const = 0; + virtual ~AbstractLTSFactory(){}; + virtual const AbstractLTSFactory* clone() const = 0; }; #endif diff --git a/RecoVertex/VertexTools/interface/AnnealingSchedule.h b/RecoVertex/VertexTools/interface/AnnealingSchedule.h index 56dff79c2633e..8ac392a048a79 100644 --- a/RecoVertex/VertexTools/interface/AnnealingSchedule.h +++ b/RecoVertex/VertexTools/interface/AnnealingSchedule.h @@ -8,20 +8,19 @@ class AnnealingSchedule { * annealing schedules. */ public: - - virtual ~AnnealingSchedule() {}; - virtual void anneal() = 0; //< One annealing step. + virtual ~AnnealingSchedule(){}; + virtual void anneal() = 0; //< One annealing step. virtual void resetAnnealing() = 0; /** * phi ( chi2 ) = e^( -.5*chi2 / T ) */ - virtual double phi ( double chi2 ) const = 0; + virtual double phi(double chi2) const = 0; /** * Returns phi(chi2) / ( phi(cutoff^2) + phi(chi2) ), */ - virtual double weight ( double chi2 ) const = 0; + virtual double weight(double chi2) const = 0; /** * Returns phi(chi2) / ( phi(cutoff^2) + sum_i { phi(chi2s[i]) } ) @@ -39,7 +38,7 @@ class AnnealingSchedule { virtual void debug() const = 0; - virtual AnnealingSchedule * clone() const = 0; + virtual AnnealingSchedule* clone() const = 0; }; #endif diff --git a/RecoVertex/VertexTools/interface/DeterministicAnnealing.h b/RecoVertex/VertexTools/interface/DeterministicAnnealing.h index 8044fc24bb851..70970a853386f 100644 --- a/RecoVertex/VertexTools/interface/DeterministicAnnealing.h +++ b/RecoVertex/VertexTools/interface/DeterministicAnnealing.h @@ -5,9 +5,7 @@ #include class DeterministicAnnealing : public AnnealingSchedule { - public: - /** * \class DeterministicAnnealing. * A very simple class that returns the association probabilty of a (any) @@ -15,22 +13,22 @@ class DeterministicAnnealing : public AnnealingSchedule { * Note that cutoff is given "sigma-like", i.e. as a sqrt ( chi2 )!! */ - DeterministicAnnealing( float cutoff = 3.0 ); - DeterministicAnnealing( const std::vector < float > & sched, float cutoff = 3.0 ); + DeterministicAnnealing(float cutoff = 3.0); + DeterministicAnnealing(const std::vector& sched, float cutoff = 3.0); - void anneal() override; //< One annealing step. theT *= theRatio. - void resetAnnealing() override; //< theT = theT0. + void anneal() override; //< One annealing step. theT *= theRatio. + void resetAnnealing() override; //< theT = theT0. /** * phi ( chi2 ) = e^( -.5*chi2 / T ) */ - double phi ( double chi2 ) const override; + double phi(double chi2) const override; /** * Returns phi(chi2) / ( phi(cutoff^2) + phi(chi2) ), */ - double weight ( double chi2 ) const override; - + double weight(double chi2) const override; + /** * is it annealed yet? */ @@ -43,15 +41,11 @@ class DeterministicAnnealing : public AnnealingSchedule { */ // double weight ( double chi2, const vector < double > & chi2s ) const; - double cutoff() const override; double currentTemp() const override; double initialTemp() const override; - DeterministicAnnealing * clone() const override - { - return new DeterministicAnnealing ( * this ); - }; + DeterministicAnnealing* clone() const override { return new DeterministicAnnealing(*this); }; private: std::vector theTemperatures; diff --git a/RecoVertex/VertexTools/interface/DummyTrackToTrackCovCalculator.h b/RecoVertex/VertexTools/interface/DummyTrackToTrackCovCalculator.h index 620b2be3f93d7..384e8e09c7ff3 100644 --- a/RecoVertex/VertexTools/interface/DummyTrackToTrackCovCalculator.h +++ b/RecoVertex/VertexTools/interface/DummyTrackToTrackCovCalculator.h @@ -10,12 +10,9 @@ template class DummyTrackToTrackCovCalculator : public TrackToTrackCovCalculator { - public: - - typename CachingVertex::TrackToTrackMap operator() (const CachingVertex &) const override; - DummyTrackToTrackCovCalculator * clone() const override; - + typename CachingVertex::TrackToTrackMap operator()(const CachingVertex &) const override; + DummyTrackToTrackCovCalculator *clone() const override; }; #endif diff --git a/RecoVertex/VertexTools/interface/DummyVertexSmoother.h b/RecoVertex/VertexTools/interface/DummyVertexSmoother.h index c742f4ac98813..f6fb25e6aca26 100644 --- a/RecoVertex/VertexTools/interface/DummyVertexSmoother.h +++ b/RecoVertex/VertexTools/interface/DummyVertexSmoother.h @@ -10,8 +10,8 @@ template class DummyVertexSmoother : public VertexSmoother { public: - CachingVertex smooth(const CachingVertex & ) const override; - DummyVertexSmoother * clone() const override; + CachingVertex smooth(const CachingVertex&) const override; + DummyVertexSmoother* clone() const override; }; #endif diff --git a/RecoVertex/VertexTools/interface/DummyVertexTrackUpdator.h b/RecoVertex/VertexTools/interface/DummyVertexTrackUpdator.h index 216af36c6b6b9..d02db6029676b 100644 --- a/RecoVertex/VertexTools/interface/DummyVertexTrackUpdator.h +++ b/RecoVertex/VertexTools/interface/DummyVertexTrackUpdator.h @@ -10,17 +10,13 @@ template class DummyVertexTrackUpdator : public VertexTrackUpdator { - public: - /** * Computes the constrained track parameters */ - typename CachingVertex::RefCountedVertexTrack - update(const CachingVertex & v, - typename CachingVertex::RefCountedVertexTrack t) const override; - DummyVertexTrackUpdator * clone() const override; - + typename CachingVertex::RefCountedVertexTrack update( + const CachingVertex& v, typename CachingVertex::RefCountedVertexTrack t) const override; + DummyVertexTrackUpdator* clone() const override; }; #endif diff --git a/RecoVertex/VertexTools/interface/FsmwModeFinder3d.h b/RecoVertex/VertexTools/interface/FsmwModeFinder3d.h index a763428d8dbac..d029e638387d5 100644 --- a/RecoVertex/VertexTools/interface/FsmwModeFinder3d.h +++ b/RecoVertex/VertexTools/interface/FsmwModeFinder3d.h @@ -9,10 +9,9 @@ * this is a half sample mode finder that works * coordinate wise, in 3d. */ -class FsmwModeFinder3d : public ModeFinder3d -{ +class FsmwModeFinder3d : public ModeFinder3d { public: - /** + /** * Constructor * \param fraction the fraction of data points that have to be * within the interval. @@ -24,15 +23,18 @@ class FsmwModeFinder3d : public ModeFinder3d * \param no_weights_above * ignore weights as long as the number of data points is > x */ - FsmwModeFinder3d( float fraction = .5, float weightExponent = -2., - float cutoff=10 /* microns */, int no_weights_above = 10 ); - GlobalPoint operator()( const std::vector< PointAndDistance> & ) const override; - FsmwModeFinder3d* clone() const override; + FsmwModeFinder3d(float fraction = .5, + float weightExponent = -2., + float cutoff = 10 /* microns */, + int no_weights_above = 10); + GlobalPoint operator()(const std::vector&) const override; + FsmwModeFinder3d* clone() const override; + private: - float theFraction; - float theWeightExponent; - float theCutoff; - int theNoWeightsAbove; + float theFraction; + float theWeightExponent; + float theCutoff; + int theNoWeightsAbove; }; #endif diff --git a/RecoVertex/VertexTools/interface/GeometricAnnealing.h b/RecoVertex/VertexTools/interface/GeometricAnnealing.h index ddda655ceff24..da476af7b427c 100644 --- a/RecoVertex/VertexTools/interface/GeometricAnnealing.h +++ b/RecoVertex/VertexTools/interface/GeometricAnnealing.h @@ -5,9 +5,7 @@ #include class GeometricAnnealing : public AnnealingSchedule { - public: - /** * \class GeometricAnnealing. * A very simple class that returns the association probabilty of a (any) @@ -15,21 +13,20 @@ class GeometricAnnealing : public AnnealingSchedule { * annealing ratio ( geometric annealing ). */ - GeometricAnnealing( const double cutoff=3.0, const double T=256.0, - const double annealing_ratio=0.25 ); + GeometricAnnealing(const double cutoff = 3.0, const double T = 256.0, const double annealing_ratio = 0.25); - void anneal() override; //< One annealing step. theT *= theRatio. - void resetAnnealing() override; //< theT = theT0. + void anneal() override; //< One annealing step. theT *= theRatio. + void resetAnnealing() override; //< theT = theT0. /** * phi ( chi2 ) = e^( -.5 * chi2 / T ) */ - double phi ( double chi2 ) const override; + double phi(double chi2) const override; /** * Returns phi(chi2) / ( phi(cutoff^2) + phi(chi2) ), */ - double weight ( double chi2 ) const override; + double weight(double chi2) const override; double cutoff() const override; double currentTemp() const override; @@ -42,17 +39,13 @@ class GeometricAnnealing : public AnnealingSchedule { void debug() const override; - GeometricAnnealing * clone() const override - { - return new GeometricAnnealing ( * this ); - }; + GeometricAnnealing* clone() const override { return new GeometricAnnealing(*this); }; private: double theT0; double theT; double theChi2cut; double theRatio; - }; #endif diff --git a/RecoVertex/VertexTools/interface/HsmModeFinder3d.h b/RecoVertex/VertexTools/interface/HsmModeFinder3d.h index 35d3315c670cb..d304be16e9b47 100644 --- a/RecoVertex/VertexTools/interface/HsmModeFinder3d.h +++ b/RecoVertex/VertexTools/interface/HsmModeFinder3d.h @@ -11,8 +11,8 @@ */ class HsmModeFinder3d : public ModeFinder3d { public: - GlobalPoint operator () ( const std::vector< PointAndDistance> & ) const override; - HsmModeFinder3d * clone() const override; + GlobalPoint operator()(const std::vector&) const override; + HsmModeFinder3d* clone() const override; }; #endif diff --git a/RecoVertex/VertexTools/interface/InvariantMassFromVertex.h b/RecoVertex/VertexTools/interface/InvariantMassFromVertex.h index 7ea58249e45dc..270c76b3031e3 100644 --- a/RecoVertex/VertexTools/interface/InvariantMassFromVertex.h +++ b/RecoVertex/VertexTools/interface/InvariantMassFromVertex.h @@ -17,40 +17,32 @@ * tree out of the information provided * by KinematicParticleVertexFitter. */ -class InvariantMassFromVertex{ - +class InvariantMassFromVertex { public: typedef ROOT::Math::PxPyPzMVector LorentzVector; - Measurement1D invariantMass(const CachingVertex<5>& vertex, - const std::vector & masses) const; + Measurement1D invariantMass(const CachingVertex<5>& vertex, const std::vector& masses) const; - Measurement1D invariantMass(const CachingVertex<5>& vertex, - const double mass) const; + Measurement1D invariantMass(const CachingVertex<5>& vertex, const double mass) const; /** * four-momentum Lorentz vector */ - LorentzVector p4 (const CachingVertex<5>& vertex, - const std::vector & masses) const; + LorentzVector p4(const CachingVertex<5>& vertex, const std::vector& masses) const; /** * four-momentum Lorentz vector */ - LorentzVector p4 (const CachingVertex<5>& vertex, - const double mass) const; + LorentzVector p4(const CachingVertex<5>& vertex, const double mass) const; GlobalVector momentum(const CachingVertex<5>& vertex) const; - private: + typedef ReferenceCountingPointer > RefCountedVertexTrack; + typedef ReferenceCountingPointer > RefCountedLinearizedTrackState; + typedef ReferenceCountingPointer > RefCountedRefittedTrackState; - typedef ReferenceCountingPointer > RefCountedVertexTrack; - typedef ReferenceCountingPointer > RefCountedLinearizedTrackState; - typedef ReferenceCountingPointer > RefCountedRefittedTrackState; - - double uncertainty(const LorentzVector & p4, const CachingVertex<5>& vertex, - const std::vector & masses) const; + double uncertainty(const LorentzVector& p4, const CachingVertex<5>& vertex, const std::vector& masses) const; }; #endif diff --git a/RecoVertex/VertexTools/interface/LinearizationPointFinder.h b/RecoVertex/VertexTools/interface/LinearizationPointFinder.h index 0bc57543e4c69..f87217abe1765 100644 --- a/RecoVertex/VertexTools/interface/LinearizationPointFinder.h +++ b/RecoVertex/VertexTools/interface/LinearizationPointFinder.h @@ -9,8 +9,7 @@ class FreeTrajectoryState; /** Generic class to make an Initial Linearization point */ -class LinearizationPointFinder{ - +class LinearizationPointFinder { public: virtual ~LinearizationPointFinder() {} @@ -18,16 +17,14 @@ class LinearizationPointFinder{ * as an object of type GlobalPoint */ - virtual GlobalPoint getLinearizationPoint(const std::vector &) - const=0; + virtual GlobalPoint getLinearizationPoint(const std::vector &) const = 0; virtual GlobalPoint getLinearizationPoint(const std::vector &) const; /** * Clone method */ - virtual LinearizationPointFinder * clone() const=0; - + virtual LinearizationPointFinder *clone() const = 0; }; #endif diff --git a/RecoVertex/VertexTools/interface/LinearizedTrackStateFactory.h b/RecoVertex/VertexTools/interface/LinearizedTrackStateFactory.h index e33014024d3a8..aff6f6fd9a065 100644 --- a/RecoVertex/VertexTools/interface/LinearizedTrackStateFactory.h +++ b/RecoVertex/VertexTools/interface/LinearizedTrackStateFactory.h @@ -12,24 +12,20 @@ */ class LinearizedTrackStateFactory : public AbstractLTSFactory<5> { - public: + RefCountedLinearizedTrackState linearizedTrackState(const GlobalPoint& linP, + const reco::TransientTrack& track) const override; - RefCountedLinearizedTrackState - linearizedTrackState(const GlobalPoint & linP, const reco::TransientTrack & track) const override; - - RefCountedLinearizedTrackState - linearizedTrackState(const GlobalPoint & linP, const reco::TransientTrack & track, - const TrajectoryStateOnSurface& tsos) const override; - - RefCountedLinearizedTrackState - linearizedTrackState(LinearizedTrackState<5> * lts) const; + RefCountedLinearizedTrackState linearizedTrackState(const GlobalPoint& linP, + const reco::TransientTrack& track, + const TrajectoryStateOnSurface& tsos) const override; - const LinearizedTrackStateFactory * clone() const override; + RefCountedLinearizedTrackState linearizedTrackState(LinearizedTrackState<5>* lts) const; -// RefCountedLinearizedTrackState -// linearizedTrackState(const GlobalPoint & linP, RefCountedKinematicParticle & prt) const; + const LinearizedTrackStateFactory* clone() const override; + // RefCountedLinearizedTrackState + // linearizedTrackState(const GlobalPoint & linP, RefCountedKinematicParticle & prt) const; }; #endif diff --git a/RecoVertex/VertexTools/interface/Lms3d.h b/RecoVertex/VertexTools/interface/Lms3d.h index 273bfc9196d1b..0976e9a61e789 100644 --- a/RecoVertex/VertexTools/interface/Lms3d.h +++ b/RecoVertex/VertexTools/interface/Lms3d.h @@ -11,7 +11,7 @@ */ class Lms3d : public ModeFinder3d { public: - virtual GlobalPoint operator () ( std::vector & values ) const; + virtual GlobalPoint operator()(std::vector& values) const; }; #endif diff --git a/RecoVertex/VertexTools/interface/LmsModeFinder3d.h b/RecoVertex/VertexTools/interface/LmsModeFinder3d.h index 219a39388f2af..7ea5f4e56cbc5 100644 --- a/RecoVertex/VertexTools/interface/LmsModeFinder3d.h +++ b/RecoVertex/VertexTools/interface/LmsModeFinder3d.h @@ -7,8 +7,8 @@ */ class LmsModeFinder3d : public ModeFinder3d { public: - GlobalPoint operator () ( const std::vector< PointAndDistance> & values ) const override; - LmsModeFinder3d * clone() const override; + GlobalPoint operator()(const std::vector& values) const override; + LmsModeFinder3d* clone() const override; }; #endif diff --git a/RecoVertex/VertexTools/interface/ModeFinder3d.h b/RecoVertex/VertexTools/interface/ModeFinder3d.h index 4cb85f5885ac3..107e7518f1005 100644 --- a/RecoVertex/VertexTools/interface/ModeFinder3d.h +++ b/RecoVertex/VertexTools/interface/ModeFinder3d.h @@ -13,11 +13,11 @@ class ModeFinder3d { public: - typedef std::pair < GlobalPoint, float > PointAndDistance; - virtual GlobalPoint operator () ( const std::vector< PointAndDistance > & ) const=0; + typedef std::pair PointAndDistance; + virtual GlobalPoint operator()(const std::vector&) const = 0; - virtual ~ModeFinder3d() {}; - virtual ModeFinder3d * clone () const =0; + virtual ~ModeFinder3d(){}; + virtual ModeFinder3d* clone() const = 0; }; #endif diff --git a/RecoVertex/VertexTools/interface/PerigeeLinearizedTrackState.h b/RecoVertex/VertexTools/interface/PerigeeLinearizedTrackState.h index 96400b5c77098..60f90b1ca2109 100644 --- a/RecoVertex/VertexTools/interface/PerigeeLinearizedTrackState.h +++ b/RecoVertex/VertexTools/interface/PerigeeLinearizedTrackState.h @@ -10,7 +10,6 @@ #include "FWCore/Utilities/interface/GCC11Compatibility.h" - /** Calculates and stores the ImpactPointMeasurement of the * impact point (point of closest approach in 3D) to the * given linearization point. @@ -33,10 +32,7 @@ */ class PerigeeLinearizedTrackState final : public LinearizedTrackState<5> { - - public: - /** Friend class properly dealing with creation * of reference-counted pointers to LinearizedTrack objects */ @@ -47,14 +43,12 @@ class PerigeeLinearizedTrackState final : public LinearizedTrackState<5> { * Returns a new linearized state with respect to a new linearization point. * A new object of the same type is returned, without change to the existing one. */ - RefCountedLinearizedTrackState stateWithNewLinearizationPoint - (const GlobalPoint & newLP) const override; - + RefCountedLinearizedTrackState stateWithNewLinearizationPoint(const GlobalPoint& newLP) const override; /** * The point at which the track state has been linearized */ - const GlobalPoint & linearizationPoint() const override { return theLinPoint; } + const GlobalPoint& linearizationPoint() const override { return theLinPoint; } reco::TransientTrack track() const override { return theTrack; } @@ -63,27 +57,27 @@ class PerigeeLinearizedTrackState final : public LinearizedTrackState<5> { /** Method returning the constant term of the Taylor expansion * of the measurement equation */ - const AlgebraicVector5 & constantTerm() const override; + const AlgebraicVector5& constantTerm() const override; /** Method returning the Position Jacobian from the Taylor expansion * (Matrix A) */ - const AlgebraicMatrix53 & positionJacobian() const override; + const AlgebraicMatrix53& positionJacobian() const override; /** Method returning the Momentum Jacobian from the Taylor expansion * (Matrix B) */ - const AlgebraicMatrix53 & momentumJacobian() const override; + const AlgebraicMatrix53& momentumJacobian() const override; /** Method returning the parameters of the Taylor expansion */ - const AlgebraicVector5 & parametersFromExpansion() const override; + const AlgebraicVector5& parametersFromExpansion() const override; /** Method returning the track state at the point of closest approach * to the linearization point, in the transverse plane (a.k.a. * transverse impact point). */ - const TrajectoryStateClosestToPoint & predictedState() const; + const TrajectoryStateClosestToPoint& predictedState() const; /** Method returning the parameters of the track state at the * transverse impact point. @@ -99,7 +93,7 @@ class PerigeeLinearizedTrackState final : public LinearizedTrackState<5> { * transverse impact point. * The error variable is 0 in case of success. */ - AlgebraicSymMatrix55 predictedStateWeight(int & error) const override; + AlgebraicSymMatrix55 predictedStateWeight(int& error) const override; /** Method returning the covariance matrix of the track state at the * transverse impact point. @@ -111,47 +105,43 @@ class PerigeeLinearizedTrackState final : public LinearizedTrackState<5> { */ AlgebraicSymMatrix33 predictedStateMomentumError() const override; -// /** Method returning the impact point measurement -// */ -// ImpactPointMeasurement impactPointMeasurement() const; + // /** Method returning the impact point measurement + // */ + // ImpactPointMeasurement impactPointMeasurement() const; - TrackCharge charge() const override {return theCharge;} + TrackCharge charge() const override { return theCharge; } bool hasError() const override; - bool operator ==(LinearizedTrackState<5> & other)const override; + bool operator==(LinearizedTrackState<5>& other) const override; - bool operator ==(ReferenceCountingPointer >& other)const; + bool operator==(ReferenceCountingPointer >& other) const; /** Creates the correct refitted state according to the results of the * track refit. */ - RefCountedRefittedTrackState createRefittedTrackState( - const GlobalPoint & vertexPosition, - const AlgebraicVector3 & vectorParameters, - const AlgebraicSymMatrix66 & covarianceMatrix) const override; + RefCountedRefittedTrackState createRefittedTrackState(const GlobalPoint& vertexPosition, + const AlgebraicVector3& vectorParameters, + const AlgebraicSymMatrix66& covarianceMatrix) const override; + AlgebraicVector5 refittedParamFromEquation(const RefCountedRefittedTrackState& theRefittedState) const override; - AlgebraicVector5 refittedParamFromEquation( - const RefCountedRefittedTrackState & theRefittedState) const override; + double weightInMixture() const override { return theTSOS.weight(); } - double weightInMixture() const override {return theTSOS.weight();} - - void inline checkParameters(AlgebraicVector5 & parameters) const override; + void inline checkParameters(AlgebraicVector5& parameters) const override; std::vector > > components() const override; bool isValid() const override; private: - /** Constructor with the linearization point and the track. * Private, can only be used by LinearizedTrackFactory. */ - PerigeeLinearizedTrackState(const GlobalPoint & linP, const reco::TransientTrack & track, - const TrajectoryStateOnSurface& tsos) - : theLinPoint(linP), theTrack(track), - theTSOS(tsos), theCharge(theTrack.charge()), jacobiansAvailable(false) {} + PerigeeLinearizedTrackState(const GlobalPoint& linP, + const reco::TransientTrack& track, + const TrajectoryStateOnSurface& tsos) + : theLinPoint(linP), theTrack(track), theTSOS(tsos), theCharge(theTrack.charge()), jacobiansAvailable(false) {} /** Method calculating the track parameters and the Jacobians. */ @@ -179,119 +169,100 @@ class PerigeeLinearizedTrackState final : public LinearizedTrackState<5> { TrackCharge theCharge; mutable bool jacobiansAvailable; - }; - - - /** Method returning the constant term of the Taylor expansion * of the measurement equation */ -inline -const AlgebraicVector5 & PerigeeLinearizedTrackState::constantTerm() const -{ - if UNLIKELY(!jacobiansAvailable) computeJacobians(); +inline const AlgebraicVector5& PerigeeLinearizedTrackState::constantTerm() const { + if + UNLIKELY(!jacobiansAvailable) computeJacobians(); return theConstantTerm; } /** * Method returning the Position Jacobian (Matrix A) */ -inline -const AlgebraicMatrix53 & PerigeeLinearizedTrackState::positionJacobian() const -{ - if UNLIKELY(!jacobiansAvailable) computeJacobians(); +inline const AlgebraicMatrix53& PerigeeLinearizedTrackState::positionJacobian() const { + if + UNLIKELY(!jacobiansAvailable) computeJacobians(); return thePositionJacobian; } /** * Method returning the Momentum Jacobian (Matrix B) */ -inline -const AlgebraicMatrix53 & PerigeeLinearizedTrackState::momentumJacobian() const -{ - if UNLIKELY(!jacobiansAvailable) computeJacobians(); +inline const AlgebraicMatrix53& PerigeeLinearizedTrackState::momentumJacobian() const { + if + UNLIKELY(!jacobiansAvailable) computeJacobians(); return theMomentumJacobian; } /** Method returning the parameters of the Taylor expansion */ -inline -const AlgebraicVector5 & PerigeeLinearizedTrackState::parametersFromExpansion() const -{ - if UNLIKELY(!jacobiansAvailable) computeJacobians(); +inline const AlgebraicVector5& PerigeeLinearizedTrackState::parametersFromExpansion() const { + if + UNLIKELY(!jacobiansAvailable) computeJacobians(); return theExpandedParams; } /** * Method returning the TrajectoryStateClosestToPoint at the point * of closest approch to the z-axis (a.k.a. transverse impact point) - */ -inline -const TrajectoryStateClosestToPoint & PerigeeLinearizedTrackState::predictedState() const -{ - if UNLIKELY(!jacobiansAvailable) computeJacobians(); + */ +inline const TrajectoryStateClosestToPoint& PerigeeLinearizedTrackState::predictedState() const { + if + UNLIKELY(!jacobiansAvailable) computeJacobians(); return thePredState; } - -inline -bool PerigeeLinearizedTrackState::hasError() const -{ - if UNLIKELY(!jacobiansAvailable) computeJacobians(); +inline bool PerigeeLinearizedTrackState::hasError() const { + if + UNLIKELY(!jacobiansAvailable) computeJacobians(); return thePredState.hasError(); } -inline -AlgebraicVector5 PerigeeLinearizedTrackState::predictedStateParameters() const -{ - if (!jacobiansAvailable) computeJacobians(); +inline AlgebraicVector5 PerigeeLinearizedTrackState::predictedStateParameters() const { + if (!jacobiansAvailable) + computeJacobians(); return thePredState.perigeeParameters().vector(); } - -inline -AlgebraicVector3 PerigeeLinearizedTrackState::predictedStateMomentumParameters() const -{ - if UNLIKELY(!jacobiansAvailable) computeJacobians(); - auto v= thePredState.perigeeParameters().vector(); - return AlgebraicVector3(v[0],v[1],v[2]); +inline AlgebraicVector3 PerigeeLinearizedTrackState::predictedStateMomentumParameters() const { + if + UNLIKELY(!jacobiansAvailable) computeJacobians(); + auto v = thePredState.perigeeParameters().vector(); + return AlgebraicVector3(v[0], v[1], v[2]); } - -inline -AlgebraicSymMatrix55 PerigeeLinearizedTrackState::predictedStateWeight(int & error) const -{ - if UNLIKELY(!jacobiansAvailable) computeJacobians(); + +inline AlgebraicSymMatrix55 PerigeeLinearizedTrackState::predictedStateWeight(int& error) const { + if + UNLIKELY(!jacobiansAvailable) computeJacobians(); if (!thePredState.isValid()) { error = 1; return AlgebraicSymMatrix55(); } return thePredState.perigeeError().weightMatrix(error); } - -inline -AlgebraicSymMatrix55 PerigeeLinearizedTrackState::predictedStateError() const -{ - if UNLIKELY(!jacobiansAvailable) computeJacobians(); + +inline AlgebraicSymMatrix55 PerigeeLinearizedTrackState::predictedStateError() const { + if + UNLIKELY(!jacobiansAvailable) computeJacobians(); return thePredState.perigeeError().covarianceMatrix(); -} - -inline -AlgebraicSymMatrix33 PerigeeLinearizedTrackState::predictedStateMomentumError() const -{ - if UNLIKELY(!jacobiansAvailable) computeJacobians(); - return thePredState.perigeeError().covarianceMatrix().Sub(0,2); -} - -inline -bool PerigeeLinearizedTrackState::isValid() const -{ - if UNLIKELY(!theTSOS.isValid()) return false; - if UNLIKELY(!jacobiansAvailable) computeJacobians(); - return jacobiansAvailable; } +inline AlgebraicSymMatrix33 PerigeeLinearizedTrackState::predictedStateMomentumError() const { + if + UNLIKELY(!jacobiansAvailable) computeJacobians(); + return thePredState.perigeeError().covarianceMatrix().Sub(0, 2); +} +inline bool PerigeeLinearizedTrackState::isValid() const { + if + UNLIKELY(!theTSOS.isValid()) return false; + if + UNLIKELY(!jacobiansAvailable) computeJacobians(); + return jacobiansAvailable; +} #endif diff --git a/RecoVertex/VertexTools/interface/PerigeeRefittedTrackState.h b/RecoVertex/VertexTools/interface/PerigeeRefittedTrackState.h index 973cec1b7c689..ecc01c7b1d323 100644 --- a/RecoVertex/VertexTools/interface/PerigeeRefittedTrackState.h +++ b/RecoVertex/VertexTools/interface/PerigeeRefittedTrackState.h @@ -16,37 +16,33 @@ class Surface; class Propagator; class PerigeeRefittedTrackState : public RefittedTrackState<5> { - public: - typedef ReferenceCountingPointer > RefCountedRefittedTrackState; - PerigeeRefittedTrackState(const TrajectoryStateClosestToPoint & tscp, - const AlgebraicVector3 & aMomentumAtVertex, - const double aWeight = 1.) : - theState(tscp), momentumAtVertex(aMomentumAtVertex), theWeight(aWeight) {} + PerigeeRefittedTrackState(const TrajectoryStateClosestToPoint& tscp, + const AlgebraicVector3& aMomentumAtVertex, + const double aWeight = 1.) + : theState(tscp), momentumAtVertex(aMomentumAtVertex), theWeight(aWeight) {} - ~PerigeeRefittedTrackState() override{} + ~PerigeeRefittedTrackState() override {} /** * Transformation into a FreeTrajectoryState */ - FreeTrajectoryState freeTrajectoryState() const override - {return theState.theState();} + FreeTrajectoryState freeTrajectoryState() const override { return theState.theState(); } /** * Transformation into a TSOS at a given surface */ - TrajectoryStateOnSurface trajectoryStateOnSurface( - const Surface & surface) const override; + TrajectoryStateOnSurface trajectoryStateOnSurface(const Surface& surface) const override; /** * Transformation into a TSOS at a given surface, with a given propagator */ - TrajectoryStateOnSurface trajectoryStateOnSurface( - const Surface & surface, const Propagator & propagator) const override; + TrajectoryStateOnSurface trajectoryStateOnSurface(const Surface& surface, + const Propagator& propagator) const override; /** * Vector containing the refitted track parameters.
@@ -54,22 +50,19 @@ class PerigeeRefittedTrackState : public RefittedTrackState<5> { * (signed) transverse , longitudinal impact parameter) */ - AlgebraicVector5 parameters() const override - {return theState.perigeeParameters().vector();} + AlgebraicVector5 parameters() const override { return theState.perigeeParameters().vector(); } /** * The covariance matrix */ - AlgebraicSymMatrix55 covariance() const override - {return theState.perigeeError().covarianceMatrix();} + AlgebraicSymMatrix55 covariance() const override { return theState.perigeeError().covarianceMatrix(); } /** * Position at which the momentum is defined. */ - GlobalPoint position() const override - {return theState.referencePoint();} + GlobalPoint position() const override { return theState.referencePoint(); } /** * Vector containing the parameters describing the momentum as the vertex. @@ -81,21 +74,19 @@ class PerigeeRefittedTrackState : public RefittedTrackState<5> { /** * The weight of this component in a mixture */ - double weight() const override {return theWeight;} + double weight() const override { return theWeight; } /** * Returns a new refitted state of the same type, but with another weight. * The current state is unchanged. */ - ReferenceCountingPointer > stateWithNewWeight - (const double newWeight) const override; + ReferenceCountingPointer > stateWithNewWeight(const double newWeight) const override; std::vector > > components() const override; reco::TransientTrack transientTrack() const override; private: - TrajectoryStateClosestToPoint theState; AlgebraicVector3 momentumAtVertex; double theWeight; diff --git a/RecoVertex/VertexTools/interface/RecTracksDistanceMatrix.h b/RecoVertex/VertexTools/interface/RecTracksDistanceMatrix.h index 764baabbddf5b..671a14bdb853c 100644 --- a/RecoVertex/VertexTools/interface/RecTracksDistanceMatrix.h +++ b/RecoVertex/VertexTools/interface/RecTracksDistanceMatrix.h @@ -14,24 +14,24 @@ * stored, as well. */ -class RecTracksDistanceMatrix { // : public ReferenceCounted { +class RecTracksDistanceMatrix { // : public ReferenceCounted { public: - virtual const std::vector < reco::TransientTrack > * tracks() const = 0; - virtual ~RecTracksDistanceMatrix() {}; + virtual const std::vector* tracks() const = 0; + virtual ~RecTracksDistanceMatrix(){}; - virtual double distance ( const reco::TransientTrack , const reco::TransientTrack ) const = 0; - virtual double weightedDistance ( const reco::TransientTrack , const reco::TransientTrack ) const = 0; + virtual double distance(const reco::TransientTrack, const reco::TransientTrack) const = 0; + virtual double weightedDistance(const reco::TransientTrack, const reco::TransientTrack) const = 0; - virtual GlobalPoint crossingPoint ( const reco::TransientTrack , const reco::TransientTrack ) const = 0; + virtual GlobalPoint crossingPoint(const reco::TransientTrack, const reco::TransientTrack) const = 0; - virtual std::pair < GlobalPoint, GlobalPoint > pointsOfClosestApproach ( - const reco::TransientTrack, const reco::TransientTrack ) const = 0; + virtual std::pair pointsOfClosestApproach(const reco::TransientTrack, + const reco::TransientTrack) const = 0; - virtual bool hasDistances() const =0; - virtual bool hasWeightedDistances() const =0; - virtual bool hasCrossingPoints() const =0; - virtual bool hasPCAs() const =0; + virtual bool hasDistances() const = 0; + virtual bool hasWeightedDistances() const = 0; + virtual bool hasCrossingPoints() const = 0; + virtual bool hasPCAs() const = 0; }; #endif diff --git a/RecoVertex/VertexTools/interface/SMS.h b/RecoVertex/VertexTools/interface/SMS.h index ac5105c6dde7b..f586cec2ed05d 100644 --- a/RecoVertex/VertexTools/interface/SMS.h +++ b/RecoVertex/VertexTools/interface/SMS.h @@ -13,28 +13,23 @@ * value of a set of observations with Small Median of Squared distances. */ -class SMS -{ +class SMS { public: - enum SMSType { None = 0, - Interpolate = 1, - Iterate = 2, - Weighted = 4 }; + enum SMSType { None = 0, Interpolate = 1, Iterate = 2, Weighted = 4 }; /** * Constructor. * \param tp What specific kind of SMS algorithm do you want? * \param q What fraction of data points are considered for the * "next step"? */ - SMS ( SMSType tp = (SMSType) (Interpolate | Iterate | Weighted), float q=0.5 ); + SMS(SMSType tp = (SMSType)(Interpolate | Iterate | Weighted), float q = 0.5); - GlobalPoint location ( const std::vector < GlobalPoint > & ) const; - GlobalPoint location ( const std::vector < std::pair < GlobalPoint, float > > & ) const; + GlobalPoint location(const std::vector&) const; + GlobalPoint location(const std::vector >&) const; private: SMSType theType; float theRatio; - }; #endif /* def SMS */ diff --git a/RecoVertex/VertexTools/interface/SequentialVertexFitter.h b/RecoVertex/VertexTools/interface/SequentialVertexFitter.h index 141f433cd1767..df13c900278a9 100644 --- a/RecoVertex/VertexTools/interface/SequentialVertexFitter.h +++ b/RecoVertex/VertexTools/interface/SequentialVertexFitter.h @@ -30,72 +30,66 @@ * constraint of the vertex position. */ - template class SequentialVertexFitter : public VertexFitter { - public: - typedef ReferenceCountingPointer > RefCountedRefittedTrackState; typedef ReferenceCountingPointer > RefCountedVertexTrack; typedef ReferenceCountingPointer > RefCountedLinearizedTrackState; - /** * Reimplemented constructors to use any kind of * linearisation point finder, vertex updator and smoother. * If no smoother is to be used, do not specify an instance for it. */ - SequentialVertexFitter(const LinearizationPointFinder & linP, - const VertexUpdator & updator, const VertexSmoother & smoother, - const AbstractLTSFactory & ltsf); + SequentialVertexFitter(const LinearizationPointFinder& linP, + const VertexUpdator& updator, + const VertexSmoother& smoother, + const AbstractLTSFactory& ltsf); /** * Same as above, using a ParameterSet to set the convergence criteria */ SequentialVertexFitter(const edm::ParameterSet& pSet, - const LinearizationPointFinder & linP, - const VertexUpdator & updator, const VertexSmoother & smoother, - const AbstractLTSFactory & ltsf); + const LinearizationPointFinder& linP, + const VertexUpdator& updator, + const VertexSmoother& smoother, + const AbstractLTSFactory& ltsf); /** * Copy constructor */ - SequentialVertexFitter(const SequentialVertexFitter & original); - + SequentialVertexFitter(const SequentialVertexFitter& original); ~SequentialVertexFitter() override; - /** * Method to set the convergence criterion * (the maximum distance between the vertex computed in the previous * and the current iterations to consider the fit to have converged) */ - void setMaximumDistance(float maxShift) {theMaxShift = maxShift;} - + void setMaximumDistance(float maxShift) { theMaxShift = maxShift; } /** * Method to set the maximum number of iterations to perform */ - void setMaximumNumberOfIterations(int maxIterations) - {theMaxStep = maxIterations;} + void setMaximumNumberOfIterations(int maxIterations) { theMaxStep = maxIterations; } - /** + /** * Method returning the fitted vertex, from a container of reco::TransientTracks. * The linearization point will be searched with the given LP finder. * No prior vertex position will be used in the vertex fit. * \param tracks The container of RecTracks to fit. * \return The fitted vertex */ - CachingVertex vertex(const std::vector & tracks) const override; + CachingVertex vertex(const std::vector& tracks) const override; - /** + /** * Method returning the fitted vertex, from a container of VertexTracks. * For the first loop, the LinearizedTrackState contained in the VertexTracks * will be used. If subsequent loops are needed, the new VertexTracks will @@ -104,47 +98,42 @@ class SequentialVertexFitter : public VertexFitter { * \param tracks The container of VertexTracks to fit. * \return The fitted vertex */ - CachingVertex vertex(const std::vector & tracks) const override; + CachingVertex vertex(const std::vector& tracks) const override; /** * Same as above, only now also with BeamSpot! */ - CachingVertex vertex(const std::vector & tracks, const reco::BeamSpot & spot ) const override; - + CachingVertex vertex(const std::vector& tracks, const reco::BeamSpot& spot) const override; /** Fit vertex out of a set of RecTracks. Uses the specified linearization point. */ - CachingVertex vertex(const std::vector & tracks, - const GlobalPoint& linPoint) const override; + CachingVertex vertex(const std::vector& tracks, const GlobalPoint& linPoint) const override; /** Fit vertex out of a set of TransientTracks. * The specified BeamSpot will be used as priot, but NOT for the linearization. * The specified LinearizationPointFinder will be used to find the linearization point. */ - CachingVertex vertex(const std::vector & tracks, - const reco::BeamSpot& beamSpot) const override; - + CachingVertex vertex(const std::vector& tracks, + const reco::BeamSpot& beamSpot) const override; /** Fit vertex out of a set of RecTracks. * Uses the position as both the linearization point AND as prior * estimate of the vertex position. The error is used for the * weight of the prior estimate. */ - CachingVertex vertex(const std::vector & tracks, - const GlobalPoint& priorPos, - const GlobalError& priorError) const override; + CachingVertex vertex(const std::vector& tracks, + const GlobalPoint& priorPos, + const GlobalError& priorError) const override; /** Fit vertex out of a set of VertexTracks * Uses the position and error for the prior estimate of the vertex. * This position is not used to relinearize the tracks. */ - CachingVertex vertex(const std::vector & tracks, - const GlobalPoint& priorPos, - const GlobalError& priorError) const override; - - + CachingVertex vertex(const std::vector& tracks, + const GlobalPoint& priorPos, + const GlobalError& priorError) const override; - /** + /** * Method returning the fitted vertex, from a VertexSeed. * For the first loop, the position of the VertexSeed will be used as * linearization point. If subsequent loops are needed, the new VertexTracks @@ -154,38 +143,28 @@ class SequentialVertexFitter : public VertexFitter { * \param seed The VertexSeed to fit. * \return The fitted vertex */ -// virtual CachingVertex vertex(const RefCountedVertexSeed seed) const; + // virtual CachingVertex vertex(const RefCountedVertexSeed seed) const; /** * Access methods */ - const LinearizationPointFinder * linearizationPointFinder() const - {return theLinP;} + const LinearizationPointFinder* linearizationPointFinder() const { return theLinP; } - const VertexUpdator * vertexUpdator() const - {return theUpdator;} + const VertexUpdator* vertexUpdator() const { return theUpdator; } - const VertexSmoother * vertexSmoother() const - {return theSmoother;} + const VertexSmoother* vertexSmoother() const { return theSmoother; } - const float maxShift() const - {return theMaxShift;} + const float maxShift() const { return theMaxShift; } - const int maxStep() const - {return theMaxStep;} + const int maxStep() const { return theMaxStep; } - const edm::ParameterSet parameterSet() const - {return thePSet;} + const edm::ParameterSet parameterSet() const { return thePSet; } - SequentialVertexFitter * clone() const override { - return new SequentialVertexFitter(* this); - } + SequentialVertexFitter* clone() const override { return new SequentialVertexFitter(*this); } - const AbstractLTSFactory * linearizedTrackStateFactory() const - { return theLTrackFactory;} + const AbstractLTSFactory* linearizedTrackStateFactory() const { return theLTrackFactory; } protected: - /** * Default constructor. Is here, as we do not want anybody to use it. */ @@ -193,7 +172,6 @@ class SequentialVertexFitter : public VertexFitter { SequentialVertexFitter() {} private: - /** * The methode where the vrte fit is actually done. The seed is used as the * prior estimate in the vertex fit (in case its error is large, it will have @@ -203,8 +181,9 @@ class SequentialVertexFitter : public VertexFitter { * \paraemter priorVertex The prior estimate of the vertex * \return The fitted vertex */ - CachingVertex fit(const std::vector & tracks, - const VertexState priorVertex, bool withPrior) const; + CachingVertex fit(const std::vector& tracks, + const VertexState priorVertex, + bool withPrior) const; /** * Construct a container of VertexTrack from a set of RecTracks. @@ -213,8 +192,8 @@ class SequentialVertexFitter : public VertexFitter { * also be used as the new linearization point. * \return The container of VertexTracks which are to be used in the next fit. */ - std::vector linearizeTracks(const std::vector & tracks, - const VertexState state) const; + std::vector linearizeTracks(const std::vector& tracks, + const VertexState state) const; /** * Construct new a container of VertexTrack with a new linearization point @@ -226,10 +205,8 @@ class SequentialVertexFitter : public VertexFitter { * also be used as the new linearization point. * \return The container of VertexTracks which are to be used in the next fit. */ - std::vector reLinearizeTracks( - const std::vector & tracks, - const VertexState state) const; - + std::vector reLinearizeTracks(const std::vector& tracks, + const VertexState state) const; /** * Reads the configurable parameters. @@ -243,19 +220,18 @@ class SequentialVertexFitter : public VertexFitter { */ inline bool hasNan(const GlobalPoint& point) const { using namespace std; - return (edm::isNotFinite(point.x())|| edm::isNotFinite(point.y()) || edm::isNotFinite(point.z())); + return (edm::isNotFinite(point.x()) || edm::isNotFinite(point.y()) || edm::isNotFinite(point.z())); } - float theMaxShift; int theMaxStep; edm::ParameterSet thePSet; - LinearizationPointFinder* theLinP; - VertexUpdator * theUpdator; - VertexSmoother * theSmoother; - const AbstractLTSFactory * theLTrackFactory; -// LinearizedTrackStateFactoryAbstractLTSFactory theLTrackFactory; + LinearizationPointFinder* theLinP; + VertexUpdator* theUpdator; + VertexSmoother* theSmoother; + const AbstractLTSFactory* theLTrackFactory; + // LinearizedTrackStateFactoryAbstractLTSFactory theLTrackFactory; VertexTrackFactory theVTrackFactory; // VertexSeedFactory theVSeedFactory; diff --git a/RecoVertex/VertexTools/interface/SequentialVertexSmoother.h b/RecoVertex/VertexTools/interface/SequentialVertexSmoother.h index 3b3693de2d80a..1e96ca6cc4559 100644 --- a/RecoVertex/VertexTools/interface/SequentialVertexSmoother.h +++ b/RecoVertex/VertexTools/interface/SequentialVertexSmoother.h @@ -1,7 +1,6 @@ #ifndef _SequentialVertexSmoother_H_ #define _SequentialVertexSmoother_H_ - #include "RecoVertex/VertexPrimitives/interface/VertexSmoother.h" #include "RecoVertex/VertexPrimitives/interface/VertexTrackUpdator.h" #include "RecoVertex/VertexPrimitives/interface/VertexSmoothedChiSquaredEstimator.h" @@ -14,9 +13,7 @@ template class SequentialVertexSmoother : public VertexSmoother { - public: - typedef ReferenceCountingPointer > RefCountedRefittedTrackState; typedef ReferenceCountingPointer > RefCountedVertexTrack; typedef ReferenceCountingPointer > RefCountedLinearizedTrackState; @@ -28,16 +25,16 @@ class SequentialVertexSmoother : public VertexSmoother { * \return covCalc The algorithm the track-to-track covariance matrix. * If this option is not required, this pointer should be 0. */ - SequentialVertexSmoother(const VertexTrackUpdator & vtu, - const VertexSmoothedChiSquaredEstimator & vse, - const TrackToTrackCovCalculator & covCalc); + SequentialVertexSmoother(const VertexTrackUpdator& vtu, + const VertexSmoothedChiSquaredEstimator& vse, + const TrackToTrackCovCalculator& covCalc); ~SequentialVertexSmoother() override; /** * Special copy constructor cloning the private data */ - SequentialVertexSmoother(const SequentialVertexSmoother & smoother); + SequentialVertexSmoother(const SequentialVertexSmoother& smoother); /** * Methode which will refit the tracks with the vertex constraint, @@ -49,30 +46,26 @@ class SequentialVertexSmoother : public VertexSmoother { * last update. * \return the final vertex estimate, with all the supplementary information */ - CachingVertex smooth(const CachingVertex & vertex) const override; + CachingVertex smooth(const CachingVertex& vertex) const override; /** * Access methods */ - const VertexTrackUpdator * vertexTrackUpdator() const - { return theVertexTrackUpdator; } - const VertexSmoothedChiSquaredEstimator * vertexSmoothedChiSquaredEstimator() const - { return theVertexSmoothedChiSquaredEstimator; } - const TrackToTrackCovCalculator * trackToTrackCovCalculator() const - { return theTrackToTrackCovCalculator; } + const VertexTrackUpdator* vertexTrackUpdator() const { return theVertexTrackUpdator; } + const VertexSmoothedChiSquaredEstimator* vertexSmoothedChiSquaredEstimator() const { + return theVertexSmoothedChiSquaredEstimator; + } + const TrackToTrackCovCalculator* trackToTrackCovCalculator() const { return theTrackToTrackCovCalculator; } /** * Clone method */ - SequentialVertexSmoother * clone() const override - { - return new SequentialVertexSmoother(* this); - } - + SequentialVertexSmoother* clone() const override { return new SequentialVertexSmoother(*this); } + private: - VertexTrackUpdator * theVertexTrackUpdator; - VertexSmoothedChiSquaredEstimator * theVertexSmoothedChiSquaredEstimator; - TrackToTrackCovCalculator * theTrackToTrackCovCalculator; + VertexTrackUpdator* theVertexTrackUpdator; + VertexSmoothedChiSquaredEstimator* theVertexSmoothedChiSquaredEstimator; + TrackToTrackCovCalculator* theTrackToTrackCovCalculator; }; #endif diff --git a/RecoVertex/VertexTools/interface/SharedTracks.h b/RecoVertex/VertexTools/interface/SharedTracks.h index 7dd447da13c7c..63a03b518a28f 100644 --- a/RecoVertex/VertexTools/interface/SharedTracks.h +++ b/RecoVertex/VertexTools/interface/SharedTracks.h @@ -7,12 +7,30 @@ #include "DataFormats/Candidate/interface/Candidate.h" namespace vertexTools { - double computeSharedTracks(const reco::Vertex &pv, const std::vector &svTracks, double minTrackWeight=0.5, float unused=0); - double computeSharedTracks(const reco::Vertex &pv, const std::vector &svTracks, double minTrackWeight=0.5,float mindist=2.0); - double computeSharedTracks(const reco::Vertex &pv, const reco::VertexCompositePtrCandidate &sv, double minTrackWeight=0.5,float mindist=2.0); - double computeSharedTracks(const reco::Vertex &pv, const reco::Vertex &sv, double minTrackWeight=0.5,float mindist=2.0); - double computeSharedTracks(const reco::VertexCompositePtrCandidate &sv, const reco::VertexCompositePtrCandidate &sv2, double minTrackWeight=0.5,float mindist=2.0); - double computeSharedTracks(const reco::VertexCompositePtrCandidate &sv2, const std::vector &svTracks, double unused1=0, float unused2=0 ); + double computeSharedTracks(const reco::Vertex &pv, + const std::vector &svTracks, + double minTrackWeight = 0.5, + float unused = 0); + double computeSharedTracks(const reco::Vertex &pv, + const std::vector &svTracks, + double minTrackWeight = 0.5, + float mindist = 2.0); + double computeSharedTracks(const reco::Vertex &pv, + const reco::VertexCompositePtrCandidate &sv, + double minTrackWeight = 0.5, + float mindist = 2.0); + double computeSharedTracks(const reco::Vertex &pv, + const reco::Vertex &sv, + double minTrackWeight = 0.5, + float mindist = 2.0); + double computeSharedTracks(const reco::VertexCompositePtrCandidate &sv, + const reco::VertexCompositePtrCandidate &sv2, + double minTrackWeight = 0.5, + float mindist = 2.0); + double computeSharedTracks(const reco::VertexCompositePtrCandidate &sv2, + const std::vector &svTracks, + double unused1 = 0, + float unused2 = 0); -} +} // namespace vertexTools #endif diff --git a/RecoVertex/VertexTools/interface/SmsModeFinder3d.h b/RecoVertex/VertexTools/interface/SmsModeFinder3d.h index 20da5c6730c05..782a6b1bf0aad 100644 --- a/RecoVertex/VertexTools/interface/SmsModeFinder3d.h +++ b/RecoVertex/VertexTools/interface/SmsModeFinder3d.h @@ -8,9 +8,10 @@ */ class SmsModeFinder3d : public ModeFinder3d { public: - SmsModeFinder3d ( const SMS & algo = SMS() ); - GlobalPoint operator () ( const std::vector< PointAndDistance> & values ) const override; - SmsModeFinder3d * clone() const override; + SmsModeFinder3d(const SMS& algo = SMS()); + GlobalPoint operator()(const std::vector& values) const override; + SmsModeFinder3d* clone() const override; + private: SMS theAlgo; }; diff --git a/RecoVertex/VertexTools/interface/SubsetHsmModeFinder3d.h b/RecoVertex/VertexTools/interface/SubsetHsmModeFinder3d.h index 66b616f4a1aff..3fda014f4cf64 100644 --- a/RecoVertex/VertexTools/interface/SubsetHsmModeFinder3d.h +++ b/RecoVertex/VertexTools/interface/SubsetHsmModeFinder3d.h @@ -13,8 +13,8 @@ */ class SubsetHsmModeFinder3d : public ModeFinder3d { public: - GlobalPoint operator () ( const std::vector< PointAndDistance> & values ) const override; - SubsetHsmModeFinder3d * clone() const override; + GlobalPoint operator()(const std::vector& values) const override; + SubsetHsmModeFinder3d* clone() const override; }; #endif diff --git a/RecoVertex/VertexTools/interface/VertexCompatibleWithBeam.h b/RecoVertex/VertexTools/interface/VertexCompatibleWithBeam.h index 881f503158e31..a2c4b453c44ec 100644 --- a/RecoVertex/VertexTools/interface/VertexCompatibleWithBeam.h +++ b/RecoVertex/VertexTools/interface/VertexCompatibleWithBeam.h @@ -13,18 +13,15 @@ class VertexDistance; */ class VertexCompatibleWithBeam { - public: + VertexCompatibleWithBeam(const VertexDistance &dist, float cut); + VertexCompatibleWithBeam(const VertexDistance &dist, float cut, const reco::BeamSpot &beamSpot); - VertexCompatibleWithBeam(const VertexDistance & dist, float cut); - VertexCompatibleWithBeam(const VertexDistance & dist, float cut, - const reco::BeamSpot & beamSpot); - - VertexCompatibleWithBeam(const VertexCompatibleWithBeam & other); - VertexCompatibleWithBeam & operator=(const VertexCompatibleWithBeam & other); + VertexCompatibleWithBeam(const VertexCompatibleWithBeam &other); + VertexCompatibleWithBeam &operator=(const VertexCompatibleWithBeam &other); virtual ~VertexCompatibleWithBeam(); - void setBeamSpot(const reco::BeamSpot & beamSpot); + void setBeamSpot(const reco::BeamSpot &beamSpot); virtual bool operator()(const reco::Vertex &) const; virtual bool operator()(const reco::Vertex &, const VertexState &) const; @@ -33,11 +30,9 @@ class VertexCompatibleWithBeam { float distanceToBeam(const reco::Vertex &, const VertexState &) const; private: - - VertexDistance * theDistance; + VertexDistance *theDistance; float theCut; VertexState theBeam; - }; #endif diff --git a/RecoVertex/VertexTools/interface/VertexDistance.h b/RecoVertex/VertexTools/interface/VertexDistance.h index 20799853557a2..fe6d94e37c90d 100644 --- a/RecoVertex/VertexTools/interface/VertexDistance.h +++ b/RecoVertex/VertexTools/interface/VertexDistance.h @@ -14,21 +14,16 @@ class VertexState; class VertexDistance { - public: - +public: virtual ~VertexDistance() {} - Measurement1D distance(const reco::Vertex &, - const reco::Vertex &) const; + Measurement1D distance(const reco::Vertex &, const reco::Vertex &) const; - Measurement1D distance(const VertexState &, - const VertexState &) const; + Measurement1D distance(const VertexState &, const VertexState &) const; - Measurement1D distance(const reco::Vertex &, - const VertexState &) const; + Measurement1D distance(const reco::Vertex &, const VertexState &) const; - Measurement1D distance(const VertexState &, - const reco::Vertex &) const; + Measurement1D distance(const VertexState &, const reco::Vertex &) const; /** * The signed distance is computed using a vector @@ -42,34 +37,29 @@ class VertexDistance { * for the 3D case: * Follows same approach, using all three components of the two vectors */ - virtual Measurement1D signedDistance(const reco::Vertex &primVtx , - const reco::Vertex &secVtx, - const GlobalVector & momentum) const = 0; - - virtual float compatibility (const reco::Vertex &, - const reco::Vertex &) const; + virtual Measurement1D signedDistance(const reco::Vertex &primVtx, + const reco::Vertex &secVtx, + const GlobalVector &momentum) const = 0; - virtual float compatibility (const VertexState &, - const VertexState &) const; + virtual float compatibility(const reco::Vertex &, const reco::Vertex &) const; - virtual float compatibility(const reco::Vertex &, - const VertexState &) const; + virtual float compatibility(const VertexState &, const VertexState &) const; - virtual float compatibility(const VertexState &, - const reco::Vertex &) const; + virtual float compatibility(const reco::Vertex &, const VertexState &) const; - virtual VertexDistance * clone() const = 0; + virtual float compatibility(const VertexState &, const reco::Vertex &) const; -protected: - virtual Measurement1D distance(const GlobalPoint & vtx1Position, - const GlobalError & vtx1PositionError, - const GlobalPoint & vtx2Position, - const GlobalError & vtx2PositionError) const = 0; + virtual VertexDistance *clone() const = 0; - virtual float compatibility(const GlobalPoint & vtx1Position, - const GlobalError & vtx1PositionError, - const GlobalPoint & vtx2Position, - const GlobalError & vtx2PositionError) const = 0; +protected: + virtual Measurement1D distance(const GlobalPoint &vtx1Position, + const GlobalError &vtx1PositionError, + const GlobalPoint &vtx2Position, + const GlobalError &vtx2PositionError) const = 0; + virtual float compatibility(const GlobalPoint &vtx1Position, + const GlobalError &vtx1PositionError, + const GlobalPoint &vtx2Position, + const GlobalError &vtx2PositionError) const = 0; }; #endif // Tracker_VertexDistance_H diff --git a/RecoVertex/VertexTools/interface/VertexDistance3D.h b/RecoVertex/VertexTools/interface/VertexDistance3D.h index bee50fd20c01b..f2d32862de171 100644 --- a/RecoVertex/VertexTools/interface/VertexDistance3D.h +++ b/RecoVertex/VertexTools/interface/VertexDistance3D.h @@ -11,7 +11,6 @@ */ class VertexDistance3D : public VertexDistance { - public: using VertexDistance::compatibility; @@ -25,33 +24,25 @@ class VertexDistance3D : public VertexDistance { * the vector connecting the vertices and the reference vector: * if the scalar product is greater than zero, the sign is +1, else -1 */ - Measurement1D signedDistance(const reco::Vertex &primVtx , - const reco::Vertex &secVtx, - const GlobalVector & momentum) const override; + Measurement1D signedDistance(const reco::Vertex &primVtx, + const reco::Vertex &secVtx, + const GlobalVector &momentum) const override; - VertexDistance3D * clone() const override - { - return new VertexDistance3D(*this); - } + VertexDistance3D *clone() const override { return new VertexDistance3D(*this); } using VertexDistance::distance; private: - AlgebraicSymMatrix33 theNullMatrix; - Measurement1D distance(const GlobalPoint & vtx1Position, - const GlobalError & vtx1PositionError, - const GlobalPoint & vtx2Position, - const GlobalError & vtx2PositionError) const override; - - float compatibility(const GlobalPoint & vtx1Position, - const GlobalError & vtx1PositionError, - const GlobalPoint & vtx2Position, - const GlobalError & vtx2PositionError) const override; + Measurement1D distance(const GlobalPoint &vtx1Position, + const GlobalError &vtx1PositionError, + const GlobalPoint &vtx2Position, + const GlobalError &vtx2PositionError) const override; + + float compatibility(const GlobalPoint &vtx1Position, + const GlobalError &vtx1PositionError, + const GlobalPoint &vtx2Position, + const GlobalError &vtx2PositionError) const override; }; - #endif - - - diff --git a/RecoVertex/VertexTools/interface/VertexDistanceXY.h b/RecoVertex/VertexTools/interface/VertexDistanceXY.h index 6559274af98bd..71e10afd0dd1d 100644 --- a/RecoVertex/VertexTools/interface/VertexDistanceXY.h +++ b/RecoVertex/VertexTools/interface/VertexDistanceXY.h @@ -9,10 +9,8 @@ */ class VertexDistanceXY : public VertexDistance { - public: - - VertexDistanceXY() {} + VertexDistanceXY() {} /** * The signed distance is computed using a vector @@ -22,36 +20,27 @@ class VertexDistanceXY : public VertexDistance { * the vector connecting the vertices and the reference vector: * if the scalar product is greater than zero, the sign is +1, else -1 */ - Measurement1D signedDistance(const reco::Vertex &primVtx , - const reco::Vertex &secVtx, - const GlobalVector & momentum) const override; - - VertexDistanceXY * clone() const override - { - return new VertexDistanceXY(*this); - } + Measurement1D signedDistance(const reco::Vertex &primVtx, + const reco::Vertex &secVtx, + const GlobalVector &momentum) const override; + VertexDistanceXY *clone() const override { return new VertexDistanceXY(*this); } - using VertexDistance::distance; using VertexDistance::compatibility; + using VertexDistance::distance; private: - AlgebraicSymMatrix22 theNullMatrix; - Measurement1D distance(const GlobalPoint & vtx1Position, - const GlobalError & vtx1PositionError, - const GlobalPoint & vtx2Position, - const GlobalError & vtx2PositionError) const override; + Measurement1D distance(const GlobalPoint &vtx1Position, + const GlobalError &vtx1PositionError, + const GlobalPoint &vtx2Position, + const GlobalError &vtx2PositionError) const override; - float compatibility(const GlobalPoint & vtx1Position, - const GlobalError & vtx1PositionError, - const GlobalPoint & vtx2Position, - const GlobalError & vtx2PositionError) const override; + float compatibility(const GlobalPoint &vtx1Position, + const GlobalError &vtx1PositionError, + const GlobalPoint &vtx2Position, + const GlobalError &vtx2PositionError) const override; }; - #endif - - - diff --git a/RecoVertex/VertexTools/interface/VertexTrackFactory.h b/RecoVertex/VertexTools/interface/VertexTrackFactory.h index ae3b915f7285e..8b51a10530c75 100644 --- a/RecoVertex/VertexTools/interface/VertexTrackFactory.h +++ b/RecoVertex/VertexTools/interface/VertexTrackFactory.h @@ -10,46 +10,41 @@ * which is a reference-counting pointer. * Should always be used in order to create a new RefCountedVertexTrack, * so that the reference-counting mechanism works well. - */ + */ template class VertexTrackFactory { - public: - typedef ReferenceCountingPointer > RefCountedRefittedTrackState; typedef ReferenceCountingPointer > RefCountedVertexTrack; typedef ReferenceCountingPointer > RefCountedLinearizedTrackState; - typedef ROOT::Math::SMatrix > AlgebraicMatrix3M; - typedef ROOT::Math::SMatrix > AlgebraicSymMatrixOO; + typedef ROOT::Math::SMatrix > AlgebraicMatrix3M; + typedef ROOT::Math::SMatrix > AlgebraicSymMatrixOO; VertexTrackFactory() {} - ~VertexTrackFactory() {} + ~VertexTrackFactory() {} - RefCountedVertexTrack - vertexTrack(const RefCountedLinearizedTrackState lt, - const VertexState vs, - float weight = 1.0 ) const { - return RefCountedVertexTrack(new VertexTrack(lt, vs, weight )); + RefCountedVertexTrack vertexTrack(const RefCountedLinearizedTrackState lt, + const VertexState vs, + float weight = 1.0) const { + return RefCountedVertexTrack(new VertexTrack(lt, vs, weight)); }; - RefCountedVertexTrack - vertexTrack(const RefCountedLinearizedTrackState lt, - const VertexState vs, - const RefCountedRefittedTrackState & refittedState, - float smoothedChi2, float weight = 1.0 ) const { - return RefCountedVertexTrack(new VertexTrack(lt, vs, weight, refittedState, - smoothedChi2)); + RefCountedVertexTrack vertexTrack(const RefCountedLinearizedTrackState lt, + const VertexState vs, + const RefCountedRefittedTrackState& refittedState, + float smoothedChi2, + float weight = 1.0) const { + return RefCountedVertexTrack(new VertexTrack(lt, vs, weight, refittedState, smoothedChi2)); }; - RefCountedVertexTrack - vertexTrack(const RefCountedLinearizedTrackState lt, - const VertexState vs, - const RefCountedRefittedTrackState & refittedState, - float smoothedChi2, - const AlgebraicSymMatrixOO & tVCov, float weight = 1.0 ) const { - return RefCountedVertexTrack(new VertexTrack(lt, vs, weight, - refittedState, smoothedChi2, tVCov)); + RefCountedVertexTrack vertexTrack(const RefCountedLinearizedTrackState lt, + const VertexState vs, + const RefCountedRefittedTrackState& refittedState, + float smoothedChi2, + const AlgebraicSymMatrixOO& tVCov, + float weight = 1.0) const { + return RefCountedVertexTrack(new VertexTrack(lt, vs, weight, refittedState, smoothedChi2, tVCov)); }; }; diff --git a/RecoVertex/VertexTools/interface/hsm_3d.h b/RecoVertex/VertexTools/interface/hsm_3d.h index 42b184bc2a7b7..9c6f504585d35 100644 --- a/RecoVertex/VertexTools/interface/hsm_3d.h +++ b/RecoVertex/VertexTools/interface/hsm_3d.h @@ -5,6 +5,6 @@ #include "DataFormats/GeometryVector/interface/GlobalPoint.h" /// cordinate wise half sample mode in 3d -GlobalPoint hsm_3d ( const std::vector & values ); +GlobalPoint hsm_3d(const std::vector& values); #endif diff --git a/RecoVertex/VertexTools/interface/lms_3d.h b/RecoVertex/VertexTools/interface/lms_3d.h index fd06eab58d56e..620b2d2fcce2c 100644 --- a/RecoVertex/VertexTools/interface/lms_3d.h +++ b/RecoVertex/VertexTools/interface/lms_3d.h @@ -6,6 +6,6 @@ /// least median of squares in three dimensions, /// doing every dimension separately -GlobalPoint lms_3d ( std::vector values ); +GlobalPoint lms_3d(std::vector values); #endif diff --git a/RecoVertex/VertexTools/src/DeterministicAnnealing.cc b/RecoVertex/VertexTools/src/DeterministicAnnealing.cc index 15b01128d2bce..8510fa9339ed7 100644 --- a/RecoVertex/VertexTools/src/DeterministicAnnealing.cc +++ b/RecoVertex/VertexTools/src/DeterministicAnnealing.cc @@ -7,81 +7,55 @@ using namespace std; -DeterministicAnnealing::DeterministicAnnealing ( float cutoff ) : - theTemperatures({256,64,16,4,2,1}), - theIndex(0), theChi2cut ( cutoff*cutoff ), theIsAnnealed ( false ) -{ -} +DeterministicAnnealing::DeterministicAnnealing(float cutoff) + : theTemperatures({256, 64, 16, 4, 2, 1}), theIndex(0), theChi2cut(cutoff * cutoff), theIsAnnealed(false) {} -DeterministicAnnealing::DeterministicAnnealing( const vector < float > & sched, float cutoff ) : - theTemperatures(sched),theIndex(0), theChi2cut ( cutoff*cutoff ), theIsAnnealed ( false ) -{ -} +DeterministicAnnealing::DeterministicAnnealing(const vector& sched, float cutoff) + : theTemperatures(sched), theIndex(0), theChi2cut(cutoff * cutoff), theIsAnnealed(false) {} -void DeterministicAnnealing::anneal() -{ - if ( theIndex < ( theTemperatures.size() - 1 ) ) - { - theIndex++; +void DeterministicAnnealing::anneal() { + if (theIndex < (theTemperatures.size() - 1)) { + theIndex++; } else { theIsAnnealed = true; }; } -double DeterministicAnnealing::weight ( double chi2 ) const -{ - long double mphi = phi ( chi2 ); +double DeterministicAnnealing::weight(double chi2) const { + long double mphi = phi(chi2); /* if ( mphi < std::numeric_limits::epsilon() ) return 0.; return 1. / ( 1. + phi ( theChi2cut * theChi2cut ) / mphi ); */ // return mphi / ( mphi + phi ( theChi2cut ) ); - long double newtmp = mphi / ( mphi + phi ( theChi2cut ) ); - if ( edm::isNotFinite(newtmp ) ) - { - if ( chi2 < theChi2cut ) newtmp=1.; - else newtmp=0.; + long double newtmp = mphi / (mphi + phi(theChi2cut)); + if (edm::isNotFinite(newtmp)) { + if (chi2 < theChi2cut) + newtmp = 1.; + else + newtmp = 0.; } return newtmp; } -void DeterministicAnnealing::resetAnnealing() -{ - theIndex=0; +void DeterministicAnnealing::resetAnnealing() { + theIndex = 0; theIsAnnealed = false; } -inline double DeterministicAnnealing::phi( double chi2 ) const -{ - return exp ( -.5 * chi2 / theTemperatures[theIndex] ); -} +inline double DeterministicAnnealing::phi(double chi2) const { return exp(-.5 * chi2 / theTemperatures[theIndex]); } -double DeterministicAnnealing::cutoff() const -{ - return sqrt(theChi2cut); -} +double DeterministicAnnealing::cutoff() const { return sqrt(theChi2cut); } -double DeterministicAnnealing::currentTemp() const -{ - return theTemperatures[theIndex]; -} +double DeterministicAnnealing::currentTemp() const { return theTemperatures[theIndex]; } -double DeterministicAnnealing::initialTemp() const -{ - return theTemperatures[0]; -} +double DeterministicAnnealing::initialTemp() const { return theTemperatures[0]; } -bool DeterministicAnnealing::isAnnealed() const -{ - return theIsAnnealed; -} +bool DeterministicAnnealing::isAnnealed() const { return theIsAnnealed; } -void DeterministicAnnealing::debug() const -{ +void DeterministicAnnealing::debug() const { cout << "[DeterministicAnnealing] schedule="; - for ( vector< float >::const_iterator i=theTemperatures.begin(); - i!=theTemperatures.end() ; ++i ) - { + for (vector::const_iterator i = theTemperatures.begin(); i != theTemperatures.end(); ++i) { cout << *i << " "; }; cout << endl; diff --git a/RecoVertex/VertexTools/src/DummyTrackToTrackCovCalculator.cc b/RecoVertex/VertexTools/src/DummyTrackToTrackCovCalculator.cc index dbca575a6ba38..dc2bec28d1655 100644 --- a/RecoVertex/VertexTools/src/DummyTrackToTrackCovCalculator.cc +++ b/RecoVertex/VertexTools/src/DummyTrackToTrackCovCalculator.cc @@ -1,17 +1,13 @@ #include "RecoVertex/VertexTools/interface/DummyTrackToTrackCovCalculator.h" - template -typename CachingVertex::TrackToTrackMap -DummyTrackToTrackCovCalculator::operator() (const CachingVertex &) const -{ +typename CachingVertex::TrackToTrackMap DummyTrackToTrackCovCalculator::operator()( + const CachingVertex &) const { return typename CachingVertex::TrackToTrackMap(); } - template -DummyTrackToTrackCovCalculator * DummyTrackToTrackCovCalculator::clone() const -{ +DummyTrackToTrackCovCalculator *DummyTrackToTrackCovCalculator::clone() const { return new DummyTrackToTrackCovCalculator(*this); } diff --git a/RecoVertex/VertexTools/src/DummyVertexSmoother.cc b/RecoVertex/VertexTools/src/DummyVertexSmoother.cc index 6fa8be0b2451b..e41ab34948c70 100644 --- a/RecoVertex/VertexTools/src/DummyVertexSmoother.cc +++ b/RecoVertex/VertexTools/src/DummyVertexSmoother.cc @@ -1,15 +1,13 @@ #include "RecoVertex/VertexTools/interface/DummyVertexSmoother.h" template -CachingVertex DummyVertexSmoother::smooth( const CachingVertex & vertex ) const -{ +CachingVertex DummyVertexSmoother::smooth(const CachingVertex& vertex) const { return vertex; } template -DummyVertexSmoother * DummyVertexSmoother::clone() const -{ - return new DummyVertexSmoother ( * this ); +DummyVertexSmoother* DummyVertexSmoother::clone() const { + return new DummyVertexSmoother(*this); } template class DummyVertexSmoother<5>; diff --git a/RecoVertex/VertexTools/src/DummyVertexTrackUpdator.cc b/RecoVertex/VertexTools/src/DummyVertexTrackUpdator.cc index 2c5c5b2290b9c..6e6297b011663 100644 --- a/RecoVertex/VertexTools/src/DummyVertexTrackUpdator.cc +++ b/RecoVertex/VertexTools/src/DummyVertexTrackUpdator.cc @@ -1,18 +1,13 @@ #include "RecoVertex/VertexTools/interface/DummyVertexTrackUpdator.h" - template -typename CachingVertex::RefCountedVertexTrack -DummyVertexTrackUpdator::update(const CachingVertex & v, - typename CachingVertex::RefCountedVertexTrack t) const -{ +typename CachingVertex::RefCountedVertexTrack DummyVertexTrackUpdator::update( + const CachingVertex& v, typename CachingVertex::RefCountedVertexTrack t) const { return t; } - template -DummyVertexTrackUpdator * DummyVertexTrackUpdator::clone() const -{ +DummyVertexTrackUpdator* DummyVertexTrackUpdator::clone() const { return new DummyVertexTrackUpdator(*this); } diff --git a/RecoVertex/VertexTools/src/FsmwModeFinder3d.cc b/RecoVertex/VertexTools/src/FsmwModeFinder3d.cc index 27adad1221c67..4716f61f431fc 100644 --- a/RecoVertex/VertexTools/src/FsmwModeFinder3d.cc +++ b/RecoVertex/VertexTools/src/FsmwModeFinder3d.cc @@ -7,61 +7,44 @@ /** Half sample mode in 3d, as a functional class. */ -FsmwModeFinder3d::FsmwModeFinder3d( float fraction, float weightExp, - float cutoff, int no_w_a ) : theFraction ( fraction ), - theWeightExponent ( weightExp ), theCutoff(cutoff), - theNoWeightsAbove ( no_w_a ) -{ - assert ( theFraction > 0. && theFraction < 1. ); +FsmwModeFinder3d::FsmwModeFinder3d(float fraction, float weightExp, float cutoff, int no_w_a) + : theFraction(fraction), theWeightExponent(weightExp), theCutoff(cutoff), theNoWeightsAbove(no_w_a) { + assert(theFraction > 0. && theFraction < 1.); } -GlobalPoint FsmwModeFinder3d::operator() ( - const std::vector< PointAndDistance> & values ) const -{ - typedef Cluster1D SimpleCluster; - std::vector< SimpleCluster > vx, vy, vz; - vx.reserve ( values.size() - 1 ); - vy.reserve ( values.size() - 1 ); - vz.reserve ( values.size() - 1 ); - std::vector < const void * > emptyvec; - - for ( std::vector< PointAndDistance >::const_iterator i = values.begin(); - i != values.end(); ++i ) - { - float weight = 1.; - if ( static_cast( values.size() ) < theNoWeightsAbove ) - { - // compute weights if we have fewer than theNoWeightsAbove - // data points - weight = pow ( theCutoff + 10000 * i->second, theWeightExponent ); - }; - - SimpleCluster tmp_x ( Measurement1D ( i->first.x(), 1.0 ), - emptyvec, weight ); - SimpleCluster tmp_y ( Measurement1D ( i->first.y(), 1.0 ), - emptyvec, weight ); - SimpleCluster tmp_z ( Measurement1D ( i->first.z(), 1.0 ), - emptyvec, weight ); - vx.push_back ( tmp_x ); - vy.push_back ( tmp_y ); - vz.push_back ( tmp_z ); +GlobalPoint FsmwModeFinder3d::operator()(const std::vector& values) const { + typedef Cluster1D SimpleCluster; + std::vector vx, vy, vz; + vx.reserve(values.size() - 1); + vy.reserve(values.size() - 1); + vz.reserve(values.size() - 1); + std::vector emptyvec; + + for (std::vector::const_iterator i = values.begin(); i != values.end(); ++i) { + float weight = 1.; + if (static_cast(values.size()) < theNoWeightsAbove) { + // compute weights if we have fewer than theNoWeightsAbove + // data points + weight = pow(theCutoff + 10000 * i->second, theWeightExponent); }; - FsmwClusterizer1D algo( theFraction ); - std::vector < SimpleCluster > cresx = algo(vx).first; - std::vector < SimpleCluster > cresy = algo(vy).first; - std::vector < SimpleCluster > cresz = algo(vz).first; - assert ( !cresx.empty() && !cresy.empty() && !cresz.empty() ); - - GlobalPoint ret ( cresx.begin()->position().value(), - cresy.begin()->position().value(), - cresz.begin()->position().value() ); - return ret; + SimpleCluster tmp_x(Measurement1D(i->first.x(), 1.0), emptyvec, weight); + SimpleCluster tmp_y(Measurement1D(i->first.y(), 1.0), emptyvec, weight); + SimpleCluster tmp_z(Measurement1D(i->first.z(), 1.0), emptyvec, weight); + vx.push_back(tmp_x); + vy.push_back(tmp_y); + vz.push_back(tmp_z); + }; + + FsmwClusterizer1D algo(theFraction); + std::vector cresx = algo(vx).first; + std::vector cresy = algo(vy).first; + std::vector cresz = algo(vz).first; + assert(!cresx.empty() && !cresy.empty() && !cresz.empty()); + + GlobalPoint ret( + cresx.begin()->position().value(), cresy.begin()->position().value(), cresz.begin()->position().value()); + return ret; } -FsmwModeFinder3d * FsmwModeFinder3d::clone() const -{ - return new FsmwModeFinder3d( *this ); -} - - +FsmwModeFinder3d* FsmwModeFinder3d::clone() const { return new FsmwModeFinder3d(*this); } diff --git a/RecoVertex/VertexTools/src/GeometricAnnealing.cc b/RecoVertex/VertexTools/src/GeometricAnnealing.cc index 809a72b03d4ec..b73f242bdaa46 100644 --- a/RecoVertex/VertexTools/src/GeometricAnnealing.cc +++ b/RecoVertex/VertexTools/src/GeometricAnnealing.cc @@ -4,61 +4,39 @@ #include #include -GeometricAnnealing::GeometricAnnealing ( - const double cutoff, const double T, const double ratio ) : - theT0(T), theT(T), theChi2cut(cutoff*cutoff), theRatio( ratio ) -{} - -void GeometricAnnealing::anneal() -{ - theT=1+(theT-1)*theRatio; -} - -double GeometricAnnealing::weight ( double chi2 ) const -{ - double mphi = phi ( chi2 ); - long double newtmp = mphi / ( mphi + phi ( theChi2cut ) ); - if ( edm::isNotFinite(newtmp) ) - { - if ( chi2 < theChi2cut ) newtmp=1.; - else newtmp=0.; +GeometricAnnealing::GeometricAnnealing(const double cutoff, const double T, const double ratio) + : theT0(T), theT(T), theChi2cut(cutoff * cutoff), theRatio(ratio) {} + +void GeometricAnnealing::anneal() { theT = 1 + (theT - 1) * theRatio; } + +double GeometricAnnealing::weight(double chi2) const { + double mphi = phi(chi2); + long double newtmp = mphi / (mphi + phi(theChi2cut)); + if (edm::isNotFinite(newtmp)) { + if (chi2 < theChi2cut) + newtmp = 1.; + else + newtmp = 0.; } return newtmp; } -void GeometricAnnealing::resetAnnealing() -{ - theT=theT0; -} +void GeometricAnnealing::resetAnnealing() { theT = theT0; } -double GeometricAnnealing::phi( double chi2 ) const -{ - return exp ( -.5 * chi2 / theT ); -} +double GeometricAnnealing::phi(double chi2) const { return exp(-.5 * chi2 / theT); } -double GeometricAnnealing::cutoff() const -{ +double GeometricAnnealing::cutoff() const { // std::cout << "[GeometricAnnealing] cutoff called!" << std::endl; return sqrt(theChi2cut); } -double GeometricAnnealing::currentTemp() const -{ - return theT; -} +double GeometricAnnealing::currentTemp() const { return theT; } -double GeometricAnnealing::initialTemp() const -{ - return theT0; -} +double GeometricAnnealing::initialTemp() const { return theT0; } -bool GeometricAnnealing::isAnnealed() const -{ - return ( theT < 1.02 ); -} +bool GeometricAnnealing::isAnnealed() const { return (theT < 1.02); } -void GeometricAnnealing::debug() const -{ - std::cout << "[GeometricAnnealing] chi2_cut=" << theChi2cut << ", Tini=" - << theT0 << ", ratio=" << theRatio << std::endl; +void GeometricAnnealing::debug() const { + std::cout << "[GeometricAnnealing] chi2_cut=" << theChi2cut << ", Tini=" << theT0 << ", ratio=" << theRatio + << std::endl; } diff --git a/RecoVertex/VertexTools/src/HsmModeFinder3d.cc b/RecoVertex/VertexTools/src/HsmModeFinder3d.cc index 6d6e7713366d4..1ed74265603fa 100644 --- a/RecoVertex/VertexTools/src/HsmModeFinder3d.cc +++ b/RecoVertex/VertexTools/src/HsmModeFinder3d.cc @@ -4,18 +4,12 @@ /** Half sample mode in 3d, as a functional class. */ -GlobalPoint HsmModeFinder3d::operator() ( const std::vector< PointAndDistance> & values ) const -{ - std::vector < GlobalPoint > v; - for ( std::vector< PointAndDistance >::const_iterator i=values.begin(); - i!=values.end() ; ++i ) - { - v.push_back ( i->first ); +GlobalPoint HsmModeFinder3d::operator()(const std::vector& values) const { + std::vector v; + for (std::vector::const_iterator i = values.begin(); i != values.end(); ++i) { + v.push_back(i->first); }; - return hsm_3d ( v ); + return hsm_3d(v); } -HsmModeFinder3d * HsmModeFinder3d::clone() const -{ - return new HsmModeFinder3d ( * this ); -} +HsmModeFinder3d* HsmModeFinder3d::clone() const { return new HsmModeFinder3d(*this); } diff --git a/RecoVertex/VertexTools/src/InvariantMassFromVertex.cc b/RecoVertex/VertexTools/src/InvariantMassFromVertex.cc index ef263b652f796..6e70b2ea61ec1 100644 --- a/RecoVertex/VertexTools/src/InvariantMassFromVertex.cc +++ b/RecoVertex/VertexTools/src/InvariantMassFromVertex.cc @@ -1,105 +1,86 @@ #include "RecoVertex/VertexTools/interface/InvariantMassFromVertex.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" - -InvariantMassFromVertex::LorentzVector InvariantMassFromVertex::p4 (const CachingVertex<5>& vertex, - const double mass) const -{ +InvariantMassFromVertex::LorentzVector InvariantMassFromVertex::p4(const CachingVertex<5>& vertex, + const double mass) const { return p4(vertex, std::vector(vertex.tracks().size(), mass)); } -InvariantMassFromVertex::LorentzVector InvariantMassFromVertex::p4 (const CachingVertex<5>& vertex, - const std::vector & masses) const -{ - +InvariantMassFromVertex::LorentzVector InvariantMassFromVertex::p4(const CachingVertex<5>& vertex, + const std::vector& masses) const { LorentzVector totalP4; // Check that tkToTkCovarianceIsAvailable if (!vertex.tkToTkCovarianceIsAvailable()) { - LogDebug("InvariantMassFromVertex") - << "Fit failed: vertex has not been smoothed\n"; + LogDebug("InvariantMassFromVertex") << "Fit failed: vertex has not been smoothed\n"; return totalP4; } if (vertex.tracks().size() != masses.size()) { - LogDebug("InvariantMassFromVertex") - << "Vector of masses does not have the same size as tracks in vertex\n"; + LogDebug("InvariantMassFromVertex") << "Vector of masses does not have the same size as tracks in vertex\n"; return totalP4; } - std::vector refTracks = vertex.tracks(); std::vector::const_iterator i_s = refTracks.begin(); std::vector::const_iterator i_m = masses.begin(); - for( ;i_s !=refTracks.end() && i_m != masses.end(); ++i_s, ++i_m) { + for (; i_s != refTracks.end() && i_m != masses.end(); ++i_s, ++i_m) { GlobalVector momentum = (**i_s).refittedState()->freeTrajectoryState().momentum(); totalP4 += LorentzVector(momentum.x(), momentum.y(), momentum.z(), *i_m); - } + } return totalP4; } -GlobalVector InvariantMassFromVertex::momentum(const CachingVertex<5>& vertex) const -{ - GlobalVector momentum_; +GlobalVector InvariantMassFromVertex::momentum(const CachingVertex<5>& vertex) const { + GlobalVector momentum_; // Check that tkToTkCovarianceIsAvailable if (!vertex.tkToTkCovarianceIsAvailable()) { - LogDebug("InvariantMassFromVertex") - << "Fit failed: vertex has not been smoothed\n"; - return momentum_; + LogDebug("InvariantMassFromVertex") << "Fit failed: vertex has not been smoothed\n"; + return momentum_; } std::vector refTracks = vertex.tracks(); std::vector::const_iterator i_s = refTracks.begin(); - for( ;i_s !=refTracks.end() ; ++i_s) { + for (; i_s != refTracks.end(); ++i_s) { momentum_ += (**i_s).refittedState()->freeTrajectoryState().momentum(); - } + } return momentum_; - } - -Measurement1D InvariantMassFromVertex::invariantMass(const CachingVertex<5>& vertex, - const double mass) const -{ +Measurement1D InvariantMassFromVertex::invariantMass(const CachingVertex<5>& vertex, const double mass) const { return invariantMass(vertex, std::vector(vertex.tracks().size(), mass)); } - Measurement1D InvariantMassFromVertex::invariantMass(const CachingVertex<5>& vertex, - const std::vector & masses) const -{ - + const std::vector& masses) const { // Check that tkToTkCovarianceIsAvailable if (!vertex.tkToTkCovarianceIsAvailable()) { - LogDebug("InvariantMassFromVertex") - << "Fit failed: vertex has not been smoothed\n"; - return Measurement1D(0.,0.); + LogDebug("InvariantMassFromVertex") << "Fit failed: vertex has not been smoothed\n"; + return Measurement1D(0., 0.); } if (vertex.tracks().size() != masses.size()) { - LogDebug("InvariantMassFromVertex") - << "Vector of masses does not have the same size as tracks in vertex\n"; - return Measurement1D(0.,0.); + LogDebug("InvariantMassFromVertex") << "Vector of masses does not have the same size as tracks in vertex\n"; + return Measurement1D(0., 0.); } LorentzVector totalP4 = p4(vertex, masses); double u = uncertainty(totalP4, vertex, masses); // std::cout << u<& vertex, const std::vector & masses) const -{ +double InvariantMassFromVertex::uncertainty(const LorentzVector& totalP4, + const CachingVertex<5>& vertex, + const std::vector& masses) const { std::vector refTracks = vertex.tracks(); int size = refTracks.size(); - AlgebraicMatrix cov(3*size,3*size); - AlgebraicMatrix jac(1,3*size); + AlgebraicMatrix cov(3 * size, 3 * size); + AlgebraicMatrix jac(1, 3 * size); double energy_total = totalP4.E(); @@ -107,53 +88,56 @@ double InvariantMassFromVertex::uncertainty(const LorentzVector & totalP4, std::vector::const_iterator i_m = masses.begin(); int i_int = 0; - for( ;rt_i !=refTracks.end() && i_m != masses.end(); ++rt_i, ++i_m) { - + for (; rt_i != refTracks.end() && i_m != masses.end(); ++rt_i, ++i_m) { double a; - AlgebraicVector5 param = (**rt_i).refittedState()->parameters(); // rho, theta, phi,tr_im, z_im + AlgebraicVector5 param = (**rt_i).refittedState()->parameters(); // rho, theta, phi,tr_im, z_im double rho = param[0]; double theta = param[1]; double phi = param[2]; double mass = *i_m; - if ((**rt_i).linearizedTrack()->charge()!=0) { - a = -(**rt_i).refittedState()->freeTrajectoryState().parameters().magneticFieldInInverseGeV(vertex.position()).z() - * (**rt_i).refittedState()->freeTrajectoryState().parameters ().charge(); - if (a==0.) throw cms::Exception("InvariantMassFromVertex", "Field is 0"); + if ((**rt_i).linearizedTrack()->charge() != 0) { + a = -(**rt_i).refittedState()->freeTrajectoryState().parameters().magneticFieldInInverseGeV(vertex.position()).z() * + (**rt_i).refittedState()->freeTrajectoryState().parameters().charge(); + if (a == 0.) + throw cms::Exception("InvariantMassFromVertex", "Field is 0"); } else { a = 1; } - double energy_local = sqrt(a*a/(rho*rho)*(1+1/(tan(theta)*tan(theta))) + mass*mass); + double energy_local = sqrt(a * a / (rho * rho) * (1 + 1 / (tan(theta) * tan(theta))) + mass * mass); - jac(1,i_int*3+1) = (-(energy_total/energy_local*a*a/(rho*rho*rho*sin(theta)*sin(theta)) ) - + totalP4.X()*a/(rho*rho)*cos(phi) + totalP4.Y()*a/(rho*rho)*sin(phi) - + totalP4.Z()*a/(rho*rho*tan(theta)) )/totalP4.M(); //dm / drho + jac(1, i_int * 3 + 1) = (-(energy_total / energy_local * a * a / (rho * rho * rho * sin(theta) * sin(theta))) + + totalP4.X() * a / (rho * rho) * cos(phi) + totalP4.Y() * a / (rho * rho) * sin(phi) + + totalP4.Z() * a / (rho * rho * tan(theta))) / + totalP4.M(); //dm / drho - jac(1,i_int*3+2) = (-(energy_total/energy_local*a*a/(rho*rho*sin(theta)*sin(theta)*tan(theta)) ) - + totalP4.Z()*a/(rho*sin(theta)*sin(theta)) )/totalP4.M();//dm d theta + jac(1, i_int * 3 + 2) = + (-(energy_total / energy_local * a * a / (rho * rho * sin(theta) * sin(theta) * tan(theta))) + + totalP4.Z() * a / (rho * sin(theta) * sin(theta))) / + totalP4.M(); //dm d theta - jac(1,i_int*3+3) = ( totalP4.X()*sin(phi) - totalP4.Y()*cos(phi) )*a/(rho*totalP4.M()); //dm/dphi + jac(1, i_int * 3 + 3) = (totalP4.X() * sin(phi) - totalP4.Y() * cos(phi)) * a / (rho * totalP4.M()); //dm/dphi // momentum corellatons: diagonal elements of the matrix - cov.sub(i_int*3 + 1, i_int*3 + 1,asHepMatrix<6>((**rt_i).fullCovariance()).sub(4,6)); + cov.sub(i_int * 3 + 1, i_int * 3 + 1, asHepMatrix<6>((**rt_i).fullCovariance()).sub(4, 6)); //off diagonal elements: track momentum - track momentum corellations int j_int = 0; - for(std::vector::const_iterator rt_j = refTracks.begin(); rt_j != refTracks.end(); rt_j++) { - if(i_int < j_int) { - AlgebraicMatrix i_k_cov_m = asHepMatrix<3,3>(vertex.tkToTkCovariance((*rt_i),(*rt_j))); - cov.sub(i_int*3 + 1, j_int*3 + 1,i_k_cov_m); - cov.sub(j_int*3 + 1, i_int*3 + 1,i_k_cov_m.T()); + for (std::vector::const_iterator rt_j = refTracks.begin(); rt_j != refTracks.end(); rt_j++) { + if (i_int < j_int) { + AlgebraicMatrix i_k_cov_m = asHepMatrix<3, 3>(vertex.tkToTkCovariance((*rt_i), (*rt_j))); + cov.sub(i_int * 3 + 1, j_int * 3 + 1, i_k_cov_m); + cov.sub(j_int * 3 + 1, i_int * 3 + 1, i_k_cov_m.T()); } j_int++; } i_int++; } -// std::cout<<"jac"< & ftses ) const -{ - std::vector < reco::TransientTrack > rectracks; +GlobalPoint LinearizationPointFinder::getLinearizationPoint(const std::vector& ftses) const { + std::vector rectracks; TransientTrackFromFTSFactory factory; - for ( std::vector< FreeTrajectoryState>::const_iterator fts=ftses.begin(); - fts!=ftses.end() ; ++fts ) - rectracks.push_back ( factory.build(*fts)); + for (std::vector::const_iterator fts = ftses.begin(); fts != ftses.end(); ++fts) + rectracks.push_back(factory.build(*fts)); return getLinearizationPoint(rectracks); } diff --git a/RecoVertex/VertexTools/src/LinearizedTrackStateFactory.cc b/RecoVertex/VertexTools/src/LinearizedTrackStateFactory.cc index 976424261664a..3a2ea464f3cae 100644 --- a/RecoVertex/VertexTools/src/LinearizedTrackStateFactory.cc +++ b/RecoVertex/VertexTools/src/LinearizedTrackStateFactory.cc @@ -1,32 +1,21 @@ #include "RecoVertex/VertexTools/interface/LinearizedTrackStateFactory.h" #include "RecoVertex/VertexTools/interface/PerigeeLinearizedTrackState.h" - -LinearizedTrackStateFactory::RefCountedLinearizedTrackState -LinearizedTrackStateFactory::linearizedTrackState(const GlobalPoint & linP, - const reco::TransientTrack & track, const TrajectoryStateOnSurface& tsos) const -{ - return RefCountedLinearizedTrackState( - new PerigeeLinearizedTrackState(linP, track, tsos ) ); +LinearizedTrackStateFactory::RefCountedLinearizedTrackState LinearizedTrackStateFactory::linearizedTrackState( + const GlobalPoint& linP, const reco::TransientTrack& track, const TrajectoryStateOnSurface& tsos) const { + return RefCountedLinearizedTrackState(new PerigeeLinearizedTrackState(linP, track, tsos)); } -LinearizedTrackStateFactory::RefCountedLinearizedTrackState -LinearizedTrackStateFactory::linearizedTrackState(const GlobalPoint & linP, - const reco::TransientTrack & track) const -{ - return RefCountedLinearizedTrackState( - new PerigeeLinearizedTrackState(linP, track, track.impactPointState() ) ); +LinearizedTrackStateFactory::RefCountedLinearizedTrackState LinearizedTrackStateFactory::linearizedTrackState( + const GlobalPoint& linP, const reco::TransientTrack& track) const { + return RefCountedLinearizedTrackState(new PerigeeLinearizedTrackState(linP, track, track.impactPointState())); } - -LinearizedTrackStateFactory::RefCountedLinearizedTrackState -LinearizedTrackStateFactory::linearizedTrackState - (LinearizedTrackState<5> * lts) const -{ - return RefCountedLinearizedTrackState(lts); -} -const LinearizedTrackStateFactory * LinearizedTrackStateFactory::clone() const -{ - return new LinearizedTrackStateFactory ( *this ); +LinearizedTrackStateFactory::RefCountedLinearizedTrackState LinearizedTrackStateFactory::linearizedTrackState( + LinearizedTrackState<5>* lts) const { + return RefCountedLinearizedTrackState(lts); } +const LinearizedTrackStateFactory* LinearizedTrackStateFactory::clone() const { + return new LinearizedTrackStateFactory(*this); +} diff --git a/RecoVertex/VertexTools/src/Lms3d.cc b/RecoVertex/VertexTools/src/Lms3d.cc index 3e67d2376dde9..f9dceb817a522 100644 --- a/RecoVertex/VertexTools/src/Lms3d.cc +++ b/RecoVertex/VertexTools/src/Lms3d.cc @@ -1,6 +1,4 @@ #include "RecoVertex/VertexTools/interface/lms_3d.h" #include "RecoVertex/VertexTools/interface/Lms3d.h" -GlobalPoint Lms3d::operator() ( std::vector & values ) const { - return lms_3d ( values ); -} +GlobalPoint Lms3d::operator()(std::vector& values) const { return lms_3d(values); } diff --git a/RecoVertex/VertexTools/src/LmsModeFinder3d.cc b/RecoVertex/VertexTools/src/LmsModeFinder3d.cc index 6bf2ffa366b70..e459dd0f4f30c 100644 --- a/RecoVertex/VertexTools/src/LmsModeFinder3d.cc +++ b/RecoVertex/VertexTools/src/LmsModeFinder3d.cc @@ -1,17 +1,12 @@ #include "RecoVertex/VertexTools/interface/lms_3d.h" #include "RecoVertex/VertexTools/interface/LmsModeFinder3d.h" -GlobalPoint LmsModeFinder3d::operator() ( const std::vector & values ) const { - std::vector < GlobalPoint > v; - for ( std::vector< PointAndDistance >::const_iterator i=values.begin(); - i!=values.end() ; ++i ) - { - v.push_back ( i->first ); +GlobalPoint LmsModeFinder3d::operator()(const std::vector& values) const { + std::vector v; + for (std::vector::const_iterator i = values.begin(); i != values.end(); ++i) { + v.push_back(i->first); }; - return lms_3d ( v ); + return lms_3d(v); } -LmsModeFinder3d * LmsModeFinder3d::clone() const -{ - return new LmsModeFinder3d ( * this ); -} +LmsModeFinder3d* LmsModeFinder3d::clone() const { return new LmsModeFinder3d(*this); } diff --git a/RecoVertex/VertexTools/src/PerigeeLinearizedTrackState.cc b/RecoVertex/VertexTools/src/PerigeeLinearizedTrackState.cc index 0def8eee4b1ef..4e2eabfc5682f 100644 --- a/RecoVertex/VertexTools/src/PerigeeLinearizedTrackState.cc +++ b/RecoVertex/VertexTools/src/PerigeeLinearizedTrackState.cc @@ -5,18 +5,16 @@ #include "MagneticField/Engine/interface/MagneticField.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" +void PerigeeLinearizedTrackState::computeJacobians() const { + GlobalPoint paramPt(theLinPoint); + thePredState = builder(theTSOS, paramPt); + if + UNLIKELY(!thePredState.isValid()) return; -void PerigeeLinearizedTrackState::computeJacobians() const -{ - GlobalPoint paramPt(theLinPoint); - - thePredState = builder(theTSOS, paramPt); - if UNLIKELY(!thePredState.isValid()) return; - - double field = theTrack.field()->inInverseGeV(thePredState.theState().position()).z(); - - if ((std::abs(theCharge)<1e-5)||(fabs(field)<1.e-10)){ + double field = theTrack.field()->inInverseGeV(thePredState.theState().position()).z(); + + if ((std::abs(theCharge) < 1e-5) || (fabs(field) < 1.e-10)) { //neutral track computeNeutralJacobians(); } else { @@ -27,191 +25,164 @@ void PerigeeLinearizedTrackState::computeJacobians() const jacobiansAvailable = true; } - - -bool PerigeeLinearizedTrackState::operator ==(LinearizedTrackState<5> & other)const -{ - const PerigeeLinearizedTrackState* otherP = - dynamic_cast(&other); +bool PerigeeLinearizedTrackState::operator==(LinearizedTrackState<5>& other) const { + const PerigeeLinearizedTrackState* otherP = dynamic_cast(&other); if (otherP == nullptr) { - throw VertexException("PerigeeLinearizedTrackState: don't know how to compare myself to non-perigee track state"); + throw VertexException("PerigeeLinearizedTrackState: don't know how to compare myself to non-perigee track state"); } return (otherP->track() == theTrack); } - -bool PerigeeLinearizedTrackState::operator ==(ReferenceCountingPointer >& other)const -{ - const PerigeeLinearizedTrackState* otherP = - dynamic_cast(other.get()); +bool PerigeeLinearizedTrackState::operator==(ReferenceCountingPointer >& other) const { + const PerigeeLinearizedTrackState* otherP = dynamic_cast(other.get()); if (otherP == nullptr) { - throw VertexException("PerigeeLinearizedTrackState: don't know how to compare myself to non-perigee track state"); + throw VertexException("PerigeeLinearizedTrackState: don't know how to compare myself to non-perigee track state"); } return (otherP->track() == theTrack); } - -PerigeeLinearizedTrackState::RefCountedLinearizedTrackState -PerigeeLinearizedTrackState::stateWithNewLinearizationPoint - (const GlobalPoint & newLP) const -{ - return RefCountedLinearizedTrackState( - new PerigeeLinearizedTrackState(newLP, track(), theTSOS)); +PerigeeLinearizedTrackState::RefCountedLinearizedTrackState PerigeeLinearizedTrackState::stateWithNewLinearizationPoint( + const GlobalPoint& newLP) const { + return RefCountedLinearizedTrackState(new PerigeeLinearizedTrackState(newLP, track(), theTSOS)); } -PerigeeLinearizedTrackState::RefCountedRefittedTrackState -PerigeeLinearizedTrackState::createRefittedTrackState( - const GlobalPoint & vertexPosition, - const AlgebraicVector3 & vectorParameters, - const AlgebraicSymMatrix66 & covarianceMatrix) const -{ - TrajectoryStateClosestToPoint refittedTSCP = - PerigeeConversions::trajectoryStateClosestToPoint( - vectorParameters, vertexPosition, charge(), covarianceMatrix, theTrack.field()); +PerigeeLinearizedTrackState::RefCountedRefittedTrackState PerigeeLinearizedTrackState::createRefittedTrackState( + const GlobalPoint& vertexPosition, + const AlgebraicVector3& vectorParameters, + const AlgebraicSymMatrix66& covarianceMatrix) const { + TrajectoryStateClosestToPoint refittedTSCP = PerigeeConversions::trajectoryStateClosestToPoint( + vectorParameters, vertexPosition, charge(), covarianceMatrix, theTrack.field()); return RefCountedRefittedTrackState(new PerigeeRefittedTrackState(refittedTSCP, vectorParameters)); } -std::vector< PerigeeLinearizedTrackState::RefCountedLinearizedTrackState > -PerigeeLinearizedTrackState::components() const -{ - std::vector result; result.reserve(1); - result.push_back(RefCountedLinearizedTrackState( - const_cast(this))); +std::vector PerigeeLinearizedTrackState::components() + const { + std::vector result; + result.reserve(1); + result.push_back(RefCountedLinearizedTrackState(const_cast(this))); return result; } - AlgebraicVector5 PerigeeLinearizedTrackState::refittedParamFromEquation( - const RefCountedRefittedTrackState & theRefittedState) const -{ + const RefCountedRefittedTrackState& theRefittedState) const { auto p = theRefittedState->position(); - AlgebraicVector3 vertexPosition(p.x(),p.y(),p.z()); + AlgebraicVector3 vertexPosition(p.x(), p.y(), p.z()); AlgebraicVector3 momentum = theRefittedState->momentumVector(); - if ((momentum(2)*predictedStateMomentumParameters()(2) < 0)&&(fabs(momentum(2))>M_PI/2) ) { - if (predictedStateMomentumParameters()(2) < 0.) momentum(2)-= 2*M_PI; - if (predictedStateMomentumParameters()(2) > 0.) momentum(2)+= 2*M_PI; + if ((momentum(2) * predictedStateMomentumParameters()(2) < 0) && (fabs(momentum(2)) > M_PI / 2)) { + if (predictedStateMomentumParameters()(2) < 0.) + momentum(2) -= 2 * M_PI; + if (predictedStateMomentumParameters()(2) > 0.) + momentum(2) += 2 * M_PI; } - AlgebraicVectorN param = constantTerm() + - positionJacobian() * vertexPosition + - momentumJacobian() * momentum; - if (param(2) > M_PI) param(2)-= 2*M_PI; - if (param(2) < -M_PI) param(2)+= 2*M_PI; + AlgebraicVectorN param = constantTerm() + positionJacobian() * vertexPosition + momentumJacobian() * momentum; + if (param(2) > M_PI) + param(2) -= 2 * M_PI; + if (param(2) < -M_PI) + param(2) += 2 * M_PI; return param; } - -void PerigeeLinearizedTrackState::checkParameters(AlgebraicVector5 & parameters) const -{ - if (parameters(2) > M_PI) parameters(2)-= 2*M_PI; - if (parameters(2) < -M_PI) parameters(2)+= 2*M_PI; +void PerigeeLinearizedTrackState::checkParameters(AlgebraicVector5& parameters) const { + if (parameters(2) > M_PI) + parameters(2) -= 2 * M_PI; + if (parameters(2) < -M_PI) + parameters(2) += 2 * M_PI; } -void PerigeeLinearizedTrackState::computeChargedJacobians() const -{ +void PerigeeLinearizedTrackState::computeChargedJacobians() const { GlobalPoint paramPt(theLinPoint); //tarjectory parameters - double field = theTrack.field()->inInverseGeV(thePredState.theState().position()).z(); + double field = theTrack.field()->inInverseGeV(thePredState.theState().position()).z(); double signTC = -theCharge; - + double thetaAtEP = thePredState.perigeeParameters().theta(); - double phiAtEP = thePredState.perigeeParameters().phi(); + double phiAtEP = thePredState.perigeeParameters().phi(); double ptAtEP = thePredState.pt(); - double transverseCurvatureAtEP = field / ptAtEP*signTC; + double transverseCurvatureAtEP = field / ptAtEP * signTC; double x_v = thePredState.theState().position().x(); double y_v = thePredState.theState().position().y(); double z_v = thePredState.theState().position().z(); double X = x_v - paramPt.x() - sin(phiAtEP) / transverseCurvatureAtEP; double Y = y_v - paramPt.y() + cos(phiAtEP) / transverseCurvatureAtEP; - double SS = X*X + Y*Y; + double SS = X * X + Y * Y; double S = sqrt(SS); // The track parameters at the expansion point theExpandedParams[0] = transverseCurvatureAtEP; theExpandedParams[1] = thetaAtEP; - theExpandedParams[3] = 1/transverseCurvatureAtEP - signTC * S; + theExpandedParams[3] = 1 / transverseCurvatureAtEP - signTC * S; double phiFEP; - if (std::abs(X)>std::abs(Y)) { - double signX = (X>0.0? +1.0:-1.0); - phiFEP = -signTC * signX*acos(signTC*Y/S); + if (std::abs(X) > std::abs(Y)) { + double signX = (X > 0.0 ? +1.0 : -1.0); + phiFEP = -signTC * signX * acos(signTC * Y / S); } else { - phiFEP = asin(-signTC*X/S); - if ((signTC*Y)<0.0) + phiFEP = asin(-signTC * X / S); + if ((signTC * Y) < 0.0) phiFEP = M_PI - phiFEP; } - if (phiFEP>M_PI) phiFEP-= 2*M_PI; + if (phiFEP > M_PI) + phiFEP -= 2 * M_PI; theExpandedParams[2] = phiFEP; - theExpandedParams[4] = z_v - paramPt.z() - - (phiAtEP - theExpandedParams[2]) / tan(thetaAtEP)/transverseCurvatureAtEP; - + theExpandedParams[4] = + z_v - paramPt.z() - (phiAtEP - theExpandedParams[2]) / tan(thetaAtEP) / transverseCurvatureAtEP; + // The Jacobian: (all at the expansion point) // [i,j] // i = 0: rho , 1: theta, 2: phi_p, 3: epsilon, 4: z_p // j = 0: x_v, 1: y_v, 2: z_v - thePositionJacobian(2,0) = - Y / (SS); - thePositionJacobian(2,1) = X / (SS); - thePositionJacobian(3,0) = - signTC * X / S; - thePositionJacobian(3,1) = - signTC * Y / S; - thePositionJacobian(4,0) = thePositionJacobian(2,0)/tan(thetaAtEP)/transverseCurvatureAtEP; - thePositionJacobian(4,1) = thePositionJacobian(2,1)/tan(thetaAtEP)/transverseCurvatureAtEP; - thePositionJacobian(4,2) = 1; + thePositionJacobian(2, 0) = -Y / (SS); + thePositionJacobian(2, 1) = X / (SS); + thePositionJacobian(3, 0) = -signTC * X / S; + thePositionJacobian(3, 1) = -signTC * Y / S; + thePositionJacobian(4, 0) = thePositionJacobian(2, 0) / tan(thetaAtEP) / transverseCurvatureAtEP; + thePositionJacobian(4, 1) = thePositionJacobian(2, 1) / tan(thetaAtEP) / transverseCurvatureAtEP; + thePositionJacobian(4, 2) = 1; // [i,j] // i = 0: rho , 1: theta, 2: phi_p, 3: epsilon, 4: z_p // j = 0: rho, 1: theta, 2: phi_v - theMomentumJacobian(0,0) = 1; - theMomentumJacobian(1,1) = 1; + theMomentumJacobian(0, 0) = 1; + theMomentumJacobian(1, 1) = 1; - theMomentumJacobian(2,0) = - - (X*cos(phiAtEP) + Y*sin(phiAtEP))/ - (SS*transverseCurvatureAtEP*transverseCurvatureAtEP); + theMomentumJacobian(2, 0) = + -(X * cos(phiAtEP) + Y * sin(phiAtEP)) / (SS * transverseCurvatureAtEP * transverseCurvatureAtEP); - theMomentumJacobian(2,2) = (Y*cos(phiAtEP) - X*sin(phiAtEP)) / - (SS*transverseCurvatureAtEP); + theMomentumJacobian(2, 2) = (Y * cos(phiAtEP) - X * sin(phiAtEP)) / (SS * transverseCurvatureAtEP); - theMomentumJacobian(3,0) = - (signTC * (Y*cos(phiAtEP) - X*sin(phiAtEP)) / S - 1)/ - (transverseCurvatureAtEP*transverseCurvatureAtEP); - - theMomentumJacobian(3,2) = signTC *(X*cos(phiAtEP) + Y*sin(phiAtEP))/ - (S*transverseCurvatureAtEP); - - theMomentumJacobian(4,0) = (phiAtEP - theExpandedParams[2]) / - tan(thetaAtEP)/(transverseCurvatureAtEP*transverseCurvatureAtEP)+ - theMomentumJacobian(2,0) / tan(thetaAtEP)/transverseCurvatureAtEP; + theMomentumJacobian(3, 0) = + (signTC * (Y * cos(phiAtEP) - X * sin(phiAtEP)) / S - 1) / (transverseCurvatureAtEP * transverseCurvatureAtEP); - theMomentumJacobian(4,1) = (phiAtEP - theExpandedParams[2]) * - (1 + 1/(tan(thetaAtEP)*tan(thetaAtEP)))/transverseCurvatureAtEP; + theMomentumJacobian(3, 2) = signTC * (X * cos(phiAtEP) + Y * sin(phiAtEP)) / (S * transverseCurvatureAtEP); - theMomentumJacobian(4,2) = (theMomentumJacobian(2,2) - 1) / - tan(thetaAtEP)/transverseCurvatureAtEP; + theMomentumJacobian(4, 0) = + (phiAtEP - theExpandedParams[2]) / tan(thetaAtEP) / (transverseCurvatureAtEP * transverseCurvatureAtEP) + + theMomentumJacobian(2, 0) / tan(thetaAtEP) / transverseCurvatureAtEP; - // And finally the residuals: - - auto p = thePredState.theState().position(); - AlgebraicVector3 expansionPoint(p.x(),p.y(),p.z()); - AlgebraicVector3 momentumAtExpansionPoint( transverseCurvatureAtEP,thetaAtEP,phiAtEP); - - theConstantTerm = AlgebraicVector5( theExpandedParams - - thePositionJacobian * expansionPoint - - theMomentumJacobian * momentumAtExpansionPoint ); - -} + theMomentumJacobian(4, 1) = + (phiAtEP - theExpandedParams[2]) * (1 + 1 / (tan(thetaAtEP) * tan(thetaAtEP))) / transverseCurvatureAtEP; + theMomentumJacobian(4, 2) = (theMomentumJacobian(2, 2) - 1) / tan(thetaAtEP) / transverseCurvatureAtEP; + // And finally the residuals: + auto p = thePredState.theState().position(); + AlgebraicVector3 expansionPoint(p.x(), p.y(), p.z()); + AlgebraicVector3 momentumAtExpansionPoint(transverseCurvatureAtEP, thetaAtEP, phiAtEP); + theConstantTerm = AlgebraicVector5(theExpandedParams - thePositionJacobian * expansionPoint - + theMomentumJacobian * momentumAtExpansionPoint); +} -void PerigeeLinearizedTrackState::computeNeutralJacobians() const -{ +void PerigeeLinearizedTrackState::computeNeutralJacobians() const { GlobalPoint paramPt(theLinPoint); //tarjectory parameters double thetaAtEP = thePredState.theState().momentum().theta(); - double phiAtEP = thePredState.theState().momentum().phi(); + double phiAtEP = thePredState.theState().momentum().phi(); double ptAtEP = thePredState.theState().momentum().perp(); double x_v = thePredState.theState().position().x(); @@ -225,45 +196,40 @@ void PerigeeLinearizedTrackState::computeNeutralJacobians() const theExpandedParams(0) = 1 / ptAtEP; theExpandedParams(1) = thetaAtEP; theExpandedParams(2) = phiAtEP; - theExpandedParams(3) = X*sin(phiAtEP) - Y*cos(phiAtEP); - theExpandedParams(4) = z_v - paramPt.z() - - (X*cos(phiAtEP) + Y*sin(phiAtEP)) / tan(thetaAtEP); + theExpandedParams(3) = X * sin(phiAtEP) - Y * cos(phiAtEP); + theExpandedParams(4) = z_v - paramPt.z() - (X * cos(phiAtEP) + Y * sin(phiAtEP)) / tan(thetaAtEP); // The Jacobian: (all at the expansion point) // [i,j] // i = 0: rho = 1/pt , 1: theta, 2: phi_p, 3: epsilon, 4: z_p // j = 0: x_v, 1: y_v, 2: z_v - thePositionJacobian(3,0) = sin(phiAtEP); - thePositionJacobian(3,1) = - cos(phiAtEP); - thePositionJacobian(4,0) = - cos(phiAtEP)/tan(thetaAtEP); - thePositionJacobian(4,1) = - sin(phiAtEP)/tan(thetaAtEP); - thePositionJacobian(4,2) = 1; + thePositionJacobian(3, 0) = sin(phiAtEP); + thePositionJacobian(3, 1) = -cos(phiAtEP); + thePositionJacobian(4, 0) = -cos(phiAtEP) / tan(thetaAtEP); + thePositionJacobian(4, 1) = -sin(phiAtEP) / tan(thetaAtEP); + thePositionJacobian(4, 2) = 1; // [i,j] // i = 0: rho = 1/pt , 1: theta, 2: phi_p, 3: epsilon, 4: z_p // j = 0: rho = 1/pt , 1: theta, 2: phi_v - theMomentumJacobian(0,0) = 1; - theMomentumJacobian(1,1) = 1; - theMomentumJacobian(2,2) = 1; + theMomentumJacobian(0, 0) = 1; + theMomentumJacobian(1, 1) = 1; + theMomentumJacobian(2, 2) = 1; - theMomentumJacobian(3,2) = X*cos(phiAtEP) + Y*sin(phiAtEP); - - theMomentumJacobian(4,1) = theMomentumJacobian(3,2)* - (1 + 1/(tan(thetaAtEP)*tan(thetaAtEP))); + theMomentumJacobian(3, 2) = X * cos(phiAtEP) + Y * sin(phiAtEP); - theMomentumJacobian(4,2) = (X*sin(phiAtEP) - Y*cos(phiAtEP))/tan(thetaAtEP); + theMomentumJacobian(4, 1) = theMomentumJacobian(3, 2) * (1 + 1 / (tan(thetaAtEP) * tan(thetaAtEP))); - // And finally the residuals: + theMomentumJacobian(4, 2) = (X * sin(phiAtEP) - Y * cos(phiAtEP)) / tan(thetaAtEP); - auto p = thePredState.theState().position(); - AlgebraicVector3 expansionPoint(p.x(),p.y(),p.z()); - AlgebraicVector3 momentumAtExpansionPoint(1./ptAtEP,thetaAtEP,phiAtEP); + // And finally the residuals: - theConstantTerm = AlgebraicVector5( theExpandedParams - - thePositionJacobian * expansionPoint - - theMomentumJacobian * momentumAtExpansionPoint ); + auto p = thePredState.theState().position(); + AlgebraicVector3 expansionPoint(p.x(), p.y(), p.z()); + AlgebraicVector3 momentumAtExpansionPoint(1. / ptAtEP, thetaAtEP, phiAtEP); + theConstantTerm = AlgebraicVector5(theExpandedParams - thePositionJacobian * expansionPoint - + theMomentumJacobian * momentumAtExpansionPoint); } - diff --git a/RecoVertex/VertexTools/src/PerigeeRefittedTrackState.cc b/RecoVertex/VertexTools/src/PerigeeRefittedTrackState.cc index 9e493b984fe1b..b5ca85e7d51b1 100644 --- a/RecoVertex/VertexTools/src/PerigeeRefittedTrackState.cc +++ b/RecoVertex/VertexTools/src/PerigeeRefittedTrackState.cc @@ -5,50 +5,36 @@ #include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" #include "TrackingTools/TransientTrack/interface/TransientTrackFromFTSFactory.h" -AlgebraicVector3 PerigeeRefittedTrackState::momentumVector() const -{ - return momentumAtVertex; -} +AlgebraicVector3 PerigeeRefittedTrackState::momentumVector() const { return momentumAtVertex; } -std::vector< PerigeeRefittedTrackState::RefCountedRefittedTrackState > -PerigeeRefittedTrackState::components() const -{ - std::vector result; result.reserve(1); - result.push_back(RefCountedRefittedTrackState( - const_cast(this))); +std::vector PerigeeRefittedTrackState::components() const { + std::vector result; + result.reserve(1); + result.push_back(RefCountedRefittedTrackState(const_cast(this))); return result; } -PerigeeRefittedTrackState::RefCountedRefittedTrackState -PerigeeRefittedTrackState::stateWithNewWeight (const double newWeight) const -{ - return RefCountedRefittedTrackState( - new PerigeeRefittedTrackState(theState, momentumAtVertex, newWeight) ); +PerigeeRefittedTrackState::RefCountedRefittedTrackState PerigeeRefittedTrackState::stateWithNewWeight( + const double newWeight) const { + return RefCountedRefittedTrackState(new PerigeeRefittedTrackState(theState, momentumAtVertex, newWeight)); } -TrajectoryStateOnSurface -PerigeeRefittedTrackState::trajectoryStateOnSurface(const Surface & surface) const -{ +TrajectoryStateOnSurface PerigeeRefittedTrackState::trajectoryStateOnSurface(const Surface& surface) const { AnalyticalPropagator thePropagator(&(theState.theState().parameters().magneticField()), anyDirection); TrajectoryStateOnSurface tsos = thePropagator.propagate(freeTrajectoryState(), surface); - return TrajectoryStateOnSurface (weight(), tsos.globalParameters(), - tsos.curvilinearError(), surface) ; -} + return TrajectoryStateOnSurface(weight(), tsos.globalParameters(), tsos.curvilinearError(), surface); +} -TrajectoryStateOnSurface -PerigeeRefittedTrackState::trajectoryStateOnSurface(const Surface & surface, - const Propagator & propagator) const -{ - std::unique_ptr thePropagator( propagator.clone()); +TrajectoryStateOnSurface PerigeeRefittedTrackState::trajectoryStateOnSurface(const Surface& surface, + const Propagator& propagator) const { + std::unique_ptr thePropagator(propagator.clone()); thePropagator->setPropagationDirection(anyDirection); TrajectoryStateOnSurface tsos = thePropagator->propagate(freeTrajectoryState(), surface); - return TrajectoryStateOnSurface (weight(), tsos.globalParameters(), - tsos.curvilinearError(), surface) ; + return TrajectoryStateOnSurface(weight(), tsos.globalParameters(), tsos.curvilinearError(), surface); } -reco::TransientTrack PerigeeRefittedTrackState::transientTrack() const -{ +reco::TransientTrack PerigeeRefittedTrackState::transientTrack() const { TransientTrackFromFTSFactory factory; return factory.build(freeTrajectoryState()); } diff --git a/RecoVertex/VertexTools/src/SMS.cc b/RecoVertex/VertexTools/src/SMS.cc index 4655b842f4a17..3d8c6f25ee7d7 100644 --- a/RecoVertex/VertexTools/src/SMS.cc +++ b/RecoVertex/VertexTools/src/SMS.cc @@ -9,101 +9,78 @@ using namespace std; namespace { + typedef std::pair MyPair; + typedef std::pair FloatPair; + typedef std::pair GlPtWt; + typedef std::pair MyPairWt; - typedef std::pair < float, const GlobalPoint * > MyPair; - typedef std::pair < float, float > FloatPair; - typedef std::pair < GlobalPoint, float > GlPtWt; - typedef std::pair < float, const GlPtWt * > MyPairWt; + struct Sorter { + bool operator()(const MyPair& pair1, const MyPair& pair2) { return (pair1.first < pair2.first); }; - struct Sorter - { - bool operator() ( const MyPair & pair1, const MyPair & pair2 ) - { - return ( pair1.first < pair2.first ); - }; - - bool operator() ( const FloatPair & pair1, const FloatPair & pair2 ) - { - return ( pair1.first < pair2.first ); - }; + bool operator()(const FloatPair& pair1, const FloatPair& pair2) { return (pair1.first < pair2.first); }; - bool operator() ( const MyPairWt & pair1, const MyPairWt & pair2 ) - { - return ( pair1.first < pair2.first ); - }; + bool operator()(const MyPairWt& pair1, const MyPairWt& pair2) { return (pair1.first < pair2.first); }; }; - bool debug() - { - return false; - } + bool debug() { return false; } - inline GlobalPoint & operator += ( GlobalPoint & a, const GlobalPoint & b ) - { - a = GlobalPoint ( a.x() + b.x(), a.y() + b.y(), a.z() + b.z() ); + inline GlobalPoint& operator+=(GlobalPoint& a, const GlobalPoint& b) { + a = GlobalPoint(a.x() + b.x(), a.y() + b.y(), a.z() + b.z()); return a; } - inline GlobalPoint & operator /= ( GlobalPoint & a, float b ) - { - a = GlobalPoint ( a.x() / b, a.y() / b, a.z() / b ); + inline GlobalPoint& operator/=(GlobalPoint& a, float b) { + a = GlobalPoint(a.x() / b, a.y() / b, a.z() / b); return a; } - GlobalPoint average ( const std::vector < MyPair > & pairs, int nq ) - { - GlobalPoint location(0,0,0); - for ( std::vector< MyPair >::const_iterator i=pairs.begin(); i!=( pairs.begin() + nq ); ++i ) - location+=*( i->second ); - location/=nq; + GlobalPoint average(const std::vector& pairs, int nq) { + GlobalPoint location(0, 0, 0); + for (std::vector::const_iterator i = pairs.begin(); i != (pairs.begin() + nq); ++i) + location += *(i->second); + location /= nq; return location; } - GlobalPoint average ( const std::vector < MyPairWt > & pairs, int nq ) - { - GlobalPoint location(0,0,0); - for ( std::vector< MyPairWt >::const_iterator i=pairs.begin(); i!=( pairs.begin() + nq ); ++i ) - location+=(i->second)->first; - location/=nq; + GlobalPoint average(const std::vector& pairs, int nq) { + GlobalPoint location(0, 0, 0); + for (std::vector::const_iterator i = pairs.begin(); i != (pairs.begin() + nq); ++i) + location += (i->second)->first; + location /= nq; return location; } typedef SMS::SMSType SMSType; -} - -SMS::SMS ( SMSType tp , float q ) : theType(tp) , theRatio(q) {} +} // namespace +SMS::SMS(SMSType tp, float q) : theType(tp), theRatio(q) {} -GlobalPoint SMS::location ( const std::vector & data ) const -{ - if ( theType & Weighted ) - { +GlobalPoint SMS::location(const std::vector& data) const { + if (theType & Weighted) { std::cout << "[SMS] warning: Weighted SMS was asked for, but data are " << "weightless!" << std::endl; }; - int nobs=data.size(); - int nq=(int) ceil( theRatio*nobs); + int nobs = data.size(); + int nq = (int)ceil(theRatio * nobs); // cout << "nobs= " << nobs << " nq= " << nq << endl; // Compute distances std::vector pairs; - for ( std::vector< GlobalPoint >::const_iterator i=data.begin(); i!=data.end() ; ++i ) - { - std::vector < float > D; + for (std::vector::const_iterator i = data.begin(); i != data.end(); ++i) { + std::vector D; // Compute squared distances to all points - for ( std::vector< GlobalPoint >::const_iterator j=data.begin(); j!=data.end() ; ++j ) - { D.push_back ( (*j - *i).mag2() ); } + for (std::vector::const_iterator j = data.begin(); j != data.end(); ++j) { + D.push_back((*j - *i).mag2()); + } // Find q-quantile in each row of the distance matrix - sort( D.begin(), D.end() ); - MyPair tmp ( D[nq-1], &(*i) ); - pairs.push_back ( tmp ); + sort(D.begin(), D.end()); + MyPair tmp(D[nq - 1], &(*i)); + pairs.push_back(tmp); }; // Sort pairs by first element - sort( pairs.begin(), pairs.end(), Sorter() ); - if ( !(theType & SMS::Interpolate) && - !(theType & SMS::Iterate) ) - { + sort(pairs.begin(), pairs.end(), Sorter()); + if (!(theType & SMS::Interpolate) && !(theType & SMS::Iterate)) { // we dont interpolate, we dont iterate, so we can stop right here. // cout << "No interpolation, no iteration" << endl; return *(pairs.begin()->second); @@ -113,109 +90,95 @@ GlobalPoint SMS::location ( const std::vector & data ) const // so we stop here // cout << "nobs= " << nobs << " nq= " << nq << endl; - if (!(theType & SMS::Iterate) || nq<=2) - return average ( pairs, nq ); + if (!(theType & SMS::Iterate) || nq <= 2) + return average(pairs, nq); // we iterate (recursively) - std::vector < GlobalPoint > data1; + std::vector data1; std::vector::iterator j; - for ( j=pairs.begin(); j-pairs.begin()second)); - - return this->location( data1 ); + for (j = pairs.begin(); j - pairs.begin() < nq; ++j) + data1.push_back(*(j->second)); + return this->location(data1); } - -GlobalPoint SMS::location ( const std::vector < GlPtWt > & wdata ) const -{ - if ( !(theType & Weighted) ) - { - std::vector < GlobalPoint > points; - for ( std::vector< GlPtWt >::const_iterator i=wdata.begin(); - i!=wdata.end() ; ++i ) - { - points.push_back ( i->first ); +GlobalPoint SMS::location(const std::vector& wdata) const { + if (!(theType & Weighted)) { + std::vector points; + for (std::vector::const_iterator i = wdata.begin(); i != wdata.end(); ++i) { + points.push_back(i->first); }; - if ( debug() ) - { - std::cout << "[SMS] Unweighted SMS was asked for; ignoring the weights." - << std::endl; + if (debug()) { + std::cout << "[SMS] Unweighted SMS was asked for; ignoring the weights." << std::endl; }; - return location ( points ); + return location(points); }; // int nobs=wdata.size(); // Sum of weights - float Sumw=0; - std::vector< GlPtWt >::const_iterator i,j; - for ( i=wdata.begin() ; i!=wdata.end() ; ++i) - Sumw+=i->second; + float Sumw = 0; + std::vector::const_iterator i, j; + for (i = wdata.begin(); i != wdata.end(); ++i) + Sumw += i->second; // Compute pairwise distances - std::vector pairs; - for ( i=wdata.begin(); i!=wdata.end() ; ++i ) - { - std::vector < FloatPair > D; + std::vector pairs; + for (i = wdata.begin(); i != wdata.end(); ++i) { + std::vector D; // Compute squared distances to all points - for ( j=wdata.begin(); j!=wdata.end() ; ++j ) - D.push_back ( FloatPair( (j->first - i->first).mag2() , j->second ) ) ; + for (j = wdata.begin(); j != wdata.end(); ++j) + D.push_back(FloatPair((j->first - i->first).mag2(), j->second)); // Find weighted q-quantile in the distance vector - sort( D.begin(), D.end() ); - float sumw=0; - std::vector< FloatPair >::const_iterator where; - for ( where=D.begin(); where!=D.end(); ++where ) - { - sumw+=where->second; + sort(D.begin(), D.end()); + float sumw = 0; + std::vector::const_iterator where; + for (where = D.begin(); where != D.end(); ++where) { + sumw += where->second; // cout << sumw << endl; - if (sumw>Sumw*theRatio) break; + if (sumw > Sumw * theRatio) + break; } - MyPairWt tmp ( where->first, &(*i) ); - pairs.push_back ( tmp ); + MyPairWt tmp(where->first, &(*i)); + pairs.push_back(tmp); // cout << where->first << endl; }; // Sort pairs by first element - sort( pairs.begin(), pairs.end(), Sorter() ); + sort(pairs.begin(), pairs.end(), Sorter()); // Find weighted q-quantile in the list of pairs - float sumw=0; - int nq=0; - std::vector < MyPairWt >::const_iterator k; - for (k=pairs.begin(); k!=pairs.end(); ++k ) - { - sumw+=k->second->second; + float sumw = 0; + int nq = 0; + std::vector::const_iterator k; + for (k = pairs.begin(); k != pairs.end(); ++k) { + sumw += k->second->second; ++nq; - if (sumw>Sumw*theRatio) break; + if (sumw > Sumw * theRatio) + break; } // cout << "nobs= " << nobs << " nq= " << nq << endl; - if ( !(theType & SMS::Interpolate) && - !(theType & SMS::Iterate) ) - { + if (!(theType & SMS::Interpolate) && !(theType & SMS::Iterate)) { // we dont interpolate, we dont iterate, so we can stop right here. // cout << "No interpolation, no iteration" << endl; return pairs.begin()->second->first; }; - - - // we dont iterate, or we dont have anything to iterate (anymore?) // so we stop here // cout << "nobs= " << nobs << " nq= " << nq << endl; - if (!(theType & SMS::Iterate) || nq<=2) return average ( pairs, nq ); + if (!(theType & SMS::Iterate) || nq <= 2) + return average(pairs, nq); // we iterate (recursively) std::vector wdata1; - for ( k=pairs.begin(); k-pairs.begin()second)); - return this->location( wdata1 ); - + return this->location(wdata1); } diff --git a/RecoVertex/VertexTools/src/SequentialVertexFitter.cc b/RecoVertex/VertexTools/src/SequentialVertexFitter.cc index 75a9fc9e4bf3f..547f001230a8c 100644 --- a/RecoVertex/VertexTools/src/SequentialVertexFitter.cc +++ b/RecoVertex/VertexTools/src/SequentialVertexFitter.cc @@ -13,39 +13,38 @@ namespace { const float TrackerBoundsRadius = 112; const float TrackerBoundsHalfLength = 273.5; bool insideTrackerBounds(const GlobalPoint& point) { - return ((point.transverse() < TrackerBoundsRadius) - && (abs(point.z()) < TrackerBoundsHalfLength)); + return ((point.transverse() < TrackerBoundsRadius) && (abs(point.z()) < TrackerBoundsHalfLength)); } -} - +} // namespace template -SequentialVertexFitter::SequentialVertexFitter( - const LinearizationPointFinder & linP, - const VertexUpdator & updator, const VertexSmoother & smoother, - const AbstractLTSFactory & ltsf ) : - theLinP(linP.clone()), theUpdator(updator.clone()), - theSmoother(smoother.clone()), theLTrackFactory ( ltsf.clone() ) -{ +SequentialVertexFitter::SequentialVertexFitter(const LinearizationPointFinder& linP, + const VertexUpdator& updator, + const VertexSmoother& smoother, + const AbstractLTSFactory& ltsf) + : theLinP(linP.clone()), + theUpdator(updator.clone()), + theSmoother(smoother.clone()), + theLTrackFactory(ltsf.clone()) { setDefaultParameters(); } template -SequentialVertexFitter::SequentialVertexFitter( - const edm::ParameterSet& pSet, const LinearizationPointFinder & linP, - const VertexUpdator & updator, const VertexSmoother & smoother, - const AbstractLTSFactory & ltsf) : - thePSet(pSet), theLinP(linP.clone()), theUpdator(updator.clone()), - theSmoother(smoother.clone()), theLTrackFactory ( ltsf.clone() ) -{ +SequentialVertexFitter::SequentialVertexFitter(const edm::ParameterSet& pSet, + const LinearizationPointFinder& linP, + const VertexUpdator& updator, + const VertexSmoother& smoother, + const AbstractLTSFactory& ltsf) + : thePSet(pSet), + theLinP(linP.clone()), + theUpdator(updator.clone()), + theSmoother(smoother.clone()), + theLTrackFactory(ltsf.clone()) { readParameters(); } - template -SequentialVertexFitter::SequentialVertexFitter( - const SequentialVertexFitter & original) -{ +SequentialVertexFitter::SequentialVertexFitter(const SequentialVertexFitter& original) { thePSet = original.parameterSet(); theLinP = original.linearizationPointFinder()->clone(); theUpdator = original.vertexUpdator()->clone(); @@ -55,109 +54,94 @@ SequentialVertexFitter::SequentialVertexFitter( theLTrackFactory = original.linearizedTrackStateFactory()->clone(); } - template -SequentialVertexFitter::~SequentialVertexFitter() -{ +SequentialVertexFitter::~SequentialVertexFitter() { delete theLinP; delete theUpdator; delete theSmoother; delete theLTrackFactory; } - template -void SequentialVertexFitter::readParameters() -{ - theMaxShift = thePSet.getParameter("maxDistance"); //0.01 - theMaxStep = thePSet.getParameter("maxNbrOfIterations"); //10 +void SequentialVertexFitter::readParameters() { + theMaxShift = thePSet.getParameter("maxDistance"); //0.01 + theMaxStep = thePSet.getParameter("maxNbrOfIterations"); //10 } template -void SequentialVertexFitter::setDefaultParameters() -{ +void SequentialVertexFitter::setDefaultParameters() { thePSet.addParameter("maxDistance", 0.01); - thePSet.addParameter("maxNbrOfIterations", 10); //10 + thePSet.addParameter("maxNbrOfIterations", 10); //10 readParameters(); } template -CachingVertex -SequentialVertexFitter::vertex(const std::vector & tracks) const -{ +CachingVertex SequentialVertexFitter::vertex(const std::vector& tracks) const { // Linearization Point GlobalPoint linP = theLinP->getLinearizationPoint(tracks); - if (!insideTrackerBounds(linP)) linP = GlobalPoint(0,0,0); + if (!insideTrackerBounds(linP)) + linP = GlobalPoint(0, 0, 0); // Initial vertex state, with a very large error matrix ROOT::Math::SMatrixIdentity id; AlgebraicSymMatrix33 we(id); - GlobalError error(we*10000); + GlobalError error(we * 10000); VertexState state(linP, error); std::vector vtContainer = linearizeTracks(tracks, state); return fit(vtContainer, state, false); } template -CachingVertex SequentialVertexFitter::vertex( - const std::vector & tracks, - const reco::BeamSpot & spot ) const -{ +CachingVertex SequentialVertexFitter::vertex(const std::vector& tracks, + const reco::BeamSpot& spot) const { VertexState state(spot); - return fit(tracks, state, true ); + return fit(tracks, state, true); } template -CachingVertex -SequentialVertexFitter::vertex(const std::vector & tracks) const -{ +CachingVertex SequentialVertexFitter::vertex(const std::vector& tracks) const { // Initial vertex state, with a very small weight matrix GlobalPoint linP = tracks[0]->linearizedTrack()->linearizationPoint(); ROOT::Math::SMatrixIdentity id; AlgebraicSymMatrix33 we(id); - GlobalError error(we*10000); + GlobalError error(we * 10000); VertexState state(linP, error); return fit(tracks, state, false); } - -// Fit vertex out of a set of RecTracks. +// Fit vertex out of a set of RecTracks. // Uses the specified linearization point. // template -CachingVertex -SequentialVertexFitter::vertex(const std::vector & tracks, - const GlobalPoint& linPoint) const -{ +CachingVertex SequentialVertexFitter::vertex(const std::vector& tracks, + const GlobalPoint& linPoint) const { // Initial vertex state, with a very large error matrix ROOT::Math::SMatrixIdentity id; AlgebraicSymMatrix33 we(id); - GlobalError error(we*10000); + GlobalError error(we * 10000); VertexState state(linPoint, error); std::vector vtContainer = linearizeTracks(tracks, state); return fit(vtContainer, state, false); } - - /** Fit vertex out of a set of TransientTracks. +/** Fit vertex out of a set of TransientTracks. * The specified BeamSpot will be used as priot, but NOT for the linearization. * The specified LinearizationPointFinder will be used to find the linearization point. */ template -CachingVertex -SequentialVertexFitter::vertex(const std::vector & tracks, - const BeamSpot& beamSpot) const -{ +CachingVertex SequentialVertexFitter::vertex(const std::vector& tracks, + const BeamSpot& beamSpot) const { VertexState beamSpotState(beamSpot); std::vector vtContainer; if (tracks.size() > 1) { // Linearization Point search if there are more than 1 track GlobalPoint linP = theLinP->getLinearizationPoint(tracks); - if (!insideTrackerBounds(linP)) linP = GlobalPoint(0,0,0); + if (!insideTrackerBounds(linP)) + linP = GlobalPoint(0, 0, 0); ROOT::Math::SMatrixIdentity id; AlgebraicSymMatrix33 we(id); - GlobalError error(we*10000); + GlobalError error(we * 10000); VertexState lpState(linP, error); vtContainer = linearizeTracks(tracks, lpState); } else { @@ -168,18 +152,15 @@ SequentialVertexFitter::vertex(const std::vector & trac return fit(vtContainer, beamSpotState, true); } - -// Fit vertex out of a set of RecTracks. +// Fit vertex out of a set of RecTracks. // Uses the position as both the linearization point AND as prior -// estimate of the vertex position. The error is used for the +// estimate of the vertex position. The error is used for the // weight of the prior estimate. // template -CachingVertex SequentialVertexFitter::vertex( - const std::vector & tracks, - const GlobalPoint& priorPos, - const GlobalError& priorError) const -{ +CachingVertex SequentialVertexFitter::vertex(const std::vector& tracks, + const GlobalPoint& priorPos, + const GlobalError& priorError) const { VertexState state(priorPos, priorError); std::vector vtContainer = linearizeTracks(tracks, state); return fit(vtContainer, state, true); @@ -190,82 +171,64 @@ CachingVertex SequentialVertexFitter::vertex( // This position is not used to relinearize the tracks. // template -CachingVertex SequentialVertexFitter::vertex( - const std::vector & tracks, - const GlobalPoint& priorPos, - const GlobalError& priorError) const -{ +CachingVertex SequentialVertexFitter::vertex(const std::vector& tracks, + const GlobalPoint& priorPos, + const GlobalError& priorError) const { VertexState state(priorPos, priorError); return fit(tracks, state, true); } - // Construct a container of VertexTrack from a set of RecTracks. // template -vector::RefCountedVertexTrack> -SequentialVertexFitter::linearizeTracks( - const std::vector & tracks, - const VertexState state) const -{ +vector::RefCountedVertexTrack> SequentialVertexFitter::linearizeTracks( + const std::vector& tracks, const VertexState state) const { GlobalPoint linP = state.position(); std::vector finalTracks; finalTracks.reserve(tracks.size()); - for(vector::const_iterator i = tracks.begin(); - i != tracks.end(); i++) { - RefCountedLinearizedTrackState lTrData - = theLTrackFactory->linearizedTrackState(linP, *i); - RefCountedVertexTrack vTrData = theVTrackFactory.vertexTrack(lTrData,state); + for (vector::const_iterator i = tracks.begin(); i != tracks.end(); i++) { + RefCountedLinearizedTrackState lTrData = theLTrackFactory->linearizedTrackState(linP, *i); + RefCountedVertexTrack vTrData = theVTrackFactory.vertexTrack(lTrData, state); finalTracks.push_back(vTrData); } return finalTracks; } - // Construct new a container of VertexTrack with a new linearization point -// and vertex state, from an existing set of VertexTrack, from which only the +// and vertex state, from an existing set of VertexTrack, from which only the // recTracks will be used. // template -vector::RefCountedVertexTrack> -SequentialVertexFitter::reLinearizeTracks( - const std::vector & tracks, - const VertexState state) const -{ - +vector::RefCountedVertexTrack> SequentialVertexFitter::reLinearizeTracks( + const std::vector& tracks, const VertexState state) const { GlobalPoint linP = state.position(); std::vector finalTracks; finalTracks.reserve(tracks.size()); - for(typename std::vector::const_iterator i = tracks.begin(); - i != tracks.end(); i++) { - RefCountedLinearizedTrackState lTrData = - (**i).linearizedTrack()->stateWithNewLinearizationPoint(linP); - // RefCountedLinearizedTrackState lTrData = - // theLTrackFactory->linearizedTrackState(linP, + for (typename std::vector::const_iterator i = tracks.begin(); i != tracks.end(); i++) { + RefCountedLinearizedTrackState lTrData = (**i).linearizedTrack()->stateWithNewLinearizationPoint(linP); + // RefCountedLinearizedTrackState lTrData = + // theLTrackFactory->linearizedTrackState(linP, // (**i).linearizedTrack()->track()); - RefCountedVertexTrack vTrData = - theVTrackFactory.vertexTrack(lTrData,state, (**i).weight() ); + RefCountedVertexTrack vTrData = theVTrackFactory.vertexTrack(lTrData, state, (**i).weight()); finalTracks.push_back(vTrData); } return finalTracks; } - // The method where the vertex fit is actually done! // template -CachingVertex -SequentialVertexFitter::fit(const std::vector & tracks, - const VertexState priorVertex, bool withPrior ) const -{ +CachingVertex SequentialVertexFitter::fit(const std::vector& tracks, + const VertexState priorVertex, + bool withPrior) const { std::vector initialTracks; GlobalPoint priorVertexPosition = priorVertex.position(); GlobalError priorVertexError = priorVertex.error(); - - CachingVertex returnVertex(priorVertexPosition,priorVertexError,initialTracks,0); + + CachingVertex returnVertex(priorVertexPosition, priorVertexError, initialTracks, 0); if (withPrior) { - returnVertex = CachingVertex(priorVertexPosition,priorVertexError, - priorVertexPosition,priorVertexError,initialTracks,0); + returnVertex = CachingVertex( + priorVertexPosition, priorVertexError, priorVertexPosition, priorVertexError, initialTracks, 0); } CachingVertex initialVertex = returnVertex; std::vector globalVTracks = tracks; @@ -278,38 +241,37 @@ SequentialVertexFitter::fit(const std::vector & tracks do { CachingVertex fVertex = initialVertex; // make new linearized and vertex tracks for the next iteration - if(step != 0) globalVTracks = reLinearizeTracks(tracks, - returnVertex.vertexState()); + if (step != 0) + globalVTracks = reLinearizeTracks(tracks, returnVertex.vertexState()); // update sequentially the vertex estimate - for (typename std::vector::const_iterator i - = globalVTracks.begin(); i != globalVTracks.end(); i++) { - fVertex = theUpdator->add(fVertex,*i); - if (!fVertex.isValid()) break; + for (typename std::vector::const_iterator i = globalVTracks.begin(); + i != globalVTracks.end(); + i++) { + fVertex = theUpdator->add(fVertex, *i); + if (!fVertex.isValid()) + break; } validVertex = fVertex.isValid(); // check tracker bounds and NaN in position if (validVertex && hasNan(fVertex.position())) { - LogDebug("RecoVertex/SequentialVertexFitter") - << "Fitted position is NaN.\n"; + LogDebug("RecoVertex/SequentialVertexFitter") << "Fitted position is NaN.\n"; validVertex = false; } if (validVertex && !insideTrackerBounds(fVertex.position())) { - LogDebug("RecoVertex/SequentialVertexFitter") - << "Fitted position is out of tracker bounds.\n"; + LogDebug("RecoVertex/SequentialVertexFitter") << "Fitted position is out of tracker bounds.\n"; validVertex = false; } if (!validVertex) { - // reset initial vertex position to (0,0,0) and force new iteration + // reset initial vertex position to (0,0,0) and force new iteration // if number of steps not exceeded ROOT::Math::SMatrixIdentity id; AlgebraicSymMatrix33 we(id); - GlobalError error(we*10000); - fVertex = CachingVertex(GlobalPoint(0,0,0), error, - initialTracks, 0); + GlobalError error(we * 10000); + fVertex = CachingVertex(GlobalPoint(0, 0, 0), error, initialTracks, 0); } previousPosition = newPosition; @@ -318,20 +280,18 @@ SequentialVertexFitter::fit(const std::vector & tracks returnVertex = fVertex; globalVTracks.clear(); step++; - } while ( (step != theMaxStep) && - (((previousPosition - newPosition).transverse() > theMaxShift) || - (!validVertex) ) ); + } while ((step != theMaxStep) && (((previousPosition - newPosition).transverse() > theMaxShift) || (!validVertex))); if (!validVertex) { - LogDebug("RecoVertex/SequentialVertexFitter") - << "Fitted position is invalid (out of tracker bounds or has NaN). Returned vertex is invalid\n"; - return CachingVertex(); // return invalid vertex + LogDebug("RecoVertex/SequentialVertexFitter") + << "Fitted position is invalid (out of tracker bounds or has NaN). Returned vertex is invalid\n"; + return CachingVertex(); // return invalid vertex } if (step >= theMaxStep) { - LogDebug("RecoVertex/SequentialVertexFitter") - << "The maximum number of steps has been exceeded. Returned vertex is invalid\n"; - return CachingVertex(); // return invalid vertex + LogDebug("RecoVertex/SequentialVertexFitter") + << "The maximum number of steps has been exceeded. Returned vertex is invalid\n"; + return CachingVertex(); // return invalid vertex } // smoothing diff --git a/RecoVertex/VertexTools/src/SequentialVertexSmoother.cc b/RecoVertex/VertexTools/src/SequentialVertexSmoother.cc index 6c8e0344c5357..62ebc56ffe68c 100644 --- a/RecoVertex/VertexTools/src/SequentialVertexSmoother.cc +++ b/RecoVertex/VertexTools/src/SequentialVertexSmoother.cc @@ -1,50 +1,35 @@ #include "RecoVertex/VertexTools/interface/SequentialVertexSmoother.h" - template -SequentialVertexSmoother::SequentialVertexSmoother( - const VertexTrackUpdator & vtu, - const VertexSmoothedChiSquaredEstimator & vse, - const TrackToTrackCovCalculator & covCalc) : - theVertexTrackUpdator(vtu.clone()), - theVertexSmoothedChiSquaredEstimator(vse.clone()), - theTrackToTrackCovCalculator(covCalc.clone()) -{} - +SequentialVertexSmoother::SequentialVertexSmoother(const VertexTrackUpdator& vtu, + const VertexSmoothedChiSquaredEstimator& vse, + const TrackToTrackCovCalculator& covCalc) + : theVertexTrackUpdator(vtu.clone()), + theVertexSmoothedChiSquaredEstimator(vse.clone()), + theTrackToTrackCovCalculator(covCalc.clone()) {} template -SequentialVertexSmoother::~SequentialVertexSmoother() -{ +SequentialVertexSmoother::~SequentialVertexSmoother() { delete theVertexTrackUpdator; delete theVertexSmoothedChiSquaredEstimator; delete theTrackToTrackCovCalculator; } - template -SequentialVertexSmoother::SequentialVertexSmoother( - const SequentialVertexSmoother & smoother) -{ +SequentialVertexSmoother::SequentialVertexSmoother(const SequentialVertexSmoother& smoother) { theVertexTrackUpdator = smoother.vertexTrackUpdator()->clone(); - theVertexSmoothedChiSquaredEstimator - = smoother.vertexSmoothedChiSquaredEstimator()->clone(); + theVertexSmoothedChiSquaredEstimator = smoother.vertexSmoothedChiSquaredEstimator()->clone(); theTrackToTrackCovCalculator = smoother.trackToTrackCovCalculator()->clone(); } - template -CachingVertex -SequentialVertexSmoother::smooth(const CachingVertex & vertex) const -{ - +CachingVertex SequentialVertexSmoother::smooth(const CachingVertex& vertex) const { // Track refit std::vector newTracks; if (theVertexTrackUpdator != nullptr) { - const std::vector& vOut=vertex.tracks(); - for(typename std::vector::const_iterator i = vOut.begin(); - i != vOut.end();i++) - { + const std::vector& vOut = vertex.tracks(); + for (typename std::vector::const_iterator i = vOut.begin(); i != vOut.end(); i++) { RefCountedVertexTrack nTrack = theVertexTrackUpdator->update(vertex, *i); newTracks.push_back(nTrack); } @@ -53,12 +38,10 @@ SequentialVertexSmoother::smooth(const CachingVertex & vertex) const } // intermediate vertex for chi2 calculation and TktoTkcovariance map - CachingVertex interVertex(vertex.position(), vertex.weight(), - newTracks, 0.); - if ( vertex.hasPrior() ) - { - interVertex = CachingVertex ( vertex.priorPosition(), vertex.priorError(), - vertex.position(), vertex.weight(), newTracks, 0.); + CachingVertex interVertex(vertex.position(), vertex.weight(), newTracks, 0.); + if (vertex.hasPrior()) { + interVertex = CachingVertex( + vertex.priorPosition(), vertex.priorError(), vertex.position(), vertex.weight(), newTracks, 0.); } // Smoothed chi2 @@ -70,28 +53,25 @@ SequentialVertexSmoother::smooth(const CachingVertex & vertex) const } if (theTrackToTrackCovCalculator == nullptr) { - if (vertex.hasPrior()) { - return CachingVertex(vertex.priorVertexState(), vertex.vertexState(), - newTracks, smChi2); + if (vertex.hasPrior()) { + return CachingVertex(vertex.priorVertexState(), vertex.vertexState(), newTracks, smChi2); } else { return CachingVertex(vertex.vertexState(), newTracks, smChi2); } } - + //TktoTkcovariance map typename CachingVertex::TrackToTrackMap tkMap = (*theTrackToTrackCovCalculator)(interVertex); -// CachingVertex finalVertex(vertex.position(), vertex.error(), -// newTracks, smChi2, tkMap); - if (vertex.hasPrior()) { - CachingVertex finalVertex(vertex.priorVertexState(), vertex.vertexState(), - newTracks, smChi2, tkMap); + // CachingVertex finalVertex(vertex.position(), vertex.error(), + // newTracks, smChi2, tkMap); + if (vertex.hasPrior()) { + CachingVertex finalVertex(vertex.priorVertexState(), vertex.vertexState(), newTracks, smChi2, tkMap); return finalVertex; } CachingVertex finalVertex(vertex.vertexState(), newTracks, smChi2, tkMap); return finalVertex; - } template class SequentialVertexSmoother<5>; diff --git a/RecoVertex/VertexTools/src/SharedTracks.cc b/RecoVertex/VertexTools/src/SharedTracks.cc index 4614d42734798..8425227ca7571 100644 --- a/RecoVertex/VertexTools/src/SharedTracks.cc +++ b/RecoVertex/VertexTools/src/SharedTracks.cc @@ -1,67 +1,61 @@ #include "RecoVertex/VertexTools/interface/SharedTracks.h" namespace vertexTools { - using namespace reco; - double computeSharedTracks(const Vertex &pv, const std::vector &svTracks, - double minTrackWeight, float ) - { - std::set pvTracks; - for(std::vector::const_iterator iter = pv.tracks_begin(); - iter != pv.tracks_end(); iter++) - if (pv.trackWeight(*iter) >= minTrackWeight) - pvTracks.insert(iter->castTo()); + using namespace reco; + double computeSharedTracks(const Vertex &pv, const std::vector &svTracks, double minTrackWeight, float) { + std::set pvTracks; + for (std::vector::const_iterator iter = pv.tracks_begin(); iter != pv.tracks_end(); iter++) + if (pv.trackWeight(*iter) >= minTrackWeight) + pvTracks.insert(iter->castTo()); - unsigned int count = 0; - for(std::vector::const_iterator iter = svTracks.begin(); - iter != svTracks.end(); iter++) - count += pvTracks.count(*iter); + unsigned int count = 0; + for (std::vector::const_iterator iter = svTracks.begin(); iter != svTracks.end(); iter++) + count += pvTracks.count(*iter); - return (double)count/(double)svTracks.size(); - } - double computeSharedTracks(const Vertex &pv, const std::vector &svTracks, - double minTrackWeight, float maxsigma) - { - unsigned int count = 0; - for(std::vector::const_iterator iter = svTracks.begin(); - iter != svTracks.end(); iter++) - { - if( std::abs((*iter)->bestTrack()->dz()-pv.z())/(*iter)->bestTrack()->dzError() < maxsigma && - std::abs((*iter)->bestTrack()->dxy(pv.position())/(*iter)->bestTrack()->dxyError()) < maxsigma - ) - count++; - } - return (double)count/(double)svTracks.size(); - } - double computeSharedTracks(const VertexCompositePtrCandidate &sv2, const std::vector &svTracks, double , float ) - { - unsigned int count = 0; - for(std::vector::const_iterator iter = svTracks.begin(); - iter != svTracks.end(); iter++) - { - if(std::find(sv2.daughterPtrVector().begin(),sv2.daughterPtrVector().end(),*iter)!= sv2.daughterPtrVector().end()) - count++; - } - return (double)count/(double)svTracks.size(); - } + return (double)count / (double)svTracks.size(); + } + double computeSharedTracks(const Vertex &pv, + const std::vector &svTracks, + double minTrackWeight, + float maxsigma) { + unsigned int count = 0; + for (std::vector::const_iterator iter = svTracks.begin(); iter != svTracks.end(); iter++) { + if (std::abs((*iter)->bestTrack()->dz() - pv.z()) / (*iter)->bestTrack()->dzError() < maxsigma && + std::abs((*iter)->bestTrack()->dxy(pv.position()) / (*iter)->bestTrack()->dxyError()) < maxsigma) + count++; + } + return (double)count / (double)svTracks.size(); + } + double computeSharedTracks(const VertexCompositePtrCandidate &sv2, + const std::vector &svTracks, + double, + float) { + unsigned int count = 0; + for (std::vector::const_iterator iter = svTracks.begin(); iter != svTracks.end(); iter++) { + if (std::find(sv2.daughterPtrVector().begin(), sv2.daughterPtrVector().end(), *iter) != + sv2.daughterPtrVector().end()) + count++; + } + return (double)count / (double)svTracks.size(); + } + double computeSharedTracks(const reco::Vertex &pv, + const reco::VertexCompositePtrCandidate &sv, + double minTrackWeight, + float mindist) { + return computeSharedTracks(pv, sv.daughterPtrVector(), minTrackWeight, mindist); + } + double computeSharedTracks(const reco::Vertex &pv, const reco::Vertex &sv, double minTrackWeight, float) { + std::vector svTracks; + for (std::vector::const_iterator iter = sv.tracks_begin(); iter != sv.tracks_end(); iter++) + if (sv.trackWeight(*iter) >= minTrackWeight) + svTracks.push_back(iter->castTo()); + return computeSharedTracks(pv, svTracks, minTrackWeight); + } + double computeSharedTracks(const reco::VertexCompositePtrCandidate &sv, + const reco::VertexCompositePtrCandidate &sv2, + double, + float) { + return computeSharedTracks(sv, sv2.daughterPtrVector()); + } - double computeSharedTracks(const reco::Vertex &pv, const reco::VertexCompositePtrCandidate &sv, double minTrackWeight,float mindist) - { - return computeSharedTracks(pv,sv.daughterPtrVector(),minTrackWeight,mindist); - } - double computeSharedTracks(const reco::Vertex &pv, const reco::Vertex &sv, double minTrackWeight,float ) - { - std::vector svTracks; - for(std::vector::const_iterator iter = sv.tracks_begin(); - iter != sv.tracks_end(); iter++) - if (sv.trackWeight(*iter) >= minTrackWeight) - svTracks.push_back(iter->castTo()); - return computeSharedTracks(pv,svTracks,minTrackWeight); - - } - double computeSharedTracks(const reco::VertexCompositePtrCandidate &sv, const reco::VertexCompositePtrCandidate &sv2, double ,float ) - { - return computeSharedTracks(sv,sv2.daughterPtrVector()); - } - - -} +} // namespace vertexTools diff --git a/RecoVertex/VertexTools/src/SmsModeFinder3d.cc b/RecoVertex/VertexTools/src/SmsModeFinder3d.cc index b07f5c6c25a30..6b9a75262efe8 100644 --- a/RecoVertex/VertexTools/src/SmsModeFinder3d.cc +++ b/RecoVertex/VertexTools/src/SmsModeFinder3d.cc @@ -1,22 +1,14 @@ #include "RecoVertex/VertexTools/interface/SmsModeFinder3d.h" -SmsModeFinder3d::SmsModeFinder3d ( const SMS & algo ) : - theAlgo(algo) -{} +SmsModeFinder3d::SmsModeFinder3d(const SMS& algo) : theAlgo(algo) {} -GlobalPoint SmsModeFinder3d::operator() ( const std::vector & values ) const -{ - std::vector < std::pair < GlobalPoint, float > > weighted; - for ( std::vector< PointAndDistance >::const_iterator i=values.begin(); - i!=values.end() ; ++i ) - { - float weight = pow ( 10 + 10000 * i->second, -2 ); - weighted.push_back ( std::pair < GlobalPoint, float > ( i->first, weight ) ); +GlobalPoint SmsModeFinder3d::operator()(const std::vector& values) const { + std::vector > weighted; + for (std::vector::const_iterator i = values.begin(); i != values.end(); ++i) { + float weight = pow(10 + 10000 * i->second, -2); + weighted.push_back(std::pair(i->first, weight)); }; - return theAlgo.location( weighted ); + return theAlgo.location(weighted); } -SmsModeFinder3d * SmsModeFinder3d::clone() const -{ - return new SmsModeFinder3d ( * this ); -} +SmsModeFinder3d* SmsModeFinder3d::clone() const { return new SmsModeFinder3d(*this); } diff --git a/RecoVertex/VertexTools/src/SubsetHsmModeFinder3d.cc b/RecoVertex/VertexTools/src/SubsetHsmModeFinder3d.cc index 49273dbb07bcf..379425cd9566d 100644 --- a/RecoVertex/VertexTools/src/SubsetHsmModeFinder3d.cc +++ b/RecoVertex/VertexTools/src/SubsetHsmModeFinder3d.cc @@ -5,59 +5,48 @@ #include -typedef std::pair < GlobalPoint, float > PointAndDistance; +typedef std::pair PointAndDistance; namespace { - struct compareByDistance - { - bool operator() ( const PointAndDistance & p1, - const PointAndDistance & p2 ) { - return ( p1.second < p2.second ); - }; + struct compareByDistance { + bool operator()(const PointAndDistance& p1, const PointAndDistance& p2) { return (p1.second < p2.second); }; }; -} +} // namespace -GlobalPoint SubsetHsmModeFinder3d::operator() ( const std::vector< PointAndDistance> & values ) - const -{ - if ( values.empty() ) - { - throw VertexException ("SubsetHsmModeFinder3d: no value given."); +GlobalPoint SubsetHsmModeFinder3d::operator()(const std::vector& values) const { + if (values.empty()) { + throw VertexException("SubsetHsmModeFinder3d: no value given."); }; - std::vector < GlobalPoint > pts; pts.reserve ( values.size()-1 ); - std::vector< PointAndDistance> sorted_values ( values.size() ); - partial_sort_copy ( values.begin(), values.end(), - sorted_values.begin(), sorted_values.end(), compareByDistance() ); + std::vector pts; + pts.reserve(values.size() - 1); + std::vector sorted_values(values.size()); + partial_sort_copy(values.begin(), values.end(), sorted_values.begin(), sorted_values.end(), compareByDistance()); - std::vector< PointAndDistance>::iterator end = sorted_values.end(); - std::vector< PointAndDistance>::iterator begin = sorted_values.begin(); + std::vector::iterator end = sorted_values.end(); + std::vector::iterator begin = sorted_values.begin(); - float dmax = 0.004; // 40 microns, as a first try. + float dmax = 0.004; // 40 microns, as a first try. // we want at least 30 values unsigned int min_num = values.size() < 30 ? values.size() : 30; // we also want at least 50 % of all values - if ( values.size() > 2 * min_num ) min_num = (int) values.size() / 2; + if (values.size() > 2 * min_num) + min_num = (int)values.size() / 2; - while ( pts.size() < min_num ) - { + while (pts.size() < min_num) { // we cut at a dmax - std::vector< PointAndDistance>::iterator i; - for ( i=begin; i!=end && ( i->second < dmax ) ; ++i ) - { - pts.push_back ( i->first ); + std::vector::iterator i; + for (i = begin; i != end && (i->second < dmax); ++i) { + pts.push_back(i->first); }; - dmax +=0.003; // add 30 microns with every iteration - begin=i; + dmax += 0.003; // add 30 microns with every iteration + begin = i; }; - GlobalPoint ret = hsm_3d ( pts ); + GlobalPoint ret = hsm_3d(pts); return ret; } -SubsetHsmModeFinder3d * SubsetHsmModeFinder3d::clone() const -{ - return new SubsetHsmModeFinder3d ( * this ); -} +SubsetHsmModeFinder3d* SubsetHsmModeFinder3d::clone() const { return new SubsetHsmModeFinder3d(*this); } diff --git a/RecoVertex/VertexTools/src/VertexCompatibleWithBeam.cc b/RecoVertex/VertexTools/src/VertexCompatibleWithBeam.cc index 206d2b9755d4b..096962b381b4d 100644 --- a/RecoVertex/VertexTools/src/VertexCompatibleWithBeam.cc +++ b/RecoVertex/VertexTools/src/VertexCompatibleWithBeam.cc @@ -5,34 +5,23 @@ using namespace reco; -VertexCompatibleWithBeam::VertexCompatibleWithBeam(const VertexDistance & d, - float cut) - : theDistance(d.clone()), theCut(cut) -{ +VertexCompatibleWithBeam::VertexCompatibleWithBeam(const VertexDistance& d, float cut) + : theDistance(d.clone()), theCut(cut) { BeamSpot beamSpot; theBeam = VertexState(beamSpot); } -VertexCompatibleWithBeam::VertexCompatibleWithBeam(const VertexDistance & d, - float cut, const BeamSpot & beamSpot) - : theDistance(d.clone()), theCut(cut), theBeam(beamSpot){} +VertexCompatibleWithBeam::VertexCompatibleWithBeam(const VertexDistance& d, float cut, const BeamSpot& beamSpot) + : theDistance(d.clone()), theCut(cut), theBeam(beamSpot) {} +VertexCompatibleWithBeam::VertexCompatibleWithBeam(const VertexCompatibleWithBeam& other) + : theDistance((*other.theDistance).clone()), theCut(other.theCut), theBeam(other.theBeam) {} -VertexCompatibleWithBeam::VertexCompatibleWithBeam( - const VertexCompatibleWithBeam & other) : - theDistance((*other.theDistance).clone()), - theCut(other.theCut), theBeam(other.theBeam) {} +VertexCompatibleWithBeam::~VertexCompatibleWithBeam() { delete theDistance; } - -VertexCompatibleWithBeam::~VertexCompatibleWithBeam() { - delete theDistance; -} - - -VertexCompatibleWithBeam & -VertexCompatibleWithBeam::operator=(const VertexCompatibleWithBeam & other) -{ - if (this == &other) return *this; +VertexCompatibleWithBeam& VertexCompatibleWithBeam::operator=(const VertexCompatibleWithBeam& other) { + if (this == &other) + return *this; theDistance = (*other.theDistance).clone(); theCut = other.theCut; @@ -40,39 +29,28 @@ VertexCompatibleWithBeam::operator=(const VertexCompatibleWithBeam & other) return *this; } -void VertexCompatibleWithBeam::setBeamSpot(const BeamSpot & beamSpot){ - theBeam = VertexState(beamSpot); -} +void VertexCompatibleWithBeam::setBeamSpot(const BeamSpot& beamSpot) { theBeam = VertexState(beamSpot); } -bool VertexCompatibleWithBeam::operator()(const reco::Vertex & v) const -{ - GlobalPoint p(Basic3DVector (v.position())); +bool VertexCompatibleWithBeam::operator()(const reco::Vertex& v) const { + GlobalPoint p(Basic3DVector(v.position())); VertexState vs(p, GlobalError(v.covariance())); return (theDistance->distance(vs, theBeam).value() < theCut); } - -float VertexCompatibleWithBeam::distanceToBeam(const reco::Vertex & v) const -{ - GlobalPoint p(Basic3DVector (v.position())); +float VertexCompatibleWithBeam::distanceToBeam(const reco::Vertex& v) const { + GlobalPoint p(Basic3DVector(v.position())); VertexState vs(p, GlobalError(v.covariance())); return theDistance->distance(vs, theBeam).value(); } - -float VertexCompatibleWithBeam::distanceToBeam(const reco::Vertex & v, const VertexState & bs) const -{ - GlobalPoint p(Basic3DVector (v.position())); +float VertexCompatibleWithBeam::distanceToBeam(const reco::Vertex& v, const VertexState& bs) const { + GlobalPoint p(Basic3DVector(v.position())); VertexState vs(p, GlobalError(v.covariance())); return theDistance->distance(vs, bs).value(); } - -bool VertexCompatibleWithBeam::operator()(const reco::Vertex & v, const VertexState & bs) const -{ - GlobalPoint p(Basic3DVector (v.position())); +bool VertexCompatibleWithBeam::operator()(const reco::Vertex& v, const VertexState& bs) const { + GlobalPoint p(Basic3DVector(v.position())); VertexState vs(p, GlobalError(v.covariance())); return (theDistance->distance(vs, bs).value() < theCut); } - - diff --git a/RecoVertex/VertexTools/src/VertexDistance.cc b/RecoVertex/VertexTools/src/VertexDistance.cc index 612e8d3cdf962..9d69f98471b7c 100644 --- a/RecoVertex/VertexTools/src/VertexDistance.cc +++ b/RecoVertex/VertexTools/src/VertexDistance.cc @@ -3,73 +3,54 @@ #include "FWCore/Utilities/interface/Exception.h" #include - using namespace reco; -Measurement1D VertexDistance::distance(const VertexState & vtx1, - const VertexState & vtx2) const -{ - return distance(vtx1.position(), vtx1.error(), - vtx2.position(), vtx2.error()); +Measurement1D VertexDistance::distance(const VertexState& vtx1, const VertexState& vtx2) const { + return distance(vtx1.position(), vtx1.error(), vtx2.position(), vtx2.error()); } -Measurement1D VertexDistance::distance(const Vertex & vtx1, - const VertexState & vtx2) const -{ - return distance(GlobalPoint(Basic3DVector (vtx1.position())), - GlobalError(vtx1.covariance()), - vtx2.position(), vtx2.error()); +Measurement1D VertexDistance::distance(const Vertex& vtx1, const VertexState& vtx2) const { + return distance(GlobalPoint(Basic3DVector(vtx1.position())), + GlobalError(vtx1.covariance()), + vtx2.position(), + vtx2.error()); } - -Measurement1D VertexDistance::distance(const VertexState & vtx1, - const Vertex & vtx2) const -{ - return distance(vtx1.position(), vtx1.error(), - GlobalPoint(Basic3DVector (vtx2.position())), - GlobalError(vtx2.covariance())); +Measurement1D VertexDistance::distance(const VertexState& vtx1, const Vertex& vtx2) const { + return distance(vtx1.position(), + vtx1.error(), + GlobalPoint(Basic3DVector(vtx2.position())), + GlobalError(vtx2.covariance())); } - -Measurement1D -VertexDistance::distance(const Vertex & vtx1, const Vertex & vtx2) const -{ - return distance(GlobalPoint(Basic3DVector (vtx1.position())), - GlobalError(vtx1.covariance()), - GlobalPoint(Basic3DVector (vtx2.position())), - GlobalError(vtx2.covariance())); +Measurement1D VertexDistance::distance(const Vertex& vtx1, const Vertex& vtx2) const { + return distance(GlobalPoint(Basic3DVector(vtx1.position())), + GlobalError(vtx1.covariance()), + GlobalPoint(Basic3DVector(vtx2.position())), + GlobalError(vtx2.covariance())); } - -float VertexDistance::compatibility(const VertexState & vtx1, - const VertexState & vtx2) const -{ - return compatibility(vtx1.position(), vtx1.error(), - vtx2.position(), vtx2.error()); +float VertexDistance::compatibility(const VertexState& vtx1, const VertexState& vtx2) const { + return compatibility(vtx1.position(), vtx1.error(), vtx2.position(), vtx2.error()); } -float VertexDistance::compatibility(const Vertex & vtx1, - const VertexState & vtx2) const -{ - return compatibility(GlobalPoint(Basic3DVector (vtx1.position())), - GlobalError(vtx1.covariance()), - vtx2.position(), vtx2.error()); +float VertexDistance::compatibility(const Vertex& vtx1, const VertexState& vtx2) const { + return compatibility(GlobalPoint(Basic3DVector(vtx1.position())), + GlobalError(vtx1.covariance()), + vtx2.position(), + vtx2.error()); } -float VertexDistance::compatibility(const VertexState & vtx1, - const Vertex & vtx2) const -{ - return compatibility(vtx1.position(), vtx1.error(), - GlobalPoint(Basic3DVector (vtx2.position())), - GlobalError(vtx2.covariance())); +float VertexDistance::compatibility(const VertexState& vtx1, const Vertex& vtx2) const { + return compatibility(vtx1.position(), + vtx1.error(), + GlobalPoint(Basic3DVector(vtx2.position())), + GlobalError(vtx2.covariance())); } - -float VertexDistance::compatibility(const Vertex & vtx1, - const Vertex & vtx2) const -{ - return compatibility(GlobalPoint(Basic3DVector (vtx1.position())), - GlobalError(vtx1.covariance()), - GlobalPoint(Basic3DVector (vtx2.position())), - GlobalError(vtx2.covariance())); +float VertexDistance::compatibility(const Vertex& vtx1, const Vertex& vtx2) const { + return compatibility(GlobalPoint(Basic3DVector(vtx1.position())), + GlobalError(vtx1.covariance()), + GlobalPoint(Basic3DVector(vtx2.position())), + GlobalError(vtx2.covariance())); } diff --git a/RecoVertex/VertexTools/src/VertexDistance3D.cc b/RecoVertex/VertexTools/src/VertexDistance3D.cc index 39e1d32a5cdb8..4169d10638361 100644 --- a/RecoVertex/VertexTools/src/VertexDistance3D.cc +++ b/RecoVertex/VertexTools/src/VertexDistance3D.cc @@ -1,59 +1,50 @@ #include "RecoVertex/VertexTools/interface/VertexDistance3D.h" #include - using namespace reco; -Measurement1D -VertexDistance3D::signedDistance(const Vertex& vtx1, const Vertex & vtx2, - const GlobalVector & momentum) const -{ +Measurement1D VertexDistance3D::signedDistance(const Vertex& vtx1, + const Vertex& vtx2, + const GlobalVector& momentum) const { Measurement1D unsignedDistance = distance(vtx1, vtx2); - Basic3DVector diff = Basic3DVector (vtx2.position()) - - Basic3DVector (vtx1.position()); -// Basic3DVector (vtx2 - vtx1); - if ((momentum.x()*diff.x() + momentum.y()*diff.y() * momentum.z()*diff.z()) < 0 ) - return Measurement1D(-1.0*unsignedDistance.value(),unsignedDistance.error()); + Basic3DVector diff = Basic3DVector(vtx2.position()) - Basic3DVector(vtx1.position()); + // Basic3DVector (vtx2 - vtx1); + if ((momentum.x() * diff.x() + momentum.y() * diff.y() * momentum.z() * diff.z()) < 0) + return Measurement1D(-1.0 * unsignedDistance.value(), unsignedDistance.error()); return unsignedDistance; } +Measurement1D VertexDistance3D::distance(const GlobalPoint& vtx1Position, + const GlobalError& vtx1PositionError, + const GlobalPoint& vtx2Position, + const GlobalError& vtx2PositionError) const { + AlgebraicSymMatrix33 error = vtx1PositionError.matrix() + vtx2PositionError.matrix(); + GlobalVector diff = vtx1Position - vtx2Position; + AlgebraicVector3 vDiff; + vDiff[0] = diff.x(); + vDiff[1] = diff.y(); + vDiff[2] = diff.z(); -Measurement1D -VertexDistance3D::distance(const GlobalPoint & vtx1Position, - const GlobalError & vtx1PositionError, - const GlobalPoint & vtx2Position, - const GlobalError & vtx2PositionError) const -{ - AlgebraicSymMatrix33 error = vtx1PositionError.matrix() - + vtx2PositionError.matrix(); - GlobalVector diff = vtx1Position - vtx2Position; - AlgebraicVector3 vDiff; - vDiff[0] = diff.x(); - vDiff[1] = diff.y(); - vDiff[2] = diff.z(); - - double dist=diff.mag(); - - double err2 = ROOT::Math::Similarity(error,vDiff); - double err = 0.; - if (dist != 0) err = sqrt(err2)/dist; - - return Measurement1D(dist,err); -} + double dist = diff.mag(); + double err2 = ROOT::Math::Similarity(error, vDiff); + double err = 0.; + if (dist != 0) + err = sqrt(err2) / dist; + return Measurement1D(dist, err); +} -float -VertexDistance3D::compatibility(const GlobalPoint & vtx1Position, - const GlobalError & vtx1PositionError, - const GlobalPoint & vtx2Position, - const GlobalError & vtx2PositionError) const -{ +float VertexDistance3D::compatibility(const GlobalPoint& vtx1Position, + const GlobalError& vtx1PositionError, + const GlobalPoint& vtx2Position, + const GlobalError& vtx2PositionError) const { // error matrix of residuals AlgebraicSymMatrix33 err1 = vtx1PositionError.matrix(); AlgebraicSymMatrix33 err2 = vtx2PositionError.matrix(); AlgebraicSymMatrix33 error = err1 + err2; - if (error == theNullMatrix) return FLT_MAX; + if (error == theNullMatrix) + return FLT_MAX; // position residuals GlobalVector diff = vtx2Position - vtx1Position; @@ -68,5 +59,5 @@ VertexDistance3D::compatibility(const GlobalPoint & vtx1Position, throw cms::Exception("VertexDistance3D::matrix inversion problem"); } - return ROOT::Math::Similarity(error,vDiff); + return ROOT::Math::Similarity(error, vDiff); } diff --git a/RecoVertex/VertexTools/src/VertexDistanceXY.cc b/RecoVertex/VertexTools/src/VertexDistanceXY.cc index 92ba2ff648b59..fa301cc11f066 100644 --- a/RecoVertex/VertexTools/src/VertexDistanceXY.cc +++ b/RecoVertex/VertexTools/src/VertexDistanceXY.cc @@ -4,61 +4,52 @@ #include "FWCore/Utilities/interface/Exception.h" #include - using namespace reco; -Measurement1D -VertexDistanceXY::signedDistance(const Vertex& vtx1, const Vertex & vtx2, - const GlobalVector & momentum) const -{ +Measurement1D VertexDistanceXY::signedDistance(const Vertex& vtx1, + const Vertex& vtx2, + const GlobalVector& momentum) const { Measurement1D unsignedDistance = distance(vtx1, vtx2); - Basic3DVector diff = Basic3DVector (vtx2.position()) - - Basic3DVector (vtx1.position()); - if ((momentum.x()*diff.x() + momentum.y()*diff.y()) < 0 ) - return Measurement1D(-1.0*unsignedDistance.value(),unsignedDistance.error()); + Basic3DVector diff = Basic3DVector(vtx2.position()) - Basic3DVector(vtx1.position()); + if ((momentum.x() * diff.x() + momentum.y() * diff.y()) < 0) + return Measurement1D(-1.0 * unsignedDistance.value(), unsignedDistance.error()); return unsignedDistance; } +Measurement1D VertexDistanceXY::distance(const GlobalPoint& vtx1Position, + const GlobalError& vtx1PositionError, + const GlobalPoint& vtx2Position, + const GlobalError& vtx2PositionError) const { + AlgebraicSymMatrix33 error = vtx1PositionError.matrix() + vtx2PositionError.matrix(); + GlobalVector diff = vtx1Position - vtx2Position; + AlgebraicVector3 vDiff; + vDiff[0] = diff.x(); + vDiff[1] = diff.y(); + vDiff[2] = 0.; + double dist = sqrt(pow(diff.x(), 2) + pow(diff.y(), 2)); -Measurement1D -VertexDistanceXY::distance(const GlobalPoint & vtx1Position, - const GlobalError & vtx1PositionError, - const GlobalPoint & vtx2Position, - const GlobalError & vtx2PositionError) const -{ - AlgebraicSymMatrix33 error = vtx1PositionError.matrix() - + vtx2PositionError.matrix(); - GlobalVector diff = vtx1Position - vtx2Position; - AlgebraicVector3 vDiff; - vDiff[0] = diff.x(); - vDiff[1] = diff.y(); - vDiff[2] = 0.; - - double dist=sqrt(pow(diff.x(),2)+pow(diff.y(),2)); - - double err2 = ROOT::Math::Similarity(error,vDiff); - double err = 0; - if( dist != 0) err = sqrt(err2)/dist; - - return Measurement1D(dist,err); -} + double err2 = ROOT::Math::Similarity(error, vDiff); + double err = 0; + if (dist != 0) + err = sqrt(err2) / dist; + return Measurement1D(dist, err); +} -float -VertexDistanceXY::compatibility(const GlobalPoint & vtx1Position, - const GlobalError & vtx1PositionError, - const GlobalPoint & vtx2Position, - const GlobalError & vtx2PositionError) const -{ +float VertexDistanceXY::compatibility(const GlobalPoint& vtx1Position, + const GlobalError& vtx1PositionError, + const GlobalPoint& vtx2Position, + const GlobalError& vtx2PositionError) const { // error matrix of residuals AlgebraicSymMatrix33 err1 = vtx1PositionError.matrix(); AlgebraicSymMatrix33 err2 = vtx2PositionError.matrix(); - AlgebraicSymMatrix22 error; + AlgebraicSymMatrix22 error; error[0][0] = err1[0][0] + err2[0][0]; error[0][1] = err1[0][1] + err2[0][1]; error[1][1] = err1[1][1] + err2[1][1]; - if (error == theNullMatrix) return FLT_MAX; + if (error == theNullMatrix) + return FLT_MAX; // position residuals GlobalVector diff = vtx2Position - vtx1Position; @@ -72,5 +63,5 @@ VertexDistanceXY::compatibility(const GlobalPoint & vtx1Position, throw cms::Exception("VertexDistanceXY::matrix inversion problem"); } - return ROOT::Math::Similarity(error,vDiff); + return ROOT::Math::Similarity(error, vDiff); } diff --git a/RecoVertex/VertexTools/src/hsm_3d.cc b/RecoVertex/VertexTools/src/hsm_3d.cc index 41a934dc6782d..d02336ca100ff 100644 --- a/RecoVertex/VertexTools/src/hsm_3d.cc +++ b/RecoVertex/VertexTools/src/hsm_3d.cc @@ -5,22 +5,19 @@ #include /// cordinate wise half sample mode in 3d -GlobalPoint hsm_3d ( const std::vector & values ) -{ +GlobalPoint hsm_3d(const std::vector& values) { const int sze = values.size(); - if ( sze == 0 ) { - throw VertexException("hsm_3d: no values given."); + if (sze == 0) { + throw VertexException("hsm_3d: no values given."); }; - std::vector x_vals, y_vals, z_vals; - x_vals.reserve(sze-1); - y_vals.reserve(sze-1); - z_vals.reserve(sze-1); - for ( std::vector::const_iterator i=values.begin(); - i!=values.end() ; i++ ) - { - x_vals.push_back( i->x() ); - y_vals.push_back( i->y() ); - z_vals.push_back( i->z() ); + std::vector x_vals, y_vals, z_vals; + x_vals.reserve(sze - 1); + y_vals.reserve(sze - 1); + z_vals.reserve(sze - 1); + for (std::vector::const_iterator i = values.begin(); i != values.end(); i++) { + x_vals.push_back(i->x()); + y_vals.push_back(i->y()); + z_vals.push_back(i->z()); }; // FIXME isnt necessary, is it? @@ -29,6 +26,6 @@ GlobalPoint hsm_3d ( const std::vector & values ) sort ( y_vals.begin(), y_vals.end() ); sort ( z_vals.begin(), z_vals.end() );*/ - GlobalPoint ret ( hsm_1d(x_vals), hsm_1d(y_vals), hsm_1d(z_vals) ); + GlobalPoint ret(hsm_1d(x_vals), hsm_1d(y_vals), hsm_1d(z_vals)); return ret; } diff --git a/RecoVertex/VertexTools/src/lms_3d.cc b/RecoVertex/VertexTools/src/lms_3d.cc index a9b4372f3c1d4..048192f8511a1 100644 --- a/RecoVertex/VertexTools/src/lms_3d.cc +++ b/RecoVertex/VertexTools/src/lms_3d.cc @@ -5,21 +5,19 @@ /// least median of squares in three dimensions, /// doing every dimension separately -GlobalPoint lms_3d ( std::vector values ) -{ +GlobalPoint lms_3d(std::vector values) { const int sze = values.size(); - if ( sze == 0 ) { - throw VertexException("lms_3d: no values given."); + if (sze == 0) { + throw VertexException("lms_3d: no values given."); }; - std::vector x_vals, y_vals, z_vals; - x_vals.reserve(sze-1); - y_vals.reserve(sze-1); - z_vals.reserve(sze-1); - for (std:: vector::iterator i=values.begin(); - i!=values.end() ; i++ ) { - x_vals.push_back( i->x() ); - y_vals.push_back( i->y() ); - z_vals.push_back( i->z() ); + std::vector x_vals, y_vals, z_vals; + x_vals.reserve(sze - 1); + y_vals.reserve(sze - 1); + z_vals.reserve(sze - 1); + for (std::vector::iterator i = values.begin(); i != values.end(); i++) { + x_vals.push_back(i->x()); + y_vals.push_back(i->y()); + z_vals.push_back(i->z()); }; - return GlobalPoint ( lms_1d(x_vals), lms_1d(y_vals), lms_1d(z_vals) ); + return GlobalPoint(lms_1d(x_vals), lms_1d(y_vals), lms_1d(z_vals)); } diff --git a/TrackingTools/DetLayers/interface/BarrelDetLayer.h b/TrackingTools/DetLayers/interface/BarrelDetLayer.h index 614d8b9c6a687..73073f973c6f9 100644 --- a/TrackingTools/DetLayers/interface/BarrelDetLayer.h +++ b/TrackingTools/DetLayers/interface/BarrelDetLayer.h @@ -19,47 +19,38 @@ #include #include - class BarrelDetLayer : public DetLayer { - public: +public: + BarrelDetLayer(bool doHaveGroup) : DetLayer(doHaveGroup, true), theCylinder(nullptr) {} - BarrelDetLayer(bool doHaveGroup) : DetLayer(doHaveGroup,true), - theCylinder(nullptr){} - ~BarrelDetLayer() override; /// GeometricSearchDet interface - const BoundSurface& surface() const final { return *theCylinder;} + const BoundSurface& surface() const final { return *theCylinder; } - std::pair - compatible( const TrajectoryStateOnSurface& ts, const Propagator&, - const MeasurementEstimator&) const final; + std::pair compatible(const TrajectoryStateOnSurface& ts, + const Propagator&, + const MeasurementEstimator&) const final; /// DetLayer interface - Location location() const final {return GeomDetEnumerators::barrel;} - + Location location() const final { return GeomDetEnumerators::barrel; } /// Extension of the interface - virtual const BoundCylinder& specificSurface() const final { return *theCylinder;} - - bool contains( const Local3DPoint& p) const; - + virtual const BoundCylinder& specificSurface() const final { return *theCylinder; } + bool contains(const Local3DPoint& p) const; protected: - virtual void initialize(); - void setSurface( BoundCylinder* cp); + void setSurface(BoundCylinder* cp); virtual BoundCylinder* computeSurface(); - SimpleCylinderBounds const & bounds() const { return static_cast(theCylinder->bounds());} - + SimpleCylinderBounds const& bounds() const { return static_cast(theCylinder->bounds()); } private: //float theRmin, theRmax, theZmin, theZmax; - ReferenceCountingPointer theCylinder; - + ReferenceCountingPointer theCylinder; }; -#endif +#endif diff --git a/TrackingTools/DetLayers/interface/CylinderBuilderFromDet.h b/TrackingTools/DetLayers/interface/CylinderBuilderFromDet.h index 4cbb9613a825f..d53706edd5be7 100644 --- a/TrackingTools/DetLayers/interface/CylinderBuilderFromDet.h +++ b/TrackingTools/DetLayers/interface/CylinderBuilderFromDet.h @@ -22,14 +22,14 @@ class CylinderBuilderFromDet { typedef Surface::RotationType RotationType; typedef PositionType::BasicVectorType Vector; - CylinderBuilderFromDet() : - rmin(std::numeric_limits::max()), - rmax(0.0), - zmin(std::numeric_limits::max()), - zmax(std::numeric_limits::min()){} - - BoundCylinder* operator()( std::vector::const_iterator first, - std::vector::const_iterator last) const; + CylinderBuilderFromDet() + : rmin(std::numeric_limits::max()), + rmax(0.0), + zmin(std::numeric_limits::max()), + zmax(std::numeric_limits::min()) {} + + BoundCylinder* operator()(std::vector::const_iterator first, + std::vector::const_iterator last) const; void operator()(const Det& det); @@ -40,7 +40,6 @@ class CylinderBuilderFromDet { float rmax; float zmin; float zmax; - }; #endif diff --git a/TrackingTools/DetLayers/interface/DetGroup.h b/TrackingTools/DetLayers/interface/DetGroup.h index e13b56a3d7d37..9eb7feffaeaf2 100644 --- a/TrackingTools/DetLayers/interface/DetGroup.h +++ b/TrackingTools/DetLayers/interface/DetGroup.h @@ -1,5 +1,5 @@ #ifndef DetLayers_DetGroup_h -#define DetLayers_DetGroup_h +#define DetLayers_DetGroup_h #include "Geometry/CommonDetUnit/interface/GeomDet.h" #include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" @@ -8,92 +8,81 @@ #include class DetGroupElement { - public: - typedef std::pair DetWithState; - typedef GeomDet Det; - - - DetGroupElement( const DetWithState& dws) : - det_(dws.first), state_(dws.second) {} - - DetGroupElement( const Det* d, const TrajectoryStateOnSurface& s) : - det_(d), state_(s) {} - - DetGroupElement(DetGroupElement const & rhs) : det_(rhs.det_), state_(rhs.state_){} - DetGroupElement(DetGroupElement && rhs) noexcept : det_(rhs.det_), state_(std::move(rhs.state_)){} - DetGroupElement & operator=(DetGroupElement const & rhs) { - det_=rhs.det_; - state_ = rhs.state_; - return *this; +public: + typedef std::pair DetWithState; + typedef GeomDet Det; + + DetGroupElement(const DetWithState& dws) : det_(dws.first), state_(dws.second) {} + + DetGroupElement(const Det* d, const TrajectoryStateOnSurface& s) : det_(d), state_(s) {} + + DetGroupElement(DetGroupElement const& rhs) : det_(rhs.det_), state_(rhs.state_) {} + DetGroupElement(DetGroupElement&& rhs) noexcept : det_(rhs.det_), state_(std::move(rhs.state_)) {} + DetGroupElement& operator=(DetGroupElement const& rhs) { + det_ = rhs.det_; + state_ = rhs.state_; + return *this; } - DetGroupElement & operator=(DetGroupElement && rhs) noexcept { - det_=rhs.det_; - state_ = std::move(rhs.state_); - return *this; + DetGroupElement& operator=(DetGroupElement&& rhs) noexcept { + det_ = rhs.det_; + state_ = std::move(rhs.state_); + return *this; } - DetGroupElement( const Det* d, TrajectoryStateOnSurface&& s) noexcept : - det_(d), state_(std::move(s)) {} + DetGroupElement(const Det* d, TrajectoryStateOnSurface&& s) noexcept : det_(d), state_(std::move(s)) {} - const Det* det() const {return det_;} - const TrajectoryStateOnSurface& trajectoryState() const {return state_;} + const Det* det() const { return det_; } + const TrajectoryStateOnSurface& trajectoryState() const { return state_; } private: - const Det* det_; TrajectoryStateOnSurface state_; - }; - -class DetGroup : public std::vector< DetGroupElement> { +class DetGroup : public std::vector { public: - - typedef std::vector< DetGroupElement> Base; - typedef DetGroupElement::DetWithState DetWithState; + typedef std::vector Base; + typedef DetGroupElement::DetWithState DetWithState; DetGroup() {} - DetGroup(DetGroup const & rhs) : Base(rhs), index_(rhs.index_), indexSize_(rhs.indexSize_) {} - DetGroup(DetGroup && rhs) noexcept : Base(std::forward(rhs)), index_(rhs.index_), indexSize_(rhs.indexSize_) {} - DetGroup & operator=(DetGroup const & rhs) { + DetGroup(DetGroup const& rhs) : Base(rhs), index_(rhs.index_), indexSize_(rhs.indexSize_) {} + DetGroup(DetGroup&& rhs) noexcept : Base(std::forward(rhs)), index_(rhs.index_), indexSize_(rhs.indexSize_) {} + DetGroup& operator=(DetGroup const& rhs) { Base::operator=(rhs); - index_ = rhs.index_; + index_ = rhs.index_; indexSize_ = rhs.indexSize_; return *this; } - DetGroup & operator=(DetGroup && rhs) noexcept { - Base::operator=(std::forward(rhs)); - index_ = rhs.index_; + DetGroup& operator=(DetGroup&& rhs) noexcept { + Base::operator=(std::forward(rhs)); + index_ = rhs.index_; indexSize_ = rhs.indexSize_; return *this; } - DetGroup(int ind, int indSize) : index_(ind), indexSize_(indSize) {} DetGroup(const std::vector& vec) { - reserve( vec.size()); - for (std::vector::const_iterator i=vec.begin(); i!=vec.end(); i++) { + reserve(vec.size()); + for (std::vector::const_iterator i = vec.begin(); i != vec.end(); i++) { push_back(DetGroupElement(*i)); } } - int index() const {return index_;} + int index() const { return index_; } - int indexSize() const {return indexSize_;} + int indexSize() const { return indexSize_; } - void setIndexSize( int newSize) {indexSize_ = newSize;} + void setIndexSize(int newSize) { indexSize_ = newSize; } - void incrementIndex( int incr) { + void incrementIndex(int incr) { // for (iterator i=begin(); i!=end(); i++) i->incrementIndex(incr); index_ += incr; indexSize_ += incr; } private: - int index_; int indexSize_; - }; #endif diff --git a/TrackingTools/DetLayers/interface/DetLayer.h b/TrackingTools/DetLayers/interface/DetLayer.h index d57be598da24f..29823a3d3bad0 100644 --- a/TrackingTools/DetLayers/interface/DetLayer.h +++ b/TrackingTools/DetLayers/interface/DetLayer.h @@ -18,9 +18,8 @@ #include -class DetLayer : public GeometricSearchDet { - public: - +class DetLayer : public GeometricSearchDet { +public: typedef GeomDetEnumerators::SubDetector SubDetector; typedef GeomDetEnumerators::Location Location; @@ -29,14 +28,14 @@ class DetLayer : public GeometricSearchDet { ~DetLayer() override; // a detLayer can be either barrel or forward - bool isBarrel() const { return iAmBarrel;} - bool isForward() const { return !isBarrel();} + bool isBarrel() const { return iAmBarrel; } + bool isForward() const { return !isBarrel(); } // sequential number to be used in "maps" - int seqNum() const { return theSeqNum;} - void setSeqNum(int sq) { theSeqNum=sq;} + int seqNum() const { return theSeqNum; } + void setSeqNum(int sq) { theSeqNum = sq; } - // Extension of the interface + // Extension of the interface /// The type of detector (PixelBarrel, PixelEndcap, TIB, TOB, TID, TEC, CSC, DT, RPCBarrel, RPCEndcap) virtual SubDetector subDetector() const = 0; @@ -44,11 +43,9 @@ class DetLayer : public GeometricSearchDet { /// Which part of the detector (barrel, endcap) virtual Location location() const = 0; - - - private: +private: int theSeqNum; bool iAmBarrel; }; -#endif +#endif diff --git a/TrackingTools/DetLayers/interface/DetLayerException.h b/TrackingTools/DetLayers/interface/DetLayerException.h index c3464c41ea54d..753655fdff38d 100644 --- a/TrackingTools/DetLayers/interface/DetLayerException.h +++ b/TrackingTools/DetLayers/interface/DetLayerException.h @@ -14,8 +14,9 @@ class DetLayerException : public cms::Exception { public: - DetLayerException( const std::string& message) throw() : cms::Exception(message) {} + DetLayerException(const std::string& message) throw() : cms::Exception(message) {} ~DetLayerException() throw() override {} + private: }; diff --git a/TrackingTools/DetLayers/interface/DetLayerGeometry.h b/TrackingTools/DetLayers/interface/DetLayerGeometry.h index df2da09bbc8d2..60a2c077dd43e 100644 --- a/TrackingTools/DetLayers/interface/DetLayerGeometry.h +++ b/TrackingTools/DetLayers/interface/DetLayerGeometry.h @@ -16,11 +16,11 @@ class DetLayer; class DetLayerGeometry { - public: +public: DetLayerGeometry(){}; - - virtual ~DetLayerGeometry() {} - + + virtual ~DetLayerGeometry() {} + /* const std::vector& allLayers() const =0; const std::vector& barrelLayers() const =0; @@ -28,12 +28,9 @@ class DetLayerGeometry { const std::vector& posForwardLayers() const =0; */ - /// Give the DetId of a module, returns the pointer to the corresponding DetLayer /// This method is dummy and has to be overridden in another derived class - virtual const DetLayer* idToLayer(const DetId& detId) const {return nullptr;} - + virtual const DetLayer* idToLayer(const DetId& detId) const { return nullptr; } }; - #endif diff --git a/TrackingTools/DetLayers/interface/DetRod.h b/TrackingTools/DetLayers/interface/DetRod.h index 12e86bfc9dc03..8ed9cf45490c8 100644 --- a/TrackingTools/DetLayers/interface/DetRod.h +++ b/TrackingTools/DetLayers/interface/DetRod.h @@ -11,34 +11,29 @@ class MeasurementEstimator; class DetRod : public GeometricSearchDet { - public: - +public: using GeometricSearchDet::GeometricSearchDet; ~DetRod() override; - - - const BoundSurface& surface() const final {return *thePlane;} + const BoundSurface& surface() const final { return *thePlane; } //--- Extension of the interface - - /// Return the rod surface as a Plane - virtual const Plane& specificSurface() const final {return *thePlane;} + /// Return the rod surface as a Plane + virtual const Plane& specificSurface() const final { return *thePlane; } protected: /// Set the rod's plane - void setPlane( Plane* plane) { thePlane = plane;} + void setPlane(Plane* plane) { thePlane = plane; } //obsolete? // Return the range in Z to be checked for compatibility //float zError( const TrajectoryStateOnSurface& tsos, // const MeasurementEstimator& est) const; - private: - ReferenceCountingPointer thePlane; - +private: + ReferenceCountingPointer thePlane; }; #endif diff --git a/TrackingTools/DetLayers/interface/DetRodOneR.h b/TrackingTools/DetLayers/interface/DetRodOneR.h index 17e5093e83e5f..68ec7ab3506ca 100644 --- a/TrackingTools/DetLayers/interface/DetRodOneR.h +++ b/TrackingTools/DetLayers/interface/DetRodOneR.h @@ -12,35 +12,31 @@ class MeasurementEstimator; class DetRodOneR : public DetRod { - public: +public: typedef std::vector DetContainer; - /// Construct from iterators on GeomDet* - DetRodOneR( std::vector::const_iterator first, - std::vector::const_iterator last); + DetRodOneR(std::vector::const_iterator first, std::vector::const_iterator last); /// Construct from a std::vector of GeomDet* - DetRodOneR( const std::vector& dets); + DetRodOneR(const std::vector& dets); ~DetRodOneR() override; - const std::vector& basicComponents() const override {return theDets;} - - + const std::vector& basicComponents() const override { return theDets; } protected: /// Query detector idet for compatible and add the output to result. - - bool add( int idet, std::vector& result, - const TrajectoryStateOnSurface& startingState, - const Propagator& prop, - const MeasurementEstimator& est) const; - - std::vector theDets; - - void initialize(); + bool add(int idet, + std::vector& result, + const TrajectoryStateOnSurface& startingState, + const Propagator& prop, + const MeasurementEstimator& est) const; + + std::vector theDets; + + void initialize(); }; #endif diff --git a/TrackingTools/DetLayers/interface/ForwardDetLayer.h b/TrackingTools/DetLayers/interface/ForwardDetLayer.h index c2b89d57b799e..c315d9876ef6d 100644 --- a/TrackingTools/DetLayers/interface/ForwardDetLayer.h +++ b/TrackingTools/DetLayers/interface/ForwardDetLayer.h @@ -10,58 +10,51 @@ */ #include "TrackingTools/DetLayers/interface/DetLayer.h" -#include "DataFormats/GeometrySurface/interface/Surface.h" +#include "DataFormats/GeometrySurface/interface/Surface.h" #include "DataFormats/GeometrySurface/interface/ReferenceCounted.h" #include "DataFormats/GeometrySurface/interface/BoundDisk.h" #include "DataFormats/GeometrySurface/interface/SimpleDiskBounds.h" #include "DataFormats/GeometrySurface/interface/SimpleCylinderBounds.h" - #include #include class ForwardDetLayer : public DetLayer { public: - - ForwardDetLayer(bool doHaveGroups): DetLayer(doHaveGroups,false) {} + ForwardDetLayer(bool doHaveGroups) : DetLayer(doHaveGroups, false) {} ~ForwardDetLayer() override; // GeometricSearchDet interface - const BoundSurface& surface() const final { return *theDisk;} + const BoundSurface& surface() const final { return *theDisk; } - std::pair - compatible( const TrajectoryStateOnSurface&, const Propagator&, - const MeasurementEstimator&) const override; + std::pair compatible(const TrajectoryStateOnSurface&, + const Propagator&, + const MeasurementEstimator&) const override; // DetLayer interface - Location location() const final {return GeomDetEnumerators::endcap;} + Location location() const final { return GeomDetEnumerators::endcap; } // Extension of the interface - virtual const BoundDisk& specificSurface() const final { return *theDisk;} + virtual const BoundDisk& specificSurface() const final { return *theDisk; } - bool contains( const Local3DPoint& p) const; - - protected: + bool contains(const Local3DPoint& p) const; +protected: virtual void initialize(); + float rmin() const { return theDisk->innerRadius(); } + float rmax() const { return theDisk->outerRadius(); } + float zmin() const { return (theDisk->position().z() - bounds().thickness() * 0.5f); } + float zmax() const { return (theDisk->position().z() + bounds().thickness() * 0.5f); } - float rmin() const { return theDisk->innerRadius();} - float rmax() const { return theDisk->outerRadius();} - float zmin() const { return (theDisk->position().z() - bounds().thickness()*0.5f);} - float zmax() const { return (theDisk->position().z() + bounds().thickness()*0.5f);} - - void setSurface( BoundDisk* cp); + void setSurface(BoundDisk* cp); virtual BoundDisk* computeSurface(); - SimpleDiskBounds const & bounds() const { return static_cast(theDisk->bounds());} + SimpleDiskBounds const& bounds() const { return static_cast(theDisk->bounds()); } - private: +private: ReferenceCountingPointer theDisk; - - }; - -#endif +#endif diff --git a/TrackingTools/DetLayers/interface/ForwardDetRing.h b/TrackingTools/DetLayers/interface/ForwardDetRing.h index d43430d500b24..5be290dfc4d0f 100644 --- a/TrackingTools/DetLayers/interface/ForwardDetRing.h +++ b/TrackingTools/DetLayers/interface/ForwardDetRing.h @@ -9,38 +9,28 @@ #include "DataFormats/GeometrySurface/interface/BoundDisk.h" class ForwardDetRing : public GeometricSearchDet { - public: - +public: using GeometricSearchDet::GeometricSearchDet; - ~ForwardDetRing() override; - - void - compatibleDetsV( const TrajectoryStateOnSurface& startingState, - const Propagator& prop, - const MeasurementEstimator& est, - std::vector& result) const override; - - const BoundSurface& surface() const final {return *theDisk;} + void compatibleDetsV(const TrajectoryStateOnSurface& startingState, + const Propagator& prop, + const MeasurementEstimator& est, + std::vector& result) const override; + + const BoundSurface& surface() const final { return *theDisk; } - //--- Extension of the interface /// Return the ring surface as a BoundDisk - const BoundDisk& specificSurface() const {return *theDisk;} - + const BoundDisk& specificSurface() const { return *theDisk; } protected: - /// Set the rod's disk - void setDisk( BoundDisk* disk) { theDisk = disk;} - - - private: - ReferenceCountingPointer theDisk; + void setDisk(BoundDisk* disk) { theDisk = disk; } +private: + ReferenceCountingPointer theDisk; }; #endif - diff --git a/TrackingTools/DetLayers/interface/ForwardDetRingOneZ.h b/TrackingTools/DetLayers/interface/ForwardDetRingOneZ.h index 7a937497e3661..5a0a9ae888195 100644 --- a/TrackingTools/DetLayers/interface/ForwardDetRingOneZ.h +++ b/TrackingTools/DetLayers/interface/ForwardDetRingOneZ.h @@ -7,33 +7,29 @@ #include "TrackingTools/DetLayers/interface/ForwardDetRing.h" - class ForwardDetRingOneZ : public ForwardDetRing { public: - /// Construct from iterators on Det*. - ForwardDetRingOneZ( std::vector::const_iterator first, - std::vector::const_iterator last); + ForwardDetRingOneZ(std::vector::const_iterator first, + std::vector::const_iterator last); // Construct from a std::vector of Det*. - ForwardDetRingOneZ( const std::vector& dets); + ForwardDetRingOneZ(const std::vector& dets); ~ForwardDetRingOneZ() override; - - const std::vector& basicComponents() const override {return theDets;} -protected: + const std::vector& basicComponents() const override { return theDets; } - bool add( int idet, std::vector& result, - const TrajectoryStateOnSurface& tsos, - const Propagator& prop, - const MeasurementEstimator& est) const; +protected: + bool add(int idet, + std::vector& result, + const TrajectoryStateOnSurface& tsos, + const Propagator& prop, + const MeasurementEstimator& est) const; private: std::vector theDets; void initialize(); - }; #endif - diff --git a/TrackingTools/DetLayers/interface/ForwardRingDiskBuilderFromDet.h b/TrackingTools/DetLayers/interface/ForwardRingDiskBuilderFromDet.h index f76f9f22dff2a..ca5d63deab3e0 100644 --- a/TrackingTools/DetLayers/interface/ForwardRingDiskBuilderFromDet.h +++ b/TrackingTools/DetLayers/interface/ForwardRingDiskBuilderFromDet.h @@ -18,14 +18,11 @@ class SimpleDiskBounds; class ForwardRingDiskBuilderFromDet { public: - /// Warning, remember to assign this pointer to a ReferenceCountingPointer! /// Should be changed to return a ReferenceCountingPointer - BoundDisk* operator()( const std::vector& dets) const; - - std::pair - computeBounds( const std::vector& dets) const; + BoundDisk* operator()(const std::vector& dets) const; + std::pair computeBounds(const std::vector& dets) const; }; #endif diff --git a/TrackingTools/DetLayers/interface/GeneralBinFinderInPhi.h b/TrackingTools/DetLayers/interface/GeneralBinFinderInPhi.h index e359f57b05f37..b7d74b8d69e1e 100644 --- a/TrackingTools/DetLayers/interface/GeneralBinFinderInPhi.h +++ b/TrackingTools/DetLayers/interface/GeneralBinFinderInPhi.h @@ -17,75 +17,67 @@ template class GeneralBinFinderInPhi : public BaseBinFinder { public: - - typedef PhiBorderFinder::Det Det; //FIXME!!! + typedef PhiBorderFinder::Det Det; //FIXME!!! GeneralBinFinderInPhi() : theNbins(0) {} /// Construct from an already initialized PhiBorderFinder GeneralBinFinderInPhi(const PhiBorderFinder& bf) { - theBorders=bf.phiBorders(); - theBins=bf.phiBins(); - theNbins=theBins.size(); + theBorders = bf.phiBorders(); + theBins = bf.phiBins(); + theNbins = theBins.size(); } /// Construct from the list of Det* - GeneralBinFinderInPhi(std::vector::const_iterator first, - std::vector::const_iterator last) - : theNbins( last-first) - { - std::vector dets(first,last); + GeneralBinFinderInPhi(std::vector::const_iterator first, std::vector::const_iterator last) + : theNbins(last - first) { + std::vector dets(first, last); PhiBorderFinder bf(dets); - theBorders=bf.phiBorders(); - theBins=bf.phiBins(); - theNbins=theBins.size(); + theBorders = bf.phiBorders(); + theBins = bf.phiBins(); + theNbins = theBins.size(); } ~GeneralBinFinderInPhi() override{}; - /// Returns an index in the valid range for the bin that contains + /// Returns an index in the valid range for the bin that contains /// AND is closest to phi - int binIndex( T phi) const override { - + int binIndex(T phi) const override { const std::string metname = "Muon|RecoMuon|RecoMuonDetLayers|GeneralBinFinderInPhi"; - static const T epsilon = 10*std::numeric_limits::epsilon(); + static const T epsilon = 10 * std::numeric_limits::epsilon(); // Assume -pi, pi range in pi (which is the case for Geom::Phi LogTrace(metname) << "GeneralBinFinderInPhi::binIndex," - << " Nbins: "<< theNbins; - - for (int i = 0; i< theNbins; i++) { + << " Nbins: " << theNbins; + for (int i = 0; i < theNbins; i++) { T cur = theBorders[i]; - T next = theBorders[binIndex(i+1)]; + T next = theBorders[binIndex(i + 1)]; T phi_ = phi; - LogTrace(metname) << "bin: " << i - << " border min " << cur << " border max: " << next << " phi: "<< phi_; + LogTrace(metname) << "bin: " << i << " border min " << cur << " border max: " << next << " phi: " << phi_; - if ( cur > next ) // we are crossing the pi edge: so move the edge to 0! - { - cur = positiveRange(cur); - next = positiveRange(next); - phi_ = positiveRange(phi_); - } - if (phi_ > cur-epsilon && phi_ < next) return i; + if (cur > next) // we are crossing the pi edge: so move the edge to 0! + { + cur = positiveRange(cur); + next = positiveRange(next); + phi_ = positiveRange(phi_); + } + if (phi_ > cur - epsilon && phi_ < next) + return i; } throw cms::Exception("UnexpectedState") << "GeneralBinFinderInPhi::binIndex( T phi) bin not found!"; } - + /// Returns an index in the valid range, modulo Nbins - int binIndex( int i) const override { + int binIndex(int i) const override { int ind = i % (int)theNbins; - return (ind < 0) ? ind+theNbins : ind; + return (ind < 0) ? ind + theNbins : ind; } /// the middle of the bin in radians - T binPosition( int ind) const override { - return theBins[binIndex(ind)]; - } - + T binPosition(int ind) const override { return theBins[binIndex(ind)]; } private: int theNbins; @@ -93,11 +85,6 @@ class GeneralBinFinderInPhi : public BaseBinFinder { std::vector theBins; // returns a positive angle; does NOT reduce the range to 2 pi - inline T positiveRange (T phi) const - { - return (phi > 0) ? phi : phi + Geom::twoPi(); - } - + inline T positiveRange(T phi) const { return (phi > 0) ? phi : phi + Geom::twoPi(); } }; #endif - diff --git a/TrackingTools/DetLayers/interface/GeneralBinFinderInR.h b/TrackingTools/DetLayers/interface/GeneralBinFinderInR.h index 53b8b8e7ac437..450c76a933e72 100644 --- a/TrackingTools/DetLayers/interface/GeneralBinFinderInR.h +++ b/TrackingTools/DetLayers/interface/GeneralBinFinderInR.h @@ -14,61 +14,50 @@ #include template -class GeneralBinFinderInR : public BaseBinFinder{ +class GeneralBinFinderInR : public BaseBinFinder { public: - - typedef RBorderFinder::Det Det; //FIXME!!! + typedef RBorderFinder::Det Det; //FIXME!!! GeneralBinFinderInR() : theNbins(0) {} /// Construct from an already initialized RBorderFinder GeneralBinFinderInR(const RBorderFinder& bf) { - theBorders=bf.RBorders(); - theBins=bf.RBins(); - theNbins=theBins.size(); + theBorders = bf.RBorders(); + theBins = bf.RBins(); + theNbins = theBins.size(); } /// Construct from the list of Det* - GeneralBinFinderInR(std::vector::const_iterator first, - std::vector::const_iterator last) - : theNbins( last-first) - { - std::vector dets(first,last); + GeneralBinFinderInR(std::vector::const_iterator first, std::vector::const_iterator last) + : theNbins(last - first) { + std::vector dets(first, last); RBorderFinder bf(dets); - theBorders=bf.RBorders(); - theBins=bf.RBins(); - theNbins=theBins.size(); + theBorders = bf.RBorders(); + theBins = bf.RBins(); + theNbins = theBins.size(); } - /// Returns an index in the valid range for the bin that contains /// AND is closest to R - int binIndex( T R) const override { + int binIndex(T R) const override { int i; - for (i = 0; i theBorders; std::vector theBins; - }; #endif - diff --git a/TrackingTools/DetLayers/interface/GeneralBinFinderInZforGeometricSearchDet.h b/TrackingTools/DetLayers/interface/GeneralBinFinderInZforGeometricSearchDet.h index 354fb2a6d30af..6a6ed74998ed9 100644 --- a/TrackingTools/DetLayers/interface/GeneralBinFinderInZforGeometricSearchDet.h +++ b/TrackingTools/DetLayers/interface/GeneralBinFinderInZforGeometricSearchDet.h @@ -9,77 +9,72 @@ #include "TrackingTools/DetLayers/interface/GeometricSearchDet.h" #include -#include +#include template class GeneralBinFinderInZforGeometricSearchDet final : public BaseBinFinder { public: - GeneralBinFinderInZforGeometricSearchDet() {} - GeneralBinFinderInZforGeometricSearchDet( - std::vector::const_iterator first, - std::vector::const_iterator last) : - theNbins( last-first -1) // -1! + GeneralBinFinderInZforGeometricSearchDet(std::vector::const_iterator first, + std::vector::const_iterator last) + : theNbins(last - first - 1) // -1! { theBins.reserve(theNbins); theBorders.reserve(theNbins); - for (auto i=first; i=theNbins) return theNbins; + int binIndex(T z) const override { + int bin = int((z - theZOffset) * theInvZStep) + 1; + if (bin <= 0) + return 0; + if (bin >= theNbins) + return theNbins; // check left border - if ( z < theBorders[bin-1]) { + if (z < theBorders[bin - 1]) { // z is to the left of the left border, the correct bin is left - for (auto i=bin-1; i>0; i--) { - if ( z > theBorders[i-1]) return i; - } - return 0; + for (auto i = bin - 1; i > 0; i--) { + if (z > theBorders[i - 1]) + return i; } - + return 0; + } + // check right border - if ( z > theBorders[bin]) { + if (z > theBorders[bin]) { // z is to the right of the right border, the correct bin is right - for (int i=bin+1; i theBorders; std::vector theBins; }; diff --git a/TrackingTools/DetLayers/interface/GeomDetCompatibilityChecker.h b/TrackingTools/DetLayers/interface/GeomDetCompatibilityChecker.h index dbd965e44b19b..a8fc2f123f76a 100644 --- a/TrackingTools/DetLayers/interface/GeomDetCompatibilityChecker.h +++ b/TrackingTools/DetLayers/interface/GeomDetCompatibilityChecker.h @@ -1,7 +1,6 @@ #ifndef DetLayers_GeomDetCompatibilityChecker_h #define DetLayers_GeomDetCompatibilityChecker_h - #include "Geometry/CommonDetUnit/interface/GeomDet.h" #include "TrackingTools/GeomPropagators/interface/Propagator.h" #include "TrackingTools/DetLayers/interface/MeasurementEstimator.h" @@ -10,8 +9,8 @@ * compatible with a TrajectoryState */ -class GeomDetCompatibilityChecker{ - public: +class GeomDetCompatibilityChecker { +public: /** tests the geometrical compatibility of the GeomDet with the predicted state. * The TrajectoryState argument is propagated to the GeomDet surface using * the Propagator argument. The resulting TrajectoryStateOnSurface is @@ -20,12 +19,10 @@ class GeomDetCompatibilityChecker{ * If the propagation fails, or if the state is not compatible, * a std::pair< false, propagatedState> is returned. */ - static std::pair isCompatible(const GeomDet* theDet, - const TrajectoryStateOnSurface& ts, - const Propagator& prop, - const MeasurementEstimator& est); + static std::pair isCompatible(const GeomDet* theDet, + const TrajectoryStateOnSurface& ts, + const Propagator& prop, + const MeasurementEstimator& est); }; - - #endif diff --git a/TrackingTools/DetLayers/interface/GeometricSearchDet.h b/TrackingTools/DetLayers/interface/GeometricSearchDet.h index 66c98acd7a1b9..c7959b2bbea61 100644 --- a/TrackingTools/DetLayers/interface/GeometricSearchDet.h +++ b/TrackingTools/DetLayers/interface/GeometricSearchDet.h @@ -5,7 +5,7 @@ #include "DataFormats/GeometrySurface/interface/BoundSurface.h" #include "TrackingTools/DetLayers/interface/DetGroup.h" -#include "DataFormats/GeometrySurface/interface/Surface.h" +#include "DataFormats/GeometrySurface/interface/Surface.h" #include "TrackingTools/DetLayers/interface/GeomDetCompatibilityChecker.h" #include "TrackingTools/GeomPropagators/interface/Propagator.h" @@ -14,23 +14,23 @@ #include "FWCore/Utilities/interface/GCC11Compatibility.h" -class MeasurementEstimator; +class MeasurementEstimator; class GeometricSearchDet { - public: - typedef std::pair DetWithState; - typedef BoundSurface::PositionType PositionType; - typedef BoundSurface::RotationType RotationType; - typedef TrajectoryStateOnSurface TrajectoryState; - - GeometricSearchDet(bool doHaveGroups ) : haveGroups(doHaveGroups) {} +public: + typedef std::pair DetWithState; + typedef BoundSurface::PositionType PositionType; + typedef BoundSurface::RotationType RotationType; + typedef TrajectoryStateOnSurface TrajectoryState; + + GeometricSearchDet(bool doHaveGroups) : haveGroups(doHaveGroups) {} virtual ~GeometricSearchDet(); - + /// The surface of the GeometricSearchDet virtual const BoundSurface& surface() const = 0; - + /// Returns position of the surface - virtual const Surface::PositionType& position() const {return surface().position();} + virtual const Surface::PositionType& position() const { return surface().position(); } /// Returns basic components, if any //virtual std::vector< const GeomDet*> basicComponents() const = 0; @@ -43,7 +43,6 @@ class GeometricSearchDet { */ virtual const std::vector& basicComponents() const = 0; - /** tests the geometrical compatibility of the Det with the predicted state. * The FreeTrajectoryState argument is propagated to the Det surface using * the Propagator argument. The resulting TrajectoryStateOnSurface is @@ -52,9 +51,9 @@ class GeometricSearchDet { * If the propagation fails, or if the state is not compatible, * a std::pair< false, propagatedState> is returned. */ - virtual std::pair - compatible( const TrajectoryStateOnSurface& ts, const Propagator&, - const MeasurementEstimator&) const=0; + virtual std::pair compatible(const TrajectoryStateOnSurface& ts, + const Propagator&, + const MeasurementEstimator&) const = 0; /** Returns all Dets compatible with a trajectory state * according to the estimator est. @@ -63,15 +62,13 @@ class GeometricSearchDet { * The default implementation should be overridden in dets with * specific surface types to avoid propagation to a generic Surface */ - virtual std::vector - compatibleDets( const TrajectoryStateOnSurface& startingState, - const Propagator& prop, - const MeasurementEstimator& est) const; - virtual void - compatibleDetsV( const TrajectoryStateOnSurface& startingState, - const Propagator& prop, - const MeasurementEstimator& est, - std::vector& result) const; //=0; + virtual std::vector compatibleDets(const TrajectoryStateOnSurface& startingState, + const Propagator& prop, + const MeasurementEstimator& est) const; + virtual void compatibleDetsV(const TrajectoryStateOnSurface& startingState, + const Propagator& prop, + const MeasurementEstimator& est, + std::vector& result) const; //=0; /** Similar to compatibleDets(), but the compatible Dets are grouped in * one or more groups. @@ -92,25 +89,20 @@ class GeometricSearchDet { * First signature: The first argument is a TrajectoryStateOnSurface, usually not * on the surface of this CompositeDet. */ - virtual std::vector - groupedCompatibleDets( const TrajectoryStateOnSurface& startingState, - const Propagator& prop, - const MeasurementEstimator& est) const; - - virtual void - groupedCompatibleDetsV( const TrajectoryStateOnSurface& startingState, - const Propagator& prop, - const MeasurementEstimator& est, - std::vector & result) const; // = 0; + virtual std::vector groupedCompatibleDets(const TrajectoryStateOnSurface& startingState, + const Propagator& prop, + const MeasurementEstimator& est) const; + virtual void groupedCompatibleDetsV(const TrajectoryStateOnSurface& startingState, + const Propagator& prop, + const MeasurementEstimator& est, + std::vector& result) const; // = 0; - bool hasGroups() const { return haveGroups; } + bool hasGroups() const { return haveGroups; } - protected: +protected: GeomDetCompatibilityChecker theCompatibilityChecker; bool haveGroups; - }; - #endif diff --git a/TrackingTools/DetLayers/interface/MeasurementEstimator.h b/TrackingTools/DetLayers/interface/MeasurementEstimator.h index 75201f6676d17..071985cf6d122 100644 --- a/TrackingTools/DetLayers/interface/MeasurementEstimator.h +++ b/TrackingTools/DetLayers/interface/MeasurementEstimator.h @@ -3,7 +3,7 @@ #include "DataFormats/GeometryVector/interface/Vector2DBase.h" #include "DataFormats/GeometryVector/interface/LocalTag.h" -#include +#include class Plane; class TrajectoryStateOnSurface; @@ -16,25 +16,22 @@ class TrackingRecHit; * It is used in the Det interface to obtain compatible measurements. */ - class MeasurementEstimator { public: + struct OpaquePayload { + virtual ~OpaquePayload() {} + int tag = 0; + }; - struct OpaquePayload { virtual ~OpaquePayload(){} int tag=0;}; - - using Local2DVector = Vector2DBase< float, LocalTag>; - + using Local2DVector = Vector2DBase; MeasurementEstimator() {} - MeasurementEstimator(float maxSag, float minToll, float mpt) : - m_maxSagitta(maxSag), - m_minTolerance2(minToll*minToll), - m_minPt2ForHitRecoveryInGluedDet(mpt*mpt) - {} + MeasurementEstimator(float maxSag, float minToll, float mpt) + : m_maxSagitta(maxSag), m_minTolerance2(minToll * minToll), m_minPt2ForHitRecoveryInGluedDet(mpt * mpt) {} virtual ~MeasurementEstimator() {} - using HitReturnType = std::pair; + using HitReturnType = std::pair; using SurfaceReturnType = bool; /** Returns pair( true, value) if the TrajectoryStateOnSurface is compatible @@ -43,23 +40,20 @@ class MeasurementEstimator { * For an estimator where there is no value computed, e.g. fixed * window estimator, only the first(bool) part is of interest. */ - virtual HitReturnType estimate( const TrajectoryStateOnSurface& ts, - const TrackingRecHit& hit) const = 0; + virtual HitReturnType estimate(const TrajectoryStateOnSurface& ts, const TrackingRecHit& hit) const = 0; /* verify the compatibility of the Hit with the Trajectory based * on hit properties other than those used in estimate * (that usually computes the compatibility of the Trajectory with the Hit) * */ - virtual bool preFilter(const TrajectoryStateOnSurface&, OpaquePayload const &) const { return true;} - + virtual bool preFilter(const TrajectoryStateOnSurface&, OpaquePayload const&) const { return true; } /** Returns true if the TrajectoryStateOnSurface is compatible with the * Plane, false otherwise. * The TrajectoryStateOnSurface must be on the plane. */ - virtual SurfaceReturnType estimate( const TrajectoryStateOnSurface& ts, - const Plane& plane) const = 0; + virtual SurfaceReturnType estimate(const TrajectoryStateOnSurface& ts, const Plane& plane) const = 0; virtual MeasurementEstimator* clone() const = 0; @@ -71,13 +65,11 @@ class MeasurementEstimator { * Plane which is entirely outside of the compatibility region defined * by maximalLocalDisplacement(). */ - virtual Local2DVector - maximalLocalDisplacement( const TrajectoryStateOnSurface& ts, - const Plane& plane) const=0; + virtual Local2DVector maximalLocalDisplacement(const TrajectoryStateOnSurface& ts, const Plane& plane) const = 0; - float maxSagitta() const { return m_maxSagitta;} - float minTolerance2() const { return m_minTolerance2;} - float minPt2ForHitRecoveryInGluedDet() const { return m_minPt2ForHitRecoveryInGluedDet;} + float maxSagitta() const { return m_maxSagitta; } + float minTolerance2() const { return m_minTolerance2; } + float minPt2ForHitRecoveryInGluedDet() const { return m_minPt2ForHitRecoveryInGluedDet; } private: /* @@ -85,10 +77,10 @@ class MeasurementEstimator { * MeasurementEstimator is the only configurable item that percolates down to geometry event by event (actually hit by hit) and not at initialization time * It is therefore the natural candidate to collect all parameters that affect pattern-recongnition * and require to be controlled with higher granularity than job level (such as iteration by iteration) - */ - float m_maxSagitta=-1.; // maximal sagitta for linear approximation - float m_minTolerance2=100.; // square of minimum tolerance ot be considered inside a detector - float m_minPt2ForHitRecoveryInGluedDet=std::numeric_limits::max(); // 0.81 to mitigate wrong preAmpl setting + */ + float m_maxSagitta = -1.; // maximal sagitta for linear approximation + float m_minTolerance2 = 100.; // square of minimum tolerance ot be considered inside a detector + float m_minPt2ForHitRecoveryInGluedDet = std::numeric_limits::max(); // 0.81 to mitigate wrong preAmpl setting }; -#endif // Tracker_MeasurementEstimator_H +#endif // Tracker_MeasurementEstimator_H diff --git a/TrackingTools/DetLayers/interface/NavigableLayer.h b/TrackingTools/DetLayers/interface/NavigableLayer.h index d103c3ff0f697..d85190a496437 100644 --- a/TrackingTools/DetLayers/interface/NavigableLayer.h +++ b/TrackingTools/DetLayers/interface/NavigableLayer.h @@ -9,7 +9,6 @@ #include "FWCore/Utilities/interface/GCC11Compatibility.h" - class DetLayer; class FreeTrajectoryState; class NavigationSchool; @@ -22,42 +21,37 @@ class NavigationSchool; * forwarded to the navigable layer. */ -class NavigableLayer { +class NavigableLayer { public: - virtual ~NavigableLayer() {} - virtual std::vector - nextLayers( NavigationDirection direction) const = 0; + virtual std::vector nextLayers(NavigationDirection direction) const = 0; - virtual std::vector - nextLayers( const FreeTrajectoryState& fts, - PropagationDirection timeDirection) const = 0; + virtual std::vector nextLayers(const FreeTrajectoryState& fts, + PropagationDirection timeDirection) const = 0; - virtual std::vector - compatibleLayers( NavigationDirection direction) const = 0; + virtual std::vector compatibleLayers(NavigationDirection direction) const = 0; - virtual std::vector - compatibleLayers( const FreeTrajectoryState& fts, - PropagationDirection timeDirection) const {int counter =0; return compatibleLayers(fts,timeDirection,counter);}; + virtual std::vector compatibleLayers(const FreeTrajectoryState& fts, + PropagationDirection timeDirection) const { + int counter = 0; + return compatibleLayers(fts, timeDirection, counter); + }; - virtual std::vector - compatibleLayers( const FreeTrajectoryState& fts, - PropagationDirection timeDirection, - int& counter)const { + virtual std::vector compatibleLayers(const FreeTrajectoryState& fts, + PropagationDirection timeDirection, + int& counter) const { edm::LogWarning("DetLayers") << "compatibleLayers(fts,dir,counter) not implemented. returning empty vector"; - return std::vector() ; + return std::vector(); } virtual DetLayer const* detLayer() const = 0; - virtual void setDetLayer( DetLayer const* dl) = 0; - - void setSchool(NavigationSchool const * sh) {school = sh;} + virtual void setDetLayer(DetLayer const* dl) = 0; -protected : + void setSchool(NavigationSchool const* sh) { school = sh; } - NavigationSchool const * school=nullptr; - +protected: + NavigationSchool const* school = nullptr; }; -#endif +#endif diff --git a/TrackingTools/DetLayers/interface/NavigationDirection.h b/TrackingTools/DetLayers/interface/NavigationDirection.h index 519e3411c7da5..8214367004f27 100644 --- a/TrackingTools/DetLayers/interface/NavigationDirection.h +++ b/TrackingTools/DetLayers/interface/NavigationDirection.h @@ -1,6 +1,6 @@ #ifndef TrackingTools_DetLayers_NavigationDirection_H #define TrackingTools_DetLayers_NavigationDirection_H -enum NavigationDirection {insideOut, outsideIn}; +enum NavigationDirection { insideOut, outsideIn }; -#endif +#endif diff --git a/TrackingTools/DetLayers/interface/NavigationSchool.h b/TrackingTools/DetLayers/interface/NavigationSchool.h index 17590c9131a63..9e8f48fd8405a 100644 --- a/TrackingTools/DetLayers/interface/NavigationSchool.h +++ b/TrackingTools/DetLayers/interface/NavigationSchool.h @@ -15,52 +15,43 @@ * The result is a container of NavigableLayers. */ - class NavigationSchool { public: - - NavigationSchool() : theAllDetLayersInSystem(nullptr){ -// std::cout << "NVSH: C "<< this << std::endl; + NavigationSchool() : theAllDetLayersInSystem(nullptr) { + // std::cout << "NVSH: C "<< this << std::endl; } virtual ~NavigationSchool() {} - typedef std::vector StateType; + typedef std::vector StateType; virtual StateType navigableLayers() = 0; - - /// Return the next (closest) layer(s) that can be reached in the specified + /// Return the next (closest) layer(s) that can be reached in the specified /// NavigationDirection - template - std::vector - nextLayers(const DetLayer & detLayer, Args && ...args) const { - assert( detLayer.seqNum()>=0); - auto nl = theAllNavigableLayer[detLayer.seqNum()]; - return nl - ? nl->nextLayers(std::forward(args)...) - : std::vector(); + template + std::vector nextLayers(const DetLayer& detLayer, Args&&... args) const { + assert(detLayer.seqNum() >= 0); + auto nl = theAllNavigableLayer[detLayer.seqNum()]; + return nl ? nl->nextLayers(std::forward(args)...) : std::vector(); } - - /// Returns all layers compatible - template - std::vector - compatibleLayers(const DetLayer & detLayer, Args && ...args) const { + + /// Returns all layers compatible + template + std::vector compatibleLayers(const DetLayer& detLayer, Args&&... args) const { auto nl = theAllNavigableLayer[detLayer.seqNum()]; - return nl - ? nl->compatibleLayers(std::forward(args)...) - : std::vector(); + return nl ? nl->compatibleLayers(std::forward(args)...) : std::vector(); } protected: - - void setState( const StateType& state) { - // std::cout << "NVSH: set "<< this << ' ' << typeid(*this).name() - // << ' ' << state.size() << ' ' << theAllNavigableLayer.size() << std::endl; + void setState(const StateType& state) { + // std::cout << "NVSH: set "<< this << ' ' << typeid(*this).name() + // << ' ' << state.size() << ' ' << theAllNavigableLayer.size() << std::endl; for (auto nl : state) { - if (!nl) continue; - theAllNavigableLayer[nl->detLayer()->seqNum()]=nl; + if (!nl) + continue; + theAllNavigableLayer[nl->detLayer()->seqNum()] = nl; nl->setSchool(this); } } @@ -68,12 +59,12 @@ class NavigationSchool { // index correspond to seqNum of DetLayers StateType theAllNavigableLayer; - // will be obsoleted together with NAvigationSetter public: - const std::vector & allLayersInSystem() const {return *theAllDetLayersInSystem;} - protected: - const std::vector * theAllDetLayersInSystem; + const std::vector& allLayersInSystem() const { return *theAllDetLayersInSystem; } + +protected: + const std::vector* theAllDetLayersInSystem; }; -#endif // NavigationSchool_H +#endif // NavigationSchool_H diff --git a/TrackingTools/DetLayers/interface/PeriodicBinFinderInZ.h b/TrackingTools/DetLayers/interface/PeriodicBinFinderInZ.h index dfa451e658bc0..ade7bfb905897 100644 --- a/TrackingTools/DetLayers/interface/PeriodicBinFinderInZ.h +++ b/TrackingTools/DetLayers/interface/PeriodicBinFinderInZ.h @@ -12,38 +12,28 @@ template class PeriodicBinFinderInZ : public BaseBinFinder { public: - PeriodicBinFinderInZ() : theNbins(0), theZStep(0), theZOffset(0) {} PeriodicBinFinderInZ(std::vector::const_iterator first, - std::vector::const_iterator last) : - theNbins( last-first) - { + std::vector::const_iterator last) + : theNbins(last - first) { float zFirst = (**first).surface().position().z(); - theZStep = ((**(last-1)).surface().position().z() - zFirst) / (theNbins-1); - theZOffset = zFirst - 0.5*theZStep; + theZStep = ((**(last - 1)).surface().position().z() - zFirst) / (theNbins - 1); + theZOffset = zFirst - 0.5 * theZStep; } /// returns an index in the valid range for the bin that contains Z - int binIndex( T z) const override { - return binIndex( int((z-theZOffset)/theZStep)); - } + int binIndex(T z) const override { return binIndex(int((z - theZOffset) / theZStep)); } /// returns an index in the valid range - int binIndex( int i) const override { - return std::min( std::max( i, 0), theNbins-1); - } - - /// the middle of the bin - T binPosition( int ind) const override { - return theZOffset + theZStep * ( ind + 0.5); - } + int binIndex(int i) const override { return std::min(std::max(i, 0), theNbins - 1); } -private: + /// the middle of the bin + T binPosition(int ind) const override { return theZOffset + theZStep * (ind + 0.5); } +private: int theNbins; T theZStep; T theZOffset; - }; #endif diff --git a/TrackingTools/DetLayers/interface/PhiBorderFinder.h b/TrackingTools/DetLayers/interface/PhiBorderFinder.h index c0bf486908222..0cb878c32ef84 100644 --- a/TrackingTools/DetLayers/interface/PhiBorderFinder.h +++ b/TrackingTools/DetLayers/interface/PhiBorderFinder.h @@ -8,7 +8,6 @@ * \author N. Amapane - INFN Torino */ - #include #include @@ -27,24 +26,22 @@ class PhiBorderFinder { public: - - typedef DetRod Det; //FIXME!!! - typedef geomsort::ExtractPhi DetPhi; - + typedef DetRod Det; //FIXME!!! + typedef geomsort::ExtractPhi DetPhi; PhiBorderFinder(const std::vector& utheDets); - + virtual ~PhiBorderFinder(){}; - inline unsigned int nBins() {return theNbins;} + inline unsigned int nBins() { return theNbins; } /// Returns true if the Dets are periodic in phi. inline bool isPhiPeriodic() const { return isPhiPeriodic_; } - + /// Returns true if any 2 of the Det overlap in phi. inline bool isPhiOverlapping() const { return isPhiOverlapping_; } - /// The borders, defined for each det as the middle between its lower + /// The borders, defined for each det as the middle between its lower /// edge and the previous Det's upper edge. inline const std::vector& phiBorders() const { return thePhiBorders; } @@ -61,17 +58,11 @@ class PhiBorderFinder { std::vector thePhiBorders; std::vector thePhiBins; - inline double positiveRange (double phi) const - { - return (phi > 0) ? phi : phi + Geom::twoPi(); - } + inline double positiveRange(double phi) const { return (phi > 0) ? phi : phi + Geom::twoPi(); } - int binIndex( int i) const { + int binIndex(int i) const { int ind = i % (int)theNbins; - return (ind < 0) ? ind+theNbins : ind; + return (ind < 0) ? ind + theNbins : ind; } - - }; #endif - diff --git a/TrackingTools/DetLayers/interface/RBorderFinder.h b/TrackingTools/DetLayers/interface/RBorderFinder.h index 2a380c975a89e..2000b64455637 100644 --- a/TrackingTools/DetLayers/interface/RBorderFinder.h +++ b/TrackingTools/DetLayers/interface/RBorderFinder.h @@ -21,21 +21,20 @@ class RBorderFinder { public: - - typedef ForwardDetRing Det; //FIXME!!! - typedef geomsort::ExtractR DetR; + typedef ForwardDetRing Det; //FIXME!!! + typedef geomsort::ExtractR DetR; RBorderFinder(const std::vector& utheDets); - + virtual ~RBorderFinder(){}; /// Returns true if the Dets are periodic in R. inline bool isRPeriodic() const { return isRPeriodic_; } - + /// Returns true if any 2 of the Det overlap in R. inline bool isROverlapping() const { return isROverlapping_; } - /// The borders, defined for each det as the middle between its lower + /// The borders, defined for each det as the middle between its lower /// edge and the previous Det's upper edge. inline std::vector RBorders() const { return theRBorders; } @@ -45,7 +44,6 @@ class RBorderFinder { // inline std::vector etaBorders() {} // inline std::vector zBorders() {} - private: int theNbins; bool isRPeriodic_; @@ -53,9 +51,6 @@ class RBorderFinder { std::vector theRBorders; std::vector theRBins; - inline int binIndex( int i) const { - return std::min( std::max( i, 0), theNbins-1); - } + inline int binIndex(int i) const { return std::min(std::max(i, 0), theNbins - 1); } }; #endif - diff --git a/TrackingTools/DetLayers/interface/RingedForwardLayer.h b/TrackingTools/DetLayers/interface/RingedForwardLayer.h index bb9bdd59f2855..879b508c73c6f 100644 --- a/TrackingTools/DetLayers/interface/RingedForwardLayer.h +++ b/TrackingTools/DetLayers/interface/RingedForwardLayer.h @@ -10,6 +10,5 @@ class ForwardDetRing; class ForwardDetRingBuilder; -using RingedForwardLayer = ForwardDetLayer; +using RingedForwardLayer = ForwardDetLayer; #endif - diff --git a/TrackingTools/DetLayers/interface/RodBarrelLayer.h b/TrackingTools/DetLayers/interface/RodBarrelLayer.h index 57c6cf891d354..b3adaf73ed300 100644 --- a/TrackingTools/DetLayers/interface/RodBarrelLayer.h +++ b/TrackingTools/DetLayers/interface/RodBarrelLayer.h @@ -10,6 +10,6 @@ class DetRod; class MeasurementEstimator; -using RodBarrelLayer=BarrelDetLayer; +using RodBarrelLayer = BarrelDetLayer; #endif diff --git a/TrackingTools/DetLayers/interface/RodPlaneBuilderFromDet.h b/TrackingTools/DetLayers/interface/RodPlaneBuilderFromDet.h index f1df48c2d36cd..5b6109f22414f 100644 --- a/TrackingTools/DetLayers/interface/RodPlaneBuilderFromDet.h +++ b/TrackingTools/DetLayers/interface/RodPlaneBuilderFromDet.h @@ -15,18 +15,16 @@ class RectangularPlaneBounds; class RodPlaneBuilderFromDet { public: typedef GeomDet Det; - + /// Warning, remember to assign this pointer to a ReferenceCountingPointer! /// Should be changed to return a ReferenceCountingPointer - Plane* operator()( const std::vector& dets) const; - - std::pair - computeBounds( const std::vector& dets, const Plane& plane) const; + Plane* operator()(const std::vector& dets) const; - Surface::RotationType - computeRotation( const std::vector& dets, - const Surface::PositionType& meanPos) const; + std::pair computeBounds(const std::vector& dets, + const Plane& plane) const; + Surface::RotationType computeRotation(const std::vector& dets, + const Surface::PositionType& meanPos) const; }; #endif diff --git a/TrackingTools/DetLayers/interface/TkLayerLess.h b/TrackingTools/DetLayers/interface/TkLayerLess.h index fcbb5b01477a2..3a3ccdaa7c807 100644 --- a/TrackingTools/DetLayers/interface/TkLayerLess.h +++ b/TrackingTools/DetLayers/interface/TkLayerLess.h @@ -13,38 +13,37 @@ class TkLayerLess { public: - - TkLayerLess( NavigationDirection dir = insideOut, const DetLayer * fromLayer = nullptr) : - theDir(dir) { - if (fromLayer){ + TkLayerLess(NavigationDirection dir = insideOut, const DetLayer* fromLayer = nullptr) : theDir(dir) { + if (fromLayer) { theOriginLayer = true; - theFromLayerSign = (fromLayer->position().z()>0 ? 1 : -1) ; - }else theOriginLayer = false; + theFromLayerSign = (fromLayer->position().z() > 0 ? 1 : -1); + } else + theOriginLayer = false; } - bool operator()( const DetLayer* a, const DetLayer* b) const { - if (!theOriginLayer){ - if (theDir == insideOut) return insideOutLess( a, b); - else return insideOutLess( b, a); - } - else{ - if (theDir == insideOut) return insideOutLessSigned( a, b); - else return insideOutLessSigned(b, a); + bool operator()(const DetLayer* a, const DetLayer* b) const { + if (!theOriginLayer) { + if (theDir == insideOut) + return insideOutLess(a, b); + else + return insideOutLess(b, a); + } else { + if (theDir == insideOut) + return insideOutLessSigned(a, b); + else + return insideOutLessSigned(b, a); } } private: - NavigationDirection theDir; - bool theOriginLayer; //true take into account next parameter, false, do as usual - int theFromLayerSign; //1 z>0: -1 z<0 - - bool insideOutLess( const DetLayer*,const DetLayer*) const; - bool insideOutLessSigned( const DetLayer*,const DetLayer*) const; + bool theOriginLayer; //true take into account next parameter, false, do as usual + int theFromLayerSign; //1 z>0: -1 z<0 - bool barrelForwardLess( const BarrelDetLayer* blb, - const ForwardDetLayer* fla) const; + bool insideOutLess(const DetLayer*, const DetLayer*) const; + bool insideOutLessSigned(const DetLayer*, const DetLayer*) const; + bool barrelForwardLess(const BarrelDetLayer* blb, const ForwardDetLayer* fla) const; }; #endif diff --git a/TrackingTools/DetLayers/interface/rangesIntersect.h b/TrackingTools/DetLayers/interface/rangesIntersect.h index b85faf1eee407..60ef0a1b731bc 100644 --- a/TrackingTools/DetLayers/interface/rangesIntersect.h +++ b/TrackingTools/DetLayers/interface/rangesIntersect.h @@ -11,18 +11,16 @@ */ template -inline bool rangesIntersect( const Range& a, const Range& b) { - return !( (a.first > b.second) | (b.first > a.second) ); +inline bool rangesIntersect(const Range& a, const Range& b) { + return !((a.first > b.second) | (b.first > a.second)); } template -inline bool rangesIntersect( const Range& a, const Range& b, - Less const &less) { - return !( less(b.second,a.first) | less(a.second,b.first)); +inline bool rangesIntersect(const Range& a, const Range& b, Less const& less) { + return !(less(b.second, a.first) | less(a.second, b.first)); } template -inline bool rangesIntersect( const Range& a, const Range& b, - bool (*less)(T,T)) { - return !( less(b.second,a.first) | less(a.second,b.first)); +inline bool rangesIntersect(const Range& a, const Range& b, bool (*less)(T, T)) { + return !(less(b.second, a.first) | less(a.second, b.first)); } #endif diff --git a/TrackingTools/DetLayers/interface/simple_stat.h b/TrackingTools/DetLayers/interface/simple_stat.h index cd989fb5b051a..9304738c69283 100644 --- a/TrackingTools/DetLayers/interface/simple_stat.h +++ b/TrackingTools/DetLayers/interface/simple_stat.h @@ -9,9 +9,9 @@ * STL container. */ -template< class CONT> -double stat_mean( const CONT & cont) { - double sum = accumulate (cont.begin(), cont.end(), 0.); +template +double stat_mean(const CONT& cont) { + double sum = accumulate(cont.begin(), cont.end(), 0.); return sum / cont.size(); } @@ -19,22 +19,20 @@ double stat_mean( const CONT & cont) { * STL container. */ - -template< class CONT> -double stat_RMS( const CONT & cont) { - +template +double stat_RMS(const CONT& cont) { typename CONT::const_iterator i; int N = cont.size(); if (N > 1) { - double sum=0., sum2=0.; - for (i=cont.begin(); i!=cont.end(); i++) { - sum += *i; - sum2 += (*i) * (*i); + double sum = 0., sum2 = 0.; + for (i = cont.begin(); i != cont.end(); i++) { + sum += *i; + sum2 += (*i) * (*i); } - return sqrt( std::max( 0., (sum2 - sum*sum/N) / (N-1))) ; - } - else return 0.; + return sqrt(std::max(0., (sum2 - sum * sum / N) / (N - 1))); + } else + return 0.; } -#endif // TrackingTools_DetLayers_simple_stat_h +#endif // TrackingTools_DetLayers_simple_stat_h diff --git a/TrackingTools/DetLayers/src/BarrelDetLayer.cc b/TrackingTools/DetLayers/src/BarrelDetLayer.cc index fe5c1abbaee59..7818e0119befd 100644 --- a/TrackingTools/DetLayers/src/BarrelDetLayer.cc +++ b/TrackingTools/DetLayers/src/BarrelDetLayer.cc @@ -1,6 +1,6 @@ #include "TrackingTools/DetLayers/interface/BarrelDetLayer.h" -#include "DataFormats/GeometrySurface/interface/Surface.h" -#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" +#include "DataFormats/GeometrySurface/interface/Surface.h" +#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "DataFormats/GeometrySurface/interface/SimpleCylinderBounds.h" #include "DataFormats/GeometrySurface/interface/BoundingBox.h" @@ -9,94 +9,77 @@ using namespace std; BarrelDetLayer::~BarrelDetLayer() {} - - //--- Extension of the interface -void BarrelDetLayer::setSurface( BoundCylinder* cp) { - theCylinder = cp; -} - -bool BarrelDetLayer::contains(const Local3DPoint& p) const { - return surface().bounds().inside(p); -} - -void BarrelDetLayer::initialize() -{ - setSurface( computeSurface()); -} +void BarrelDetLayer::setSurface(BoundCylinder* cp) { theCylinder = cp; } +bool BarrelDetLayer::contains(const Local3DPoint& p) const { return surface().bounds().inside(p); } +void BarrelDetLayer::initialize() { setSurface(computeSurface()); } //--- protected methods BoundCylinder* BarrelDetLayer::computeSurface() { - vector< const GeomDet*> comps = basicComponents(); + vector comps = basicComponents(); // Find extension in Z - float theRmin = comps.front()->position().perp(); + float theRmin = comps.front()->position().perp(); float theRmax = theRmin; - float theZmin = comps.front()->position().z(); + float theZmin = comps.front()->position().z(); float theZmax = theZmin; - for ( vector< const GeomDet*>::const_iterator deti = comps.begin(); - deti != comps.end(); deti++) { - vector corners = - BoundingBox().corners( dynamic_cast((*deti)->surface())); - for (vector::const_iterator ic = corners.begin(); - ic != corners.end(); ic++) { + for (vector::const_iterator deti = comps.begin(); deti != comps.end(); deti++) { + vector corners = BoundingBox().corners(dynamic_cast((*deti)->surface())); + for (vector::const_iterator ic = corners.begin(); ic != corners.end(); ic++) { float r = ic->perp(); float z = ic->z(); - theRmin = min( theRmin, r); - theRmax = max( theRmax, r); - theZmin = min( theZmin, z); - theZmax = max( theZmax, z); + theRmin = min(theRmin, r); + theRmax = max(theRmax, r); + theZmin = min(theZmin, z); + theZmax = max(theZmax, z); } - // in addition to the corners we have to check the middle of the + // in addition to the corners we have to check the middle of the // det +/- thickness/2 // , since the min radius for some barrel dets is reached there float rdet = (**deti).position().perp(); float thick = (**deti).surface().bounds().thickness(); - theRmin = min( theRmin, rdet-thick/2.F); - theRmax = max( theRmax, rdet+thick/2.F); + theRmin = min(theRmin, rdet - thick / 2.F); + theRmax = max(theRmax, rdet + thick / 2.F); } - - // By default the barrel layers are positioned at the center of the - // global frame, and the axes of their local frame coincide with + + // By default the barrel layers are positioned at the center of the + // global frame, and the axes of their local frame coincide with // those of the global grame (z along the cylinder axis) - PositionType pos(0.,0.,0.); + PositionType pos(0., 0., 0.); RotationType rot; - auto scp = new SimpleCylinderBounds( theRmin, theRmax, - theZmin, theZmax); + auto scp = new SimpleCylinderBounds(theRmin, theRmax, theZmin, theZmax); return new Cylinder(Cylinder::computeRadius(*scp), pos, rot, scp); -} - +} -pair -BarrelDetLayer::compatible( const TrajectoryStateOnSurface& ts, - const Propagator& prop, - const MeasurementEstimator&) const -{ - if UNLIKELY(theCylinder == nullptr) edm::LogError("DetLayers") - << "ERROR: BarrelDetLayer::compatible() is used before the layer surface is initialized" ; +pair BarrelDetLayer::compatible(const TrajectoryStateOnSurface& ts, + const Propagator& prop, + const MeasurementEstimator&) const { + if + UNLIKELY(theCylinder == nullptr) + edm::LogError("DetLayers") << "ERROR: BarrelDetLayer::compatible() is used before the layer surface is initialized"; // throw an exception? which one? - TrajectoryStateOnSurface myState = prop.propagate( ts, specificSurface()); - if UNLIKELY(!myState.isValid()) return make_pair( false, myState); - + TrajectoryStateOnSurface myState = prop.propagate(ts, specificSurface()); + if + UNLIKELY(!myState.isValid()) return make_pair(false, myState); // check z assuming symmetric bounds around position().z() - auto z0 = std::abs(myState.globalPosition().z()-specificSurface().position().z()); - auto deltaZ = 0.5f*bounds().length(); - if (z0::const_iterator first, - vector::const_iterator last) const -{ +BoundCylinder* CylinderBuilderFromDet::operator()(vector::const_iterator first, + vector::const_iterator last) const { // find mean position and radius typedef PositionType::BasicVectorType Vector; - Vector posSum(0,0,0); + Vector posSum(0, 0, 0); float rSum = 0; - for (vector::const_iterator i=first; i!=last; i++) { + for (vector::const_iterator i = first; i != last; i++) { posSum += (**i).surface().position().basicVector(); rSum += (**i).surface().position().perp(); } - float div(1/float(last-first)); - PositionType meanPos( div*posSum); - float meanR( div*rSum); + float div(1 / float(last - first)); + PositionType meanPos(div * posSum); + float meanR(div * rSum); // find max deviations from mean pos in Z and from mean R float rmin = meanR; float rmax = meanR; float zmin = meanPos.z(); float zmax = meanPos.z(); - for (vector::const_iterator i=first; i!=last; i++) { - vector corners = - BoundingBox::corners( dynamic_cast((**i).surface())); - for (vector::const_iterator ic = corners.begin(); - ic != corners.end(); ic++) { + for (vector::const_iterator i = first; i != last; i++) { + vector corners = BoundingBox::corners(dynamic_cast((**i).surface())); + for (vector::const_iterator ic = corners.begin(); ic != corners.end(); ic++) { float r = ic->perp(); float z = ic->z(); - rmin = min( rmin, r); - rmax = max( rmax, r); - zmin = min( zmin, z); - zmax = max( zmax, z); + rmin = min(rmin, r); + rmax = max(rmax, r); + zmin = min(zmin, z); + zmax = max(zmax, z); } - // in addition to the corners we have to check the middle of the + // in addition to the corners we have to check the middle of the // det +/- thickness/2 // , since the min radius for some barrel dets is reached there float rdet = (**i).surface().position().perp(); float halfThick = (**i).surface().bounds().thickness() / 2.F; - rmin = min( rmin, rdet-halfThick); - rmax = max( rmax, rdet+halfThick); + rmin = min(rmin, rdet - halfThick); + rmax = max(rmax, rdet + halfThick); } // the transverse position is zero by construction. - // the Z position is the average between zmin and zmax, since the bounds + // the Z position is the average between zmin and zmax, since the bounds // are symmetric // for the same reason the R is the average between rmin and rmax, // but this is done by the Bounds anyway. - PositionType pos( 0, 0, 0.5*(zmin+zmax)); - RotationType rot; // only "barrel" orientation supported - - auto scp = new SimpleCylinderBounds( rmin, rmax, - zmin-pos.z(), zmax-pos.z()); - return new Cylinder(Cylinder::computeRadius(*scp), pos, rot, scp); + PositionType pos(0, 0, 0.5 * (zmin + zmax)); + RotationType rot; // only "barrel" orientation supported + auto scp = new SimpleCylinderBounds(rmin, rmax, zmin - pos.z(), zmax - pos.z()); + return new Cylinder(Cylinder::computeRadius(*scp), pos, rot, scp); } void CylinderBuilderFromDet::operator()(const Det& det) { - BoundingBox bb( dynamic_cast(det.surface())); - for (int nc=0; nc<8; ++nc) { + BoundingBox bb(dynamic_cast(det.surface())); + for (int nc = 0; nc < 8; ++nc) { float r = bb[nc].perp(); float z = bb[nc].z(); - rmin = std::min( rmin, r); - rmax = std::max( rmax, r); - zmin = std::min( zmin, z); - zmax = std::max( zmax, z); + rmin = std::min(rmin, r); + rmax = std::max(rmax, r); + zmin = std::min(zmin, z); + zmax = std::max(zmax, z); } - // in addition to the corners we have to check the middle of the + // in addition to the corners we have to check the middle of the // det +/- thickness/2 // , since the min radius for some barrel dets is reached there float rdet = det.surface().position().perp(); float halfThick = det.surface().bounds().thickness() / 2.F; - rmin = std::min( rmin, rdet-halfThick); - rmax = std::max( rmax, rdet+halfThick); + rmin = std::min(rmin, rdet - halfThick); + rmax = std::max(rmax, rdet + halfThick); } BoundCylinder* CylinderBuilderFromDet::build() const { - - PositionType pos( 0, 0, 0.5*(zmin+zmax)); - RotationType rot; // only "barrel" orientation supported + PositionType pos(0, 0, 0.5 * (zmin + zmax)); + RotationType rot; // only "barrel" orientation supported - auto scp = new SimpleCylinderBounds( rmin, rmax, - zmin-pos.z(), zmax-pos.z()); + auto scp = new SimpleCylinderBounds(rmin, rmax, zmin - pos.z(), zmax - pos.z()); return new Cylinder(Cylinder::computeRadius(*scp), pos, rot, scp); - } diff --git a/TrackingTools/DetLayers/src/DetLayer.cc b/TrackingTools/DetLayers/src/DetLayer.cc index e2bb1c0a8b9be..fed25bf92453d 100644 --- a/TrackingTools/DetLayers/src/DetLayer.cc +++ b/TrackingTools/DetLayers/src/DetLayer.cc @@ -1,5 +1,3 @@ #include "TrackingTools/DetLayers/interface/DetLayer.h" DetLayer::~DetLayer() {} - - diff --git a/TrackingTools/DetLayers/src/DetLessZ.h b/TrackingTools/DetLayers/src/DetLessZ.h index f662f126f354a..52201a8718410 100644 --- a/TrackingTools/DetLayers/src/DetLessZ.h +++ b/TrackingTools/DetLayers/src/DetLessZ.h @@ -7,19 +7,16 @@ #include "TrackingTools/DetLayers/src/DetLessZ.h" #include "TrackingTools/DetLayers/interface/GeometricSearchDet.h" -inline bool isDetLessZ( const GeometricSearchDet* a, const GeometricSearchDet* b) { - +inline bool isDetLessZ(const GeometricSearchDet* a, const GeometricSearchDet* b) { // multiply by 1+epsilon to make it numericaly stable // the epsilon should depend on the scalar precision, // this is just a quick fix! if (a->position().z() > 0) { - return a->position().z()*1.000001 < b->position().z(); - } - else if (b->position().z() < 0) { - return a->position().z() < b->position().z()*1.000001; - } - else return true; + return a->position().z() * 1.000001 < b->position().z(); + } else if (b->position().z() < 0) { + return a->position().z() < b->position().z() * 1.000001; + } else + return true; } - -#endif +#endif diff --git a/TrackingTools/DetLayers/src/DetRod.cc b/TrackingTools/DetLayers/src/DetRod.cc index 15126925f33ba..61e503231fac9 100644 --- a/TrackingTools/DetLayers/src/DetRod.cc +++ b/TrackingTools/DetLayers/src/DetRod.cc @@ -2,9 +2,7 @@ using namespace std; -DetRod::~DetRod(){} - - +DetRod::~DetRod() {} //obsolete? /* diff --git a/TrackingTools/DetLayers/src/DetRodOneR.cc b/TrackingTools/DetLayers/src/DetRodOneR.cc index 2022838b246eb..faccf36ce2c71 100644 --- a/TrackingTools/DetLayers/src/DetRodOneR.cc +++ b/TrackingTools/DetLayers/src/DetRodOneR.cc @@ -1,5 +1,5 @@ #include "TrackingTools/DetLayers/interface/DetRodOneR.h" -#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" +#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" #include "TrackingTools/DetLayers/interface/RodPlaneBuilderFromDet.h" #include @@ -10,45 +10,35 @@ using namespace std; -DetRodOneR::~DetRodOneR(){} +DetRodOneR::~DetRodOneR() {} -DetRodOneR::DetRodOneR(vector::const_iterator first, - vector::const_iterator last) - : DetRod(false), theDets(first,last) -{ - initialize(); -} - -DetRodOneR::DetRodOneR( const vector& dets) - : DetRod(false), theDets(dets) -{ +DetRodOneR::DetRodOneR(vector::const_iterator first, vector::const_iterator last) + : DetRod(false), theDets(first, last) { initialize(); } +DetRodOneR::DetRodOneR(const vector& dets) : DetRod(false), theDets(dets) { initialize(); } -void DetRodOneR::initialize() -{ +void DetRodOneR::initialize() { // assume the dets ARE in a rod; // sort them in Z - precomputed_value_sort( theDets.begin(), theDets.end(), geomsort::DetZ()); - - setPlane( RodPlaneBuilderFromDet()( theDets)); - -} + precomputed_value_sort(theDets.begin(), theDets.end(), geomsort::DetZ()); + setPlane(RodPlaneBuilderFromDet()(theDets)); +} // It needs that the basic component to have the compatible() method -bool DetRodOneR::add( int idet, vector& result, - const TrajectoryStateOnSurface& startingState, - const Propagator& prop, - const MeasurementEstimator& est) const -{ - pair compat = - theCompatibilityChecker.isCompatible(theDets[idet],startingState, prop, est); - +bool DetRodOneR::add(int idet, + vector& result, + const TrajectoryStateOnSurface& startingState, + const Propagator& prop, + const MeasurementEstimator& est) const { + pair compat = + theCompatibilityChecker.isCompatible(theDets[idet], startingState, prop, est); + if (compat.first) { - result.push_back( DetWithState( theDets[idet], compat.second)); + result.push_back(DetWithState(theDets[idet], compat.second)); } return compat.first; diff --git a/TrackingTools/DetLayers/src/ForwardDetLayer.cc b/TrackingTools/DetLayers/src/ForwardDetLayer.cc index 987d305144cc3..9393029cc3859 100644 --- a/TrackingTools/DetLayers/src/ForwardDetLayer.cc +++ b/TrackingTools/DetLayers/src/ForwardDetLayer.cc @@ -1,130 +1,108 @@ #include "TrackingTools/DetLayers/interface/ForwardDetLayer.h" -#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" +#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "DataFormats/GeometrySurface/interface/SimpleDiskBounds.h" #include "DataFormats/GeometrySurface/interface/BoundingBox.h" using namespace std; - -ForwardDetLayer::~ForwardDetLayer() { -} - +ForwardDetLayer::~ForwardDetLayer() {} //--- Extension of the interface -void ForwardDetLayer::setSurface( BoundDisk* cp) { - theDisk = cp; -} - -bool ForwardDetLayer::contains(const Local3DPoint& p) const { - return surface().bounds().inside(p); -} - +void ForwardDetLayer::setSurface(BoundDisk* cp) { theDisk = cp; } -void ForwardDetLayer::initialize() { - setSurface( computeSurface()); -} +bool ForwardDetLayer::contains(const Local3DPoint& p) const { return surface().bounds().inside(p); } +void ForwardDetLayer::initialize() { setSurface(computeSurface()); } BoundDisk* ForwardDetLayer::computeSurface() { - LogDebug("DetLayers") << "ForwaLayer::computeSurface callded" ; - vector comps= basicComponents(); + LogDebug("DetLayers") << "ForwaLayer::computeSurface callded"; + vector comps = basicComponents(); vector::const_iterator ifirst = comps.begin(); - vector::const_iterator ilast = comps.end(); + vector::const_iterator ilast = comps.end(); // Find extension in R - float theRmin = components().front()->position().perp(); + float theRmin = components().front()->position().perp(); float theRmax = theRmin; float theZmin = components().back()->position().z(); float theZmax = theZmin; - for ( vector::const_iterator deti = ifirst; - deti != ilast; deti++) { - vector corners = - BoundingBox().corners( dynamic_cast((**deti).surface())); - for (vector::const_iterator ic = corners.begin(); - ic != corners.end(); ic++) { + for (vector::const_iterator deti = ifirst; deti != ilast; deti++) { + vector corners = BoundingBox().corners(dynamic_cast((**deti).surface())); + for (vector::const_iterator ic = corners.begin(); ic != corners.end(); ic++) { float r = ic->perp(); - LogDebug("DetLayers") << "corner.perp(): " << r ; + LogDebug("DetLayers") << "corner.perp(): " << r; float z = ic->z(); - theRmin = min( theRmin, r); - theRmax = max( theRmax, r); - theZmin = min( theZmin, z); - theZmax = max( theZmax, z); + theRmin = min(theRmin, r); + theRmax = max(theRmax, r); + theZmin = min(theZmin, z); + theZmax = max(theZmax, z); } - // in addition to the corners we have to check the middle of the + // in addition to the corners we have to check the middle of the // det +/- length/2 // , since the min (max) radius for typical fw dets is reached there - float rdet = (**deti).position().perp(); - float len = (**deti).surface().bounds().length(); + float rdet = (**deti).position().perp(); + float len = (**deti).surface().bounds().length(); float width = (**deti).surface().bounds().width(); - GlobalVector xAxis = (**deti).toGlobal(LocalVector(1,0,0)); - GlobalVector yAxis = (**deti).toGlobal(LocalVector(0,1,0)); - GlobalVector perpDir = GlobalVector( (**deti).position() - GlobalPoint(0,0,(**deti).position().z()) ); + GlobalVector xAxis = (**deti).toGlobal(LocalVector(1, 0, 0)); + GlobalVector yAxis = (**deti).toGlobal(LocalVector(0, 1, 0)); + GlobalVector perpDir = GlobalVector((**deti).position() - GlobalPoint(0, 0, (**deti).position().z())); double xAxisCos = xAxis.unit().dot(perpDir.unit()); double yAxisCos = yAxis.unit().dot(perpDir.unit()); - LogDebug("DetLayers") << "in ForwardDetLayer::computeSurface(),xAxisCos,yAxisCos: " << xAxisCos << " , " << yAxisCos ; - LogDebug("DetLayers") << "det pos.perp,length,width: " - << rdet << " , " - << len << " , " - << width ; - - if( fabs(xAxisCos) > fabs(yAxisCos) ) { - theRmin = min( theRmin, rdet-width/2.F); - theRmax = max( theRmax, rdet+width/2.F); - }else{ - theRmin = min( theRmin, rdet-len/2.F); - theRmax = max( theRmax, rdet+len/2.F); + LogDebug("DetLayers") << "in ForwardDetLayer::computeSurface(),xAxisCos,yAxisCos: " << xAxisCos << " , " + << yAxisCos; + LogDebug("DetLayers") << "det pos.perp,length,width: " << rdet << " , " << len << " , " << width; + + if (fabs(xAxisCos) > fabs(yAxisCos)) { + theRmin = min(theRmin, rdet - width / 2.F); + theRmax = max(theRmax, rdet + width / 2.F); + } else { + theRmin = min(theRmin, rdet - len / 2.F); + theRmax = max(theRmax, rdet + len / 2.F); } } - - LogDebug("DetLayers") << "creating SimpleDiskBounds with r range" << theRmin << " " - << theRmax << " and z range " << theZmin << " " << theZmax ; + LogDebug("DetLayers") << "creating SimpleDiskBounds with r range" << theRmin << " " << theRmax << " and z range " + << theZmin << " " << theZmax; // By default the forward layers are positioned around the z axis of the - // global frame, and the axes of their local frame coincide with + // global frame, and the axes of their local frame coincide with // those of the global grame (z along the disk axis) - float zPos = (theZmax+theZmin)/2.; - PositionType pos(0.,0.,zPos); + float zPos = (theZmax + theZmin) / 2.; + PositionType pos(0., 0., zPos); RotationType rot; - return new BoundDisk( pos, rot, - new SimpleDiskBounds( theRmin, theRmax, - theZmin-zPos, theZmax-zPos)); -} - + return new BoundDisk(pos, rot, new SimpleDiskBounds(theRmin, theRmax, theZmin - zPos, theZmax - zPos)); +} -pair -ForwardDetLayer::compatible( const TrajectoryStateOnSurface& ts, - const Propagator& prop, - const MeasurementEstimator&) const -{ - if UNLIKELY(theDisk == nullptr) edm::LogError("DetLayers") - << "ERROR: BarrelDetLayer::compatible() is used before the layer surface is initialized" ; +pair ForwardDetLayer::compatible(const TrajectoryStateOnSurface& ts, + const Propagator& prop, + const MeasurementEstimator&) const { + if + UNLIKELY(theDisk == nullptr) + edm::LogError("DetLayers") << "ERROR: BarrelDetLayer::compatible() is used before the layer surface is initialized"; // throw an exception? which one? - TrajectoryStateOnSurface myState = prop.propagate( ts, specificSurface()); - if UNLIKELY( !myState.isValid()) return make_pair( false, myState); - + TrajectoryStateOnSurface myState = prop.propagate(ts, specificSurface()); + if + UNLIKELY(!myState.isValid()) return make_pair(false, myState); // check z; (are we sure?????) // auto z = myState.localPosition().z(); // if ( zbounds().maxZ) return make_pair( false, myState); // check r - auto r2 = myState.localPosition().perp2(); - if ( (r2 > rmin()*rmin()) & (r2< rmax()*rmax()) ) return make_pair( true, myState); - + auto r2 = myState.localPosition().perp2(); + if ((r2 > rmin() * rmin()) & (r2 < rmax() * rmax())) + return make_pair(true, myState); // take into account the thickness of the layer - float deltaR = 0.5f*bounds().thickness() * - myState.localDirection().perp()/std::abs(myState.localDirection().z()); + float deltaR = 0.5f * bounds().thickness() * myState.localDirection().perp() / std::abs(myState.localDirection().z()); // and take into account the error on the predicted state const float nSigma = 3.; @@ -135,7 +113,9 @@ ForwardDetLayer::compatible( const TrajectoryStateOnSurface& ts, } // check r again; - auto ri2 = std::max(rmin()-deltaR,0.f); ri2*=ri2; - auto ro2 = rmax()+deltaR; ro2*=ro2; - return make_pair( (r2>ri2) & (r2 ri2) & (r2 < ro2), myState); } diff --git a/TrackingTools/DetLayers/src/ForwardDetRing.cc b/TrackingTools/DetLayers/src/ForwardDetRing.cc index 60ee3bb9f399e..ee097fcf3ce95 100644 --- a/TrackingTools/DetLayers/src/ForwardDetRing.cc +++ b/TrackingTools/DetLayers/src/ForwardDetRing.cc @@ -8,13 +8,11 @@ using namespace std; -ForwardDetRing::~ForwardDetRing(){} +ForwardDetRing::~ForwardDetRing() {} -void -ForwardDetRing::compatibleDetsV( const TrajectoryStateOnSurface&, - const Propagator&, - const MeasurementEstimator&, - std::vector&) const{ - edm::LogError("DetLayers") << "At the moment not a real implementation" ; +void ForwardDetRing::compatibleDetsV(const TrajectoryStateOnSurface&, + const Propagator&, + const MeasurementEstimator&, + std::vector&) const { + edm::LogError("DetLayers") << "At the moment not a real implementation"; } - diff --git a/TrackingTools/DetLayers/src/ForwardDetRingOneZ.cc b/TrackingTools/DetLayers/src/ForwardDetRingOneZ.cc index 5f53cdfc93703..86d654cfce0ac 100644 --- a/TrackingTools/DetLayers/src/ForwardDetRingOneZ.cc +++ b/TrackingTools/DetLayers/src/ForwardDetRingOneZ.cc @@ -1,5 +1,5 @@ #include "TrackingTools/DetLayers/interface/ForwardDetRingOneZ.h" -#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" +#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" #include "TrackingTools/DetLayers/interface/ForwardRingDiskBuilderFromDet.h" //#include "TrackingTools/GeomPropagators/interface/Propagator.h" @@ -11,37 +11,31 @@ using namespace std; -ForwardDetRingOneZ::~ForwardDetRingOneZ(){} +ForwardDetRingOneZ::~ForwardDetRingOneZ() {} ForwardDetRingOneZ::ForwardDetRingOneZ(vector::const_iterator first, - vector::const_iterator last) - : ForwardDetRing(false), theDets(first,last) -{ + vector::const_iterator last) + : ForwardDetRing(false), theDets(first, last) { initialize(); } -ForwardDetRingOneZ::ForwardDetRingOneZ( const vector& dets) - : ForwardDetRing(false), theDets(dets) -{ +ForwardDetRingOneZ::ForwardDetRingOneZ(const vector& dets) : ForwardDetRing(false), theDets(dets) { initialize(); } - -void ForwardDetRingOneZ::initialize() -{ +void ForwardDetRingOneZ::initialize() { // assume the dets ARE in a ring // sort them in phi - precomputed_value_sort( theDets.begin(), theDets.end(), geomsort::DetPhi()); + precomputed_value_sort(theDets.begin(), theDets.end(), geomsort::DetPhi()); setDisk(ForwardRingDiskBuilderFromDet()(theDets)); } - -bool ForwardDetRingOneZ::add(int idet, vector& result, - const TrajectoryStateOnSurface& tsos, - const Propagator& prop, - const MeasurementEstimator& est) const { - pair compat = - theCompatibilityChecker.isCompatible(theDets[idet],tsos, prop, est); +bool ForwardDetRingOneZ::add(int idet, + vector& result, + const TrajectoryStateOnSurface& tsos, + const Propagator& prop, + const MeasurementEstimator& est) const { + pair compat = theCompatibilityChecker.isCompatible(theDets[idet], tsos, prop, est); if (compat.first) { result.push_back(DetWithState(theDets[idet], compat.second)); @@ -49,4 +43,3 @@ bool ForwardDetRingOneZ::add(int idet, vector& result, return compat.first; } - diff --git a/TrackingTools/DetLayers/src/ForwardRingDiskBuilderFromDet.cc b/TrackingTools/DetLayers/src/ForwardRingDiskBuilderFromDet.cc index 891ee7b40adac..64a6a3abf19de 100644 --- a/TrackingTools/DetLayers/src/ForwardRingDiskBuilderFromDet.cc +++ b/TrackingTools/DetLayers/src/ForwardRingDiskBuilderFromDet.cc @@ -5,42 +5,36 @@ using namespace std; // Warning, remember to assign this pointer to a ReferenceCountingPointer! -BoundDisk* -ForwardRingDiskBuilderFromDet::operator()( const vector& dets) const -{ - auto bo = computeBounds( dets ); +BoundDisk* ForwardRingDiskBuilderFromDet::operator()(const vector& dets) const { + auto bo = computeBounds(dets); -// LogDebug("DetLayers") << "Creating disk at Z: " << bo.second << "\n" -// << "Bounds are (rmin/rmax/thick) " << bo.first.innerRadius() -// << " / " << bo.first.outerRadius() -// << " / " << bo.first.thickness() ; + // LogDebug("DetLayers") << "Creating disk at Z: " << bo.second << "\n" + // << "Bounds are (rmin/rmax/thick) " << bo.first.innerRadius() + // << " / " << bo.first.outerRadius() + // << " / " << bo.first.thickness() ; -// typedef Det::PositionType::BasicVectorType Vector; -// Vector posSum(0,0,0); -// for (vector::const_iterator i=dets.begin(); i!=dets.end(); i++) { -// Vector pp = (**i).position().basicVector(); -// // LogDebug("DetLayers") << " "<< (int) ( i-dets.begin()) << " at " << pp ; -// posSum += pp; -// } -// Det::PositionType meanPos( posSum/float(dets.size())); -// LogDebug("DetLayers") << " meanPos "<< meanPos ; + // typedef Det::PositionType::BasicVectorType Vector; + // Vector posSum(0,0,0); + // for (vector::const_iterator i=dets.begin(); i!=dets.end(); i++) { + // Vector pp = (**i).position().basicVector(); + // // LogDebug("DetLayers") << " "<< (int) ( i-dets.begin()) << " at " << pp ; + // posSum += pp; + // } + // Det::PositionType meanPos( posSum/float(dets.size())); + // LogDebug("DetLayers") << " meanPos "<< meanPos ; - Surface::PositionType pos(0.,0.,bo.second); + Surface::PositionType pos(0., 0., bo.second); Surface::RotationType rot; - return new BoundDisk( pos, rot, bo.first); + return new BoundDisk(pos, rot, bo.first); } -pair -ForwardRingDiskBuilderFromDet::computeBounds( const vector& dets) const -{ +pair ForwardRingDiskBuilderFromDet::computeBounds(const vector& dets) const { // go over all corners and compute maximum deviations from mean pos. float rmin((**(dets.begin())).surface().position().perp()); - float rmax(rmin); + float rmax(rmin); float zmin((**(dets.begin())).surface().position().z()); float zmax(zmin); - for (vector::const_iterator idet=dets.begin(); - idet != dets.end(); idet++) { - + for (vector::const_iterator idet = dets.begin(); idet != dets.end(); idet++) { /* ---- original implementation. Is it obsolete? vector detUnits = (**idet).detUnits(); for (vector::const_iterator detu=detUnits.begin(); @@ -49,41 +43,39 @@ ForwardRingDiskBuilderFromDet::computeBounds( const vector& dets dynamic_cast((**detu).surface())); } ----- */ - vector corners = BoundingBox().corners( (**idet).specificSurface() ); - for (vector::const_iterator i=corners.begin(); - i!=corners.end(); i++) { + vector corners = BoundingBox().corners((**idet).specificSurface()); + for (vector::const_iterator i = corners.begin(); i != corners.end(); i++) { float r = i->perp(); float z = i->z(); - rmin = min( rmin, r); - rmax = max( rmax, r); - zmin = min( zmin, z); - zmax = max( zmax, z); + rmin = min(rmin, r); + rmax = max(rmax, r); + zmin = min(zmin, z); + zmax = max(zmax, z); } - // in addition to the corners we have to check the middle of the + // in addition to the corners we have to check the middle of the // det +/- length/2, since the min (max) radius for typical fw // dets is reached there - float rdet = (**idet).position().perp(); - float len = (**idet).surface().bounds().length(); + float rdet = (**idet).position().perp(); + float len = (**idet).surface().bounds().length(); float width = (**idet).surface().bounds().width(); - GlobalVector xAxis = (**idet).toGlobal(LocalVector(1,0,0)); - GlobalVector yAxis = (**idet).toGlobal(LocalVector(0,1,0)); - GlobalVector perpDir = GlobalVector( (**idet).position() - GlobalPoint(0,0,(**idet).position().z()) ); + GlobalVector xAxis = (**idet).toGlobal(LocalVector(1, 0, 0)); + GlobalVector yAxis = (**idet).toGlobal(LocalVector(0, 1, 0)); + GlobalVector perpDir = GlobalVector((**idet).position() - GlobalPoint(0, 0, (**idet).position().z())); double xAxisCos = xAxis.unit().dot(perpDir.unit()); double yAxisCos = yAxis.unit().dot(perpDir.unit()); - if( fabs(xAxisCos) > fabs(yAxisCos) ) { - rmin = min( rmin, rdet-width/2.F); - rmax = max( rmax, rdet+width/2.F); - }else{ - rmin = min( rmin, rdet-len/2.F); - rmax = max( rmax, rdet+len/2.F); + if (fabs(xAxisCos) > fabs(yAxisCos)) { + rmin = min(rmin, rdet - width / 2.F); + rmax = max(rmax, rdet + width / 2.F); + } else { + rmin = min(rmin, rdet - len / 2.F); + rmax = max(rmax, rdet + len / 2.F); } } - - float zPos = (zmax+zmin)/2.; - return make_pair(new SimpleDiskBounds(rmin,rmax,zmin-zPos,zmax-zPos), zPos); + float zPos = (zmax + zmin) / 2.; + return make_pair(new SimpleDiskBounds(rmin, rmax, zmin - zPos, zmax - zPos), zPos); } diff --git a/TrackingTools/DetLayers/src/GeomDetCompatibilityChecker.cc b/TrackingTools/DetLayers/src/GeomDetCompatibilityChecker.cc index b75f0b5f0f324..db65be36775d0 100644 --- a/TrackingTools/DetLayers/src/GeomDetCompatibilityChecker.cc +++ b/TrackingTools/DetLayers/src/GeomDetCompatibilityChecker.cc @@ -8,55 +8,59 @@ #include "FWCore/Utilities/interface/thread_safety_macros.h" #include "TrackingTools/DetLayers/interface/GeomDetCompatibilityChecker.h" #include "TrackingTools/GeomPropagators/interface/StraightLinePlaneCrossing.h" -#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" +#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" -namespace{ +namespace { struct Stat { - - struct Nop { Nop(int=0){} Nop& operator=(int){return *this;} void operator++(int){}}; + struct Nop { + Nop(int = 0) {} + Nop& operator=(int) { return *this; } + void operator++(int) {} + }; #ifdef STAT_TSB - using VAR=long long; + using VAR = long long; #else - using VAR=Nop; + using VAR = Nop; #endif - VAR ntot=0; - VAR nf1=0; - VAR nf2=0; - - VAR ns1=0; - VAR ns2=0; - VAR ns11=0; - VAR ns21=0; - - VAR nth=0; - VAR nle=0; - - - //Geom checker 1337311 84696 634946 20369 259701 241266 18435 614128 - // Geom checker 124,567,704 3,862,821 36,055,605 3,799,127 29,825,229 4,573,316 320,063 75,420,840 - // Geom checker 119,618,014 2,307,939 31,142,922 2,903,245 34,673,978 5,139,741 539,152 86,847,116 18,196,497 - // Geom checker 125,554,439 3,431,348 31,900,589 3,706,531 37,272,039 5,160,257 1,670,236 90,573,031 19,505,412 - // Geom checker 119,583,440 2,379,307 28,357,175 2,960,173 38,977,837 6,239,242 620,636 86,726,732 9,574,902 - // Geom checker 214,884,027 6,756,424 54,479,049 7,059,696 78,135,883 18443999 1124058 158,174,933 17153503 - // Geom checker 453,155,905 14,054,554 79,733,432 14,837,002 163,414,609 0 0 324,629,999 0 + VAR ntot = 0; + VAR nf1 = 0; + VAR nf2 = 0; + + VAR ns1 = 0; + VAR ns2 = 0; + VAR ns11 = 0; + VAR ns21 = 0; + + VAR nth = 0; + VAR nle = 0; + + //Geom checker 1337311 84696 634946 20369 259701 241266 18435 614128 + // Geom checker 124,567,704 3,862,821 36,055,605 3,799,127 29,825,229 4,573,316 320,063 75,420,840 + // Geom checker 119,618,014 2,307,939 31,142,922 2,903,245 34,673,978 5,139,741 539,152 86,847,116 18,196,497 + // Geom checker 125,554,439 3,431,348 31,900,589 3,706,531 37,272,039 5,160,257 1,670,236 90,573,031 19,505,412 + // Geom checker 119,583,440 2,379,307 28,357,175 2,960,173 38,977,837 6,239,242 620,636 86,726,732 9,574,902 + // Geom checker 214,884,027 6,756,424 54,479,049 7,059,696 78,135,883 18443999 1124058 158,174,933 17153503 + // Geom checker 453,155,905 14,054,554 79,733,432 14,837,002 163,414,609 0 0 324,629,999 0 #ifdef STAT_TSB - ~Stat() { std::cout << "Geom checker " << ntot<<' '<< nf1<<' '<< nf2 <<' '<< ns1<< ' '<< ns2 << ' ' << ns11 << ' '<< ns21 << ' ' << nth << ' ' << nle < -GeomDetCompatibilityChecker::isCompatible(const GeomDet* theDet, - const TrajectoryStateOnSurface& tsos, - const Propagator& prop, - const MeasurementEstimator& est) { +std::pair GeomDetCompatibilityChecker::isCompatible(const GeomDet* theDet, + const TrajectoryStateOnSurface& tsos, + const Propagator& prop, + const MeasurementEstimator& est) { stat.ntot++; - auto const sagCut = est.maxSagitta(); + auto const sagCut = est.maxSagitta(); auto const minTol2 = est.minTolerance2(); // std::cout << "param " << sagCut << ' ' << std::sqrt(minTol2) << std::endl; @@ -67,47 +71,57 @@ GeomDetCompatibilityChecker::isCompatible(const GeomDet* theDet, if (largeErr) stat.nle++; */ - bool isIn = false; - float sagitta=99999999; - bool close = false; - if LIKELY(sagCut>0) { - // linear approximation - auto const & plane = theDet->specificSurface(); - StraightLinePlaneCrossing crossing(tsos.globalPosition().basicVector(),tsos.globalMomentum().basicVector(), prop.propagationDirection()); - auto path = crossing.pathLength(plane); - isIn = path.first; - if UNLIKELY(!path.first) stat.ns1++; - else { - auto gpos = GlobalPoint(crossing.position(path.second)); - auto tpath2 = (gpos-tsos.globalPosition()).perp2(); - // sagitta = d^2*c/2 - sagitta = 0.5f*std::abs(tpath2*tsos.globalParameters().transverseCurvature()); - close = sagitta 0) { + // linear approximation + auto const& plane = theDet->specificSurface(); + StraightLinePlaneCrossing crossing( + tsos.globalPosition().basicVector(), tsos.globalMomentum().basicVector(), prop.propagationDirection()); + auto path = crossing.pathLength(plane); + isIn = path.first; + if + UNLIKELY(!path.first) stat.ns1++; + else { + auto gpos = GlobalPoint(crossing.position(path.second)); + auto tpath2 = (gpos - tsos.globalPosition()).perp2(); + // sagitta = d^2*c/2 + sagitta = 0.5f * std::abs(tpath2 * tsos.globalParameters().transverseCurvature()); + close = sagitta < sagCut; + LogDebug("TkDetLayer") << "GeomDetCompatibilityChecker: sagitta " << sagitta << std::endl; + if (close) { + stat.nth++; + auto pos = plane.toLocal(GlobalPoint(crossing.position(path.second))); + // auto toll = LocalError(tolerance2,0,tolerance2); + auto tollL2 = std::max(sagitta * sagitta, minTol2); + auto toll = LocalError(tollL2, 0, tollL2); + isIn = plane.bounds().inside(pos, toll); + if (!isIn) { + stat.ns2++; + LogDebug("TkDetLayer") << "GeomDetCompatibilityChecker: not in " << pos << std::endl; + return std::make_pair(false, TrajectoryStateOnSurface()); + } + } } } - } // precise propagation - TrajectoryStateOnSurface && propSt = prop.propagate( tsos, theDet->specificSurface()); - if UNLIKELY ( !propSt.isValid()) { stat.nf1++; return std::make_pair( false, std::move(propSt));} - - - auto es = est.estimate( propSt, theDet->specificSurface()); - if (!es) stat.nf2++; - if (close && (!isIn) && (!es) ) stat.ns11++; - if (close && es &&(!isIn)) { stat.ns21++; } // std::cout << sagitta << std::endl;} - return std::make_pair( es, std::move(propSt)); + TrajectoryStateOnSurface&& propSt = prop.propagate(tsos, theDet->specificSurface()); + if + UNLIKELY(!propSt.isValid()) { + stat.nf1++; + return std::make_pair(false, std::move(propSt)); + } + auto es = est.estimate(propSt, theDet->specificSurface()); + if (!es) + stat.nf2++; + if (close && (!isIn) && (!es)) + stat.ns11++; + if (close && es && (!isIn)) { + stat.ns21++; + } // std::cout << sagitta << std::endl;} + return std::make_pair(es, std::move(propSt)); } - diff --git a/TrackingTools/DetLayers/src/GeometricSearchDet.cc b/TrackingTools/DetLayers/src/GeometricSearchDet.cc index 587dc8dff59e3..181367cb5f84d 100644 --- a/TrackingTools/DetLayers/src/GeometricSearchDet.cc +++ b/TrackingTools/DetLayers/src/GeometricSearchDet.cc @@ -1,55 +1,47 @@ #include "TrackingTools/DetLayers/interface/GeometricSearchDet.h" -#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" +#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" -GeometricSearchDet::~GeometricSearchDet(){} +GeometricSearchDet::~GeometricSearchDet() {} -void -GeometricSearchDet::compatibleDetsV( const TrajectoryStateOnSurface& startingState, - const Propagator& prop, - const MeasurementEstimator& est, - std::vector& result) const { - - if UNLIKELY(!hasGroups()) edm::LogError("DetLayers") << "At the moment not a real implementation" ; +void GeometricSearchDet::compatibleDetsV(const TrajectoryStateOnSurface& startingState, + const Propagator& prop, + const MeasurementEstimator& est, + std::vector& result) const { + if + UNLIKELY(!hasGroups()) edm::LogError("DetLayers") << "At the moment not a real implementation"; - - // standard implementation of compatibleDets() for class which have + // standard implementation of compatibleDets() for class which have // groupedCompatibleDets implemented. std::vector vectorGroups; - groupedCompatibleDetsV(startingState,prop,est,vectorGroups); - for(auto itDG=vectorGroups.begin(); itDG!=vectorGroups.end();itDG++){ - for(auto itDGE=itDG->begin(); itDGE!=itDG->end();itDGE++){ - result.emplace_back(itDGE->det(),itDGE->trajectoryState()); + groupedCompatibleDetsV(startingState, prop, est, vectorGroups); + for (auto itDG = vectorGroups.begin(); itDG != vectorGroups.end(); itDG++) { + for (auto itDGE = itDG->begin(); itDGE != itDG->end(); itDGE++) { + result.emplace_back(itDGE->det(), itDGE->trajectoryState()); } } } -void -GeometricSearchDet::groupedCompatibleDetsV( const TrajectoryStateOnSurface& startingState, - const Propagator&, - const MeasurementEstimator&, - std::vector &) const { - edm::LogError("DetLayers") << "At the moment not a real implementation" ; +void GeometricSearchDet::groupedCompatibleDetsV(const TrajectoryStateOnSurface& startingState, + const Propagator&, + const MeasurementEstimator&, + std::vector&) const { + edm::LogError("DetLayers") << "At the moment not a real implementation"; } - -std::vector -GeometricSearchDet::compatibleDets( const TrajectoryStateOnSurface& startingState, - const Propagator& prop, - const MeasurementEstimator& est) const { +std::vector GeometricSearchDet::compatibleDets( + const TrajectoryStateOnSurface& startingState, const Propagator& prop, const MeasurementEstimator& est) const { std::vector result; - compatibleDetsV( startingState, prop, est,result); + compatibleDetsV(startingState, prop, est, result); return result; } -std::vector -GeometricSearchDet::groupedCompatibleDets( const TrajectoryStateOnSurface& startingState, - const Propagator& prop, - const MeasurementEstimator& est) const { +std::vector GeometricSearchDet::groupedCompatibleDets(const TrajectoryStateOnSurface& startingState, + const Propagator& prop, + const MeasurementEstimator& est) const { std::vector result; - groupedCompatibleDetsV(startingState, prop, est,result); + groupedCompatibleDetsV(startingState, prop, est, result); return result; } - diff --git a/TrackingTools/DetLayers/src/NavigationSchool.cc b/TrackingTools/DetLayers/src/NavigationSchool.cc index d49bcc1dc106f..3a33e303407f4 100644 --- a/TrackingTools/DetLayers/src/NavigationSchool.cc +++ b/TrackingTools/DetLayers/src/NavigationSchool.cc @@ -1,7 +1,6 @@ #include "FWCore/PluginManager/interface/ModuleDef.h" #include "FWCore/Framework/interface/MakerMacros.h" - #include "TrackingTools/DetLayers/interface/NavigationSchool.h" #include "FWCore/Utilities/interface/typelookup.h" diff --git a/TrackingTools/DetLayers/src/PhiBorderFinder.cc b/TrackingTools/DetLayers/src/PhiBorderFinder.cc index 49b0483d3981c..c31eb3d2c73fd 100644 --- a/TrackingTools/DetLayers/src/PhiBorderFinder.cc +++ b/TrackingTools/DetLayers/src/PhiBorderFinder.cc @@ -1,96 +1,87 @@ #include "TrackingTools/DetLayers/interface/PhiBorderFinder.h" -PhiBorderFinder::PhiBorderFinder(const std::vector& utheDets) - : theNbins(utheDets.size()), - isPhiPeriodic_(false), - isPhiOverlapping_(false) { +PhiBorderFinder::PhiBorderFinder(const std::vector& utheDets) + : theNbins(utheDets.size()), isPhiPeriodic_(false), isPhiOverlapping_(false) { std::vector theDets = utheDets; precomputed_value_sort(theDets.begin(), theDets.end(), DetPhi()); - + const std::string metname = "Muon|RecoMuon|RecoMuonDetLayers|PhiBorderFinder"; - - double step = 2.*Geom::pi()/theNbins; - + + double step = 2. * Geom::pi() / theNbins; + LogTrace(metname) << "RecoMuonDetLayers::PhiBorderFinder " - << "step w: " << step << " # of bins: " << theNbins; - + << "step w: " << step << " # of bins: " << theNbins; + std::vector spread(theNbins); - std::vector > phiEdge; + std::vector > phiEdge; phiEdge.reserve(theNbins); thePhiBorders.reserve(theNbins); thePhiBins.reserve(theNbins); - for ( unsigned int i = 0; i < theNbins; i++ ) { + for (unsigned int i = 0; i < theNbins; i++) { thePhiBins.push_back(theDets[i]->position().phi()); - spread.push_back(theDets[i]->position().phi() - - (theDets[0]->position().phi() + i*step)); - - LogTrace(metname) << "bin: " << i << " phi bin: " << thePhiBins[i] - << " spread: " << spread[i]; - - - ConstReferenceCountingPointer plane = - dynamic_cast(&theDets[i]->surface()); - if (plane==nullptr) { + spread.push_back(theDets[i]->position().phi() - (theDets[0]->position().phi() + i * step)); + + LogTrace(metname) << "bin: " << i << " phi bin: " << thePhiBins[i] << " spread: " << spread[i]; + + ConstReferenceCountingPointer plane = dynamic_cast(&theDets[i]->surface()); + if (plane == nullptr) { //FIXME throw cms::Exception("UnexpectedState") << ("PhiBorderFinder: det surface is not a BoundPlane"); } - - std::vector dc = - BoundingBox().corners(*plane); - + + std::vector dc = BoundingBox().corners(*plane); + float phimin(999.), phimax(-999.); - for (std::vector::const_iterator pt=dc.begin(); - pt!=dc.end(); pt++) { + for (std::vector::const_iterator pt = dc.begin(); pt != dc.end(); pt++) { float phi = (*pt).phi(); // float z = pt->z(); - if (phi < phimin) phimin = phi; - if (phi > phimax) phimax = phi; + if (phi < phimin) + phimin = phi; + if (phi > phimax) + phimax = phi; } - if (phimin*phimax < 0. && //Handle pi border: - phimax - phimin > Geom::pi()) { //Assume that the Det is on - //the shortest side - std::swap(phimin,phimax); + if (phimin * phimax < 0. && //Handle pi border: + phimax - phimin > Geom::pi()) { //Assume that the Det is on + //the shortest side + std::swap(phimin, phimax); } - phiEdge.push_back(std::pair(phimin,phimax)); + phiEdge.push_back(std::pair(phimin, phimax)); } - + for (unsigned int i = 0; i < theNbins; i++) { - // Put the two phi values in the [0,2pi] range - double firstPhi = positiveRange(phiEdge[i].first); - double secondPhi = positiveRange(phiEdge[binIndex(i-1)].second); - + double firstPhi = positiveRange(phiEdge[i].first); + double secondPhi = positiveRange(phiEdge[binIndex(i - 1)].second); + // Reformat them in the [-pi,pi] range Geom::Phi firstEdge(firstPhi); Geom::Phi secondEdge(secondPhi); - + // Calculate the mean and format the result in the [-pi,pi] range // Get their value in order to perform the mean in the correct way - Geom::Phi mean((firstEdge.value() + secondEdge.value())/2.); - + Geom::Phi mean((firstEdge.value() + secondEdge.value()) / 2.); + // Special case: at +-pi there is a discontinuity - if ( phiEdge[i].first * phiEdge[binIndex(i-1)].second < 0 && - fabs(firstPhi-secondPhi) < Geom::pi() ) + if (phiEdge[i].first * phiEdge[binIndex(i - 1)].second < 0 && fabs(firstPhi - secondPhi) < Geom::pi()) mean = Geom::pi() - mean; - + thePhiBorders.push_back(mean); } - + for (unsigned int i = 0; i < theNbins; i++) { - if (Geom::Phi(phiEdge[i].first) - - Geom::Phi(phiEdge[binIndex(i-1)].second) < 0) { + if (Geom::Phi(phiEdge[i].first) - Geom::Phi(phiEdge[binIndex(i - 1)].second) < 0) { isPhiOverlapping_ = true; break; } } - - double rms = stat_RMS(spread); - if ( rms < 0.01*step) { + + double rms = stat_RMS(spread); + if (rms < 0.01 * step) { isPhiPeriodic_ = true; } - + //Check that everything is proper - if (thePhiBorders.size() != theNbins || thePhiBins.size() != theNbins) + if (thePhiBorders.size() != theNbins || thePhiBins.size() != theNbins) //FIXME throw cms::Exception("UnexpectedState") << "PhiBorderFinder: consistency error"; } diff --git a/TrackingTools/DetLayers/src/RBorderFinder.cc b/TrackingTools/DetLayers/src/RBorderFinder.cc index 76901c81c6a22..34799cba0348c 100644 --- a/TrackingTools/DetLayers/src/RBorderFinder.cc +++ b/TrackingTools/DetLayers/src/RBorderFinder.cc @@ -1,68 +1,61 @@ #include "TrackingTools/DetLayers/interface/RBorderFinder.h" -RBorderFinder::RBorderFinder(const std::vector& utheDets) - : theNbins(utheDets.size()), - isRPeriodic_(false), - isROverlapping_(false) -{ +RBorderFinder::RBorderFinder(const std::vector& utheDets) + : theNbins(utheDets.size()), isRPeriodic_(false), isROverlapping_(false) { std::vector theDets = utheDets; precomputed_value_sort(theDets.begin(), theDets.end(), DetR()); - + std::vector > disks(theNbins); - for ( int i = 0; i < theNbins; i++ ) { - disks[i] = - dynamic_cast (&(theDets[i]->surface())); - if (disks[i]==nullptr) { + for (int i = 0; i < theNbins; i++) { + disks[i] = dynamic_cast(&(theDets[i]->surface())); + if (disks[i] == nullptr) { throw cms::Exception("UnexpectedState") << "RBorderFinder: implemented for BoundDisks only"; } } - - - if (theNbins==1) { // Trivial case - isRPeriodic_ = true; // meaningless in this case + + if (theNbins == 1) { // Trivial case + isRPeriodic_ = true; // meaningless in this case theRBorders.push_back(disks.front()->innerRadius()); - theRBins.push_back((disks.front()->outerRadius()+disks.front()->innerRadius())); + theRBins.push_back((disks.front()->outerRadius() + disks.front()->innerRadius())); // std::cout << "RBorderFinder: theNbins " << theNbins << std::endl // << " C: " << theRBins[0] // << " Border: " << theRBorders[0] << std::endl; - } else { // More than 1 bin - double step = (disks.back()->innerRadius() - - disks.front()->innerRadius())/(theNbins-1); + } else { // More than 1 bin + double step = (disks.back()->innerRadius() - disks.front()->innerRadius()) / (theNbins - 1); std::vector spread; - std::vector > REdge; + std::vector > REdge; REdge.reserve(theNbins); theRBorders.reserve(theNbins); theRBins.reserve(theNbins); spread.reserve(theNbins); - - for ( int i = 0; i < theNbins; i++ ) { - theRBins.push_back((disks[i]->outerRadius()+disks[i]->innerRadius())/2.); - spread.push_back(theRBins.back() - (theRBins[0] + i*step)); - REdge.push_back(std::pair(disks[i]->innerRadius(), - disks[i]->outerRadius())); + + for (int i = 0; i < theNbins; i++) { + theRBins.push_back((disks[i]->outerRadius() + disks[i]->innerRadius()) / 2.); + spread.push_back(theRBins.back() - (theRBins[0] + i * step)); + REdge.push_back(std::pair(disks[i]->innerRadius(), disks[i]->outerRadius())); } - + theRBorders.push_back(REdge[0].first); for (int i = 1; i < theNbins; i++) { // Average borders of previous and next bins - double br = (REdge[(i-1)].second + REdge[i].first)/2.; + double br = (REdge[(i - 1)].second + REdge[i].first) / 2.; theRBorders.push_back(br); } - + for (int i = 1; i < theNbins; i++) { - if (REdge[i].first - REdge[i-1].second < 0) { - isROverlapping_ = true; - break; + if (REdge[i].first - REdge[i - 1].second < 0) { + isROverlapping_ = true; + break; } } - - double rms = stat_RMS(spread); - if ( rms < 0.01*step) { + + double rms = stat_RMS(spread); + if (rms < 0.01 * step) { isRPeriodic_ = true; } } - + //Check that everything is proper - if ((int)theRBorders.size() != theNbins || (int)theRBins.size() != theNbins) + if ((int)theRBorders.size() != theNbins || (int)theRBins.size() != theNbins) throw cms::Exception("UnexpectedState") << "RBorderFinder consistency error"; } diff --git a/TrackingTools/DetLayers/src/RodPlaneBuilderFromDet.cc b/TrackingTools/DetLayers/src/RodPlaneBuilderFromDet.cc index c82a29e2d9e43..d92bf2ba7553f 100644 --- a/TrackingTools/DetLayers/src/RodPlaneBuilderFromDet.cc +++ b/TrackingTools/DetLayers/src/RodPlaneBuilderFromDet.cc @@ -7,40 +7,34 @@ using namespace std; // Warning, remember to assign this pointer to a ReferenceCountingPointer! -Plane* -RodPlaneBuilderFromDet::operator()( const vector& dets) const -{ +Plane* RodPlaneBuilderFromDet::operator()(const vector& dets) const { // find mean position typedef Surface::PositionType::BasicVectorType Vector; - Vector posSum(0,0,0); - for (vector::const_iterator i=dets.begin(); i!=dets.end(); i++) { + Vector posSum(0, 0, 0); + for (vector::const_iterator i = dets.begin(); i != dets.end(); i++) { posSum += (**i).surface().position().basicVector(); } - Surface::PositionType meanPos( posSum/float(dets.size())); - + Surface::PositionType meanPos(posSum / float(dets.size())); + // temporary plane - for the computation of bounds - Surface::RotationType rotation = computeRotation( dets, meanPos); - Plane tmpPlane( meanPos, rotation); - auto bo = computeBounds( dets, tmpPlane); + Surface::RotationType rotation = computeRotation(dets, meanPos); + Plane tmpPlane(meanPos, rotation); + auto bo = computeBounds(dets, tmpPlane); -// LogDebug("DetLayers") << "Creating plane at position " << meanPos -// << " displaced by " << bo.second ; -// LogDebug("DetLayers") << "Bounds are (wid/len/thick) " << bo.first.width() -// << " / " << bo.first.length() -// << " / " << bo.first.thickness() ; + // LogDebug("DetLayers") << "Creating plane at position " << meanPos + // << " displaced by " << bo.second ; + // LogDebug("DetLayers") << "Bounds are (wid/len/thick) " << bo.first.width() + // << " / " << bo.first.length() + // << " / " << bo.first.thickness() ; - return new Plane( meanPos+bo.second, rotation, bo.first); + return new Plane(meanPos + bo.second, rotation, bo.first); } -pair -RodPlaneBuilderFromDet::computeBounds( const vector& dets, - const Plane& plane) const -{ +pair RodPlaneBuilderFromDet::computeBounds(const vector& dets, + const Plane& plane) const { // go over all corners and compute maximum deviations from mean pos. vector corners; - for (vector::const_iterator idet=dets.begin(); - idet != dets.end(); idet++) { - + for (vector::const_iterator idet = dets.begin(); idet != dets.end(); idet++) { /* ---- original implementation. Is it obsolete? vector detUnits = (**idet).basicComponents(); for (vector::const_iterator detu=detUnits.begin(); @@ -54,60 +48,63 @@ RodPlaneBuilderFromDet::computeBounds( const vector& dets, // temporary implementation (May be the final one if the GluedDet surface // really contains both the mono and the stereo surfaces vector dc = BoundingBox().corners((**idet).specificSurface()); - corners.insert( corners.end(),dc.begin(), dc.end() ); + corners.insert(corners.end(), dc.begin(), dc.end()); } - + float xmin(0), xmax(0), ymin(0), ymax(0), zmin(0), zmax(0); - for (vector::const_iterator i=corners.begin(); - i!=corners.end(); i++) { + for (vector::const_iterator i = corners.begin(); i != corners.end(); i++) { LocalPoint p = plane.toLocal(*i); - if (p.x() < xmin) xmin = p.x(); - if (p.x() > xmax) xmax = p.x(); - if (p.y() < ymin) ymin = p.y(); - if (p.y() > ymax) ymax = p.y(); - if (p.z() < zmin) zmin = p.z(); - if (p.z() > zmax) zmax = p.z(); + if (p.x() < xmin) + xmin = p.x(); + if (p.x() > xmax) + xmax = p.x(); + if (p.y() < ymin) + ymin = p.y(); + if (p.y() > ymax) + ymax = p.y(); + if (p.z() < zmin) + zmin = p.z(); + if (p.z() > zmax) + zmax = p.z(); } - LocalVector localOffset( (xmin+xmax)/2., (ymin+ymax)/2., (zmin+zmax)/2.); - GlobalVector offset( plane.toGlobal(localOffset)); - - pair result(new RectangularPlaneBounds((xmax-xmin)/2, (ymax-ymin)/2, (zmax-zmin)/2), offset); + LocalVector localOffset((xmin + xmax) / 2., (ymin + ymax) / 2., (zmin + zmax) / 2.); + GlobalVector offset(plane.toGlobal(localOffset)); + + pair result( + new RectangularPlaneBounds((xmax - xmin) / 2, (ymax - ymin) / 2, (zmax - zmin) / 2), offset); return result; } -Surface::RotationType -RodPlaneBuilderFromDet:: -computeRotation( const vector& dets, - const Surface::PositionType& meanPos) const -{ +Surface::RotationType RodPlaneBuilderFromDet::computeRotation(const vector& dets, + const Surface::PositionType& meanPos) const { // choose first mono out-pointing rotation // the rotations of GluedDets coincide with the mono part // Simply take the x,y of the first Det if z points out, // or -x, y if it doesn't - const Plane& plane = - dynamic_cast(dets.front()->surface()); + const Plane& plane = dynamic_cast(dets.front()->surface()); //GlobalVector n = plane.normalVector(); GlobalVector xAxis; GlobalVector yAxis; - GlobalVector planeYAxis = plane.toGlobal( LocalVector( 0, 1, 0)); - if (planeYAxis.z() < 0) yAxis = -planeYAxis; - else yAxis = planeYAxis; + GlobalVector planeYAxis = plane.toGlobal(LocalVector(0, 1, 0)); + if (planeYAxis.z() < 0) + yAxis = -planeYAxis; + else + yAxis = planeYAxis; - GlobalVector planeXAxis = plane.toGlobal( LocalVector( 1, 0, 0)); - GlobalVector n = planeXAxis.cross( planeYAxis); + GlobalVector planeXAxis = plane.toGlobal(LocalVector(1, 0, 0)); + GlobalVector n = planeXAxis.cross(planeYAxis); if (n.x() * meanPos.x() + n.y() * meanPos.y() > 0) { xAxis = planeXAxis; - } - else { + } else { xAxis = -planeXAxis; } -// LogDebug("DetLayers") << "Creating rotation with x,y axis " -// << xAxis << ", " << yAxis ; + // LogDebug("DetLayers") << "Creating rotation with x,y axis " + // << xAxis << ", " << yAxis ; - return Surface::RotationType( xAxis, yAxis); + return Surface::RotationType(xAxis, yAxis); } diff --git a/TrackingTools/DetLayers/src/TkLayerLess.cc b/TrackingTools/DetLayers/src/TkLayerLess.cc index 9286200af1358..8c729e35bf204 100644 --- a/TrackingTools/DetLayers/src/TkLayerLess.cc +++ b/TrackingTools/DetLayers/src/TkLayerLess.cc @@ -2,99 +2,79 @@ #include "FWCore/Utilities/interface/Exception.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" -bool TkLayerLess::insideOutLess( const DetLayer* a, const DetLayer* b) const -{ - if (a == b) return false; +bool TkLayerLess::insideOutLess(const DetLayer* a, const DetLayer* b) const { + if (a == b) + return false; - const BarrelDetLayer* bla = - dynamic_cast(a); - const BarrelDetLayer* blb = - dynamic_cast(b); + const BarrelDetLayer* bla = dynamic_cast(a); + const BarrelDetLayer* blb = dynamic_cast(b); - if ( bla!=nullptr && blb!=nullptr) { // barrel with barrel + if (bla != nullptr && blb != nullptr) { // barrel with barrel return bla->specificSurface().radius() < blb->specificSurface().radius(); } - const ForwardDetLayer* flb = - dynamic_cast(b); + const ForwardDetLayer* flb = dynamic_cast(b); - if ( bla!=nullptr && flb!=nullptr) { // barrel with forward - return barrelForwardLess( bla, flb); + if (bla != nullptr && flb != nullptr) { // barrel with forward + return barrelForwardLess(bla, flb); } - const ForwardDetLayer* fla = - dynamic_cast(a); + const ForwardDetLayer* fla = dynamic_cast(a); - if (fla!=nullptr && flb!=nullptr) { // forward with forward - return fabs( fla->position().z()) < fabs( flb->position().z()); + if (fla != nullptr && flb != nullptr) { // forward with forward + return fabs(fla->position().z()) < fabs(flb->position().z()); } - if ( fla!=nullptr && blb!=nullptr) { // forward with barrel - return !barrelForwardLess( blb, fla); + if (fla != nullptr && blb != nullptr) { // forward with barrel + return !barrelForwardLess(blb, fla); } //throw DetLogicError("TkLayerLess: arguments are not Barrel or Forward DetLayers"); throw cms::Exception("TkLayerLess", "Arguments are not Barrel or Forward DetLayers"); - } -bool TkLayerLess::barrelForwardLess( const BarrelDetLayer* bla, - const ForwardDetLayer* flb) const -{ - return bla->surface().bounds().length()/2. < fabs( flb->position().z()); +bool TkLayerLess::barrelForwardLess(const BarrelDetLayer* bla, const ForwardDetLayer* flb) const { + return bla->surface().bounds().length() / 2. < fabs(flb->position().z()); } +bool TkLayerLess::insideOutLessSigned(const DetLayer* a, const DetLayer* b) const { + if (a == b) + return false; -bool TkLayerLess::insideOutLessSigned( const DetLayer* a, const DetLayer* b) const -{ - if (a == b) return false; - - const BarrelDetLayer* bla = - dynamic_cast(a); - const BarrelDetLayer* blb = - dynamic_cast(b); + const BarrelDetLayer* bla = dynamic_cast(a); + const BarrelDetLayer* blb = dynamic_cast(b); - if ( bla!=nullptr && blb!=nullptr) { // barrel with barrel + if (bla != nullptr && blb != nullptr) { // barrel with barrel return bla->specificSurface().radius() < blb->specificSurface().radius(); } - const ForwardDetLayer* flb = - dynamic_cast(b); + const ForwardDetLayer* flb = dynamic_cast(b); - if ( bla!=nullptr && flb!=nullptr) { // barrel with forward - return barrelForwardLess( bla, flb); + if (bla != nullptr && flb != nullptr) { // barrel with forward + return barrelForwardLess(bla, flb); } - const ForwardDetLayer* fla = - dynamic_cast(a); + const ForwardDetLayer* fla = dynamic_cast(a); - if (fla!=nullptr && flb!=nullptr) { // forward with forward - if (fla->position().z()*flb->position().z() > 0) {// same z-sign + if (fla != nullptr && flb != nullptr) { // forward with forward + if (fla->position().z() * flb->position().z() > 0) { // same z-sign //regular ordering when same sign - LogDebug("BeamHaloTkLayerLess")<<"reaching this: " - <position().z()<<" " - <position().z(); - return (fabs(fla->position().z()) < fabs( flb->position().z())); - } - else{//layers compared are not on the same z-side - LogDebug("BeamHaloTkLayerLess")<<"reaching this at least: " - <position().z()<<" " - <position().z(); - - if (theFromLayerSign*fla->position().z()>0){ - //"fla" and original layer are on the same side - //say that fla is less than flb - return false; - }else{ - return true; + LogDebug("BeamHaloTkLayerLess") << "reaching this: " << theFromLayerSign << " " << fla->position().z() << " " + << flb->position().z(); + return (fabs(fla->position().z()) < fabs(flb->position().z())); + } else { //layers compared are not on the same z-side + LogDebug("BeamHaloTkLayerLess") << "reaching this at least: " << theFromLayerSign << " " << fla->position().z() + << " " << flb->position().z(); + + if (theFromLayerSign * fla->position().z() > 0) { + //"fla" and original layer are on the same side + //say that fla is less than flb + return false; + } else { + return true; } } } - if ( fla!=nullptr && blb!=nullptr) { // forward with barrel - return !barrelForwardLess( blb, fla); + if (fla != nullptr && blb != nullptr) { // forward with barrel + return !barrelForwardLess(blb, fla); } throw cms::Exception("BeamHaloTkLayerLess", "Arguments are not Barrel or Forward DetLayers"); - } - - diff --git a/TrackingTools/TrajectoryCleaning/interface/FastTrajectoryCleaner.h b/TrackingTools/TrajectoryCleaning/interface/FastTrajectoryCleaner.h index f4ed68f643db3..09ad2b516ef58 100644 --- a/TrackingTools/TrajectoryCleaning/interface/FastTrajectoryCleaner.h +++ b/TrackingTools/TrajectoryCleaning/interface/FastTrajectoryCleaner.h @@ -11,38 +11,28 @@ * As it can be used during PatternReco there is the option to not consider hits from the common seed */ - class FastTrajectoryCleaner final : public TrajectoryCleaner { - public: - +public: using TrajectoryPointerContainer = TrajectoryCleaner::TrajectoryPointerContainer; - using TempTrajectoryContainer = TrajectoryCleaner::TempTrajectoryContainer; - - FastTrajectoryCleaner() : - validHitBonus_(0.5f*5.0f), - missingHitPenalty_(20.0f), - dismissSeed_(true){} - - - FastTrajectoryCleaner(float bonus, float penalty, bool noSeed=true) : - validHitBonus_(0.5f*bonus), - missingHitPenalty_(penalty), - dismissSeed_(noSeed){} + using TempTrajectoryContainer = TrajectoryCleaner::TempTrajectoryContainer; + FastTrajectoryCleaner() : validHitBonus_(0.5f * 5.0f), missingHitPenalty_(20.0f), dismissSeed_(true) {} + FastTrajectoryCleaner(float bonus, float penalty, bool noSeed = true) + : validHitBonus_(0.5f * bonus), missingHitPenalty_(penalty), dismissSeed_(noSeed) {} - FastTrajectoryCleaner(const edm::ParameterSet & iConfig) : - validHitBonus_(0.5*iConfig.getParameter("ValidHitBonus")), - missingHitPenalty_(iConfig.getParameter("MissingHitPenalty")), - dismissSeed_(iConfig.getParameter("dismissSeed")){} + FastTrajectoryCleaner(const edm::ParameterSet& iConfig) + : validHitBonus_(0.5 * iConfig.getParameter("ValidHitBonus")), + missingHitPenalty_(iConfig.getParameter("MissingHitPenalty")), + dismissSeed_(iConfig.getParameter("dismissSeed")) {} - ~FastTrajectoryCleaner() override{} + ~FastTrajectoryCleaner() override {} void clean(TempTrajectoryContainer&) const override; void clean(TrajectoryPointerContainer&) const override; - private: - float validHitBonus_; // here per dof +private: + float validHitBonus_; // here per dof float missingHitPenalty_; bool dismissSeed_; }; diff --git a/TrackingTools/TrajectoryCleaning/interface/TrajectoryCleaner.h b/TrackingTools/TrajectoryCleaning/interface/TrajectoryCleaner.h index dd4083eabe7b6..00ef4f95cb9dd 100644 --- a/TrackingTools/TrajectoryCleaning/interface/TrajectoryCleaner.h +++ b/TrackingTools/TrajectoryCleaning/interface/TrajectoryCleaner.h @@ -12,26 +12,22 @@ class TrackingComponentsRecord; class TrajectoryCleaner { - - public: - typedef TrackingComponentsRecord Record; - typedef std::vector TrajectoryContainer; - typedef std::vector TrajectoryPointerContainer; +public: + typedef TrackingComponentsRecord Record; + typedef std::vector TrajectoryContainer; + typedef std::vector TrajectoryPointerContainer; typedef TrajectoryContainer::iterator TrajectoryIterator; typedef TrajectoryPointerContainer::iterator TrajectoryPointerIterator; - using TempTrajectoryContainer = std::vector; - - - - TrajectoryCleaner(){} - TrajectoryCleaner(edm::ParameterSet & iConfig){} - virtual ~TrajectoryCleaner(){} + using TempTrajectoryContainer = std::vector; - virtual void clean( TempTrajectoryContainer&) const; - virtual void clean( TrajectoryContainer&) const; - virtual void clean( TrajectoryPointerContainer&) const = 0; + TrajectoryCleaner() {} + TrajectoryCleaner(edm::ParameterSet& iConfig) {} + virtual ~TrajectoryCleaner() {} + virtual void clean(TempTrajectoryContainer&) const; + virtual void clean(TrajectoryContainer&) const; + virtual void clean(TrajectoryPointerContainer&) const = 0; }; #endif diff --git a/TrackingTools/TrajectoryCleaning/interface/TrajectoryCleanerBySharedHits.h b/TrackingTools/TrajectoryCleaning/interface/TrajectoryCleanerBySharedHits.h index 913f289445d3c..15516af092362 100644 --- a/TrackingTools/TrajectoryCleaning/interface/TrajectoryCleanerBySharedHits.h +++ b/TrackingTools/TrajectoryCleaning/interface/TrajectoryCleanerBySharedHits.h @@ -12,35 +12,28 @@ * reconstructed hits, and number of lost hits. */ - class TrajectoryCleanerBySharedHits : public TrajectoryCleaner { +public: + typedef std::vector TrajectoryPointerContainer; - public: - - typedef std::vector TrajectoryPointerContainer; - - TrajectoryCleanerBySharedHits() : - theFraction(0.19), - validHitBonus_(5.0), - missingHitPenalty_(20.0), - allowSharedFirstHit(true){} - TrajectoryCleanerBySharedHits(const edm::ParameterSet & iConfig) : - theFraction(iConfig.getParameter("fractionShared")), - validHitBonus_(iConfig.getParameter("ValidHitBonus")), - missingHitPenalty_(iConfig.getParameter("MissingHitPenalty")), - allowSharedFirstHit(iConfig.getParameter("allowSharedFirstHit")){} + TrajectoryCleanerBySharedHits() + : theFraction(0.19), validHitBonus_(5.0), missingHitPenalty_(20.0), allowSharedFirstHit(true) {} + TrajectoryCleanerBySharedHits(const edm::ParameterSet& iConfig) + : theFraction(iConfig.getParameter("fractionShared")), + validHitBonus_(iConfig.getParameter("ValidHitBonus")), + missingHitPenalty_(iConfig.getParameter("MissingHitPenalty")), + allowSharedFirstHit(iConfig.getParameter("allowSharedFirstHit")) {} ~TrajectoryCleanerBySharedHits() override{}; using TrajectoryCleaner::clean; - void clean( TrajectoryPointerContainer&) const override; + void clean(TrajectoryPointerContainer&) const override; - private: +private: float theFraction; float validHitBonus_; float missingHitPenalty_; bool allowSharedFirstHit; - }; #endif diff --git a/TrackingTools/TrajectoryCleaning/interface/TrajectoryCleanerFactory.h b/TrackingTools/TrajectoryCleaning/interface/TrajectoryCleanerFactory.h index 6ea1d60ecc822..68a020601f6c9 100644 --- a/TrackingTools/TrajectoryCleaning/interface/TrajectoryCleanerFactory.h +++ b/TrackingTools/TrajectoryCleaning/interface/TrajectoryCleanerFactory.h @@ -2,8 +2,8 @@ #define TrackingTools_TrajectoryCleaning_TrajectoryCleanerFactory_H #include "TrackingTools/TrajectoryCleaning/interface/TrajectoryCleaner.h" -#include "FWCore/PluginManager/interface/PluginFactory.h" +#include "FWCore/PluginManager/interface/PluginFactory.h" -typedef edmplugin::PluginFactory TrajectoryCleanerFactory; +typedef edmplugin::PluginFactory TrajectoryCleanerFactory; #endif diff --git a/TrackingTools/TrajectoryCleaning/plugins/modules.cc b/TrackingTools/TrajectoryCleaning/plugins/modules.cc index 00f3f6c7ad58f..f8a6ad19de475 100644 --- a/TrackingTools/TrajectoryCleaning/plugins/modules.cc +++ b/TrackingTools/TrajectoryCleaning/plugins/modules.cc @@ -2,7 +2,6 @@ #include "FWCore/Framework/interface/ModuleFactory.h" #include "FWCore/Framework/interface/ESProducer.h" - #include "TrackingTools/TrajectoryCleaning/interface/TrajectoryCleanerFactory.h" #include "TrackingTools/TrajectoryCleaning/interface/TrajectoryCleanerBySharedHits.h" DEFINE_EDM_PLUGIN(TrajectoryCleanerFactory, TrajectoryCleanerBySharedHits, "TrajectoryCleanerBySharedHits"); diff --git a/TrackingTools/TrajectoryCleaning/src/FastTrajectoryCleaner.cc b/TrackingTools/TrajectoryCleaning/src/FastTrajectoryCleaner.cc index b9cf75508fe46..566cb190413f6 100644 --- a/TrackingTools/TrajectoryCleaning/src/FastTrajectoryCleaner.cc +++ b/TrackingTools/TrajectoryCleaning/src/FastTrajectoryCleaner.cc @@ -1,41 +1,43 @@ #include "TrackingTools/TrajectoryCleaning/interface/FastTrajectoryCleaner.h" -void FastTrajectoryCleaner::clean( TrajectoryPointerContainer & tc) const -{ +void FastTrajectoryCleaner::clean(TrajectoryPointerContainer& tc) const { edm::LogError("FastTrajectoryCleaner") << "not implemented for Trajectory"; assert(false); } -void FastTrajectoryCleaner::clean( TempTrajectoryContainer & tc) const -{ - - if (tc.size() <= 1) return; // nothing to clean - float maxScore= -std::numeric_limits::max(); - TempTrajectory * bestTr = nullptr; - for (auto & it : tc) { - if (!it.isValid()) continue; - auto const & pd = it.measurements(); +void FastTrajectoryCleaner::clean(TempTrajectoryContainer& tc) const { + if (tc.size() <= 1) + return; // nothing to clean + float maxScore = -std::numeric_limits::max(); + TempTrajectory* bestTr = nullptr; + for (auto& it : tc) { + if (!it.isValid()) + continue; + auto const& pd = it.measurements(); // count active degree of freedom - int dof=0; - for (auto const & im : pd) { - if(dismissSeed_ & (im.estimate()==0)) continue; - auto const & h = im.recHitR(); - if (!h.isValid()) continue; - dof+=h.dimension(); + int dof = 0; + for (auto const& im : pd) { + if (dismissSeed_ & (im.estimate() == 0)) + continue; + auto const& h = im.recHitR(); + if (!h.isValid()) + continue; + dof += h.dimension(); } - float score = validHitBonus_*float(dof) - missingHitPenalty_*it.lostHits() - it.chiSquared(); - if ( it.lastMeasurement().updatedState().globalMomentum().perp2() < 0.81f ) score -= 0.5f*validHitBonus_*float(dof); - else if (it.dPhiCacheForLoopersReconstruction()==0 &&it.foundHits()>8) score+=validHitBonus_*float(dof); // extra bonus for long tracks - if (score>=maxScore) { - bestTr = ⁢ - maxScore = score; + float score = validHitBonus_ * float(dof) - missingHitPenalty_ * it.lostHits() - it.chiSquared(); + if (it.lastMeasurement().updatedState().globalMomentum().perp2() < 0.81f) + score -= 0.5f * validHitBonus_ * float(dof); + else if (it.dPhiCacheForLoopersReconstruction() == 0 && it.foundHits() > 8) + score += validHitBonus_ * float(dof); // extra bonus for long tracks + if (score >= maxScore) { + bestTr = ⁢ + maxScore = score; } } - - for (auto & it : tc) { - if ((&it)!=bestTr) it.invalidate(); - } - + for (auto& it : tc) { + if ((&it) != bestTr) + it.invalidate(); + } } /* diff --git a/TrackingTools/TrajectoryCleaning/src/OtherHashMaps.h b/TrackingTools/TrajectoryCleaning/src/OtherHashMaps.h index aba5fe4251193..a47a23f09c4bd 100644 --- a/TrackingTools/TrajectoryCleaning/src/OtherHashMaps.h +++ b/TrackingTools/TrajectoryCleaning/src/OtherHashMaps.h @@ -16,9 +16,9 @@ #include -namespace cmsutil { +namespace cmsutil { -/*** The concept is the same of std::map>, but the implementation is much different (and the interface is not really compatible) + /*** The concept is the same of std::map>, but the implementation is much different (and the interface is not really compatible) * It works only for K and V objects with trivial destructors (primitive types and bare pointers are fine) * The main implementation difference w.r.t. unordered_map> is that this map is optimized to do very few memory allocations * (in particular, clear does not redeme memory so if you just clear the map instead of deleting it you won't call malloc each time you fill it) @@ -27,309 +27,335 @@ namespace cmsutil { * Although it can take an allocator as template argument, it has been tested only with std::allocator. * When used in the TrajectoryCleanerBySharedHits it works and it does improve the performance. Any other usecase was not checked at all. * */ -template, typename Equals=std::equal_to, typename Alloc=std::allocator > -class SimpleAllocHashMultiMap { + template , + typename Equals = std::equal_to, + typename Alloc = std::allocator > + class SimpleAllocHashMultiMap { // taking Alloc definition from http://www.codeproject.com/KB/cpp/allocator.aspx - BOOST_MPL_ASSERT( (boost::mpl::and_, boost::has_trivial_destructor > )); - public: - typedef Hasher hasher; - typedef SimpleAllocHashMultiMap map_type; - typedef typename boost::mpl::if_, V, V const &>::type value_ref; // otherwise we get problems with 'const' if V is a pointer - - SimpleAllocHashMultiMap(size_t buckets, size_t keyRowSize, size_t valueRowSize, size_t maxRows=50) ; - - ~SimpleAllocHashMultiMap() ; - - void clear(size_t newBucketSize=0) { - if (newBucketSize != 0) { - if (newBucketSize > bucketCapacity_) { - ptrAlloc_.deallocate(buckets_, bucketCapacity_); - bucketCapacity_ = newBucketSize; - buckets_ = ptrAlloc_.allocate(bucketCapacity_); - } - bucketSize_ = newBucketSize; - } - memset(buckets_, 0, bucketSize_ * sizeof(KeyItem *)); - currentKeyRow_ = keyRows_.begin(); - nextKeyItem_ = keyRows_.front(); keyEndMarker_ = nextKeyItem_ + keyRowSize_; - currentValueRow_ = valueRows_.begin(); - nextValueItem_ = valueRows_.front(); valueEndMarker_ = nextValueItem_ + valueRowSize_; - if ((keyRows_.size() > maxRows_) || (valueRows_.size() > maxRows_)) freeRows(); + BOOST_MPL_ASSERT((boost::mpl::and_, boost::has_trivial_destructor >)); + + public: + typedef Hasher hasher; + typedef SimpleAllocHashMultiMap map_type; + typedef typename boost::mpl::if_, V, V const &>::type + value_ref; // otherwise we get problems with 'const' if V is a pointer + + SimpleAllocHashMultiMap(size_t buckets, size_t keyRowSize, size_t valueRowSize, size_t maxRows = 50); + + ~SimpleAllocHashMultiMap(); + + void clear(size_t newBucketSize = 0) { + if (newBucketSize != 0) { + if (newBucketSize > bucketCapacity_) { + ptrAlloc_.deallocate(buckets_, bucketCapacity_); + bucketCapacity_ = newBucketSize; + buckets_ = ptrAlloc_.allocate(bucketCapacity_); } - void freeRows() ; - - bool empty() const { return nextKeyItem_ == keyRows_.front(); } - - void insert(K const &key, value_ref value ); - - struct ValueItem { - ValueItem(ValueItem *next1, value_ref val) : next(next1), value(val) {} - ValueItem * next; - V value; - typedef V value_type; - const value_type & operator()() const { return value; } - }; - - struct KeyItem { - KeyItem (KeyItem *next1, K const &key1, ValueItem *val1) : key(key1), next(next1), value(val1) {} - K key; - KeyItem * next; - ValueItem * value; - typedef KeyItem value_type; - const value_type & operator()() const { return *this; } - }; - - template - class item_iterator { - public: - typedef ::std::forward_iterator_tag iterator_category; - typedef const typename Item::value_type value_type; - typedef const value_type & reference; - typedef const value_type * pointer; - typedef ptrdiff_t difference_type; - typedef item_iterator self_type; - - item_iterator() : it_(nullptr) {} - item_iterator(const Item *it) : it_(it) {} - const value_type & operator*() const { return (*it_)(); } - const value_type * operator->() const { return & (*it_)(); } - self_type & operator++() { - if (it_ != nullptr) it_ = it_->next; - return *this; - } - bool operator==(const self_type &other) const { return it_ == other.it_; } - bool operator!=(const self_type &other) const { return it_ != other.it_; } - bool good() const { return (it_ != nullptr); } - private: - const Item *it_; - }; - typedef item_iterator value_iterator; - - value_iterator values(K const &key) ; + bucketSize_ = newBucketSize; + } + memset(buckets_, 0, bucketSize_ * sizeof(KeyItem *)); + currentKeyRow_ = keyRows_.begin(); + nextKeyItem_ = keyRows_.front(); + keyEndMarker_ = nextKeyItem_ + keyRowSize_; + currentValueRow_ = valueRows_.begin(); + nextValueItem_ = valueRows_.front(); + valueEndMarker_ = nextValueItem_ + valueRowSize_; + if ((keyRows_.size() > maxRows_) || (valueRows_.size() > maxRows_)) + freeRows(); + } + void freeRows(); - private: - typedef typename Alloc::template rebind::other KeyItemAllocator; - typedef typename Alloc::template rebind::other KeyItemPtrAllocator; - typedef typename Alloc::template rebind::other ValueItemAllocator; - - // --- buckets --- - size_t bucketSize_, bucketCapacity_; - KeyItem ** buckets_; - // --- keys --- - size_t keyRowSize_; - std::list keyRows_; - typename std::list::iterator currentKeyRow_; // last row that is currently in use. nextItem_ and the last valid item are both on this row. it is never rows_.end() - KeyItem *nextKeyItem_, *keyEndMarker_; - // --- values --- - size_t valueRowSize_; - std::list valueRows_; - typename std::list::iterator currentValueRow_; // last row that is currently in use. nextItem_ and the last valid item are both on this row. it is never rows_.end() - ValueItem *nextValueItem_, *valueEndMarker_; - // --- other --- - size_t maxRows_; - Hasher hasher_; - Equals eq_; - KeyItemAllocator keyAlloc_; - ValueItemAllocator valueAlloc_; - KeyItemPtrAllocator ptrAlloc_; - - KeyItem * push_back_(K const &key, KeyItem *next) ; - ValueItem * push_back_(value_ref value, ValueItem *next) ; - KeyItem & find_or_insert_(K const &key) ; + bool empty() const { return nextKeyItem_ == keyRows_.front(); } + + void insert(K const &key, value_ref value); + + struct ValueItem { + ValueItem(ValueItem *next1, value_ref val) : next(next1), value(val) {} + ValueItem *next; + V value; + typedef V value_type; + const value_type &operator()() const { return value; } + }; + + struct KeyItem { + KeyItem(KeyItem *next1, K const &key1, ValueItem *val1) : key(key1), next(next1), value(val1) {} + K key; + KeyItem *next; + ValueItem *value; + typedef KeyItem value_type; + const value_type &operator()() const { return *this; } + }; + + template + class item_iterator { public: - void dump() { - std::cout << "Dumping HASH MULTIMAP" << std::endl; - std::cout << " Key items: " << (std::distance(keyRows_.begin(), currentKeyRow_) * keyRowSize_ + (nextKeyItem_ - *currentKeyRow_)) << std::endl; - std::cout << " Value items: " << (std::distance(valueRows_.begin(), currentValueRow_) * valueRowSize_ + (nextValueItem_ - *currentValueRow_)) << std::endl; - size_t row = 0; - std::cout << " Buckets (size " << bucketSize_ << ", capacity " << bucketCapacity_ << ")"; - for (KeyItem **p = buckets_; p != buckets_ + bucketSize_; ++p, ++row) { - std::cout << " ["<::iterator it = keyRows_.begin(), last = keyRows_.end(); it != last; ++it, ++row) { - KeyItem *lastI = *it + keyRowSize_; - std::cout << " Key Row " << row << " (of size " << keyRowSize_ << ")" << std::endl; - for (KeyItem *p = *it; p != lastI; ++p) { - std::cout << " @ " << p << " [" << p->key << ", @" << p->value <<"], next = " << p->next << std::endl; - if ((it == currentKeyRow_) && (p == nextKeyItem_ - 1)) { - std::cout << " ^^^ this was the last valid item." << std::endl; - last = 0; break; - } - } - if (lastI == 0) break; - } - row = 0; - std::cout << " Value Items " << std::endl; - for (typename std::list::iterator it = valueRows_.begin(), last = valueRows_.end(); it != last; ++it, ++row) { - ValueItem *lastI = *it + valueRowSize_; - std::cout << " Value Row " << row << " (of size " << valueRowSize_ << ")" << std::endl; - for (ValueItem *p = *it; p != lastI; ++p) { - std::cout << " @ " << p << " [" << p->value <<"], next = " << p->next << std::endl; - if ((it == currentValueRow_) && (p == nextValueItem_ - 1)) { - std::cout << " ^^^ this was the last valid item." << std::endl; - last = 0; break; - } - } - if (lastI == 0) break; - } - std::cout << " End of dump" << std::endl; - + typedef ::std::forward_iterator_tag iterator_category; + typedef const typename Item::value_type value_type; + typedef const value_type &reference; + typedef const value_type *pointer; + typedef ptrdiff_t difference_type; + typedef item_iterator self_type; + + item_iterator() : it_(nullptr) {} + item_iterator(const Item *it) : it_(it) {} + const value_type &operator*() const { return (*it_)(); } + const value_type *operator->() const { return &(*it_)(); } + self_type &operator++() { + if (it_ != nullptr) + it_ = it_->next; + return *this; + } + bool operator==(const self_type &other) const { return it_ == other.it_; } + bool operator!=(const self_type &other) const { return it_ != other.it_; } + bool good() const { return (it_ != nullptr); } + + private: + const Item *it_; + }; + typedef item_iterator value_iterator; + + value_iterator values(K const &key); + + private: + typedef typename Alloc::template rebind::other KeyItemAllocator; + typedef typename Alloc::template rebind::other KeyItemPtrAllocator; + typedef typename Alloc::template rebind::other ValueItemAllocator; + + // --- buckets --- + size_t bucketSize_, bucketCapacity_; + KeyItem **buckets_; + // --- keys --- + size_t keyRowSize_; + std::list keyRows_; + typename std::list::iterator + currentKeyRow_; // last row that is currently in use. nextItem_ and the last valid item are both on this row. it is never rows_.end() + KeyItem *nextKeyItem_, *keyEndMarker_; + // --- values --- + size_t valueRowSize_; + std::list valueRows_; + typename std::list::iterator + currentValueRow_; // last row that is currently in use. nextItem_ and the last valid item are both on this row. it is never rows_.end() + ValueItem *nextValueItem_, *valueEndMarker_; + // --- other --- + size_t maxRows_; + Hasher hasher_; + Equals eq_; + KeyItemAllocator keyAlloc_; + ValueItemAllocator valueAlloc_; + KeyItemPtrAllocator ptrAlloc_; + + KeyItem *push_back_(K const &key, KeyItem *next); + ValueItem *push_back_(value_ref value, ValueItem *next); + KeyItem &find_or_insert_(K const &key); + + public: + void dump() { + std::cout << "Dumping HASH MULTIMAP" << std::endl; + std::cout << " Key items: " + << (std::distance(keyRows_.begin(), currentKeyRow_) * keyRowSize_ + (nextKeyItem_ - *currentKeyRow_)) + << std::endl; + std::cout << " Value items: " + << (std::distance(valueRows_.begin(), currentValueRow_) * valueRowSize_ + + (nextValueItem_ - *currentValueRow_)) + << std::endl; + size_t row = 0; + std::cout << " Buckets (size " << bucketSize_ << ", capacity " << bucketCapacity_ << ")"; + for (KeyItem **p = buckets_; p != buckets_ + bucketSize_; ++p, ++row) { + std::cout << " [" << row << "] " << *p << std::endl; + } + row = 0; + std::cout << " Key Items " << std::endl; + for (typename std::list::iterator it = keyRows_.begin(), last = keyRows_.end(); it != last; + ++it, ++row) { + KeyItem *lastI = *it + keyRowSize_; + std::cout << " Key Row " << row << " (of size " << keyRowSize_ << ")" << std::endl; + for (KeyItem *p = *it; p != lastI; ++p) { + std::cout << " @ " << p << " [" << p->key << ", @" << p->value << "], next = " << p->next << std::endl; + if ((it == currentKeyRow_) && (p == nextKeyItem_ - 1)) { + std::cout << " ^^^ this was the last valid item." << std::endl; + last = 0; + break; + } + } + if (lastI == 0) + break; + } + row = 0; + std::cout << " Value Items " << std::endl; + for (typename std::list::iterator it = valueRows_.begin(), last = valueRows_.end(); it != last; + ++it, ++row) { + ValueItem *lastI = *it + valueRowSize_; + std::cout << " Value Row " << row << " (of size " << valueRowSize_ << ")" << std::endl; + for (ValueItem *p = *it; p != lastI; ++p) { + std::cout << " @ " << p << " [" << p->value << "], next = " << p->next << std::endl; + if ((it == currentValueRow_) && (p == nextValueItem_ - 1)) { + std::cout << " ^^^ this was the last valid item." << std::endl; + last = 0; + break; + } } -}; - -template -SimpleAllocHashMultiMap::SimpleAllocHashMultiMap(size_t buckets, size_t keyRowSize, size_t valueRowSize, size_t maxRows) : - bucketSize_(buckets), bucketCapacity_(bucketSize_), - keyRowSize_(keyRowSize), - valueRowSize_(valueRowSize), - maxRows_(maxRows) -{ + if (lastI == 0) + break; + } + std::cout << " End of dump" << std::endl; + } + }; + + template + SimpleAllocHashMultiMap::SimpleAllocHashMultiMap(size_t buckets, + size_t keyRowSize, + size_t valueRowSize, + size_t maxRows) + : bucketSize_(buckets), + bucketCapacity_(bucketSize_), + keyRowSize_(keyRowSize), + valueRowSize_(valueRowSize), + maxRows_(maxRows) { buckets_ = ptrAlloc_.allocate(bucketCapacity_); keyRows_.push_back(keyAlloc_.allocate(keyRowSize_)); valueRows_.push_back(valueAlloc_.allocate(valueRowSize_)); clear(); -} -template -SimpleAllocHashMultiMap::~SimpleAllocHashMultiMap() -{ + } + template + SimpleAllocHashMultiMap::~SimpleAllocHashMultiMap() { for (typename std::list::iterator it = keyRows_.begin(), last = keyRows_.end(); it != last; ++it) { - keyAlloc_.deallocate(*it, keyRowSize_); + keyAlloc_.deallocate(*it, keyRowSize_); } for (typename std::list::iterator it = valueRows_.begin(), last = valueRows_.end(); it != last; ++it) { - valueAlloc_.deallocate(*it, valueRowSize_); + valueAlloc_.deallocate(*it, valueRowSize_); } ptrAlloc_.deallocate(buckets_, bucketCapacity_); -} - -template -void -SimpleAllocHashMultiMap::freeRows() { - if (keyRows_.size() > maxRows_) { - //std::cerr << "Freeing key rows, current size is " << keyRows_.size() << std::endl; - typename std::list::iterator it = keyRows_.begin(), last = keyRows_.end(); - for (std::advance(it, maxRows_); it != last; ++it) { - keyAlloc_.deallocate(*it, keyRowSize_); - } - keyRows_.resize(maxRows_); - } - if (valueRows_.size() > maxRows_) { - //std::cerr << "Freeing value rows, current size is " << valueRows_.size() << std::endl; - typename std::list::iterator it = valueRows_.begin(), last = valueRows_.end(); - for (std::advance(it, maxRows_); it != last; ++it) { - valueAlloc_.deallocate(*it, valueRowSize_); - } - valueRows_.resize(maxRows_); - } -} + } + + template + void SimpleAllocHashMultiMap::freeRows() { + if (keyRows_.size() > maxRows_) { + //std::cerr << "Freeing key rows, current size is " << keyRows_.size() << std::endl; + typename std::list::iterator it = keyRows_.begin(), last = keyRows_.end(); + for (std::advance(it, maxRows_); it != last; ++it) { + keyAlloc_.deallocate(*it, keyRowSize_); + } + keyRows_.resize(maxRows_); + } + if (valueRows_.size() > maxRows_) { + //std::cerr << "Freeing value rows, current size is " << valueRows_.size() << std::endl; + typename std::list::iterator it = valueRows_.begin(), last = valueRows_.end(); + for (std::advance(it, maxRows_); it != last; ++it) { + valueAlloc_.deallocate(*it, valueRowSize_); + } + valueRows_.resize(maxRows_); + } + } -template -typename SimpleAllocHashMultiMap::KeyItem * -SimpleAllocHashMultiMap::push_back_(K const &key, KeyItem *next) { + template + typename SimpleAllocHashMultiMap::KeyItem * + SimpleAllocHashMultiMap::push_back_(K const &key, KeyItem *next) { if (nextKeyItem_ == keyEndMarker_) { - ++currentKeyRow_; - if (currentKeyRow_ == keyRows_.end()) { - keyRows_.push_back(keyAlloc_.allocate(keyRowSize_)); - currentKeyRow_ = keyRows_.end(); --currentKeyRow_; // end - 1 doesn't work! - } - nextKeyItem_ = *currentKeyRow_; - keyEndMarker_ = nextKeyItem_ + keyRowSize_; + ++currentKeyRow_; + if (currentKeyRow_ == keyRows_.end()) { + keyRows_.push_back(keyAlloc_.allocate(keyRowSize_)); + currentKeyRow_ = keyRows_.end(); + --currentKeyRow_; // end - 1 doesn't work! + } + nextKeyItem_ = *currentKeyRow_; + keyEndMarker_ = nextKeyItem_ + keyRowSize_; } keyAlloc_.construct(nextKeyItem_, KeyItem(next, key, nullptr)); nextKeyItem_++; - return (nextKeyItem_-1); -} -template -typename SimpleAllocHashMultiMap::ValueItem * -SimpleAllocHashMultiMap::push_back_(value_ref value, ValueItem *next) { + return (nextKeyItem_ - 1); + } + template + typename SimpleAllocHashMultiMap::ValueItem * + SimpleAllocHashMultiMap::push_back_(value_ref value, ValueItem *next) { if (nextValueItem_ == valueEndMarker_) { - ++currentValueRow_; - if (currentValueRow_ == valueRows_.end()) { - valueRows_.push_back(valueAlloc_.allocate(valueRowSize_)); - currentValueRow_ = valueRows_.end(); --currentValueRow_; // end - 1 doesn't work! - } - nextValueItem_ = *currentValueRow_; - valueEndMarker_ = nextValueItem_ + valueRowSize_; + ++currentValueRow_; + if (currentValueRow_ == valueRows_.end()) { + valueRows_.push_back(valueAlloc_.allocate(valueRowSize_)); + currentValueRow_ = valueRows_.end(); + --currentValueRow_; // end - 1 doesn't work! + } + nextValueItem_ = *currentValueRow_; + valueEndMarker_ = nextValueItem_ + valueRowSize_; } valueAlloc_.construct(nextValueItem_, ValueItem(next, value)); nextValueItem_++; - return (nextValueItem_-1); -} + return (nextValueItem_ - 1); + } -template -typename SimpleAllocHashMultiMap::KeyItem & -SimpleAllocHashMultiMap::find_or_insert_(K const &key) { + template + typename SimpleAllocHashMultiMap::KeyItem & + SimpleAllocHashMultiMap::find_or_insert_(K const &key) { //std::cout << "Find or insert for key " << key << std::endl; size_t hash = hasher_(key); - KeyItem * & buck = buckets_[hash % bucketSize_]; - KeyItem * curr = buck; + KeyItem *&buck = buckets_[hash % bucketSize_]; + KeyItem *curr = buck; while (curr) { - if (eq_(curr->key, key)) { - //std::cout << " Key " << key << " was found." << std::endl; - return *curr; - } - curr = curr->next; - } + if (eq_(curr->key, key)) { + //std::cout << " Key " << key << " was found." << std::endl; + return *curr; + } + curr = curr->next; + } buck = push_back_(key, buck); return *buck; -} + } -template -void SimpleAllocHashMultiMap::insert(K const &key, value_ref value) { + template + void SimpleAllocHashMultiMap::insert(K const &key, value_ref value) { //std::cout << "Pushing back value " << value << " for key " << key << std::endl; KeyItem &k = find_or_insert_(key); //std::cout << "Key " << (k.value ? "exists" : " is new") << std::endl; k.value = push_back_(value, k.value); -} + } -template -typename SimpleAllocHashMultiMap::value_iterator -SimpleAllocHashMultiMap::values(K const &key) { + template + typename SimpleAllocHashMultiMap::value_iterator + SimpleAllocHashMultiMap::values(K const &key) { //std::cout << "Gettinv values for key " << key << std::endl; size_t hash = hasher_(key); - for (KeyItem * curr = buckets_[hash % bucketSize_]; curr; curr = curr->next) { - if (eq_(curr->key, key)) return value_iterator(curr->value); + for (KeyItem *curr = buckets_[hash % bucketSize_]; curr; curr = curr->next) { + if (eq_(curr->key, key)) + return value_iterator(curr->value); } return value_iterator(); -} - + } -/*** Very very simple map implementation + /*** Very very simple map implementation * It's just a std::vector>, and the operator[] does a linear search to find the key (it's O(N) time, both if the key exists and if it doesn't) * Anyway, if your map is very small and if you clear it often, it performs better than more complex variants * Semantics is as std::map, except that only very few methods are implemented. * */ -template -class UnsortedDumbVectorMap { - public: - typedef std::pair value_type; - typedef typename std::vector::const_iterator const_iterator; - typedef typename std::vector::iterator iterator; // but please don't mutate the keys - - void clear() { data_.clear(); } - bool empty() const { return data_.empty(); } - const_iterator begin() const { return data_.begin(); } - const_iterator end() const { return data_.end(); } - iterator begin() { return data_.begin(); } - iterator end() { return data_.end(); } - - V & operator[](const K &k) { - for (typename std::vector::iterator it = data_.begin(), ed = data_.end(); it != ed; ++it) { - if (it->first == k) return it->second; - } - data_.push_back(value_type(k,V())); - return data_.back().second; - } + template + class UnsortedDumbVectorMap { + public: + typedef std::pair value_type; + typedef typename std::vector::const_iterator const_iterator; + typedef typename std::vector::iterator iterator; // but please don't mutate the keys + void clear() { data_.clear(); } + bool empty() const { return data_.empty(); } + const_iterator begin() const { return data_.begin(); } + const_iterator end() const { return data_.end(); } + iterator begin() { return data_.begin(); } + iterator end() { return data_.end(); } - UnsortedDumbVectorMap() {} - - private: - std::vector data_; + V &operator[](const K &k) { + for (typename std::vector::iterator it = data_.begin(), ed = data_.end(); it != ed; ++it) { + if (it->first == k) + return it->second; + } + data_.push_back(value_type(k, V())); + return data_.back().second; + } + + UnsortedDumbVectorMap() {} -}; + private: + std::vector data_; + }; -} // namespace +} // namespace cmsutil #endif diff --git a/TrackingTools/TrajectoryCleaning/src/TrajectoryCleaner.cc b/TrackingTools/TrajectoryCleaning/src/TrajectoryCleaner.cc index fb2c691c1ae4d..06442576f41fa 100644 --- a/TrackingTools/TrajectoryCleaning/src/TrajectoryCleaner.cc +++ b/TrackingTools/TrajectoryCleaning/src/TrajectoryCleaner.cc @@ -1,24 +1,21 @@ #include "TrackingTools/TrajectoryCleaning/interface/TrajectoryCleaner.h" -#include +#include -void TrajectoryCleaner::clean( TempTrajectoryContainer&) const -{ +void TrajectoryCleaner::clean(TempTrajectoryContainer&) const { edm::LogError("TrajectoryCleaner") << "not implemented for TempTrajectory"; assert(false); } -void TrajectoryCleaner::clean( TrajectoryContainer& tc) const -{ +void TrajectoryCleaner::clean(TrajectoryContainer& tc) const { TrajectoryPointerContainer thePointerContainer; thePointerContainer.reserve(tc.size()); for (TrajectoryCleaner::TrajectoryIterator it = tc.begin(); it != tc.end(); it++) { - thePointerContainer.push_back( &(*it) ); + thePointerContainer.push_back(&(*it)); } clean(thePointerContainer); } - #include "FWCore/Utilities/interface/typelookup.h" TYPELOOKUP_DATA_REG(TrajectoryCleaner); diff --git a/TrackingTools/TrajectoryCleaning/src/TrajectoryCleanerBySharedHits.cc b/TrackingTools/TrajectoryCleaning/src/TrajectoryCleanerBySharedHits.cc index e173e9f3d6a32..9539f428f9eae 100644 --- a/TrackingTools/TrajectoryCleaning/src/TrajectoryCleanerBySharedHits.cc +++ b/TrackingTools/TrajectoryCleaning/src/TrajectoryCleanerBySharedHits.cc @@ -4,54 +4,56 @@ #include "TrackingTools/TrajectoryCleaning/src/OtherHashMaps.h" - //#define DEBUG_PRINT(X) X -#define DEBUG_PRINT(X) +#define DEBUG_PRINT(X) namespace { -// Define when two rechits are equals -struct EqualsBySharesInput { + // Define when two rechits are equals + struct EqualsBySharesInput { bool operator()(const TransientTrackingRecHit *h1, const TransientTrackingRecHit *h2) const { - return (h1 == h2) || ((h1->geographicalId() == h2->geographicalId()) && (h1->hit()->sharesInput(h2->hit(), TrackingRecHit::some))); + return (h1 == h2) || ((h1->geographicalId() == h2->geographicalId()) && + (h1->hit()->sharesInput(h2->hit(), TrackingRecHit::some))); } -}; -// Define a hash, i.e. a number that must be equal if hits are equal, and should be different if they're not -struct HashByDetId { - std::size_t operator()(const TransientTrackingRecHit *hit) const { - boost::hash hasher; - return hasher(hit->geographicalId().rawId()); + }; + // Define a hash, i.e. a number that must be equal if hits are equal, and should be different if they're not + struct HashByDetId { + std::size_t operator()(const TransientTrackingRecHit *hit) const { + boost::hash hasher; + return hasher(hit->geographicalId().rawId()); } -}; + }; -using RecHitMap = cmsutil::SimpleAllocHashMultiMap; -using TrajMap = cmsutil::UnsortedDumbVectorMap; + using RecHitMap = + cmsutil::SimpleAllocHashMultiMap; + using TrajMap = cmsutil::UnsortedDumbVectorMap; -struct Maps { - Maps() : theRecHitMap(128,256,1024){} // allocate 128 buckets, one row for 256 keys and one row for 512 values - RecHitMap theRecHitMap; - TrajMap theTrajMap; -}; + struct Maps { + Maps() : theRecHitMap(128, 256, 1024) {} // allocate 128 buckets, one row for 256 keys and one row for 512 values + RecHitMap theRecHitMap; + TrajMap theTrajMap; + }; -thread_local Maps theMaps; -} + thread_local Maps theMaps; +} // namespace using namespace std; -void TrajectoryCleanerBySharedHits::clean( TrajectoryPointerContainer & tc) const -{ - if (tc.size() <= 1) return; // nothing to clean +void TrajectoryCleanerBySharedHits::clean(TrajectoryPointerContainer &tc) const { + if (tc.size() <= 1) + return; // nothing to clean - auto & theRecHitMap = theMaps.theRecHitMap; + auto &theRecHitMap = theMaps.theRecHitMap; - theRecHitMap.clear(10*tc.size()); // set 10*tc.size() active buckets - // numbers are not optimized + theRecHitMap.clear(10 * tc.size()); // set 10*tc.size() active buckets + // numbers are not optimized DEBUG_PRINT(std::cout << "Filling RecHit map" << std::endl); - for (auto const & it : tc) { - DEBUG_PRINT(std::cout << " Processing trajectory " << it << " (" << it->foundHits() << " valid hits)" << std::endl); - auto const & pd = it->measurements(); - for (auto const & im : pd) { + for (auto const &it : tc) { + DEBUG_PRINT(std::cout << " Processing trajectory " << it << " (" << it->foundHits() << " valid hits)" + << std::endl); + auto const &pd = it->measurements(); + for (auto const &im : pd) { auto theRecHit = &(*im.recHit()); if (theRecHit->isValid()) { DEBUG_PRINT(std::cout << " Added hit " << theRecHit << " for trajectory " << it << std::endl); @@ -63,66 +65,68 @@ void TrajectoryCleanerBySharedHits::clean( TrajectoryPointerContainer & tc) cons DEBUG_PRINT(std::cout << "Using RecHit map" << std::endl); // for each trajectory fill theTrajMap - auto & theTrajMap = theMaps.theTrajMap; - for (auto const & itt : tc) { - if(itt->isValid()){ - DEBUG_PRINT(std::cout << " Processing trajectory " << itt << " (" << itt->foundHits() << " valid hits)" << std::endl); + auto &theTrajMap = theMaps.theTrajMap; + for (auto const &itt : tc) { + if (itt->isValid()) { + DEBUG_PRINT(std::cout << " Processing trajectory " << itt << " (" << itt->foundHits() << " valid hits)" + << std::endl); theTrajMap.clear(); - const Trajectory::DataContainer & pd = itt->measurements(); - for (auto const & im : pd) { - auto theRecHit = &(*im.recHit()); + const Trajectory::DataContainer &pd = itt->measurements(); + for (auto const &im : pd) { + auto theRecHit = &(*im.recHit()); if (theRecHit->isValid()) { - DEBUG_PRINT(std::cout << " Searching for overlaps on hit " << theRecHit << " for trajectory " << itt << std::endl); - for (RecHitMap::value_iterator ivec = theRecHitMap.values(theRecHit); - ivec.good(); ++ivec) { - if (*ivec != itt){ - if ((*ivec)->isValid()){ - theTrajMap[*ivec]++; - } + DEBUG_PRINT(std::cout << " Searching for overlaps on hit " << theRecHit << " for trajectory " << itt + << std::endl); + for (RecHitMap::value_iterator ivec = theRecHitMap.values(theRecHit); ivec.good(); ++ivec) { + if (*ivec != itt) { + if ((*ivec)->isValid()) { + theTrajMap[*ivec]++; } + } } - } + } } //end filling theTrajMap - auto score = [&](Trajectory const&t)->float { - // possible variant under study - // auto ns = t.foundHits()-t.trailingFoundHits(); - //auto penalty = 0.8f*missingHitPenalty_; - // return validHitBonus_*(t.foundHits()-0.2f*t.cccBadHits()) - penalty*t.lostHits() - t.chiSquared(); - // classical score - return validHitBonus_*t.foundHits() - missingHitPenalty_*t.lostHits() - t.chiSquared(); - }; + auto score = [&](Trajectory const &t) -> float { + // possible variant under study + // auto ns = t.foundHits()-t.trailingFoundHits(); + //auto penalty = 0.8f*missingHitPenalty_; + // return validHitBonus_*(t.foundHits()-0.2f*t.cccBadHits()) - penalty*t.lostHits() - t.chiSquared(); + // classical score + return validHitBonus_ * t.foundHits() - missingHitPenalty_ * t.lostHits() - t.chiSquared(); + }; // check for duplicated tracks - if(!theTrajMap.empty() > 0){ - for(auto const & imapp : theTrajMap) { - if(imapp.second > 0 ){ // at least 1 hits in common!!! - int innerHit = 0; - if ( allowSharedFirstHit ) { - const TrajectoryMeasurement & innerMeasure1 = ( itt->direction() == alongMomentum ) ? - itt->firstMeasurement() : itt->lastMeasurement(); - const TransientTrackingRecHit* h1 = &(*(innerMeasure1).recHit()); - const TrajectoryMeasurement & innerMeasure2 = ( imapp.first->direction() == alongMomentum ) ? - imapp.first->firstMeasurement() : imapp.first->lastMeasurement(); - const TransientTrackingRecHit* h2 = &(*(innerMeasure2).recHit()); - if ( (h1 == h2) || ((h1->geographicalId() == h2->geographicalId()) && - (h1->hit()->sharesInput(h2->hit(), TrackingRecHit::some))) ) { - innerHit = 1; - } - } - int nhit1 = itt->foundHits(); - int nhit2 = imapp.first->foundHits(); - if( (imapp.second - innerHit) >= ( (min(nhit1, nhit2)-innerHit) * theFraction) ){ - Trajectory* badtraj; - auto score1 = score(*itt); - auto score2 = score(*imapp.first); - badtraj = (score1 > score2) ? imapp.first : itt; - badtraj->invalidate(); // invalidate this trajectory - } - } - } - } + if (!theTrajMap.empty() > 0) { + for (auto const &imapp : theTrajMap) { + if (imapp.second > 0) { // at least 1 hits in common!!! + int innerHit = 0; + if (allowSharedFirstHit) { + const TrajectoryMeasurement &innerMeasure1 = + (itt->direction() == alongMomentum) ? itt->firstMeasurement() : itt->lastMeasurement(); + const TransientTrackingRecHit *h1 = &(*(innerMeasure1).recHit()); + const TrajectoryMeasurement &innerMeasure2 = (imapp.first->direction() == alongMomentum) + ? imapp.first->firstMeasurement() + : imapp.first->lastMeasurement(); + const TransientTrackingRecHit *h2 = &(*(innerMeasure2).recHit()); + if ((h1 == h2) || ((h1->geographicalId() == h2->geographicalId()) && + (h1->hit()->sharesInput(h2->hit(), TrackingRecHit::some)))) { + innerHit = 1; + } + } + int nhit1 = itt->foundHits(); + int nhit2 = imapp.first->foundHits(); + if ((imapp.second - innerHit) >= ((min(nhit1, nhit2) - innerHit) * theFraction)) { + Trajectory *badtraj; + auto score1 = score(*itt); + auto score2 = score(*imapp.first); + badtraj = (score1 > score2) ? imapp.first : itt; + badtraj->invalidate(); // invalidate this trajectory + } + } + } + } } } } diff --git a/TrackingTools/TrajectoryCleaning/src/TrajectoryCleanerFactory.cc b/TrackingTools/TrajectoryCleaning/src/TrajectoryCleanerFactory.cc index 451910d51a06a..fe9d0b23cc53d 100644 --- a/TrackingTools/TrajectoryCleaning/src/TrajectoryCleanerFactory.cc +++ b/TrackingTools/TrajectoryCleaning/src/TrajectoryCleanerFactory.cc @@ -1,5 +1,5 @@ #include "TrackingTools/TrajectoryCleaning/interface/TrajectoryCleanerFactory.h" #include "FWCore/PluginManager/interface/PluginFactory.h" - + EDM_REGISTER_PLUGINFACTORY(TrajectoryCleanerFactory, "TrajectoryCleanerFactory"); diff --git a/TrackingTools/TrajectoryCleaning/test/TrajectoryCleanerAnalyzer.cc b/TrackingTools/TrajectoryCleaning/test/TrajectoryCleanerAnalyzer.cc index 0a2be38be2b68..239f916bab0f5 100644 --- a/TrackingTools/TrajectoryCleaning/test/TrajectoryCleanerAnalyzer.cc +++ b/TrackingTools/TrajectoryCleaning/test/TrajectoryCleanerAnalyzer.cc @@ -2,7 +2,7 @@ // // Package: TrajectoryCleanerAnalyzer // Class: TrajectoryCleanerAnalyzer -// +// /**\class TrajectoryCleanerAnalyzer TrajectoryCleanerAnalyzer.cc TrackingTools/TrajectoryCleanerAnalyzer/src/TrajectoryCleanerAnalyzer.cc Description: @@ -16,7 +16,6 @@ // // - // system include files #include @@ -34,48 +33,41 @@ #include "TrackingTools/Records/interface/TrackingComponentsRecord.h" class TrajectoryCleanerAnalyzer : public edm::EDAnalyzer { - public: - explicit TrajectoryCleanerAnalyzer(const edm::ParameterSet&); - ~TrajectoryCleanerAnalyzer(); +public: + explicit TrajectoryCleanerAnalyzer(const edm::ParameterSet&); + ~TrajectoryCleanerAnalyzer(); - - private: - virtual void beginJob() ; - virtual void analyze(const edm::Event&, const edm::EventSetup&); - virtual void endJob() ; +private: + virtual void beginJob(); + virtual void analyze(const edm::Event&, const edm::EventSetup&); + virtual void endJob(); std::vector cleanerNames; }; -TrajectoryCleanerAnalyzer::TrajectoryCleanerAnalyzer(const edm::ParameterSet& iConfig) -{cleanerNames= iConfig.getParameter >("cleanerNames");} +TrajectoryCleanerAnalyzer::TrajectoryCleanerAnalyzer(const edm::ParameterSet& iConfig) { + cleanerNames = iConfig.getParameter >("cleanerNames"); +} -TrajectoryCleanerAnalyzer::~TrajectoryCleanerAnalyzer(){} +TrajectoryCleanerAnalyzer::~TrajectoryCleanerAnalyzer() {} -void TrajectoryCleanerAnalyzer::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) -{ - using namespace edm; +void TrajectoryCleanerAnalyzer::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { + using namespace edm; - edm::ESHandle pTC; - edm::LogInfo("TrajectoryCleanerAnalyzer")<<" I am happy to try and get: "<().get(cleanerNames[i], pTC); - edm::LogInfo("TrajectoryCleanerAnalyzer")<<"I was able to create: "< pTC; + edm::LogInfo("TrajectoryCleanerAnalyzer") + << " I am happy to try and get: " << cleanerNames.size() << " TrajectoryFilter from TrajectoryCleaner::Record"; + for (unsigned int i = 0; i != cleanerNames.size(); i++) { + iSetup.get().get(cleanerNames[i], pTC); + edm::LogInfo("TrajectoryCleanerAnalyzer") << "I was able to create: " << cleanerNames[i]; + } } - // ------------ method called once each job just before starting event loop ------------ -void -TrajectoryCleanerAnalyzer::beginJob() -{ -} +void TrajectoryCleanerAnalyzer::beginJob() {} // ------------ method called once each job just after ending the event loop ------------ -void -TrajectoryCleanerAnalyzer::endJob() { -} +void TrajectoryCleanerAnalyzer::endJob() {} //define this as a plug-in DEFINE_FWK_MODULE(TrajectoryCleanerAnalyzer);